dirwrap.c 28.5 KB
Newer Older
1
/* Directory-related system-call wrappers */
2
// vi: tabstop=4
3
4
5
6
7
8
9

/* $Id$ */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
rswindell's avatar
rswindell committed
10
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
11
 *																			*
12
13
 * This library is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU Lesser General Public License		*
14
15
 * as published by the Free Software Foundation; either version 2			*
 * of the License, or (at your option) any later version.					*
16
17
 * See the GNU Lesser General Public License for more details: lgpl.txt or	*
 * http://www.fsf.org/copyleft/lesser.html									*
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 *																			*
 * Anonymous FTP access to the most recent released source is available at	*
 * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net	*
 *																			*
 * Anonymous CVS access to the development source and modification history	*
 * is available at cvs.synchro.net:/cvsroot/sbbs, example:					*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login			*
 *     (just hit return, no password is necessary)							*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src		*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * You are encouraged to submit any modifications (preferably in Unix diff	*
 * format) via e-mail to mods@synchro.net									*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

37
38
#include <string.h>	/* strrchr */

39
#if defined(_WIN32)
40

41
42
	#include <windows.h>	/* WINAPI, etc */
	#include <io.h>			/* _findfirst */
43
44
45

#elif defined __unix__

46
47
48
	#include <unistd.h>		/* usleep */
	#include <fcntl.h>		/* O_NOCCTY */
	#include <ctype.h>		/* toupper */
rswindell's avatar
rswindell committed
49
	#include <sys/param.h>
50

rswindell's avatar
rswindell committed
51
	#if defined(BSD)
52
		#include <sys/mount.h>
53
	#endif
rswindell's avatar
rswindell committed
54
	#if defined(__FreeBSD__)
55
56
		#include <sys/kbio.h>
	#endif
57
58
	#if defined(__NetBSD_Version__) && (__NetBSD_Version__ >= 300000000 /* NetBSD 3.0 */)
		#include <sys/statvfs.h>
rswindell's avatar
rswindell committed
59
	#endif
60

61
	#include <sys/ioctl.h>	/* ioctl */
62

63
64
65
	#if defined(__GLIBC__)		/* actually, BSD, but will work for now */
		#include <sys/vfs.h>    /* statfs() */
	#endif
66

deuce's avatar
deuce committed
67
68
69
70
	#if defined(__solaris__)
		#include <sys/statvfs.h>
	#endif

71
#endif /* __unix__ */
72

rswindell's avatar
rswindell committed
73
74
75
#if defined(__WATCOMC__)
	#include <dos.h>
#endif
76

77
78
79
80
81
82
83
#include <sys/types.h>	/* _dev_t */
#include <sys/stat.h>	/* struct stat */

#include <stdio.h>		/* sprintf */
#include <stdlib.h>		/* rand */
#include <errno.h>		/* ENOENT definitions */

84
#include "genwrap.h"	/* strupr/strlwr */
85
86
#include "dirwrap.h"	/* DLLCALL */

87
88
89
90
#if !defined(S_ISDIR)
	#define S_ISDIR(x)	((x)&S_IFDIR)
#endif

91
92
93
/****************************************************************************/
/* Return the filename portion of a full pathname							*/
/****************************************************************************/
94
char* DLLCALL getfname(const char* path)
95
{
96
97
	const char* fname;
	const char* bslash;
98
99

	fname=strrchr(path,'/');
100
101
102
	bslash=strrchr(path,'\\');
	if(bslash>fname)
		fname=bslash;
103
	if(fname!=NULL)
104
		fname++;
105
	else
106
		fname=(char*)path;
107
	return((char*)fname);
108
109
}

110
/****************************************************************************/
111
112
113
114
115
116
117
118
119
/* Return the filename or last directory portion of a full pathname			*/
/* A directory pathname is expected to end in a '/'							*/
/****************************************************************************/
char* DLLCALL getdirname(const char* path)
{
	char* last = lastchar(path);
	if(*last == '/') {
		if(last == path)
			return last;
120
121
		for(last--; last >= path; last--) {
			if(IS_PATH_DELIM(*last))
122
123
				return last + 1;
		}
124
		return (char*)path;
125
126
127
128
129
130
	}
	return getfname(path);
}

/****************************************************************************/
/* Return a pointer to a file's extension/suffix (beginning with '.')		*/
131
132
133
134
135
136
137
138
/****************************************************************************/
char* DLLCALL getfext(const char* path)
{
	char *fname;
	char *fext;

	fname=getfname(path);
	fext=strrchr(fname,'.');
139
	if(fext==NULL || fext==fname)
140
141
142
		return(NULL);
	return(fext);
}
143
144
145
146
147
148
149
150
151
152

