forked from ruby/ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dir.c
3155 lines (2852 loc) · 78.7 KB
/
dir.c
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
dir.c -
$Author$
created at: Wed Jan 5 09:51:01 JST 1994
Copyright (C) 1993-2007 Yukihiro Matsumoto
Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright (C) 2000 Information-technology Promotion Agency, Japan
**********************************************************************/
#include "internal.h"
#include "encindex.h"
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifndef USE_OPENDIR_AT
# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD) && \
defined(HAVE_OPENAT) && defined(HAVE_FSTATAT)
# define USE_OPENDIR_AT 1
# else
# define USE_OPENDIR_AT 0
# endif
#endif
#if USE_OPENDIR_AT
# include <fcntl.h>
#endif
#ifndef AT_FDCWD
# define AT_FDCWD -1
#endif
#undef HAVE_DIRENT_NAMLEN
#if defined HAVE_DIRENT_H && !defined _WIN32
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#elif defined HAVE_DIRECT_H && !defined _WIN32
# include <direct.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# define HAVE_DIRENT_NAMLEN 1
# if HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# if HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# if HAVE_NDIR_H
# include <ndir.h>
# endif
# ifdef _WIN32
# include "win32/dir.h"
# endif
#endif
#if defined(__native_client__) && defined(NACL_NEWLIB)
# include "nacl/dirent.h"
# include "nacl/stat.h"
#endif
#include <errno.h>
#ifndef HAVE_STDLIB_H
char *getenv();
#endif
#ifndef HAVE_STRING_H
char *strchr(char*,char);
#endif
#include <ctype.h>
#include "ruby/util.h"
/* define system APIs */
#ifdef _WIN32
#undef chdir
#define chdir(p) rb_w32_uchdir(p)
#undef mkdir
#define mkdir(p, m) rb_w32_umkdir((p), (m))
#undef rmdir
#define rmdir(p) rb_w32_urmdir(p)
#undef opendir
#define opendir(p) rb_w32_uopendir(p)
#define ruby_getcwd() rb_w32_ugetcwd(NULL, 0)
#define IS_WIN32 1
#else
#define IS_WIN32 0
#endif
#ifdef HAVE_SYS_ATTR_H
#include <sys/attr.h>
#endif
#define USE_NAME_ON_FS_REAL_BASENAME 1 /* platform dependent APIs to
* get real basenames */
#define USE_NAME_ON_FS_BY_FNMATCH 2 /* select the matching
* basename by fnmatch */
#ifdef HAVE_GETATTRLIST
# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
# define RUP32(size) ((size)+3/4)
# define SIZEUP32(type) RUP32(sizeof(type))
#elif defined _WIN32
# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
#elif defined DOSISH
# define USE_NAME_ON_FS USE_NAME_ON_FS_BY_FNMATCH
#else
# define USE_NAME_ON_FS 0
#endif
#ifdef __APPLE__
# define NORMALIZE_UTF8PATH 1
#else
# define NORMALIZE_UTF8PATH 0
#endif
#if NORMALIZE_UTF8PATH
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/vnode.h>
# if defined HAVE_FGETATTRLIST || !defined HAVE_GETATTRLIST
# define need_normalization(dirp, path) need_normalization(dirp)
# else
# define need_normalization(dirp, path) need_normalization(path)
# endif
static inline int
need_normalization(DIR *dirp, const char *path)
{
# if defined HAVE_FGETATTRLIST || defined HAVE_GETATTRLIST
u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
# if defined HAVE_FGETATTRLIST
int ret = fgetattrlist(dirfd(dirp), &al, attrbuf, sizeof(attrbuf), 0);
# else
int ret = getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0);
# endif
if (!ret) {
const fsobj_tag_t *tag = (void *)(attrbuf+1);
switch (*tag) {
case VT_HFS:
case VT_CIFS:
return TRUE;
}
}
# endif
return FALSE;
}
static inline int
has_nonascii(const char *ptr, size_t len)
{
while (len > 0) {
if (!ISASCII(*ptr)) return 1;
ptr++;
--len;
}
return 0;
}
# define IF_NORMALIZE_UTF8PATH(something) something
#else
# define IF_NORMALIZE_UTF8PATH(something) /* nothing */
#endif
#ifndef IFTODT
# define IFTODT(m) (((m) & S_IFMT) / ((~S_IFMT & S_IFMT-1) + 1))
#endif
typedef enum {
#ifdef DT_UNKNOWN
path_exist = DT_UNKNOWN,
path_directory = DT_DIR,
path_regular = DT_REG,
path_symlink = DT_LNK,
#else
path_exist,
path_directory = IFTODT(S_IFDIR),
path_regular = IFTODT(S_IFREG),
path_symlink = IFTODT(S_IFLNK),
#endif
path_noent = -1,
path_unknown = -2
} rb_pathtype_t;
#define FNM_NOESCAPE 0x01
#define FNM_PATHNAME 0x02
#define FNM_DOTMATCH 0x04
#define FNM_CASEFOLD 0x08
#define FNM_EXTGLOB 0x10
#if CASEFOLD_FILESYSTEM
#define FNM_SYSCASE FNM_CASEFOLD
#else
#define FNM_SYSCASE 0
#endif
#if _WIN32
#define FNM_SHORTNAME 0x20
#else
#define FNM_SHORTNAME 0
#endif
#define FNM_NOMATCH 1
#define FNM_ERROR 2
# define Next(p, e, enc) ((p)+ rb_enc_mbclen((p), (e), (enc)))
# define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
static char *
bracket(
const char *p, /* pattern (next to '[') */
const char *pend,
const char *s, /* string */
const char *send,
int flags,
rb_encoding *enc)
{
const int nocase = flags & FNM_CASEFOLD;
const int escape = !(flags & FNM_NOESCAPE);
unsigned int c1, c2;
int r;
int ok = 0, not = 0;
if (p >= pend) return NULL;
if (*p == '!' || *p == '^') {
not = 1;
p++;
}
while (*p != ']') {
const char *t1 = p;
if (escape && *t1 == '\\')
t1++;
if (!*t1)
return NULL;
p = t1 + (r = rb_enc_mbclen(t1, pend, enc));
if (p >= pend) return NULL;
if (p[0] == '-' && p[1] != ']') {
const char *t2 = p + 1;
int r2;
if (escape && *t2 == '\\')
t2++;
if (!*t2)
return NULL;
p = t2 + (r2 = rb_enc_mbclen(t2, pend, enc));
if (ok) continue;
if ((r <= (send-s) && memcmp(t1, s, r) == 0) ||
(r2 <= (send-s) && memcmp(t2, s, r2) == 0)) {
ok = 1;
continue;
}
c1 = rb_enc_codepoint(s, send, enc);
if (nocase) c1 = rb_enc_toupper(c1, enc);
c2 = rb_enc_codepoint(t1, pend, enc);
if (nocase) c2 = rb_enc_toupper(c2, enc);
if (c1 < c2) continue;
c2 = rb_enc_codepoint(t2, pend, enc);
if (nocase) c2 = rb_enc_toupper(c2, enc);
if (c1 > c2) continue;
}
else {
if (ok) continue;
if (r <= (send-s) && memcmp(t1, s, r) == 0) {
ok = 1;
continue;
}
if (!nocase) continue;
c1 = rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc);
c2 = rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc);
if (c1 != c2) continue;
}
ok = 1;
}
return ok == not ? NULL : (char *)p + 1;
}
/* If FNM_PATHNAME is set, only path element will be matched. (up to '/' or '\0')
Otherwise, entire string will be matched.
End marker itself won't be compared.
And if function succeeds, *pcur reaches end marker.
*/
#define UNESCAPE(p) (escape && *(p) == '\\' ? (p) + 1 : (p))
#define ISEND(p) (!*(p) || (pathname && *(p) == '/'))
#define RETURN(val) return *pcur = p, *scur = s, (val);
static int
fnmatch_helper(
const char **pcur, /* pattern */
const char **scur, /* string */
int flags,
rb_encoding *enc)
{
const int period = !(flags & FNM_DOTMATCH);
const int pathname = flags & FNM_PATHNAME;
const int escape = !(flags & FNM_NOESCAPE);
const int nocase = flags & FNM_CASEFOLD;
const char *ptmp = 0;
const char *stmp = 0;
const char *p = *pcur;
const char *pend = p + strlen(p);
const char *s = *scur;
const char *send = s + strlen(s);
int r;
if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */
RETURN(FNM_NOMATCH);
while (1) {
switch (*p) {
case '*':
do { p++; } while (*p == '*');
if (ISEND(UNESCAPE(p))) {
p = UNESCAPE(p);
RETURN(0);
}
if (ISEND(s))
RETURN(FNM_NOMATCH);
ptmp = p;
stmp = s;
continue;
case '?':
if (ISEND(s))
RETURN(FNM_NOMATCH);
p++;
Inc(s, send, enc);
continue;
case '[': {
const char *t;
if (ISEND(s))
RETURN(FNM_NOMATCH);
if ((t = bracket(p + 1, pend, s, send, flags, enc)) != 0) {
p = t;
Inc(s, send, enc);
continue;
}
goto failed;
}
}
/* ordinary */
p = UNESCAPE(p);
if (ISEND(s))
RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
if (ISEND(p))
goto failed;
r = rb_enc_precise_mbclen(p, pend, enc);
if (!MBCLEN_CHARFOUND_P(r))
goto failed;
if (r <= (send-s) && memcmp(p, s, r) == 0) {
p += r;
s += r;
continue;
}
if (!nocase) goto failed;
if (rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc) !=
rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc))
goto failed;
p += r;
Inc(s, send, enc);
continue;
failed: /* try next '*' position */
if (ptmp && stmp) {
p = ptmp;
Inc(stmp, send, enc); /* !ISEND(*stmp) */
s = stmp;
continue;
}
RETURN(FNM_NOMATCH);
}
}
static int
fnmatch(
const char *pattern,
rb_encoding *enc,
const char *string,
int flags)
{
const char *p = pattern;
const char *s = string;
const char *send = s + strlen(string);
const int period = !(flags & FNM_DOTMATCH);
const int pathname = flags & FNM_PATHNAME;
const char *ptmp = 0;
const char *stmp = 0;
if (pathname) {
while (1) {
if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
ptmp = p;
stmp = s;
}
if (fnmatch_helper(&p, &s, flags, enc) == 0) {
while (*s && *s != '/') Inc(s, send, enc);
if (*p && *s) {
p++;
s++;
continue;
}
if (!*p && !*s)
return 0;
}
/* failed : try next recursion */
if (ptmp && stmp && !(period && *stmp == '.')) {
while (*stmp && *stmp != '/') Inc(stmp, send, enc);
if (*stmp) {
p = ptmp;
stmp++;
s = stmp;
continue;
}
}
return FNM_NOMATCH;
}
}
else
return fnmatch_helper(&p, &s, flags, enc);
}
VALUE rb_cDir;
struct dir_data {
DIR *dir;
const VALUE path;
rb_encoding *enc;
};
static void
dir_mark(void *ptr)
{
struct dir_data *dir = ptr;
rb_gc_mark(dir->path);
}
static void
dir_free(void *ptr)
{
struct dir_data *dir = ptr;
if (dir->dir) closedir(dir->dir);
xfree(dir);
}
static size_t
dir_memsize(const void *ptr)
{
return sizeof(struct dir_data);
}
static const rb_data_type_t dir_data_type = {
"dir",
{dir_mark, dir_free, dir_memsize,},
0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
};
static VALUE dir_close(VALUE);
#define GlobPathValue(str, safe) \
/* can contain null bytes as separators */ \
(!RB_TYPE_P((str), T_STRING) ? \
(void)FilePathValue(str) : \
(void)(check_safe_glob((str), (safe)), \
check_glob_encoding(str), (str)))
#define check_safe_glob(str, safe) ((safe) ? rb_check_safe_obj(str) : (void)0)
#define check_glob_encoding(str) rb_enc_check((str), rb_enc_from_encoding(rb_usascii_encoding()))
static VALUE
dir_s_alloc(VALUE klass)
{
struct dir_data *dirp;
VALUE obj = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dirp);
dirp->dir = NULL;
RB_OBJ_WRITE(obj, &dirp->path, Qnil);
dirp->enc = NULL;
return obj;
}
/*
* call-seq:
* Dir.new( string ) -> aDir
* Dir.new( string, encoding: enc ) -> aDir
*
* Returns a new directory object for the named directory.
*
* The optional <i>encoding</i> keyword argument specifies the encoding of the directory.
* If not specified, the filesystem encoding is used.
*/
static VALUE
dir_initialize(int argc, VALUE *argv, VALUE dir)
{
struct dir_data *dp;
rb_encoding *fsenc;
VALUE dirname, opt, orig;
static ID keyword_ids[1];
const char *path;
if (!keyword_ids[0]) {
keyword_ids[0] = rb_id_encoding();
}
fsenc = rb_filesystem_encoding();
rb_scan_args(argc, argv, "1:", &dirname, &opt);
if (!NIL_P(opt)) {
VALUE enc;
rb_get_kwargs(opt, keyword_ids, 0, 1, &enc);
if (enc != Qundef && !NIL_P(enc)) {
fsenc = rb_to_encoding(enc);
}
}
GlobPathValue(dirname, FALSE);
orig = rb_str_dup_frozen(dirname);
dirname = rb_str_encode_ospath(dirname);
dirname = rb_str_dup_frozen(dirname);
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dp);
if (dp->dir) closedir(dp->dir);
dp->dir = NULL;
RB_OBJ_WRITE(dir, &dp->path, Qnil);
dp->enc = fsenc;
path = RSTRING_PTR(dirname);
dp->dir = opendir(path);
if (dp->dir == NULL) {
int e = errno;
if (rb_gc_for_fd(e)) {
dp->dir = opendir(path);
}
#ifdef HAVE_GETATTRLIST
else if (e == EIO) {
u_int32_t attrbuf[1];
struct attrlist al = {ATTR_BIT_MAP_COUNT, 0};
if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW) == 0) {
dp->dir = opendir(path);
}
}
#endif
if (dp->dir == NULL) {
RB_GC_GUARD(dirname);
rb_syserr_fail_path(e, orig);
}
}
RB_OBJ_WRITE(dir, &dp->path, orig);
return dir;
}
/*
* call-seq:
* Dir.open( string ) -> aDir
* Dir.open( string, encoding: enc ) -> aDir
* Dir.open( string ) {| aDir | block } -> anObject
* Dir.open( string, encoding: enc ) {| aDir | block } -> anObject
*
* The optional <i>encoding</i> keyword argument specifies the encoding of the directory.
* If not specified, the filesystem encoding is used.
*
* With no block, <code>open</code> is a synonym for
* <code>Dir::new</code>. If a block is present, it is passed
* <i>aDir</i> as a parameter. The directory is closed at the end of
* the block, and <code>Dir::open</code> returns the value of the
* block.
*/
static VALUE
dir_s_open(int argc, VALUE *argv, VALUE klass)
{
struct dir_data *dp;
VALUE dir = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dp);
dir_initialize(argc, argv, dir);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, dir, dir_close, dir);
}
return dir;
}
static void
dir_closed(void)
{
rb_raise(rb_eIOError, "closed directory");
}
static struct dir_data *
dir_get(VALUE dir)
{
rb_check_frozen(dir);
return rb_check_typeddata(dir, &dir_data_type);
}
static struct dir_data *
dir_check(VALUE dir)
{
struct dir_data *dirp = dir_get(dir);
if (!dirp->dir) dir_closed();
return dirp;
}
#define GetDIR(obj, dirp) ((dirp) = dir_check(obj))
/*
* call-seq:
* dir.inspect -> string
*
* Return a string describing this Dir object.
*/
static VALUE
dir_inspect(VALUE dir)
{
struct dir_data *dirp;
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp);
if (!NIL_P(dirp->path)) {
VALUE str = rb_str_new_cstr("#<");
rb_str_append(str, rb_class_name(CLASS_OF(dir)));
rb_str_cat2(str, ":");
rb_str_append(str, dirp->path);
rb_str_cat2(str, ">");
return str;
}
return rb_funcallv(dir, rb_intern("to_s"), 0, 0);
}
/* Workaround for Solaris 10 that does not have dirfd.
Note: Solaris 11 (POSIX.1-2008 compliant) has dirfd(3C).
*/
#if defined(__sun) && !defined(HAVE_DIRFD)
# if defined(HAVE_DIR_D_FD)
# define dirfd(x) ((x)->d_fd)
# define HAVE_DIRFD 1
# elif defined(HAVE_DIR_DD_FD)
# define dirfd(x) ((x)->dd_fd)
# define HAVE_DIRFD 1
# endif
#endif
#ifdef HAVE_DIRFD
/*
* call-seq:
* dir.fileno -> integer
*
* Returns the file descriptor used in <em>dir</em>.
*
* d = Dir.new("..")
* d.fileno #=> 8
*
* This method uses dirfd() function defined by POSIX 2008.
* NotImplementedError is raised on other platforms, such as Windows,
* which doesn't provide the function.
*
*/
static VALUE
dir_fileno(VALUE dir)
{
struct dir_data *dirp;
int fd;
GetDIR(dir, dirp);
fd = dirfd(dirp->dir);
if (fd == -1)
rb_sys_fail("dirfd");
return INT2NUM(fd);
}
#else
#define dir_fileno rb_f_notimplement
#endif
/*
* call-seq:
* dir.path -> string or nil
* dir.to_path -> string or nil
*
* Returns the path parameter passed to <em>dir</em>'s constructor.
*
* d = Dir.new("..")
* d.path #=> ".."
*/
static VALUE
dir_path(VALUE dir)
{
struct dir_data *dirp;
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp);
if (NIL_P(dirp->path)) return Qnil;
return rb_str_dup(dirp->path);
}
#if defined _WIN32
static int
fundamental_encoding_p(rb_encoding *enc)
{
switch (rb_enc_to_index(enc)) {
case ENCINDEX_ASCII:
case ENCINDEX_US_ASCII:
case ENCINDEX_UTF_8:
return TRUE;
default:
return FALSE;
}
}
# define READDIR(dir, enc) rb_w32_readdir((dir), (enc))
#else
# define READDIR(dir, enc) readdir((dir))
#endif
static int
to_be_skipped(const struct dirent *dp)
{
const char *name = dp->d_name;
if (name[0] != '.') return FALSE;
#ifdef HAVE_DIRENT_NAMLEN
switch (NAMLEN(dp)) {
case 2:
if (name[1] != '.') return FALSE;
case 1:
return TRUE;
default:
break;
}
#else
if (!name[1]) return TRUE;
if (name[1] != '.') return FALSE;
if (!name[2]) return TRUE;
#endif
return FALSE;
}
/*
* call-seq:
* dir.read -> string or nil
*
* Reads the next entry from <em>dir</em> and returns it as a string.
* Returns <code>nil</code> at the end of the stream.
*
* d = Dir.new("testdir")
* d.read #=> "."
* d.read #=> ".."
* d.read #=> "config.h"
*/
static VALUE
dir_read(VALUE dir)
{
struct dir_data *dirp;
struct dirent *dp;
GetDIR(dir, dirp);
errno = 0;
if ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
return rb_external_str_new_with_enc(dp->d_name, NAMLEN(dp), dirp->enc);
}
else {
int e = errno;
if (e != 0) rb_syserr_fail(e, 0);
return Qnil; /* end of stream */
}
}
static VALUE dir_each_entry(VALUE, VALUE (*)(VALUE, VALUE), VALUE, int);
static VALUE
dir_yield(VALUE arg, VALUE path)
{
return rb_yield(path);
}
/*
* call-seq:
* dir.each { |filename| block } -> dir
* dir.each -> an_enumerator
*
* Calls the block once for each entry in this directory, passing the
* filename of each entry as a parameter to the block.
*
* If no block is given, an enumerator is returned instead.
*
* d = Dir.new("testdir")
* d.each {|x| puts "Got #{x}" }
*
* <em>produces:</em>
*
* Got .
* Got ..
* Got config.h
* Got main.rb
*/
static VALUE
dir_each(VALUE dir)
{
RETURN_ENUMERATOR(dir, 0, 0);
return dir_each_entry(dir, dir_yield, Qnil, FALSE);
}
static VALUE
dir_each_entry(VALUE dir, VALUE (*each)(VALUE, VALUE), VALUE arg, int children_only)
{
struct dir_data *dirp;
struct dirent *dp;
IF_NORMALIZE_UTF8PATH(int norm_p);
GetDIR(dir, dirp);
rewinddir(dirp->dir);
IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp->dir, RSTRING_PTR(dirp->path)));
while ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
const char *name = dp->d_name;
size_t namlen = NAMLEN(dp);
VALUE path;
if (children_only && name[0] == '.') {
if (namlen == 1) continue; /* current directory */
if (namlen == 2 && name[1] == '.') continue; /* parent directory */
}
#if NORMALIZE_UTF8PATH
if (norm_p && has_nonascii(name, namlen) &&
!NIL_P(path = rb_str_normalize_ospath(name, namlen))) {
path = rb_external_str_with_enc(path, dirp->enc);
}
else
#endif
path = rb_external_str_new_with_enc(name, namlen, dirp->enc);
(*each)(arg, path);
if (dirp->dir == NULL) dir_closed();
}
return dir;
}
#ifdef HAVE_TELLDIR
/*
* call-seq:
* dir.pos -> integer
* dir.tell -> integer
*
* Returns the current position in <em>dir</em>. See also
* <code>Dir#seek</code>.
*
* d = Dir.new("testdir")
* d.tell #=> 0
* d.read #=> "."
* d.tell #=> 12
*/
static VALUE
dir_tell(VALUE dir)
{
struct dir_data *dirp;
long pos;
GetDIR(dir, dirp);
pos = telldir(dirp->dir);
return rb_int2inum(pos);
}
#else
#define dir_tell rb_f_notimplement
#endif
#ifdef HAVE_SEEKDIR
/*
* call-seq:
* dir.seek( integer ) -> dir
*
* Seeks to a particular location in <em>dir</em>. <i>integer</i>
* must be a value returned by <code>Dir#tell</code>.
*
* d = Dir.new("testdir") #=> #<Dir:0x401b3c40>
* d.read #=> "."
* i = d.tell #=> 12
* d.read #=> ".."
* d.seek(i) #=> #<Dir:0x401b3c40>
* d.read #=> ".."
*/
static VALUE
dir_seek(VALUE dir, VALUE pos)
{
struct dir_data *dirp;
long p = NUM2LONG(pos);
GetDIR(dir, dirp);
seekdir(dirp->dir, p);
return dir;
}
#else
#define dir_seek rb_f_notimplement
#endif
#ifdef HAVE_SEEKDIR
/*
* call-seq:
* dir.pos = integer -> integer
*
* Synonym for <code>Dir#seek</code>, but returns the position
* parameter.
*
* d = Dir.new("testdir") #=> #<Dir:0x401b3c40>
* d.read #=> "."
* i = d.pos #=> 12
* d.read #=> ".."
* d.pos = i #=> 12
* d.read #=> ".."
*/
static VALUE
dir_set_pos(VALUE dir, VALUE pos)
{
dir_seek(dir, pos);
return pos;
}
#else
#define dir_set_pos rb_f_notimplement
#endif
/*
* call-seq:
* dir.rewind -> dir
*
* Repositions <em>dir</em> to the first entry.
*
* d = Dir.new("testdir")
* d.read #=> "."
* d.rewind #=> #<Dir:0x401b3fb0>
* d.read #=> "."
*/
static VALUE
dir_rewind(VALUE dir)
{
struct dir_data *dirp;
GetDIR(dir, dirp);
rewinddir(dirp->dir);
return dir;
}
/*
* call-seq:
* dir.close -> nil
*
* Closes the directory stream.
* Calling this method on closed Dir object is ignored since Ruby 2.3.
*
* d = Dir.new("testdir")
* d.close #=> nil
*/
static VALUE
dir_close(VALUE dir)
{
struct dir_data *dirp;
dirp = dir_get(dir);
if (!dirp->dir) return Qnil;
closedir(dirp->dir);
dirp->dir = NULL;
return Qnil;
}
static void
dir_chdir(VALUE path)
{
if (chdir(RSTRING_PTR(path)) < 0)
rb_sys_fail_path(path);
}
static int chdir_blocking = 0;
static VALUE chdir_thread = Qnil;
struct chdir_data {
VALUE old_path, new_path;
int done;
};
static VALUE
chdir_yield(struct chdir_data *args)
{
dir_chdir(args->new_path);
args->done = TRUE;
chdir_blocking++;
if (chdir_thread == Qnil)
chdir_thread = rb_thread_current();
return rb_yield(args->new_path);
}
static VALUE
chdir_restore(struct chdir_data *args)
{
if (args->done) {