summaryrefslogtreecommitdiff
path: root/src/libs/file/dirs.c
blob: 39a44f5e5f17da083aa3be6335636395f6482670 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

// Contains code handling directories

#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "port.h"
#include "config.h"
#include "filintrn.h"
#include "libs/compiler.h"
#include "libs/memlib.h"
#include "libs/misc.h"
#include "libs/log.h"

#ifdef HAVE_DRIVE_LETTERS
#	include <ctype.h>
			// For tolower()
#endif  /* HAVE_DRIVE_LETTERS */
#ifdef WIN32
#	include <direct.h>
			// For _getdcwd()
#else
#	include <pwd.h>
			// For getpwuid()
#endif

/* Try to find a suitable value for %APPDATA% if it isn't defined on
 * Windows.
 */
#define APPDATA_FALLBACK


static char *expandPathAbsolute (char *dest, size_t destLen, const char *src,
		size_t *skipSrc, int what);
static char *strrchr2(const char *start, int c, const char *end);


int
createDirectory(const char *dir, int mode)
{
	return MKDIR(dir, mode);
}

// make all components of the path if they don't exist already
// returns 0 on success, -1 on failure.
// on failure, some parts may still have been created.
int
mkdirhier (const char *path)
{
	char *buf;              // buffer
	char *ptr;              // end of the string in buf
	const char *pathstart;  // start of a component of path
	const char *pathend;    // first char past the end of a component of path
	size_t len;
	struct stat statbuf;
	
	len = strlen (path);
	buf = HMalloc (len + 2);  // one extra for possibly added '/'

	ptr = buf;
	pathstart = path;

#ifdef HAVE_DRIVE_LETTERS
	if (isDriveLetter(pathstart[0]) && pathstart[1] == ':')
	{
		// Driveletter + semicolon on Windows.
		// Copy as is; don't try to create directories for it.
		*(ptr++) = *(pathstart++);
		*(ptr++) = *(pathstart++);

		ptr[0] = '/';
		ptr[1] = '\0';
		if (stat (buf, &statbuf) == -1)
		{
			log_add (log_Error, "Can't stat \"%s\": %s", buf, strerror (errno));
			goto err;
		}
	}
	else
#endif  /* HAVE_DRIVE_LETTERS */
#ifdef HAVE_UNC_PATHS
	if (pathstart[0] == '\\' && pathstart[1] == '\\')
	{
		// Universal Naming Convention path. (\\server\share\...)
		// Copy the server part as is; don't try to create directories for
		// it, or stat it. Don't create a dir for the share either.
		*(ptr++) = *(pathstart++);
		*(ptr++) = *(pathstart++);

		// Copy the server part
		while (*pathstart != '\0' && *pathstart != '\\' && *pathstart != '/')
			*(ptr++) = *(pathstart++);
		
		if (*pathstart == '\0')
		{
			log_add (log_Error, "Incomplete UNC path \"%s\"", pathstart);
			goto err;
		}

		// Copy the path seperator.
		*(ptr++) = *(pathstart++);
	
		// Copy the share part
		while (*pathstart != '\0' && *pathstart != '\\' && *pathstart != '/')
			*(ptr++) = *(pathstart++);

		ptr[0] = '/';
		ptr[1] = '\0';
		if (stat (buf, &statbuf) == -1)
		{
			log_add (log_Error, "Can't stat \"%s\": %s", buf, strerror (errno));
			goto err;
		}
	}
#else
	{
		// Making sure that there is an 'else' case if HAVE_DRIVE_LETTERS is
		// defined.
	}
#endif  /* HAVE_UNC_PATHS */

	if (*pathstart == '/')
		*(ptr++) = *(pathstart++);

	if (*pathstart == '\0') {
		// path exists completely, nothing more to do
		goto success;
	}

	// walk through the path as long as the components exist
	while (1)
	{
		pathend = strchr (pathstart, '/');
		if (pathend == NULL)
			pathend = path + len;
		memcpy(ptr, pathstart, pathend - pathstart);
		ptr += pathend - pathstart;
		*ptr = '\0';
		
		if (stat (buf, &statbuf) == -1)
		{
			if (errno == ENOENT)
				break;
#ifdef __SYMBIAN32__
			// XXX: HACK: If we don't have access to a directory, we can
			// still have access to the underlying entries. We don't
			// actually know whether the entry is a directory, but I know of
			// no way to find out. We just pretend that it is; if we were
			// wrong, an error will occur when we try to do something with
			// the directory. That /should/ not be a problem, as any such
			// action should have its own error checking.
			if (errno != EACCES)
#endif			
			{
				log_add (log_Error, "Can't stat \"%s\": %s", buf,
						strerror (errno));
				goto err;
			}
		}
		
		if (*pathend == '\0')
			goto success;

		*ptr = '/';
		ptr++;
		pathstart = pathend + 1;
		while (*pathstart == '/')
			pathstart++;
		// pathstart is the next non-slash character

		if (*pathstart == '\0')
			goto success;
	}
	
	// create all components left
	while (1)
	{
		if (createDirectory (buf, 0777) == -1)
		{
			log_add (log_Error, "Error: Can't create %s: %s", buf,
					strerror (errno));
			goto err;
		}

		if (*pathend == '\0')
			break;

		*ptr = '/';
		ptr++;
		pathstart = pathend + 1;
		while (*pathstart == '/')
			pathstart++;
		// pathstart is the next non-slash character

		if (*pathstart == '\0')
			break;

		pathend = strchr (pathstart, '/');
		if (pathend == NULL)
			pathend = path + len;
		
		memcpy (ptr, pathstart, pathend - pathstart);
		ptr += pathend - pathstart;
		*ptr = '\0';
	}

success:
	HFree (buf);
	return 0;

err:
	{
		int savedErrno = errno;
		HFree (buf);
		errno = savedErrno;
	}
	return -1;
}