/****************************************************************************/
/* Break a path name into components.										*/
/****************************************************************************/
#if defined(__unix__)
void DLLCALL _splitpath(const char *path, char *drive, char *dir, char *fname, char *ext)
{
	char*	p;

	ext[0]=0;
153
154
155
156
157
158
159
160
161
162
	drive[0]=0;			/* no drive letters on Unix */

	strcpy(dir,path);	/* Optional directory path, including trailing slash. */
	p=getfname(dir);
	strcpy(fname,p);	/* Base filename (no extension) */
	if(p==dir)
		dir[0]=0;		/* no directory specified in path */
	else
		*p=0;			/* truncate dir at filename */
	p=getfext(fname);
163
	if(p!=NULL) {
164
		strcpy(ext,p);	/* Optional filename extension, including leading period (.) */
165
166
167
168
169
		*p=0;
	}
}
#endif

170
171
172
173
/****************************************************************************/
/* Win32 (minimal) implementation of POSIX.2 glob() function				*/
/* This code _may_ work on other DOS-based platforms (e.g. OS/2)			*/
/****************************************************************************/
174
#if !defined(__unix__)
deuce's avatar
deuce committed
175
static int __cdecl glob_compare( const void *arg1, const void *arg2 )
176
177
{
   /* Compare all of both strings: */
178
   return strcmp( * ( char** ) arg1, * ( char** ) arg2 );
179
180
}

181
#if defined(__BORLANDC__)
182
183
184
	#pragma argsused
#endif

rswindell's avatar
rswindell committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#if defined(__WATCOMC__)

int	DLLCALL	glob(const char *pattern, int flags, void* unused, glob_t* glob)
{
    struct	find_t ff;
	size_t	found=0;
	char	path[MAX_PATH+1];
	char*	p;
	char**	new_pathv;

	if(!(flags&GLOB_APPEND)) {
		glob->gl_pathc=0;
		glob->gl_pathv=NULL;
	}

200
	if(_dos_findfirst((char*)pattern,(flags&GLOB_PERIOD) ? _A_HIDDEN : _A_NORMAL,&ff)!=0)
rswindell's avatar
rswindell committed
201
202
203
		return(GLOB_NOMATCH);

	do {
204
205
		if((flags&GLOB_PERIOD || ff.name[0]!='.') &&
			(!(flags&GLOB_ONLYDIR) || ff.attrib&_A_SUBDIR)) {
rswindell's avatar
rswindell committed
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
			if((new_pathv=realloc(glob->gl_pathv
				,(glob->gl_pathc+1)*sizeof(char*)))==NULL) {
				globfree(glob);
				return(GLOB_NOSPACE);
			}
			glob->gl_pathv=new_pathv;

			/* build the full pathname */
			SAFECOPY(path,pattern);
			p=getfname(path);
			*p=0;
			strcat(path,ff.name);

			if((glob->gl_pathv[glob->gl_pathc]=malloc(strlen(path)+2))==NULL) {
				globfree(glob);
				return(GLOB_NOSPACE);
			}
			strcpy(glob->gl_pathv[glob->gl_pathc],path);
			if(flags&GLOB_MARK && ff.attrib&_A_SUBDIR)
				strcat(glob->gl_pathv[glob->gl_pathc],"/");

			glob->gl_pathc++;
			found++;
		}
	} while(_dos_findnext(&ff)==0);
	_dos_findclose(&ff);

	if(found==0)
		return(GLOB_NOMATCH);

	if(!(flags&GLOB_NOSORT)) {
		qsort(glob->gl_pathv,found,sizeof(char*),glob_compare);
	}

	return(0);	/* success */
}

#else

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
int	DLLCALL	glob(const char *pattern, int flags, void* unused, glob_t* glob)
{
    struct	_finddata_t ff;
	long	ff_handle;
	size_t	found=0;
	char	path[MAX_PATH+1];
	char*	p;
	char**	new_pathv;

	if(!(flags&GLOB_APPEND)) {
		glob->gl_pathc=0;
		glob->gl_pathv=NULL;
	}

	ff_handle=_findfirst((char*)pattern,&ff);
	while(ff_handle!=-1) {
261
		if((flags&GLOB_PERIOD || (ff.name[0]!='.' && !(ff.attrib&_A_HIDDEN))) &&
262
			(!(flags&GLOB_ONLYDIR) || ff.attrib&_A_SUBDIR)) {
263
			if((new_pathv=(char**)realloc(glob->gl_pathv
264
265
266
267
268
269
270
				,(glob->gl_pathc+1)*sizeof(char*)))==NULL) {
				globfree(glob);
				return(GLOB_NOSPACE);
			}
			glob->gl_pathv=new_pathv;

			/* build the full pathname */
271
			SAFECOPY(path,pattern);
272
273
			p=getfname(path);
			*p=0;
274
			SAFECAT(path,ff.name);
275

276
			if((glob->gl_pathv[glob->gl_pathc]=(char*)malloc(strlen(path)+2))==NULL) {
277
278
279
280
281
282
283
284
285
286
287
288
				globfree(glob);
				return(GLOB_NOSPACE);
			}
			strcpy(glob->gl_pathv[glob->gl_pathc],path);
			if(flags&GLOB_MARK && ff.attrib&_A_SUBDIR)
				strcat(glob->gl_pathv[glob->gl_pathc],"/");

			glob->gl_pathc++;
			found++;
		}
		if(_findnext(ff_handle, &ff)!=0) {
			_findclose(ff_handle);
289
290
			ff_handle=-1;
		}
291
292
293
294
295
296
297
298
299
300
301
302
	}

	if(found==0)
		return(GLOB_NOMATCH);

	if(!(flags&GLOB_NOSORT)) {
		qsort(glob->gl_pathv,found,sizeof(char*),glob_compare);
	}

	return(0);	/* success */
}

