Debian Codegraph @

extern/igfd/dirent/dirent.h

raw
1 /*
2 * Dirent interface for Microsoft Visual Studio
3 *
4 * Copyright (C) 1998-2019 Toni Ronkko
5 * This file is part of dirent. Dirent may be freely distributed
6 * under the MIT license. For all details and documentation, see
7 * https://github.com/tronkko/dirent
8 */
9 #ifndef DIRENT_H
10 #define DIRENT_H
11
12 /* Hide warnings about unreferenced local functions */
13 #if defined(__clang__)
14 # pragma clang diagnostic ignored "-Wunused-function"
15 #elif defined(_MSC_VER)
16 # pragma warning(disable:4505)
17 #elif defined(__GNUC__)
18 # pragma GCC diagnostic ignored "-Wunused-function"
19 #endif
20
21 /*
22 * Include windows.h without Windows Sockets 1.1 to prevent conflicts with
23 * Windows Sockets 2.0.
24 */
25 #ifndef WIN32_LEAN_AND_MEAN
26 # define WIN32_LEAN_AND_MEAN
27 #endif
28 #include <windows.h>
29
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <wchar.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <malloc.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <errno.h>
39
40 /* Indicates that d_type field is available in dirent structure */
41 #define _DIRENT_HAVE_D_TYPE
42
43 /* Indicates that d_namlen field is available in dirent structure */
44 #define _DIRENT_HAVE_D_NAMLEN
45
46 /* Entries missing from MSVC 6.0 */
47 #if !defined(FILE_ATTRIBUTE_DEVICE)
48 # define FILE_ATTRIBUTE_DEVICE 0x40
49 #endif
50
51 /* File type and permission flags for stat(), general mask */
52 #if !defined(S_IFMT)
53 # define S_IFMT _S_IFMT
54 #endif
55
56 /* Directory bit */
57 #if !defined(S_IFDIR)
58 # define S_IFDIR _S_IFDIR
59 #endif
60
61 /* Character device bit */
62 #if !defined(S_IFCHR)
63 # define S_IFCHR _S_IFCHR
64 #endif
65
66 /* Pipe bit */
67 #if !defined(S_IFFIFO)
68 # define S_IFFIFO _S_IFFIFO
69 #endif
70
71 /* Regular file bit */
72 #if !defined(S_IFREG)
73 # define S_IFREG _S_IFREG
74 #endif
75
76 /* Read permission */
77 #if !defined(S_IREAD)
78 # define S_IREAD _S_IREAD
79 #endif
80
81 /* Write permission */
82 #if !defined(S_IWRITE)
83 # define S_IWRITE _S_IWRITE
84 #endif
85
86 /* Execute permission */
87 #if !defined(S_IEXEC)
88 # define S_IEXEC _S_IEXEC
89 #endif
90
91 /* Pipe */
92 #if !defined(S_IFIFO)
93 # define S_IFIFO _S_IFIFO
94 #endif
95
96 /* Block device */
97 #if !defined(S_IFBLK)
98 # define S_IFBLK 0
99 #endif
100
101 /* Link */
102 #if !defined(S_IFLNK)
103 # define S_IFLNK 0
104 #endif
105
106 /* Socket */
107 #if !defined(S_IFSOCK)
108 # define S_IFSOCK 0
109 #endif
110
111 /* Read user permission */
112 #if !defined(S_IRUSR)
113 # define S_IRUSR S_IREAD
114 #endif
115
116 /* Write user permission */
117 #if !defined(S_IWUSR)
118 # define S_IWUSR S_IWRITE
119 #endif
120
121 /* Execute user permission */
122 #if !defined(S_IXUSR)
123 # define S_IXUSR 0
124 #endif
125
126 /* Read group permission */
127 #if !defined(S_IRGRP)
128 # define S_IRGRP 0
129 #endif
130
131 /* Write group permission */
132 #if !defined(S_IWGRP)
133 # define S_IWGRP 0
134 #endif
135
136 /* Execute group permission */
137 #if !defined(S_IXGRP)
138 # define S_IXGRP 0
139 #endif
140
141 /* Read others permission */
142 #if !defined(S_IROTH)
143 # define S_IROTH 0
144 #endif
145
146 /* Write others permission */
147 #if !defined(S_IWOTH)
148 # define S_IWOTH 0
149 #endif
150
151 /* Execute others permission */
152 #if !defined(S_IXOTH)
153 # define S_IXOTH 0
154 #endif
155
156 /* Maximum length of file name */
157 #if !defined(PATH_MAX)
158 # define PATH_MAX MAX_PATH
159 #endif
160 #if !defined(FILENAME_MAX)
161 # define FILENAME_MAX MAX_PATH
162 #endif
163 #if !defined(NAME_MAX)
164 # define NAME_MAX FILENAME_MAX
165 #endif
166
167 /* File type flags for d_type */
168 #define DT_UNKNOWN 0
169 #define DT_REG S_IFREG
170 #define DT_DIR S_IFDIR
171 #define DT_FIFO S_IFIFO
172 #define DT_SOCK S_IFSOCK
173 #define DT_CHR S_IFCHR
174 #define DT_BLK S_IFBLK
175 #define DT_LNK S_IFLNK
176
177 /* Macros for converting between st_mode and d_type */
178 #define IFTODT(mode) ((mode) & S_IFMT)
179 #define DTTOIF(type) (type)
180
181 /*
182 * File type macros. Note that block devices, sockets and links cannot be
183 * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
184 * only defined for compatibility. These macros should always return false
185 * on Windows.
186 */
187 #if !defined(S_ISFIFO)
188 # define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
189 #endif
190 #if !defined(S_ISDIR)
191 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
192 #endif
193 #if !defined(S_ISREG)
194 # define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
195 #endif
196 #if !defined(S_ISLNK)
197 # define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
198 #endif
199 #if !defined(S_ISSOCK)
200 # define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
201 #endif
202 #if !defined(S_ISCHR)
203 # define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
204 #endif
205 #if !defined(S_ISBLK)
206 # define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
207 #endif
208
209 /* Return the exact length of the file name without zero terminator */
210 #define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
211
212 /* Return the maximum size of a file name */
213 #define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1)
214
215
216 #ifdef __cplusplus
217 extern "C" {
218 #endif
219
220
221 /* Wide-character version */
222 struct _wdirent {
223 /* Always zero */
224 long d_ino;
225
226 /* File position within stream */
227 long d_off;
228
229 /* Structure size */
230 unsigned short d_reclen;
231
232 /* Length of name without \0 */
233 size_t d_namlen;
234
235 /* File type */
236 int d_type;
237
238 /* File name */
239 wchar_t d_name[PATH_MAX+1];
240
241 /* Windows extensions */
242 size_t dwin_size;
243 FILETIME dwin_mtime;
244 };
245 typedef struct _wdirent _wdirent;
246
247 struct _WDIR {
248 /* Current directory entry */
249 struct _wdirent ent;
250
251 /* Private file data */
252 WIN32_FIND_DATAW data;
253
254 /* True if data is valid */
255 int cached;
256
257 /* Win32 search handle */
258 HANDLE handle;
259
260 /* Initial directory name */
261 wchar_t *patt;
262 };
263 typedef struct _WDIR _WDIR;
264
265 /* Multi-byte character version */
266 struct dirent {
267 /* Always zero */
268 long d_ino;
269
270 /* File position within stream */
271 long d_off;
272
273 /* Structure size */
274 unsigned short d_reclen;
275
276 /* Length of name without \0 */
277 size_t d_namlen;
278
279 /* File type */
280 int d_type;
281
282 /* File name */
283 char d_name[PATH_MAX+1];
284
285 /* Windows extensions */
286 size_t dwin_size;
287 FILETIME dwin_mtime;
288 };
289 typedef struct dirent dirent;
290
291 struct DIR {
292 struct dirent ent;
293 struct _WDIR *wdirp;
294 };
295 typedef struct DIR DIR;
296
297
298 /* Dirent functions */
299 static DIR *opendir (const char *dirname);
300 static _WDIR *_wopendir (const wchar_t *dirname);
301
302 static struct dirent *readdir (DIR *dirp);
303 static struct _wdirent *_wreaddir (_WDIR *dirp);
304
305 static int readdir_r(
306 DIR *dirp, struct dirent *entry, struct dirent **result);
307 static int _wreaddir_r(
308 _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result);
309
310 static int closedir (DIR *dirp);
311 static int _wclosedir (_WDIR *dirp);
312
313 static void rewinddir (DIR* dirp);
314 static void _wrewinddir (_WDIR* dirp);
315
316 static int scandir (const char *dirname, struct dirent ***namelist,
317 int (*filter)(const struct dirent*),
318 int (*compare)(const struct dirent**, const struct dirent**));
319
320 static int alphasort (const struct dirent **a, const struct dirent **b);
321
322 static int versionsort (const struct dirent **a, const struct dirent **b);
323
324
325 /* For compatibility with Symbian */
326 #define wdirent _wdirent
327 #define WDIR _WDIR
328 #define wopendir _wopendir
329 #define wreaddir _wreaddir
330 #define wclosedir _wclosedir
331 #define wrewinddir _wrewinddir
332
333
334 /* Internal utility functions */
335 static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp);
336 static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp);
337
338 static int dirent_mbstowcs_s(
339 size_t *pReturnValue,
340 wchar_t *wcstr,
341 size_t sizeInWords,
342 const char *mbstr,
343 size_t count);
344
345 static int dirent_wcstombs_s(
346 size_t *pReturnValue,
347 char *mbstr,
348 size_t sizeInBytes,
349 const wchar_t *wcstr,
350 size_t count);
351
352 static void dirent_set_errno (int error);
353
354
355 /*
356 * Open directory stream DIRNAME for read and return a pointer to the
357 * internal working area that is used to retrieve individual directory
358 * entries.
359 */
360 static _WDIR*
361 _wopendir(
362 const wchar_t *dirname)
363 {
364 _WDIR *dirp;
365 DWORD n;
366 wchar_t *p;
367
368 /* Must have directory name */
369 if (dirname == NULL || dirname[0] == '\0') {
370 dirent_set_errno (ENOENT);
371 return NULL;
372 }
373
374 /* Allocate new _WDIR structure */
375 dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
376 if (!dirp) {
377 return NULL;
378 }
379
380 /* Reset _WDIR structure */
381 dirp->handle = INVALID_HANDLE_VALUE;
382 dirp->patt = NULL;
383 dirp->cached = 0;
384
385 /*
386 * Compute the length of full path plus zero terminator
387 *
388 * Note that on WinRT there's no way to convert relative paths
389 * into absolute paths, so just assume it is an absolute path.
390 */
391 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
392 /* Desktop */
393 n = GetFullPathNameW (dirname, 0, NULL, NULL);
394 #else
395 /* WinRT */
396 n = wcslen (dirname);
397 #endif
398
399 /* Allocate room for absolute directory name and search pattern */
400 dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
401 if (dirp->patt == NULL) {
402 goto exit_closedir;
403 }
404
405 /*
406 * Convert relative directory name to an absolute one. This
407 * allows rewinddir() to function correctly even when current
408 * working directory is changed between opendir() and rewinddir().
409 *
410 * Note that on WinRT there's no way to convert relative paths
411 * into absolute paths, so just assume it is an absolute path.
412 */
413 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
414 /* Desktop */
415 n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
416 if (n <= 0) {
417 goto exit_closedir;
418 }
419 #else
420 /* WinRT */
421 wcsncpy_s (dirp->patt, n+1, dirname, n);
422 #endif
423
424 /* Append search pattern \* to the directory name */
425 p = dirp->patt + n;
426 switch (p[-1]) {
427 case '\\':
428 case '/':
429 case ':':
430 /* Directory ends in path separator, e.g. c:\temp\ */
431 /*NOP*/;
432 break;
433
434 default:
435 /* Directory name doesn't end in path separator */
436 *p++ = '\\';
437 }
438 *p++ = '*';
439 *p = '\0';
440
441 /* Open directory stream and retrieve the first entry */
442 if (!dirent_first (dirp)) {
443 goto exit_closedir;
444 }
445
446 /* Success */
447 return dirp;
448
449 /* Failure */
450 exit_closedir:
451 _wclosedir (dirp);
452 return NULL;
453 }
454
455 /*
456 * Read next directory entry.
457 *
458 * Returns pointer to static directory entry which may be overwritten by
459 * subsequent calls to _wreaddir().
460 */
461 static struct _wdirent*
462 _wreaddir(
463 _WDIR *dirp)
464 {
465 struct _wdirent *entry;
466
467 /*
468 * Read directory entry to buffer. We can safely ignore the return value
469 * as entry will be set to NULL in case of error.
470 */
471 (void) _wreaddir_r (dirp, &dirp->ent, &entry);
472
473 /* Return pointer to statically allocated directory entry */
474 return entry;
475 }
476
477 /*
478 * Read next directory entry.
479 *
480 * Returns zero on success. If end of directory stream is reached, then sets
481 * result to NULL and returns zero.
482 */
483 static int
484 _wreaddir_r(
485 _WDIR *dirp,
486 struct _wdirent *entry,
487 struct _wdirent **result)
488 {
489 WIN32_FIND_DATAW *datap;
490
491 /* Read next directory entry */
492 datap = dirent_next (dirp);
493 if (datap) {
494 size_t n;
495 DWORD attr;
496
497 /*
498 * Copy file name as wide-character string. If the file name is too
499 * long to fit in to the destination buffer, then truncate file name
500 * to PATH_MAX characters and zero-terminate the buffer.
501 */
502 n = 0;
503 while (n < PATH_MAX && datap->cFileName[n] != 0) {
504 entry->d_name[n] = datap->cFileName[n];
505 n++;
506 }
507 entry->d_name[n] = 0;
508
509 /* Length of file name excluding zero terminator */
510 entry->d_namlen = n;
511
512 /* File type */
513 attr = datap->dwFileAttributes;
514 if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
515 entry->d_type = DT_CHR;
516 } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
517 entry->d_type = DT_DIR;
518 } else {
519 entry->d_type = DT_REG;
520 }
521
522 /* Reset dummy fields */
523 entry->d_ino = 0;
524 entry->d_off = 0;
525 entry->d_reclen = sizeof (struct _wdirent);
526
527 #ifdef _WIN64
528 entry->dwin_size = ((size_t)datap->nFileSizeHigh<<32) | datap->nFileSizeLow;
529 #else
530 if (datap->nFileSizeHigh) {
531 entry->dwin_size = 0xffffffff;
532 } else {
533 entry->dwin_size = datap->nFileSizeLow;
534 }
535 #endif
536 entry->dwin_mtime = datap->ftLastWriteTime;
537
538 /* Set result address */
539 *result = entry;
540
541 } else {
542
543 /* Return NULL to indicate end of directory */
544 *result = NULL;
545
546 }
547
548 return /*OK*/0;
549 }
550
551 /*
552 * Close directory stream opened by opendir() function. This invalidates the
553 * DIR structure as well as any directory entry read previously by
554 * _wreaddir().
555 */
556 static int
557 _wclosedir(
558 _WDIR *dirp)
559 {
560 int ok;
561 if (dirp) {
562
563 /* Release search handle */
564 if (dirp->handle != INVALID_HANDLE_VALUE) {
565 FindClose (dirp->handle);
566 }
567
568 /* Release search pattern */
569 free (dirp->patt);
570
571 /* Release directory structure */
572 free (dirp);
573 ok = /*success*/0;
574
575 } else {
576
577 /* Invalid directory stream */
578 dirent_set_errno (EBADF);
579 ok = /*failure*/-1;
580
581 }
582 return ok;
583 }
584
585 /*
586 * Rewind directory stream such that _wreaddir() returns the very first
587 * file name again.
588 */
589 static void
590 _wrewinddir(
591 _WDIR* dirp)
592 {
593 if (dirp) {
594 /* Release existing search handle */
595 if (dirp->handle != INVALID_HANDLE_VALUE) {
596 FindClose (dirp->handle);
597 }
598
599 /* Open new search handle */
600 dirent_first (dirp);
601 }
602 }
603
604 /* Get first directory entry (internal) */
605 static WIN32_FIND_DATAW*
606 dirent_first(
607 _WDIR *dirp)
608 {
609 WIN32_FIND_DATAW *datap;
610 DWORD error;
611
612 /* Open directory and retrieve the first entry */
613 dirp->handle = FindFirstFileExW(
614 dirp->patt, FindExInfoStandard, &dirp->data,
615 FindExSearchNameMatch, NULL, 0);
616 if (dirp->handle != INVALID_HANDLE_VALUE) {
617
618 /* a directory entry is now waiting in memory */
619 datap = &dirp->data;
620 dirp->cached = 1;
621
622 } else {
623
624 /* Failed to open directory: no directory entry in memory */
625 dirp->cached = 0;
626 datap = NULL;
627
628 /* Set error code */
629 error = GetLastError ();
630 switch (error) {
631 case ERROR_ACCESS_DENIED:
632 /* No read access to directory */
633 dirent_set_errno (EACCES);
634 break;
635
636 case ERROR_DIRECTORY:
637 /* Directory name is invalid */
638 dirent_set_errno (ENOTDIR);
639 break;
640
641 case ERROR_PATH_NOT_FOUND:
642 default:
643 /* Cannot find the file */
644 dirent_set_errno (ENOENT);
645 }
646
647 }
648 return datap;
649 }
650
651 /*
652 * Get next directory entry (internal).
653 *
654 * Returns
655 */
656 static WIN32_FIND_DATAW*
657 dirent_next(
658 _WDIR *dirp)
659 {
660 WIN32_FIND_DATAW *p;
661
662 /* Get next directory entry */
663 if (dirp->cached != 0) {
664
665 /* A valid directory entry already in memory */
666 p = &dirp->data;
667 dirp->cached = 0;
668
669 } else if (dirp->handle != INVALID_HANDLE_VALUE) {
670
671 /* Get the next directory entry from stream */
672 if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
673 /* Got a file */
674 p = &dirp->data;
675 } else {
676 /* The very last entry has been processed or an error occurred */
677 FindClose (dirp->handle);
678 dirp->handle = INVALID_HANDLE_VALUE;
679 p = NULL;
680 }
681
682 } else {
683
684 /* End of directory stream reached */
685 p = NULL;
686
687 }
688
689 return p;
690 }
691
692 /*
693 * Open directory stream using plain old C-string.
694 */
695 static DIR*
696 opendir(
697 const char *dirname)
698 {
699 struct DIR *dirp;
700
701 /* Must have directory name */
702 if (dirname == NULL || dirname[0] == '\0') {
703 dirent_set_errno (ENOENT);
704 return NULL;
705 }
706
707 /* Allocate memory for DIR structure */
708 dirp = (DIR*) malloc (sizeof (struct DIR));
709 if (!dirp) {
710 return NULL;
711 }
712 {
713 int error;
714 wchar_t wname[PATH_MAX + 1];
715 size_t n;
716
717 /* Convert directory name to wide-character string */
718 error = dirent_mbstowcs_s(
719 &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1);
720 if (error) {
721 /*
722 * Cannot convert file name to wide-character string. This
723 * occurs if the string contains invalid multi-byte sequences or
724 * the output buffer is too small to contain the resulting
725 * string.
726 */
727 goto exit_free;
728 }
729
730
731 /* Open directory stream using wide-character name */
732 dirp->wdirp = _wopendir (wname);
733 if (!dirp->wdirp) {
734 goto exit_free;
735 }
736
737 }
738
739 /* Success */
740 return dirp;
741
742 /* Failure */
743 exit_free:
744 free (dirp);
745 return NULL;
746 }
747
748 /*
749 * Read next directory entry.
750 */
751 static struct dirent*
752 readdir(
753 DIR *dirp)
754 {
755 struct dirent *entry;
756
757 /*
758 * Read directory entry to buffer. We can safely ignore the return value
759 * as entry will be set to NULL in case of error.
760 */
761 (void) readdir_r (dirp, &dirp->ent, &entry);
762
763 /* Return pointer to statically allocated directory entry */
764 return entry;
765 }
766
767 /*
768 * Read next directory entry into called-allocated buffer.
769 *
770 * Returns zero on success. If the end of directory stream is reached, then
771 * sets result to NULL and returns zero.
772 */
773 static int
774 readdir_r(
775 DIR *dirp,
776 struct dirent *entry,
777 struct dirent **result)
778 {
779 WIN32_FIND_DATAW *datap;
780
781 /* Read next directory entry */
782 datap = dirent_next (dirp->wdirp);
783 if (datap) {
784 size_t n;
785 int error;
786
787 /* Attempt to convert file name to multi-byte string */
788 error = dirent_wcstombs_s(
789 &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1);
790
791 /*
792 * If the file name cannot be represented by a multi-byte string,
793 * then attempt to use old 8+3 file name. This allows traditional
794 * Unix-code to access some file names despite of unicode
795 * characters, although file names may seem unfamiliar to the user.
796 *
797 * Be ware that the code below cannot come up with a short file
798 * name unless the file system provides one. At least
799 * VirtualBox shared folders fail to do this.
800 */
801 if (error && datap->cAlternateFileName[0] != '\0') {
802 error = dirent_wcstombs_s(
803 &n, entry->d_name, PATH_MAX + 1,
804 datap->cAlternateFileName, PATH_MAX + 1);
805 }
806
807 if (!error) {
808 DWORD attr;
809
810 /* Length of file name excluding zero terminator */
811 entry->d_namlen = n - 1;
812
813 /* File attributes */
814 attr = datap->dwFileAttributes;
815 if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
816 entry->d_type = DT_CHR;
817 } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
818 entry->d_type = DT_DIR;
819 } else {
820 entry->d_type = DT_REG;
821 }
822
823 /* Reset dummy fields */
824 entry->d_ino = 0;
825 entry->d_off = 0;
826 entry->d_reclen = sizeof (struct dirent);
827
828 #ifdef _WIN64
829 entry->dwin_size = ((size_t)datap->nFileSizeHigh<<32) | datap->nFileSizeLow;
830 #else
831 if (datap->nFileSizeHigh) {
832 entry->dwin_size = 0xffffffff;
833 } else {
834 entry->dwin_size = datap->nFileSizeLow;
835 }
836 #endif
837 entry->dwin_mtime = datap->ftLastWriteTime;
838
839 } else {
840
841 /*
842 * Cannot convert file name to multi-byte string so construct
843 * an erroneous directory entry and return that. Note that
844 * we cannot return NULL as that would stop the processing
845 * of directory entries completely.
846 */
847 entry->d_name[0] = '?';
848 entry->d_name[1] = '\0';
849 entry->d_namlen = 1;
850 entry->d_type = DT_UNKNOWN;
851 entry->d_ino = 0;
852 entry->d_off = -1;
853 entry->d_reclen = 0;
854 entry->dwin_size = 0;
855 entry->dwin_mtime.dwHighDateTime = 0;
856 entry->dwin_mtime.dwLowDateTime = 0;
857
858 }
859
860 /* Return pointer to directory entry */
861 *result = entry;
862
863 } else {
864
865 /* No more directory entries */
866 *result = NULL;
867
868 }
869
870 return /*OK*/0;
871 }
872
873 /*
874 * Close directory stream.
875 */
876 static int
877 closedir(
878 DIR *dirp)
879 {
880 int ok;
881 if (dirp) {
882
883 /* Close wide-character directory stream */
884 ok = _wclosedir (dirp->wdirp);
885 dirp->wdirp = NULL;
886
887 /* Release multi-byte character version */
888 free (dirp);
889
890 } else {
891
892 /* Invalid directory stream */
893 dirent_set_errno (EBADF);
894 ok = /*failure*/-1;
895
896 }
897 return ok;
898 }
899
900 /*
901 * Rewind directory stream to beginning.
902 */
903 static void
904 rewinddir(
905 DIR* dirp)
906 {
907 /* Rewind wide-character string directory stream */
908 _wrewinddir (dirp->wdirp);
909 }
910
911 /*
912 * Scan directory for entries.
913 */
914 static int
915 scandir(
916 const char *dirname,
917 struct dirent ***namelist,
918 int (*filter)(const struct dirent*),
919 int (*compare)(const struct dirent**, const struct dirent**))
920 {
921 struct dirent **files = NULL;
922 size_t size = 0;
923 size_t allocated = 0;
924 const size_t init_size = 1;
925 DIR *dir = NULL;
926 struct dirent *entry;
927 struct dirent *tmp = NULL;
928 size_t i;
929 int result = 0;
930
931 /* Open directory stream */
932 dir = opendir (dirname);
933 if (dir) {
934
935 /* Read directory entries to memory */
936 while (1) {
937
938 /* Enlarge pointer table to make room for another pointer */
939 if (size >= allocated) {
940 void *p;
941 size_t num_entries;
942
943 /* Compute number of entries in the enlarged pointer table */
944 if (size < init_size) {
945 /* Allocate initial pointer table */
946 num_entries = init_size;
947 } else {
948 /* Double the size */
949 num_entries = size * 2;
950 }
951
952 /* Allocate first pointer table or enlarge existing table */
953 p = realloc (files, sizeof (void*) * num_entries);
954 if (p != NULL) {
955 /* Got the memory */
956 files = (dirent**) p;
957 allocated = num_entries;
958 } else {
959 /* Out of memory */
960 result = -1;
961 break;
962 }
963
964 }
965
966 /* Allocate room for temporary directory entry */
967 if (tmp == NULL) {
968 tmp = (struct dirent*) malloc (sizeof (struct dirent));
969 if (tmp == NULL) {
970 /* Cannot allocate temporary directory entry */
971 result = -1;
972 break;
973 }
974 }
975
976 /* Read directory entry to temporary area */
977 if (readdir_r (dir, tmp, &entry) == /*OK*/0) {
978
979 /* Did we get an entry? */
980 if (entry != NULL) {
981 int pass;
982
983 /* Determine whether to include the entry in result */
984 if (filter) {
985 /* Let the filter function decide */
986 pass = filter (tmp);
987 } else {
988 /* No filter function, include everything */
989 pass = 1;
990 }
991
992 if (pass) {
993 /* Store the temporary entry to pointer table */
994 files[size++] = tmp;
995 tmp = NULL;
996
997 /* Keep up with the number of files */
998 result++;
999 }
1000
1001 } else {
1002
1003 /*
1004 * End of directory stream reached => sort entries and
1005 * exit.
1006 */
1007 qsort (files, size, sizeof (void*),
1008 (int (*) (const void*, const void*)) compare);
1009 break;
1010
1011 }
1012
1013 } else {
1014 /* Error reading directory entry */
1015 result = /*Error*/ -1;
1016 break;
1017 }
1018
1019 }
1020
1021 } else {
1022 /* Cannot open directory */
1023 result = /*Error*/ -1;
1024 }
1025
1026 /* Release temporary directory entry */
1027 free (tmp);
1028
1029 /* Release allocated memory on error */
1030 if (result < 0) {
1031 for (i = 0; i < size; i++) {
1032 free (files[i]);
1033 }
1034 free (files);
1035 files = NULL;
1036 }
1037
1038 /* Close directory stream */
1039 if (dir) {
1040 closedir (dir);
1041 }
1042
1043 /* Pass pointer table to caller */
1044 if (namelist) {
1045 *namelist = files;
1046 }
1047 return result;
1048 }
1049
1050 /* Alphabetical sorting */
1051 static int
1052 alphasort(
1053 const struct dirent **a, const struct dirent **b)
1054 {
1055 return strcoll ((*a)->d_name, (*b)->d_name);
1056 }
1057
1058 /* Sort versions */
1059 static int
1060 versionsort(
1061 const struct dirent **a, const struct dirent **b)
1062 {
1063 /* FIXME: implement strverscmp and use that */
1064 return alphasort (a, b);
1065 }
1066
1067
1068 int decodeUTF8s(const unsigned char* data, char* len) {
1069 int ret=0xfffd;
1070 if (data[0]<0x80) {
1071 ret=data[0];
1072 *len=1;
1073 } else if (data[0]<0xc0) {
1074 ret=0xfffd; // invalid
1075 *len=1;
1076 } else if (data[0]<0xe0) {
1077 if (data[1]>=0x80 && data[1]<0xc0) {
1078 *len=2;
1079 ret=((data[0]&31)<<6)|
1080 (data[1]&63);
1081 } else *len=1;
1082 } else if (data[0]<0xf0) {
1083 if (data[1]>=0x80 && data[1]<0xc0) {
1084 if (data[2]>=0x80 && data[2]<0xc0) {
1085 *len=3;
1086 ret=((data[0]&15)<<12)|
1087 ((data[1]&63)<<6)|
1088 (data[2]&63);
1089 } else *len=2;
1090 } else *len=1;
1091 } else if (data[0]<0xf5) {
1092 if (data[1]>=0x80 && data[1]<0xc0) {
1093 if (data[2]>=0x80 && data[2]<0xc0) {
1094 if (data[3]>=0x80 && data[3]<0xc0) {
1095 *len=4;
1096 ret=((data[0]&7)<<18)|
1097 ((data[1]&63)<<12)|
1098 ((data[2]&63)<<6)|
1099 (data[3]&63);
1100 } else *len=3;
1101 } else *len=2;
1102 } else *len=1;
1103 } else {
1104 *len=1;
1105 return 0xfffd;
1106 }
1107
1108 if ((ret>=0xd800 && ret<=0xdfff) || ret>=0x110000) return 0xfffd;
1109 return ret;
1110 }
1111
1112 static int u8to16s(wchar_t* dest, const char* src, size_t limit) {
1113 size_t ret=0;
1114 int ch, p;
1115 char chs;
1116 p=0;
1117 while (src[p]!=0 && ret<limit-1) {
1118 ch=decodeUTF8s((const unsigned char*)&src[p],&chs);
1119 // surrogates
1120 if (ch>=0x10000) {
1121 ch-=0x10000;
1122 if (ret+1>=limit-1) break;
1123 dest[ret++]=(unsigned short)(0xd800|((ch>>10)&0x3ff));
1124 dest[ret++]=(unsigned short)(0xdc00|(ch&0x3ff));
1125 } else if (ch<0xd800 || ch>0xdfff) {
1126 dest[ret++]=(unsigned short)ch;
1127 }
1128 p+=chs;
1129 }
1130 dest[ret]=0;
1131 return ret;
1132 }
1133
1134 /* Convert multi-byte string to wide character string */
1135 static int
1136 dirent_mbstowcs_s(
1137 size_t *pReturnValue,
1138 wchar_t *wcstr,
1139 size_t sizeInWords,
1140 const char *mbstr,
1141 size_t count)
1142 {
1143 int error;
1144
1145 /* Older Visual Studio or non-Microsoft compiler */
1146 size_t n;
1147
1148 /* Convert to wide-character string (or count characters) */
1149 n = u8to16s (wcstr, mbstr, sizeInWords);
1150 if (!wcstr || n < count) {
1151
1152 /* Zero-terminate output buffer */
1153 if (wcstr && sizeInWords) {
1154 if (n >= sizeInWords) {
1155 n = sizeInWords - 1;
1156 }
1157 wcstr[n] = 0;
1158 }
1159
1160 /* Length of resulting multi-byte string WITH zero terminator */
1161 if (pReturnValue) {
1162 *pReturnValue = n + 1;
1163 }
1164
1165 /* Success */
1166 error = 0;
1167
1168 } else {
1169
1170 /* Could not convert string */
1171 error = 1;
1172
1173 }
1174
1175 return error;
1176 }
1177
1178 static int u16to8s(char* dest, const wchar_t* src, size_t limit) {
1179 size_t ret=0;
1180 unsigned int next=0;
1181 for (; (*src)!=0; src++) {
1182 if ((*src)>=0xd800 && (*src)<0xdc00) {
1183 next=0x10000+(((*src)&0x3ff)<<10);
1184 continue;
1185 } else if ((*src)>=0xdc00 && (*src)<0xe000) {
1186 next|=(*src)&0x3ff;
1187 } else {
1188 next=(*src);
1189 }
1190 if (next<0x80) {
1191 if (ret+1>=limit-1) break;
1192 dest[ret++]=next;
1193 } else if (next<0x800) {
1194 if (ret+2>=limit-1) break;
1195 dest[ret++]=(0xc0+((next>>6)&31));
1196 dest[ret++]=(0x80+(next&63));
1197 } else if (next<0x10000) {
1198 if (ret+3>=limit-1) break;
1199 dest[ret++]=(0xe0+((next>>12)&15));
1200 dest[ret++]=(0x80+((next>>6)&63));
1201 dest[ret++]=(0x80+(next&63));
1202 } else {
1203 if (ret+4>=limit-1) break;
1204 dest[ret++]=(0xf0+((next>>18)&7));
1205 dest[ret++]=(0x80+((next>>12)&63));
1206 dest[ret++]=(0x80+((next>>6)&63));
1207 dest[ret++]=(0x80+(next&63));
1208 }
1209 }
1210 dest[ret]=0;
1211 return ret;
1212 }
1213
1214 /* Convert wide-character string to multi-byte string */
1215 static int
1216 dirent_wcstombs_s(
1217 size_t *pReturnValue,
1218 char *mbstr,
1219 size_t sizeInBytes, /* max size of mbstr */
1220 const wchar_t *wcstr,
1221 size_t count)
1222 {
1223 int error;
1224
1225 /* Older Visual Studio or non-Microsoft compiler */
1226 size_t n;
1227
1228 /* Convert to multi-byte string (or count the number of bytes needed) */
1229 // TODO: please fix for internationalization! issue #22
1230 n = u16to8s(mbstr, wcstr, sizeInBytes);
1231 if (!mbstr || n < count) {
1232
1233 /* Zero-terminate output buffer */
1234 if (mbstr && sizeInBytes) {
1235 if (n >= sizeInBytes) {
1236 n = sizeInBytes - 1;
1237 }
1238 mbstr[n] = '\0';
1239 }
1240
1241 /* Length of resulting multi-bytes string WITH zero-terminator */
1242 if (pReturnValue) {
1243 *pReturnValue = n + 1;
1244 }
1245
1246 /* Success */
1247 error = 0;
1248
1249 } else {
1250
1251 /* Cannot convert string */
1252 error = 1;
1253
1254 }
1255
1256 return error;
1257 }
1258
1259 /* Set errno variable */
1260 static void
1261 dirent_set_errno(
1262 int error)
1263 {
1264 #if defined(_MSC_VER) && _MSC_VER >= 1400
1265
1266 /* Microsoft Visual Studio 2005 and later */
1267 _set_errno (error);
1268
1269 #else
1270
1271 /* Non-Microsoft compiler or older Microsoft compiler */
1272 errno = error;
1273
1274 #endif
1275 }
1276
1277
1278 #ifdef __cplusplus
1279 }
1280 #endif
1281 #endif /*DIRENT_H*/