// Get the user's home dir
// returns a pointer to a static buffer from either getenv() or getpwuid().
const char *
getHomeDir (void)
{
#ifdef WIN32
	return getenv ("HOME");
#else
	const char *home;
	struct passwd *pw;

	home = getenv ("HOME");
	if (home != NULL)
		return home;

	pw = getpwuid (getuid ());
	if (pw == NULL)
		return NULL;
	// NB: pw points to a static buffer.

	return pw->pw_dir;
#endif
}

// Performs various types of string expansions on a path.
// 'what' is an OR'd compination of the folowing flags, which
// specify what type of exmansions will be performed.
// EP_HOME - Expand '~' for home dirs.
// EP_ABSOLUTE - Make relative paths absolute
// EP_ENVVARS - Expand environment variables
// EP_DOTS - Process ".." and "."
// EP_SLASHES - Consider backslashes as path component separators.
//              They will be replaced by slashes.
// EP_SINGLESEP - Replace multiple consecutive path seperators (which POSIX
//                considers equivalent to a single one) by a single one.
// Additionally, there's EP_ALL, which indicates all of the above,
// and EP_ALL_SYSTEM, which does the same as EP_ALL, with the exception
// of EP_SLASHES, which will only be included if the operating system
// accepts backslashes as path terminators.
// Returns 0 on success.
// Returns -1 on failure, setting errno.
int
expandPath (char *dest, size_t len, const char *src, int what)
{
	char *destptr, *destend;
	char *buf = NULL;
	char *bufptr, *bufend;
	const char *srcend;

#define CHECKLEN(bufname, n) \
		if (bufname##ptr + (n) >= bufname##end) \
		{ \
			errno = ENAMETOOLONG; \
			goto err; \
		} \
		else \
			(void) 0

	destptr = dest;
	destend = dest + len;

	if (what & EP_ENVVARS)
	{
		buf = HMalloc (len);
		bufptr = buf;
		bufend = buf + len;
		while (*src != '\0')
		{
			switch (*src)
			{
#ifdef WIN32
				case '%':
				{
					/* Environment variable substitution in Windows */
					const char *end;     // end of env var name in src
					const char *envVar;
					char *envName;
					size_t envNameLen, envVarLen;
					
					src++;
					end = strchr (src, '%');
					if (end == NULL)
					{
						errno = EINVAL;
						goto err;
					}
					
					envNameLen = end - src;
					envName = HMalloc (envNameLen + 1);
					memcpy (envName, src, envNameLen + 1);
					envName[envNameLen] = '\0';
					envVar = getenv (envName);
					HFree (envName);

					if (envVar == NULL)
					{
#ifdef APPDATA_FALLBACK
						if (strncmp (src, "APPDATA", envNameLen) != 0)
						{
							// Substitute an empty string
							src = end + 1;
							break;
						}

						// fallback for when the APPDATA env var is not set
						// Using SHGetFolderPath or SHGetSpecialFolderPath
						// is problematic (not everywhere available).
						log_add (log_Warning, "Warning: %%APPDATA%% is not set. "
								"Falling back to \"%%USERPROFILE%%\\Application "
								"Data\"");
						envVar = getenv ("USERPROFILE");
						if (envVar != NULL)
						{
#define APPDATA_STRING "\\Application Data"
							envVarLen = strlen (envVar);
							CHECKLEN (buf,
									envVarLen + sizeof (APPDATA_STRING) - 1);
							strcpy (bufptr, envVar);
							bufptr += envVarLen;
							strcpy (bufptr, APPDATA_STRING);
							bufptr += sizeof (APPDATA_STRING) - 1;
							src = end + 1;
							break;
						}
						
						// fallback to "./userdata"
#define APPDATA_FALLBACK_STRING ".\\userdata"
						log_add (log_Warning,
								"Warning: %%USERPROFILE%% is not set. "
								"Falling back to \"%s\" for %%APPDATA%%",
								APPDATA_FALLBACK_STRING);
						CHECKLEN (buf, sizeof (APPDATA_FALLBACK_STRING) - 1);
						strcpy (bufptr, APPDATA_FALLBACK_STRING);
						bufptr += sizeof (APPDATA_FALLBACK_STRING) - 1;
						src = end + 1;
						break;

#else  /* !defined (APPDATA_FALLBACK) */
						// Substitute an empty string
						src = end + 1;
						break;
#endif  /* APPDATA_FALLBACK */
					}

					envVarLen = strlen (envVar);
					CHECKLEN (buf, envVarLen);
					strcpy (bufptr, envVar);
					bufptr += envVarLen;
					src = end + 1;
					break;
				}
#endif
#ifndef WIN32
				case '$':
				{
					const char *end;
					char *envName;
					size_t envNameLen;
					const char *envVar;
					size_t envVarLen;

					src++;
					if (*src == '{')
					{
						src++;
						end = strchr(src, '}');
						if (end == NULL)
						{
							errno = EINVAL;
							goto err;
						}
						envNameLen = end - src;
						end++;  // Skip the '}'
					}
					else
					{
						end = src;
						while ((*end >= 'A' && *end <= 'Z') ||
								(*end >= 'a' && *end <= 'z') ||
								(*end >= '0' && *end <= '9') ||
								*end == '_')
							end++;
						envNameLen = end - src;
					}

					envName = HMalloc (envNameLen + 1);
					memcpy (envName, src, envNameLen + 1);
					envName[envNameLen] = '\0';
					envVar = getenv (envName);
					HFree (envName);

					if (envVar != NULL)
					{
						envVarLen = strlen (envVar);
						CHECKLEN (buf, envVarLen);
						memcpy (bufptr, envVar, envVarLen);
						bufptr += envVarLen;
					}

					src = end;
					break;
				}
#endif
				default:
					CHECKLEN(buf, 1);
					*(bufptr++) = *(src++);
					break;
			}  // switch
		}  // while
		*bufptr = '\0';
		src = buf;
		srcend = bufptr;
	}  // if (what & EP_ENVVARS)
	else
		srcend = src + strlen (src);

	if (what & EP_HOME)
	{
		if (src[0] == '~')
		{
			const char *home;
			size_t homelen;
			
			if (src[1] != '/')
			{
				errno = EINVAL;
				goto err;
			}

			home = getHomeDir ();
			if (home == NULL)
			{
				errno = ENOENT;
				goto err;
			}
			homelen = strlen (home);
		
			if (what & EP_ABSOLUTE) {
				size_t skip;
				destptr = expandPathAbsolute (dest, destend - dest,
						home, &skip, what);
				if (destptr == NULL)
				{
					// errno is set
					goto err;
				}
				home += skip;
				what &= ~EP_ABSOLUTE;
						// The part after the '~' should not be seen
						// as absolute.
			}

			CHECKLEN (dest, homelen);
			memcpy (destptr, home, homelen);
			destptr += homelen;
			src++;  /* skip the ~ */
		}
	}
	
	if (what & EP_ABSOLUTE)
	{
		size_t skip;
		destptr = expandPathAbsolute (destptr, destend - destptr, src,
				&skip, what);
		if (destptr == NULL)
		{
			// errno is set
			goto err;
		}
		src += skip;
	}

	CHECKLEN (dest, srcend - src);
	memcpy (destptr, src, srcend - src + 1);
			// The +1 is for the '\0'. It is already taken into account by
			// CHECKLEN.
	
	if (what & EP_SLASHES)
	{
		/* Replacing backslashes in path by slashes. */
		destptr = dest;
#ifdef HAVE_UNC_PATHS
		{
			// A UNC path should always start with two backslashes
			// and have a backslash in between the server and share part.
			size_t skip = skipUNCServerShare (destptr);
			if (skip != 0)
			{
				char *slash = (char *) memchr (destptr + 2, '/', skip - 2);
				if (slash)
					*slash = '\\';
				destptr += skip;
			}
		}
#endif  /* HAVE_UNC_PATHS */
		while (*destptr != '\0')
		{
			if (*destptr == '\\')
				*destptr = '/';
			destptr++;
		}
	}
	
	if (what & EP_DOTS) {
		// At this point backslashes are already replaced by slashes if they
		// are specified to be path seperators.
		// Note that the path can only get smaller, so no size checks
		// need to be done.
		char *pathStart;
				// Start of the first path component, after any
				// leading slashes or drive letters.
		char *startPart;
		char *endPart;

		pathStart = dest;
#ifdef HAVE_DRIVE_LETTERS
		if (isDriveLetter(pathStart[0]) && (pathStart[1] == ':'))
		{
			pathStart += 2;
		}
		else
#endif  /* HAVE_DRIVE_LETTERS */
#ifdef HAVE_UNC_PATHS
		{
			// Test for a Universal Naming Convention path.
			pathStart += skipUNCServerShare(pathStart);
		}
#else
		{
			// Making sure that there is an 'else' case if HAVE_DRIVE_LETTERS is
			// defined.
		}
#endif  /* HAVE_UNC_PATHS */
		if (pathStart[0] == '/')
			pathStart++;

		startPart = pathStart;
		destptr = pathStart;
		for (;;)
		{
			endPart = strchr(startPart, '/');
			if (endPart == NULL)
				endPart = startPart + strlen(startPart);

			if (endPart - startPart == 1 && startPart[0] == '.')
			{
				// Found "." as path component. Ignore this component.
			}
			else if (endPart - startPart == 2 &&
					startPart[0] == '.' && startPart[1] == '.')
			{
				// Found ".." as path component. Remove the previous
				// component, and ignore this one.
				char *lastSlash;
				lastSlash = strrchr2(pathStart, '/', destptr - 1);
				if (lastSlash == NULL)
				{
					if (destptr == pathStart)
					{
						// We ran out of path components to back out of.
						errno = EINVAL;
						goto err;
					}
					destptr = pathStart;
				}
				else
				{
					destptr = lastSlash;
					if (*endPart == '/')
						destptr++;
				}
			}
			else
			{
				// A normal path component; copy it.
				// Using memmove as source and destination may overlap.
				memmove(destptr, startPart, endPart - startPart);
				destptr += (endPart - startPart);
				if (*endPart == '/')
				{
					*destptr = '/';
					destptr++;
				}
			}
			if (*endPart == '\0')
				break;
			startPart = endPart + 1;
		}
		*destptr = '\0';	
	}
	
	if (what & EP_SINGLESEP)
	{
		char *srcptr;
		srcptr = dest;
		destptr = dest;
		while (*srcptr != '\0')
		{
			char ch = *srcptr;
			*(destptr++) = *(srcptr++);
			if (ch == '/')
			{
				while (*srcptr == '/')
					srcptr++;
			}
		}
		*destptr = '\0';
	}
	
	HFree (buf);
	return 0;

err:
	if (buf != NULL) {
		int savedErrno = errno;
		HFree (buf);
		errno = savedErrno;
	}
	return -1;
}

#if defined(HAVE_DRIVE_LETTERS) && defined(HAVE_CWD_PER_DRIVE)
		// This code is only needed if we have a current working directory
		// per drive.
// letter is 0 based: 0 = A, 1 = B, ...
static bool
driveLetterExists(int letter)
{
	unsigned long drives;

	drives = _getdrives ();

	return ((drives >> letter) & 1) != 0;
}
#endif  /* if defined(HAVE_DRIVE_LETTERS) && defined(HAVE_CWD_PER_DRIVE) */

// helper for expandPath, expanding an absolute path
// returns a pointer to the end of the filled in part of dest.
static char *
expandPathAbsolute (char *dest, size_t destLen, const char *src,
		size_t *skipSrc, int what)
{
	const char *orgSrc;

	if (src[0] == '/' || ((what & EP_SLASHES) && src[0] == '\\'))
	{
		// Path is already absolute; nothing to do
		*skipSrc = 0;
		return dest;
	}

	orgSrc = src;
#ifdef HAVE_DRIVE_LETTERS
	if (isDriveLetter(src[0]) && (src[1] == ':'))
	{
		int letter;

		if (src[2] == '/' || src[2] == '\\')
		{
			// Path is already absolute (of the form "d:/"); nothing to do
			*skipSrc = 0;
			return dest;
		}

		// Path is of the form "d:path", without a (back)slash after the
		// semicolon.

#ifdef REJECT_DRIVE_PATH_WITHOUT_SLASH
		// We reject paths of the form "d:foo/bar".
		errno = EINVAL;
		return NULL;
#elif defined(HAVE_CWD_PER_DRIVE)
		// Paths of the form "d:foo/bar" are treated as "foo/bar" relative
		// to the working directory of d:.
		letter = tolower(src[0]) - 'a';

		// _getdcwd() should only be called on drives that exist.
		// This is weird though, because it means a race condition
		// in between the existance check and the call to _getdcwd()
		// cannot be avoided, unless a drive still exists for Windows
		// when the physical drive is removed.
		if (!driveLetterExists (letter))
		{
			errno = ENOENT;
			return NULL;
		}

		// Get the working directory for a specific drive.
		if (_getdcwd (letter + 1, dest, destLen) == NULL)
		{
			// errno is set
			return NULL;
		}

		src += 2;
#else  /* if !defined(HAVE_CWD_PER_DRIVE) */
		// We treat paths of the form "d:foo/bar" as "d:/foo/bar".
		if (destLen < 3) {
			errno = ERANGE;
			return NULL;
		}
		dest[0] = src[0];
		dest[1] = ':';
		dest[2] = '/';
		*skipSrc = 2;
		dest += 3;
		return dest;
#endif  /* HAVE_CWD_PER_DRIVE */
	}
	else
#endif  /* HAVE_DRIVE_LETTERS */
	{
		// Relative dir
		if (getcwd (dest, destLen) == NULL)
		{
			// errno is set
			return NULL;
		}
	}

	{
		size_t tempLen;
		tempLen = strlen (dest);
		if (tempLen == 0)
		{
			// getcwd() or _getdcwd() returned a 0-length string.
			errno = ENOENT;
			return NULL;
		}
		dest += tempLen;
		destLen -= tempLen;
	}
	if (dest[-1] != '/'
#ifdef BACKSLASH_IS_PATH_SEPARATOR
			&& dest[-1] != '\\'
#endif  /* BACKSLASH_IS_PATH_SEPARATOR */
			)
	{
		// Need to add a slash.
		// There's always space, as we overwrite the '\0' that getcwd()
		// always returns.
		dest[0] = '/';
		dest++;
		destLen--;
	}

	*skipSrc = (size_t) (src - orgSrc);
	return dest;
}

// As strrchr, but starts searching from the indicated end of the string.
static char *
strrchr2(const char *start, int c, const char *end) {
	for (;;) {
		end--;
		if (end < start)
			return (char *) NULL;
		if (*end == c)
			return (char *) unconst(end);
	}
}

#ifdef HAVE_UNC_PATHS
// returns 0 if the path is not a valid UNC path.
// Does not skip trailing slashes.
size_t
skipUNCServerShare(const char *inPath) {
	const char *path = inPath;

	// Skip the initial two backslashes.
	if (path[0] != '\\' || path[1] != '\\')
		return (size_t) 0;
	path += 2;

	// Skip the server part.
	while (*path != '\\' && *path != '/') {
		if (*path == '\0')
			return (size_t) 0;
		path++;
	}

	// Skip the seperator.
	path++;

	// Skip the share part.
	while (*path != '\0' && *path != '\\' && *path != '/')
		path++;
	
	return (size_t) (path - inPath);
}
#endif  /* HAVE_UNC_PATHS */