rswindell's avatar
rswindell committed
303
304
#endif

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
void DLLCALL globfree(glob_t* glob)
{
	size_t i;

	if(glob==NULL)
		return;

	if(glob->gl_pathv!=NULL) {
		for(i=0;i<glob->gl_pathc;i++)
			if(glob->gl_pathv[i]!=NULL)
				free(glob->gl_pathv[i]);

		free(glob->gl_pathv);
		glob->gl_pathv=NULL;
	}
	glob->gl_pathc=0;
}

#endif /* !defined(__unix__) */

325
326
327
328
/****************************************************************************/
/* Returns number of files and/or sub-directories in directory (path)		*/
/* Similar, but not identical, to getfilecount()							*/
/****************************************************************************/
329
330
331
332
333
334
335
336
337
338
339
340
long DLLCALL getdirsize(const char* path, BOOL include_subdirs, BOOL subdir_only)
{
	char		match[MAX_PATH+1];
	glob_t		g;
	unsigned	gi;
	long		count=0;

	if(!isdir(path))
		return -1;

	SAFECOPY(match,path);
	backslash(match);
341
	SAFECAT(match,ALLFILES);
deuce's avatar
deuce committed
342
343
	if (glob(match,GLOB_MARK,NULL,&g) != 0)
		return 0;
344
	if(include_subdirs && !subdir_only)
345
346
		count=g.gl_pathc;
	else
347
348
349
350
351
352
353
354
355
		for(gi=0;gi<g.gl_pathc;gi++) {
			if(*lastchar(g.gl_pathv[gi])=='/') {
				if(!include_subdirs)
					continue;
			} else
				if(subdir_only)
					continue;
			count++;
		}
356
357
358
359
	globfree(&g);
	return(count);
}

360
361
362
/****************************************************************************/
/* POSIX directory operations using Microsoft _findfirst/next API.			*/
/****************************************************************************/
363
#if defined(_MSC_VER) || defined(__DMC__)
deuce's avatar
deuce committed
364
DIR* DLLCALL opendir(const char* dirname)
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
{
	DIR*	dir;

	if((dir=(DIR*)calloc(1,sizeof(DIR)))==NULL) {
		errno=ENOMEM;
		return(NULL);
	}
	sprintf(dir->filespec,"%.*s",sizeof(dir->filespec)-5,dirname);
	if(*dir->filespec && dir->filespec[strlen(dir->filespec)-1]!='\\')
		strcat(dir->filespec,"\\");
	strcat(dir->filespec,"*.*");
	dir->handle=_findfirst(dir->filespec,&dir->finddata);
	if(dir->handle==-1) {
		errno=ENOENT;
		free(dir);
		return(NULL);
	}
	return(dir);
}
deuce's avatar
deuce committed
384
struct dirent* DLLCALL readdir(DIR* dir)
385
386
387
388
389
390
391
392
393
394
395
396
{
	if(dir==NULL)
		return(NULL);
	if(dir->end==TRUE)
		return(NULL);
	if(dir->handle==-1)
		return(NULL);
	sprintf(dir->dirent.d_name,"%.*s",sizeof(struct dirent)-1,dir->finddata.name);
	if(_findnext(dir->handle,&dir->finddata)!=0)
		dir->end=TRUE;
	return(&dir->dirent);
}
deuce's avatar
deuce committed
397
int DLLCALL closedir (DIR* dir)
398
399
400
401
402
403
404
{
	if(dir==NULL)
		return(-1);
	_findclose(dir->handle);
	free(dir);
	return(0);
}
deuce's avatar
deuce committed
405
void DLLCALL rewinddir(DIR* dir)
406
407
408
409
410
411
412
413
414
{
	if(dir==NULL)
		return;
	_findclose(dir->handle);
	dir->end=FALSE;
	dir->handle=_findfirst(dir->filespec,&dir->finddata);
}
#endif /* defined(_MSC_VER) */

415
416
417
418
419
420
421
422
423
424
425
426
427
/****************************************************************************/
/* Returns the creation time of the file 'filename' in time_t format		*/
/****************************************************************************/
time_t DLLCALL fcdate(const char* filename)
{
	struct stat st;

	if(stat(filename, &st) != 0)
		return -1;

	return st.st_ctime;
}

