xref: /openbsd/gnu/usr.bin/perl/lib/File/stat.pm (revision 09467b48)
1package File::stat;
2use 5.006;
3
4use strict;
5use warnings;
6use warnings::register;
7use Carp;
8
9BEGIN { *warnif = \&warnings::warnif }
10
11our(@EXPORT, @EXPORT_OK, %EXPORT_TAGS);
12
13our $VERSION = '1.08';
14
15our @fields;
16our ( $st_dev, $st_ino, $st_mode,
17    $st_nlink, $st_uid, $st_gid,
18    $st_rdev, $st_size,
19    $st_atime, $st_mtime, $st_ctime,
20    $st_blksize, $st_blocks
21);
22
23BEGIN {
24    use Exporter   ();
25    @EXPORT      = qw(stat lstat);
26    @fields      = qw( $st_dev	   $st_ino    $st_mode
27		       $st_nlink   $st_uid    $st_gid
28		       $st_rdev    $st_size
29		       $st_atime   $st_mtime  $st_ctime
30		       $st_blksize $st_blocks
31		    );
32    @EXPORT_OK   = ( @fields, "stat_cando" );
33    %EXPORT_TAGS = ( FIELDS => [ @fields, @EXPORT ] );
34}
35
36use Fcntl qw(S_IRUSR S_IWUSR S_IXUSR);
37
38BEGIN {
39    # These constants will croak on use if the platform doesn't define
40    # them. It's important to avoid inflicting that on the user.
41    no strict 'refs';
42    for (qw(suid sgid svtx)) {
43        my $val = eval { &{"Fcntl::S_I\U$_"} };
44        *{"_$_"} = defined $val ? sub { $_[0] & $val ? 1 : "" } : sub { "" };
45    }
46    for (qw(SOCK CHR BLK REG DIR LNK)) {
47        *{"S_IS$_"} = defined eval { &{"Fcntl::S_IF$_"} }
48            ? \&{"Fcntl::S_IS$_"} : sub { "" };
49    }
50    # FIFO flag and macro don't quite follow the S_IF/S_IS pattern above
51    # RT #111638
52    *{"S_ISFIFO"} = defined &Fcntl::S_IFIFO
53      ? \&Fcntl::S_ISFIFO : sub { "" };
54}
55
56# from doio.c
57sub _ingroup {
58    my ($gid, $eff)   = @_;
59
60    # I am assuming that since VMS doesn't have getgroups(2), $) will
61    # always only contain a single entry.
62    $^O eq "VMS"    and return $_[0] == $);
63
64    my ($egid, @supp) = split " ", $);
65    my ($rgid)        = split " ", $(;
66
67    $gid == ($eff ? $egid : $rgid)  and return 1;
68    grep $gid == $_, @supp          and return 1;
69
70    return "";
71}
72
73# VMS uses the Unix version of the routine, even though this is very
74# suboptimal. VMS has a permissions structure that doesn't really fit
75# into struct stat, and unlike on Win32 the normal -X operators respect
76# that, but unfortunately by the time we get here we've already lost the
77# information we need. It looks to me as though if we were to preserve
78# the st_devnam entry of vmsish.h's fake struct stat (which actually
79# holds the filename) it might be possible to do this right, but both
80# getting that value out of the struct (perl's stat doesn't return it)
81# and interpreting it later would require this module to have an XS
82# component (at which point we might as well just call Perl_cando and
83# have done with it).
84
85if (grep $^O eq $_, qw/os2 MSWin32 dos/) {
86
87    # from doio.c
88    *cando = sub { ($_[0][2] & $_[1]) ? 1 : "" };
89}
90else {
91
92    # from doio.c
93    *cando = sub {
94        my ($s, $mode, $eff) = @_;
95        my $uid = $eff ? $> : $<;
96        my ($stmode, $stuid, $stgid) = @$s[2,4,5];
97
98        # This code basically assumes that the rwx bits of the mode are
99        # the 0777 bits, but so does Perl_cando.
100
101        if ($uid == 0 && $^O ne "VMS") {
102            # If we're root on unix
103            # not testing for executable status => all file tests are true
104            return 1 if !($mode & 0111);
105            # testing for executable status =>
106            # for a file, any x bit will do
107            # for a directory, always true
108            return 1 if $stmode & 0111 || S_ISDIR($stmode);
109            return "";
110        }
111
112        if ($stuid == $uid) {
113            $stmode & $mode         and return 1;
114        }
115        elsif (_ingroup($stgid, $eff)) {
116            $stmode & ($mode >> 3)  and return 1;
117        }
118        else {
119            $stmode & ($mode >> 6)  and return 1;
120        }
121        return "";
122    };
123}
124
125# alias for those who don't like objects
126*stat_cando = \&cando;
127
128my %op = (
129    r => sub { cando($_[0], S_IRUSR, 1) },
130    w => sub { cando($_[0], S_IWUSR, 1) },
131    x => sub { cando($_[0], S_IXUSR, 1) },
132    o => sub { $_[0][4] == $>           },
133
134    R => sub { cando($_[0], S_IRUSR, 0) },
135    W => sub { cando($_[0], S_IWUSR, 0) },
136    X => sub { cando($_[0], S_IXUSR, 0) },
137    O => sub { $_[0][4] == $<           },
138
139    e => sub { 1 },
140    z => sub { $_[0][7] == 0    },
141    s => sub { $_[0][7]         },
142
143    f => sub { S_ISREG ($_[0][2]) },
144    d => sub { S_ISDIR ($_[0][2]) },
145    l => sub { S_ISLNK ($_[0][2]) },
146    p => sub { S_ISFIFO($_[0][2]) },
147    S => sub { S_ISSOCK($_[0][2]) },
148    b => sub { S_ISBLK ($_[0][2]) },
149    c => sub { S_ISCHR ($_[0][2]) },
150
151    u => sub { _suid($_[0][2]) },
152    g => sub { _sgid($_[0][2]) },
153    k => sub { _svtx($_[0][2]) },
154
155    M => sub { ($^T - $_[0][9] ) / 86400 },
156    C => sub { ($^T - $_[0][10]) / 86400 },
157    A => sub { ($^T - $_[0][8] ) / 86400 },
158);
159
160use constant HINT_FILETEST_ACCESS => 0x00400000;
161
162# we need fallback=>1 or stringifying breaks
163use overload
164    fallback => 1,
165    -X => sub {
166        my ($s, $op) = @_;
167
168        if (index("rwxRWX", $op) >= 0) {
169            (caller 0)[8] & HINT_FILETEST_ACCESS
170                and warnif("File::stat ignores use filetest 'access'");
171
172            $^O eq "VMS" and warnif("File::stat ignores VMS ACLs");
173
174            # It would be nice to have a warning about using -l on a
175            # non-lstat, but that would require an extra member in the
176            # object.
177        }
178
179        if ($op{$op}) {
180            return $op{$op}->($_[0]);
181        }
182        else {
183            croak "-$op is not implemented on a File::stat object";
184        }
185    };
186
187# Class::Struct forbids use of @ISA
188sub import { goto &Exporter::import }
189
190use Class::Struct qw(struct);
191struct 'File::stat' => [
192     map { $_ => '$' } qw{
193	 dev ino mode nlink uid gid rdev size
194	 atime mtime ctime blksize blocks
195     }
196];
197
198sub populate (@) {
199    return unless @_;
200    my $stob = new();
201    @$stob = (
202	$st_dev, $st_ino, $st_mode, $st_nlink, $st_uid, $st_gid, $st_rdev,
203        $st_size, $st_atime, $st_mtime, $st_ctime, $st_blksize, $st_blocks )
204	    = @_;
205    return $stob;
206}
207
208sub lstat ($)  { populate(CORE::lstat(shift)) }
209
210sub stat ($) {
211    my $arg = shift;
212    my $st = populate(CORE::stat $arg);
213    return $st if defined $st;
214	my $fh;
215    {
216		local $!;
217		no strict 'refs';
218		require Symbol;
219		$fh = \*{ Symbol::qualify( $arg, caller() )};
220		return unless defined fileno $fh;
221	}
222    return populate(CORE::stat $fh);
223}
224
2251;
226__END__
227
228=head1 NAME
229
230File::stat - by-name interface to Perl's built-in stat() functions
231
232=head1 SYNOPSIS
233
234 use File::stat;
235 $st = stat($file) or die "No $file: $!";
236 if ( ($st->mode & 0111) && $st->nlink > 1) ) {
237     print "$file is executable with lotsa links\n";
238 }
239
240 if ( -x $st ) {
241     print "$file is executable\n";
242 }
243
244 use Fcntl "S_IRUSR";
245 if ( $st->cando(S_IRUSR, 1) ) {
246     print "My effective uid can read $file\n";
247 }
248
249 use File::stat qw(:FIELDS);
250 stat($file) or die "No $file: $!";
251 if ( ($st_mode & 0111) && ($st_nlink > 1) ) {
252     print "$file is executable with lotsa links\n";
253 }
254
255=head1 DESCRIPTION
256
257This module's default exports override the core stat()
258and lstat() functions, replacing them with versions that return
259"File::stat" objects.  This object has methods that
260return the similarly named structure field name from the
261stat(2) function; namely,
262dev,
263ino,
264mode,
265nlink,
266uid,
267gid,
268rdev,
269size,
270atime,
271mtime,
272ctime,
273blksize,
274and
275blocks.
276
277As of version 1.02 (provided with perl 5.12) the object provides C<"-X">
278overloading, so you can call filetest operators (C<-f>, C<-x>, and so
279on) on it. It also provides a C<< ->cando >> method, called like
280
281 $st->cando( ACCESS, EFFECTIVE )
282
283where I<ACCESS> is one of C<S_IRUSR>, C<S_IWUSR> or C<S_IXUSR> from the
284L<Fcntl|Fcntl> module, and I<EFFECTIVE> indicates whether to use
285effective (true) or real (false) ids. The method interprets the C<mode>,
286C<uid> and C<gid> fields, and returns whether or not the current process
287would be allowed the specified access.
288
289If you don't want to use the objects, you may import the C<< ->cando >>
290method into your namespace as a regular function called C<stat_cando>.
291This takes an arrayref containing the return values of C<stat> or
292C<lstat> as its first argument, and interprets it for you.
293
294You may also import all the structure fields directly into your namespace
295as regular variables using the :FIELDS import tag.  (Note that this still
296overrides your stat() and lstat() functions.)  Access these fields as
297variables named with a preceding C<st_> in front their method names.
298Thus, C<$stat_obj-E<gt>dev()> corresponds to $st_dev if you import
299the fields.
300
301To access this functionality without the core overrides,
302pass the C<use> an empty import list, and then access
303function functions with their full qualified names.
304On the other hand, the built-ins are still available
305via the C<CORE::> pseudo-package.
306
307=head1 BUGS
308
309As of Perl 5.8.0 after using this module you cannot use the implicit
310C<$_> or the special filehandle C<_> with stat() or lstat(), trying
311to do so leads into strange errors.  The workaround is for C<$_> to
312be explicit
313
314    my $stat_obj = stat $_;
315
316and for C<_> to explicitly populate the object using the unexported
317and undocumented populate() function with CORE::stat():
318
319    my $stat_obj = File::stat::populate(CORE::stat(_));
320
321=head1 ERRORS
322
323=over 4
324
325=item -%s is not implemented on a File::stat object
326
327The filetest operators C<-t>, C<-T> and C<-B> are not implemented, as
328they require more information than just a stat buffer.
329
330=back
331
332=head1 WARNINGS
333
334These can all be disabled with
335
336    no warnings "File::stat";
337
338=over 4
339
340=item File::stat ignores use filetest 'access'
341
342You have tried to use one of the C<-rwxRWX> filetests with C<use
343filetest 'access'> in effect. C<File::stat> will ignore the pragma, and
344just use the information in the C<mode> member as usual.
345
346=item File::stat ignores VMS ACLs
347
348VMS systems have a permissions structure that cannot be completely
349represented in a stat buffer, and unlike on other systems the builtin
350filetest operators respect this. The C<File::stat> overloads, however,
351do not, since the information required is not available.
352
353=back
354
355=head1 NOTE
356
357While this class is currently implemented using the Class::Struct
358module to build a struct-like class, you shouldn't rely upon this.
359
360=head1 AUTHOR
361
362Tom Christiansen
363