xref: /openbsd-src/gnu/usr.bin/perl/lib/User/pwent.pm (revision e2e5c5d36e4398ba94879f0a31b0307421edcfdb)
1package User::pwent;
2
3use 5.006;
4
5use strict;
6use warnings;
7
8use Config;
9use Carp;
10
11our(@EXPORT, @EXPORT_OK, %EXPORT_TAGS);
12BEGIN {
13    use Exporter   ();
14    @EXPORT      = qw(getpwent getpwuid getpwnam getpw);
15    @EXPORT_OK   = qw(
16                        pw_has
17
18                        $pw_name    $pw_passwd  $pw_uid  $pw_gid
19                        $pw_gecos   $pw_dir     $pw_shell
20                        $pw_expire  $pw_change  $pw_class
21                        $pw_age
22                        $pw_quota   $pw_comment
23                        $pw_expire
24
25                   );
26    %EXPORT_TAGS = (
27        FIELDS => [ grep(/^\$pw_/, @EXPORT_OK), @EXPORT ],
28        ALL    => [ @EXPORT, @EXPORT_OK ],
29    );
30}
31use vars grep /^\$pw_/, @EXPORT_OK;
32
33#
34# XXX: these mean somebody hacked this module's source
35#      without understanding the underlying assumptions.
36#
37my $IE = "[INTERNAL ERROR]";
38
39# Class::Struct forbids use of @ISA
40sub import { goto &Exporter::import }
41
42use Class::Struct qw(struct);
43struct 'User::pwent' => [
44    name    => '$',         # pwent[0]
45    passwd  => '$',         # pwent[1]
46    uid     => '$',         # pwent[2]
47    gid     => '$',         # pwent[3]
48
49    # you'll only have one/none of these three
50    change  => '$',         # pwent[4]
51    age     => '$',         # pwent[4]
52    quota   => '$',         # pwent[4]
53
54    # you'll only have one/none of these two
55    comment => '$',         # pwent[5]
56    class   => '$',         # pwent[5]
57
58    # you might not have this one
59    gecos   => '$',         # pwent[6]
60
61    dir     => '$',         # pwent[7]
62    shell   => '$',         # pwent[8]
63
64    # you might not have this one
65    expire  => '$',         # pwent[9]
66
67];
68
69
70# init our groks hash to be true if the built platform knew how
71# to do each struct pwd field that perl can ever under any circumstances
72# know about.  we do not use /^pw_?/, but just the tails.
73sub _feature_init {
74    our %Groks;         # whether build system knew how to do this feature
75    for my $feep ( qw{
76                         pwage      pwchange   pwclass    pwcomment
77                         pwexpire   pwgecos    pwpasswd   pwquota
78                     }
79                 )
80    {
81        my $short = $feep =~ /^pw(.*)/
82                  ? $1
83                  : do {
84                        # not cluck, as we know we called ourselves,
85                        # and a confession is probably imminent anyway
86                        warn("$IE $feep is a funny struct pwd field");
87                        $feep;
88                    };
89
90        exists $Config{ "d_" . $feep }
91            || confess("$IE Configure doesn't d_$feep");
92        $Groks{$short} = defined $Config{ "d_" . $feep };
93    }
94    # assume that any that are left are always there
95    for my $feep (grep /^\$pw_/s, @EXPORT_OK) {
96        $feep =~ /^\$pw_(.*)/;
97        $Groks{$1} = 1 unless defined $Groks{$1};
98    }
99}
100
101# With arguments, reports whether one or more fields are all implemented
102# in the build machine's struct pwd pw_*.  May be whitespace separated.
103# We do not use /^pw_?/, just the tails.
104#
105# Without arguments, returns the list of fields implemented on build
106# machine, space separated in scalar context.
107#
108# Takes exception to being asked whether this machine's struct pwd has
109# a field that Perl never knows how to provide under any circumstances.
110# If the module does this idiocy to itself, the explosion is noisier.
111#
112sub pw_has {
113    our %Groks;         # whether build system knew how to do this feature
114    my $cando = 1;
115    my $sploder = caller() ne __PACKAGE__
116                    ? \&croak
117                    : sub { confess("$IE @_") };
118    if (@_ == 0) {
119        my @valid = sort grep { $Groks{$_} } keys %Groks;
120        return wantarray ? @valid : "@valid";
121    }
122    for my $feep (map { split } @_) {
123        defined $Groks{$feep}
124            || $sploder->("$feep is never a valid struct pwd field");
125        $cando &&= $Groks{$feep};
126    }
127    return $cando;
128}
129
130sub _populate (@) {
131    return unless @_;
132    my $pwob = new();
133
134    # Any that haven't been pw_had are assumed on "all" platforms of
135    # course, this may not be so, but you can't get here otherwise,
136    # since the underlying core call already took exception to your
137    # impudence.
138
139    $pw_name    = $pwob->name   ( $_[0] );
140    $pw_passwd  = $pwob->passwd ( $_[1] )   if pw_has("passwd");
141    $pw_uid     = $pwob->uid    ( $_[2] );
142    $pw_gid     = $pwob->gid    ( $_[3] );
143
144    if (pw_has("change")) {
145        $pw_change      = $pwob->change ( $_[4] );
146    }
147    elsif (pw_has("age")) {
148        $pw_age         = $pwob->age    ( $_[4] );
149    }
150    elsif (pw_has("quota")) {
151        $pw_quota       = $pwob->quota  ( $_[4] );
152    }
153
154    if (pw_has("class")) {
155        $pw_class       = $pwob->class  ( $_[5] );
156    }
157    elsif (pw_has("comment")) {
158        $pw_comment     = $pwob->comment( $_[5] );
159    }
160
161    $pw_gecos   = $pwob->gecos  ( $_[6] ) if pw_has("gecos");
162
163    $pw_dir     = $pwob->dir    ( $_[7] );
164    $pw_shell   = $pwob->shell  ( $_[8] );
165
166    $pw_expire  = $pwob->expire ( $_[9] ) if pw_has("expire");
167
168    return $pwob;
169}
170
171sub getpwent ( ) { _populate(CORE::getpwent()) }
172sub getpwnam ($) { _populate(CORE::getpwnam(shift)) }
173sub getpwuid ($) { _populate(CORE::getpwuid(shift)) }
174sub getpw    ($) { ($_[0] =~ /^\d+\z/s) ? &getpwuid : &getpwnam }
175
176_feature_init();
177
1781;
179__END__
180
181=head1 NAME
182
183User::pwent - by-name interface to Perl's built-in getpw*() functions
184
185=head1 SYNOPSIS
186
187 use User::pwent;
188 $pw = getpwnam('daemon')       || die "No daemon user";
189 if ( $pw->uid == 1 && $pw->dir =~ m#^/(bin|tmp)?\z#s ) {
190     print "gid 1 on root dir";
191 }
192
193 $real_shell = $pw->shell || '/bin/sh';
194
195 for (($fullname, $office, $workphone, $homephone) =
196        split /\s*,\s*/, $pw->gecos)
197 {
198    s/&/ucfirst(lc($pw->name))/ge;
199 }
200
201 use User::pwent qw(:FIELDS);
202 getpwnam('daemon')             || die "No daemon user";
203 if ( $pw_uid == 1 && $pw_dir =~ m#^/(bin|tmp)?\z#s ) {
204     print "gid 1 on root dir";
205 }
206
207 $pw = getpw($whoever);
208
209 use User::pwent qw/:DEFAULT pw_has/;
210 if (pw_has(qw[gecos expire quota])) { .... }
211 if (pw_has("name uid gid passwd"))  { .... }
212 print "Your struct pwd has: ", scalar pw_has(), "\n";
213
214=head1 DESCRIPTION
215
216This module's default exports override the core getpwent(), getpwuid(),
217and getpwnam() functions, replacing them with versions that return
218C<User::pwent> objects.  This object has methods that return the
219similarly named structure field name from the C's passwd structure
220from F<pwd.h>, stripped of their leading "pw_" parts, namely C<name>,
221C<passwd>, C<uid>, C<gid>, C<change>, C<age>, C<quota>, C<comment>,
222C<class>, C<gecos>, C<dir>, C<shell>, and C<expire>.  The C<passwd>,
223C<gecos>, and C<shell> fields are tainted when running in taint mode.
224
225You may also import all the structure fields directly into your
226namespace as regular variables using the :FIELDS import tag.  (Note
227that this still overrides your core functions.)  Access these fields
228as variables named with a preceding C<pw_> in front their method
229names.  Thus, C<< $passwd_obj->shell >> corresponds to $pw_shell
230if you import the fields.
231
232The getpw() function is a simple front-end that forwards
233a numeric argument to getpwuid() and the rest to getpwnam().
234
235To access this functionality without the core overrides, pass the
236C<use> an empty import list, and then access function functions
237with their full qualified names.  The built-ins are always still
238available via the C<CORE::> pseudo-package.
239
240=head2 System Specifics
241
242Perl believes that no machine ever has more than one of C<change>,
243C<age>, or C<quota> implemented, nor more than one of either
244C<comment> or C<class>.  Some machines do not support C<expire>,
245C<gecos>, or allegedly, C<passwd>.  You may call these methods
246no matter what machine you're on, but they return C<undef> if
247unimplemented.
248
249You may ask whether one of these was implemented on the system Perl
250was built on by asking the importable C<pw_has> function about them.
251This function returns true if all parameters are supported fields
252on the build platform, false if one or more were not, and raises
253an exception if you asked about a field that Perl never knows how
254to provide.  Parameters may be in a space-separated string, or as
255separate arguments.  If you pass no parameters, the function returns
256the list of C<struct pwd> fields supported by your build platform's
257C library, as a list in list context, or a space-separated string
258in scalar context.  Note that just because your C library had
259a field doesn't necessarily mean that it's fully implemented on
260that system.
261
262Interpretation of the C<gecos> field varies between systems, but
263traditionally holds 4 comma-separated fields containing the user's
264full name, office location, work phone number, and home phone number.
265An C<&> in the gecos field should be replaced by the user's properly
266capitalized login C<name>.  The C<shell> field, if blank, must be
267assumed to be F</bin/sh>.  Perl does not do this for you.  The
268C<passwd> is one-way hashed garble, not clear text, and may not be
269unhashed save by brute-force guessing.  Secure systems use more a
270more secure hashing than DES.  On systems supporting shadow password
271systems, Perl automatically returns the shadow password entry when
272called by a suitably empowered user, even if your underlying
273vendor-provided C library was too short-sighted to realize it should
274do this.
275
276See passwd(5) and getpwent(3) for details.
277
278=head1 NOTE
279
280While this class is currently implemented using the Class::Struct
281module to build a struct-like class, you shouldn't rely upon this.
282
283=head1 AUTHOR
284
285Tom Christiansen
286
287=head1 HISTORY
288
289=over
290
291=item March 18th, 2000
292
293Reworked internals to support better interface to dodgey fields
294than normal Perl function provides.  Added pw_has() field.  Improved
295documentation.
296
297=back
298