428
429
430
/****************************************************************************/
/* Returns the time/date of the file in 'filename' in time_t (unix) format  */
/****************************************************************************/
431
time_t DLLCALL fdate(const char* filename)
432
433
434
435
436
437
438
439
440
{
	struct stat st;

	if(stat(filename, &st)!=0)
		return(-1);

	return(st.st_mtime);
}

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/****************************************************************************/
/* Change the access and modification times for specified filename			*/
/****************************************************************************/
int DLLCALL setfdate(const char* filename, time_t t)
{
	struct utimbuf ut;

	memset(&ut,0,sizeof(ut));

	ut.actime=t;
	ut.modtime=t;

	return(utime(filename,&ut));
}

456
457
/****************************************************************************/
/* Returns the length of the file in 'filename'                             */
458
/* or -1 if the file doesn't exist											*/
459
/****************************************************************************/
460
off_t DLLCALL flength(const char *filename)
461
{
462
#if defined(__BORLANDC__) && !defined(__unix__)	/* stat() doesn't work right */
463
464
465
466

	long	handle;
	struct _finddata_t f;

467
	if((handle=_findfirst((char*)filename,&f))==-1)
468
469
470
471
472
473
		return(-1);

 	_findclose(handle);

	return(f.size);

474
#else
475
476
477
478

	struct stat st;

	if(stat(filename, &st)!=0)
479
		return(-1);
480
481
482
483
484
485

	return(st.st_size);

#endif
}

486
487

/****************************************************************************/
488
/* Checks the file system for the existence of a file.						*/
489
/* Returns TRUE if it exists, FALSE if it doesn't.                          */
490
/* 'filename' may *NOT* contain wildcards!									*/
491
492
493
/****************************************************************************/
static BOOL fnameexist(const char *filename)
{
494
495
496
497
498
499
500
501
502
	struct stat st;

	if(stat(filename, &st) != 0)
		return FALSE;

	if(S_ISDIR(st.st_mode))
		return FALSE;

	return TRUE;
503
504
}

505
506
507
508
509
/****************************************************************************/
/* Checks the file system for the existence of one or more files.			*/
/* Returns TRUE if it exists, FALSE if it doesn't.                          */
/* 'filespec' may contain wildcards!										*/
/****************************************************************************/
510
BOOL DLLCALL fexist(const char *filespec)
511
{
512
#if defined(_WIN32)
513
514
515

	long	handle;
	struct _finddata_t f;
516
	BOOL	found;
517

518
519
	if(!strchr(filespec,'*') && !strchr(filespec,'?'))
		return(fnameexist(filespec));
520

521
	if((handle=_findfirst((char*)filespec,&f))==-1)
522
		return(FALSE);
523
524
525
526
527
528
	found=TRUE;
	while(f.attrib&_A_SUBDIR)
		if(_findnext(handle,&f)!=0) {
			found=FALSE;
			break;
		}
529
530
531

 	_findclose(handle);

532
	return(found);
533

rswindell's avatar
rswindell committed
534
#else /* Unix or OS/2 */
535

rswindell's avatar
rswindell committed
536
	/* portion by cmartin */
537
538
539
540

	glob_t g;
    int c;

541
542
	if(!strchr(filespec,'*') && !strchr(filespec,'?'))
		return(fnameexist(filespec));
543

544
    /* start the search */
545
546
547
    glob(filespec, GLOB_MARK | GLOB_NOSORT, NULL, &g);

    if (!g.gl_pathc) {
548
	    /* no results */
549
550
551
552
    	globfree(&g);
    	return FALSE;
    }

553
    /* make sure it's not a directory */
554
555
	c = g.gl_pathc;
    while (c--) {
556
    	if (*lastchar(g.gl_pathv[c]) != '/') {
557
558
559
560
        	globfree(&g);
            return TRUE;
        }
    }
561

562
563
564
565
566
567
    globfree(&g);
    return FALSE;

#endif
}

568
569
570
571
572
/****************************************************************************/
/* Fixes upper/lowercase filename for Unix file systems						*/
/****************************************************************************/
BOOL DLLCALL fexistcase(char *path)
{
573
574
575
576
577
578
#if defined(_WIN32)

	char*	fname;
	long	handle;
	struct _finddata_t f;

579
	if(access(path, F_OK)==-1 && !strchr(path,'*') && !strchr(path,'?'))
580
		return(FALSE);
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596

	if((handle=_findfirst((char*)path,&f))==-1)
		return(FALSE);

 	_findclose(handle);

 	if(f.attrib&_A_SUBDIR)
		return(FALSE);

	fname=getfname(path);	/* Find filename in path */
	strcpy(fname,f.name);	/* Correct filename */

	return(TRUE);

#else /* Unix or OS/2 */

597
598
599
600
	char globme[MAX_PATH*4+1];
	char fname[MAX_PATH+1];
	char tmp[5];
	char *p;
601
	int  i;
602
	glob_t	glb;
603

604
	if(path[0]==0)		/* work around glibc bug 574274 */
605
606
		return FALSE;

607
608
609
	if(!strchr(path,'*') && !strchr(path,'?') && fnameexist(path))
		return(TRUE);

610
	SAFECOPY(globme,path);
611
	p=getfname(globme);
612
	SAFECOPY(fname,p);
613
614
	*p=0;
	for(i=0;fname[i];i++)  {
615
		if(isalpha(fname[i]))
616
			sprintf(tmp,"[%c%c]",toupper(fname[i]),tolower(fname[i]));
617
		else
618
619
620
			sprintf(tmp,"%c",fname[i]);
		strncat(globme,tmp,MAX_PATH*4);
	}
621
#if 0
622
	if(strcspn(path,"?*")!=strlen(path))  {
623
		sprintf(path,"%.*s",MAX_PATH,globme);
624
		return(fexist(path));
625
	}
626
#endif
627

628
	if(glob(globme,GLOB_MARK,NULL,&glb) != 0)
629
		return(FALSE);
630

631
632
	if(glb.gl_pathc>0)  {
		for(i=0;i<glb.gl_pathc;i++)  {
633
634
			if(*lastchar(glb.gl_pathv[i]) != '/')
				break;
635
		}
636
		if(i<glb.gl_pathc)  {
637
			sprintf(path,"%.*s",MAX_PATH,glb.gl_pathv[i]);
638
639
640
			globfree(&glb);
			return TRUE;
		}
641
	}
642
643
644

	globfree(&glb);
	return FALSE;
645

646
647
648
#endif
}

649
650
651
/****************************************************************************/
/* Returns TRUE if the filename specified is a directory					*/
/****************************************************************************/
652
BOOL DLLCALL isdir(const char *filename)
653
{
654
655
	char	path[MAX_PATH+1];
	char*	p;
656
657
	struct stat st;

658
659
660
	SAFECOPY(path,filename);

	p=lastchar(path);
661
	if(p!=path && IS_PATH_DELIM(*p)) {	/* chop off trailing slash */
662
663
664
665
666
667
#if !defined(__unix__)
		if(*(p-1)!=':')		/* Don't change C:\ to C: */
#endif
			*p=0;
	}

668
669
670
#if defined(__BORLANDC__) && !defined(__unix__)	/* stat() doesn't work right */
	if(stat(path, &st)!=0 || strchr(path,'*')!=NULL || strchr(path,'?')!=NULL)
#else
671
	if(stat(path, &st)!=0)
672
#endif
673
674
		return(FALSE);

675
	return(S_ISDIR(st.st_mode) ? TRUE : FALSE);
676
677
678
}

/****************************************************************************/
679
680
/* Returns the attributes (mode) for specified 'filename' or -1 on failure.	*/
/* The return value on Windows is *not* compatible with chmod().			*/
681
/****************************************************************************/
682
int DLLCALL getfattr(const char* filename)
683
{
684
#if defined(_WIN32)
685
686
687
	long handle;
	struct _finddata_t	finddata;

688
	if((handle=_findfirst((char*)filename,&finddata))==-1) {
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
		errno=ENOENT;
		return(-1);
	}
	_findclose(handle);
	return(finddata.attrib);
#else
	struct stat st;

	if(stat(filename, &st)!=0) {
		errno=ENOENT;
		return(-1L);
	}

	return(st.st_mode);
#endif
}

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/****************************************************************************/
/* Returns the mode / type flags for specified 'filename'					*/
/* The return value *is* compatible with chmod(), or -1 upon failure.		*/
/****************************************************************************/
int DLLCALL getfmode(const char* filename)
{
	struct stat st;

	if(stat(filename, &st) != 0)
		return -1;

	return st.st_mode;
}


deuce's avatar
   
deuce committed
721
#ifdef __unix__
rswindell's avatar
rswindell committed
722
int removecase(const char *path)
deuce's avatar
   
deuce committed
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
{
	char inpath[MAX_PATH+1];
	char fname[MAX_PATH*4+1];
	char tmp[5];
	char *p;
	int  i;

	if(strchr(path,'?') || strchr(path,'*'))
		return(-1);
	SAFECOPY(inpath,path);
	p=getfname(inpath);
	fname[0]=0;
	for(i=0;p[i];i++)  {
		if(isalpha(p[i]))
			sprintf(tmp,"[%c%c]",toupper(p[i]),tolower(p[i]));
		else
			sprintf(tmp,"%c",p[i]);
		strncat(fname,tmp,MAX_PATH*4);
	}
	*p=0;

744
	return(delfiles(inpath,fname,0) >=1 ? 0 : -1);
deuce's avatar
   
deuce committed
745
746
747
748
749
}
#endif

/****************************************************************************/
/* Deletes all files in dir 'path' that match file spec 'spec'              */
750
/* Optionally, keep the last so many files (sorted by name)                 */
751
/* Returns number of files deleted or negative on error						*/
deuce's avatar
   
deuce committed
752
/****************************************************************************/
753
long DLLCALL delfiles(const char *inpath, const char *spec, size_t keep)
deuce's avatar
   
deuce committed
754
{
755
	char	*path;
756
	char	lastch;
757
	size_t	i;
758
    ulong	files = 0;
759
	long	errors = 0;
760
	glob_t	g;
761
	size_t	inpath_len=strlen(inpath);
762

763
764
765
766
767
768
	if(inpath_len==0)
		lastch=0;
	else
		lastch=inpath[inpath_len-1];
	path=(char *)malloc(inpath_len+1/*Delim*/+strlen(spec)+1/*Terminator*/);
	if(path==NULL)
769
		return -1;
770
771
772
773
774
775
	if(!IS_PATH_DELIM(lastch) && lastch)
		sprintf(path,"%s%c",inpath,PATH_DELIM);
	else
		strcpy(path,inpath);
	strcat(path,spec);
	glob(path,0,NULL,&g);
776
	free(path);
777
778
779
	if(keep >= g.gl_pathc)
		return 0;
	for(i = 0; i < g.gl_pathc && files < g.gl_pathc - keep; i++) {
780
781
		if(isdir(g.gl_pathv[i]))
			continue;
782
		CHMOD(g.gl_pathv[i],S_IWRITE);	/* In case it's been marked RDONLY */
783
784
		if(remove(g.gl_pathv[i])==0)
			files++;
785
786
		else
			errors++;
787
788
	}
	globfree(&g);
789
790
791
	if(errors)
		return -errors;
	return files;
deuce's avatar
   
deuce committed
792
793
}

794
795
796
797
798
799
800
801
802
803
804
805
806
/****************************************************************************/
/* Returns number of files in a directory (inpath) matching 'pattern'		*/
/* Similar, but not identical, to getdirsize(), e.g. subdirs never counted	*/
/****************************************************************************/
ulong DLLCALL getfilecount(const char *inpath, const char* pattern)
{
	char path[MAX_PATH+1];
	glob_t	g;
	uint	gi;
	ulong	count = 0;

	SAFECOPY(path, inpath);
	backslash(path);
807
	SAFECAT(path, pattern);
808
809
810
811
812
813
814
815
816
817
818
	if(glob(path, GLOB_MARK, NULL, &g))
		return 0;
	for(gi = 0; gi < g.gl_pathc; ++gi) {
		if(*lastchar(g.gl_pathv[gi]) == '/')
			continue;
		count++;
	}
	globfree(&g);
	return count;
}

819
/****************************************************************************/
820
821
/* Return free disk space in bytes (up to a maximum of 4GB)					*/
/****************************************************************************/
822
#if defined(_WIN32)
823
typedef BOOL(WINAPI * GetDiskFreeSpaceEx_t)
824
	(LPCTSTR,PULARGE_INTEGER,PULARGE_INTEGER,PULARGE_INTEGER);
825
826
827
828
829
830
831
832
833
834
835

static int bit_num(ulong val)
{
	int i;

	for(i=31;i>=0;i--)
		if(val&(1<<i))
			return(i);

	return(-1);
}
836
837
#endif

838
839
/* Unit should be a power-of-2 (e.g. 1024 to report kilobytes) or 1 (to report bytes) */
static ulong getdiskspace(const char* path, ulong unit, BOOL freespace)
840
{
841
#if defined(_WIN32)
842
843
844
845
846
847
848
849
850
851
852
853
	char			root[16];
	DWORD			TotalNumberOfClusters;
	DWORD			NumberOfFreeClusters;
	DWORD			BytesPerSector;
	DWORD			SectorsPerCluster;
	ULARGE_INTEGER	avail;
	ULARGE_INTEGER	size;
	static HINSTANCE hK32;
	GetDiskFreeSpaceEx_t GetDiskFreeSpaceEx;

	if(hK32 == NULL)
		hK32 = LoadLibrary("KERNEL32");
854
	GetDiskFreeSpaceEx
855
		= (GetDiskFreeSpaceEx_t)GetProcAddress(hK32,"GetDiskFreeSpaceExA");
856

857
858
	if (GetDiskFreeSpaceEx!=NULL) {	/* Windows 95-OSR2 or later */
		if(!GetDiskFreeSpaceEx(
859
860
861
862
			path,		/* pointer to the directory name */
			&avail,		/* receives the number of bytes on disk avail to the caller */
			&size,		/* receives the number of bytes on disk */
			NULL))		/* receives the free bytes on disk */
863
			return(0);
864

865
866
867
		if(freespace)
			size=avail;

868
		if(unit>1)
869
			size.QuadPart=Int64ShrlMod32(size.QuadPart,bit_num(unit));
870

871
#if defined(_ANONYMOUS_STRUCT)
872
		if(size.HighPart)
873
#else
874
		if(size.u.HighPart)
875
876
877
#endif
			return(0xffffffff);	/* 4GB max */

878
#if defined(_ANONYMOUS_STRUCT)
879
		return(size.LowPart);
880
#else
881
		return(size.u.LowPart);
882
883
884
885
886
887
#endif
	}

	/* Windows 95 (old way), limited to 2GB */
	sprintf(root,"%.3s",path);
	if(!GetDiskFreeSpace(
888
		root,					/* pointer to root path */
889
890
891
892
		(PDWORD)&SectorsPerCluster,		/* pointer to sectors per cluster */
		(PDWORD)&BytesPerSector,		/* pointer to bytes per sector */
		(PDWORD)&NumberOfFreeClusters,	/* pointer to number of free clusters */
		(PDWORD)&TotalNumberOfClusters  /* pointer to total number of clusters */
893
894
895
		))
		return(0);

896
897
	if(freespace)
		TotalNumberOfClusters = NumberOfFreeClusters;
898
	if(unit>1)
899
900
		TotalNumberOfClusters/=unit;
	return(TotalNumberOfClusters*SectorsPerCluster*BytesPerSector);
901
902


903
#elif defined(__solaris__) || (defined(__NetBSD_Version__) && (__NetBSD_Version__ >= 300000000 /* NetBSD 3.0 */))
904

905
	struct statvfs fs;
906
	unsigned long blocks;
907

908
    if (statvfs(path, &fs) < 0)
909
910
    	return 0;

911
912
913
914
915
	if(freespace)
		blocks=fs.f_bavail;
	else
		blocks=fs.f_blocks;

916
	if(unit>1)
917
918
		blocks/=unit;
    return fs.f_bsize * blocks;
919

920
921
/* statfs is also used under FreeBSD (Though it *supports* statvfs() now too) */
#elif defined(__GLIBC__) || defined(BSD)
deuce's avatar
deuce committed
922

923
	struct statfs fs;
924
	unsigned long blocks;
deuce's avatar
deuce committed
925

926
	if(statfs(path, &fs) < 0)
deuce's avatar
deuce committed
927
928
    	return 0;

929
930
931
932
933
	if(freespace)
		blocks=fs.f_bavail;
	else
		blocks=fs.f_blocks;

deuce's avatar
deuce committed
934
	if(unit>1)
935
936
		blocks/=unit;
    return fs.f_bsize * blocks;
937

938
939
#else

rswindell's avatar
rswindell committed
940
	fprintf(stderr,"\n*** !Missing getfreediskspace implementation ***\n");
941
942
943
944
	return(0);

#endif
}
945

946
947
948
949
950
951
952
953
954
955
ulong DLLCALL getfreediskspace(const char* path, ulong unit)
{
	return getdiskspace(path, unit, /* freespace? */TRUE);
}

ulong DLLCALL getdisksize(const char* path, ulong unit)
{
	return getdiskspace(path, unit, /* freespace? */FALSE);
}

956
/****************************************************************************/
rswindell's avatar
rswindell committed
957
/* Resolves //, /./, and /../ in a path. Should work identically to Windows */
958
959
960
961
962
/****************************************************************************/
#if defined(__unix__)
char * DLLCALL _fullpath(char *target, const char *path, size_t size)  {
	char	*out;
	char	*p;
963
	BOOL	target_alloced=FALSE;
964

965
966
967
968
	if(target==NULL)  {
		if((target=malloc(MAX_PATH+1))==NULL) {
			return(NULL);
		}
969
		target_alloced=TRUE;
970
971
972
973
974
	}
	out=target;
	*out=0;

	if(*path != '/')  {
975
976
		if(*path == '~') {
			p=getenv("HOME");
977
			if(p==NULL || strlen(p)+strlen(path)>=size) {
978
979
				if(target_alloced)
					free(target);
980
				return(NULL);
981
			}
982
983
984
985
986
987
			strcpy(target,p);
			out=strrchr(target,'\0');
			path++;
		}
		else {
			p=getcwd(NULL,size);
988
			if(p==NULL || strlen(p)+strlen(path)>=size) {
989
990
				if(target_alloced)
					free(target);
991
				return(NULL);
992
			}
993
994
995
996
997
998
999
			strcpy(target,p);
			free(p);
			out=strrchr(target,'\0');
			*(out++)='/';
			*out=0;
			out--;
		}
1000
1001
	}
	strncat(target,path,size-1);
1002

1003
1004
1005
1006
1007
/*	if(stat(target,&sb))
		return(NULL);
	if(sb.st_mode&S_IFDIR)
		strcat(target,"/"); */

1008
1009
	for(;*out;out++) {
		while(*out=='/') {
1010
1011
			if(*(out+1)=='/')
				memmove(out,out+1,strlen(out));
1012
			else if(*(out+1)=='.' && (*(out+2)=='/' || *(out+2)==0))
1013
				memmove(out,out+2,strlen(out)-1);
1014
			else if(*(out+1)=='.' && *(out+2)=='.' && (*(out+3)=='/' || *(out+3)==0))  {
1015
1016
				*out=0;
				p=strrchr(target,'/');
1017
1018
				if(p==NULL)
					p=target;
1019
1020
1021
1022
1023
1024
1025
				memmove(p,out+3,strlen(out+3)+1);
				out=p;
			}
			else  {
				out++;
			}
		}
1026
1027
		if (!*out)
			break;
1028
1029
1030
1031
	}
	return(target);
}
#endif
1032
1033

/****************************************************************************/
1034
/* Adds a trailing slash/backslash (path delimiter) on path strings 		*/
1035
1036
1037
1038
1039
/****************************************************************************/
char* DLLCALL backslash(char* path)
{
	char* p;

rswindell's avatar
rswindell committed
1040
	p=lastchar(path);
1041

1042
	if(*p && !IS_PATH_DELIM(*p)) {
1043
1044
#if defined(__unix__)
		/* Convert trailing backslash to forwardslash on *nix */
1045
		if(*p!='\\')
1046
#endif
1047
			p++;
1048
		*p=PATH_DELIM;
rswindell's avatar
rswindell committed
1049
		*(++p)=0;
1050
1051
1052
	}
	return(path);
}
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068

/****************************************************************************/
/* Returns true if the specified filename an aboslute pathname				*/
/****************************************************************************/
BOOL DLLCALL isabspath(const char *filename)
{
	char path[MAX_PATH+1];

	return(stricmp(filename,FULLPATH(path,filename,sizeof(path)))==0);
}

/****************************************************************************/
/* Returns true if the specified filename is a full ("rooted") path			*/
/****************************************************************************/
BOOL DLLCALL isfullpath(const char* filename)
{
1069
	return(filename[0]=='/'
1070
#ifdef WIN32
deuce's avatar
deuce committed
1071
		|| filename[0]=='\\' || (isalpha(filename[0]) && filename[1]==':')
1072
1073
1074
#endif
		);
}
1075
1076
1077
1078
1079

/****************************************************************************/
/* Matches file name against filespec										*/
/* Optionally not allowing * to match PATH_DELIM (for paths)				*/
/****************************************************************************/
1080

1081
1082
1083
1084
BOOL DLLCALL wildmatch(const char *fname, const char *spec, BOOL path)
{
	char *specp;
	char *fnamep;
1085
	char *wildend;
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099

	specp=(char *)spec;
	fnamep=(char *)fname;
	for(;;specp++, fnamep++) {
		switch(*specp) {
			case '?':
				if(!(*fnamep))
					return(FALSE);
				break;
			case 0:
				if(!*fnamep)
					return(TRUE);
				break;
			case '*':
1100
1101
				while(*specp=='*')
					specp++;
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
				if(path) {
					for(wildend=fnamep; *wildend; wildend++) {
						if(IS_PATH_DELIM(*wildend)) {
							wildend--;
							break;
						}
					}
				}
				else
					wildend=strchr(fnamep, 0);
				for(;wildend >= fnamep;wildend--) {
					if(wildmatch(wildend, specp, path))
						return(TRUE);
1115
				}
1116
				return(FALSE);
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
			default:
				if(*specp != *fnamep)
					return(FALSE);
		}
		if(!(*specp && *fnamep))
			break;
	}
	while(*specp=='*')
		specp++;
	if(*specp==*fnamep)
		return(TRUE);
	return(FALSE);
}
1130

1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
/****************************************************************************/
/* Matches file name against filespec, ignoring case						*/
/****************************************************************************/
BOOL DLLCALL wildmatchi(const char *fname, const char *spec, BOOL path)
{
	char* s1;
	char* s2;
	BOOL result;

	if((s1=strdup(fname))==NULL)
		return(FALSE);
rswindell's avatar
rswindell committed
1142
	if((s2=strdup(spec))==NULL) {
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
		free(s1);
		return(FALSE);
	}
	strupr(s1);
	strupr(s2);
	result = wildmatch(s1, s2, path);
	free(s1);
	free(s2);
	return(result);
}

1154
1155
1156
/****************************************************************************/
/* Creates all the necessary directories in the specified path				*/
/****************************************************************************/
rswindell's avatar
rswindell committed
1157
int DLLCALL mkpath(const char* path)
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
{
	const char*	p=path;
	const char*	tp;
	const char*	sep=
#ifdef _WIN32
		"\\"
#endif
		"/";
	char	dir[MAX_PATH+1];
	int		result=0;

#ifdef _WIN32
	if(p[1]==':')	/* Skip drive letter, if specified */
		p+=2;
#endif

	while(*p) {
		SKIP_CHARSET(p,sep);
1176
1177
		if(*p==0)
			break;
1178
1179
		tp=p;
		FIND_CHARSET(tp,sep);
1180
		safe_snprintf(dir,sizeof(dir),"%.*s", (int)(tp-path), path);
1181
1182
1183
		if(!isdir(dir)) {
			if((result=MKDIR(dir))!=0)
				break;
1184
1185
1186
1187
1188
1189
		}
		p=tp;
	}

	return(result);
}