update from main archive 961105
[glibc.git] / manual / users.texi
blobce6d526b4a311c5afcd1c1bf2f12b67daee0a8f3
1 @node Users and Groups
2 @chapter Users and Groups
4 Every user who can log in on the system is identified by a unique number
5 called the @dfn{user ID}.  Each process has an effective user ID which
6 says which user's access permissions it has.
8 Users are classified into @dfn{groups} for access control purposes.  Each
9 process has one or more @dfn{group ID values} which say which groups the
10 process can use for access to files.
12 The effective user and group IDs of a process collectively form its
13 @dfn{persona}.  This determines which files the process can access.
14 Normally, a process inherits its persona from the parent process, but
15 under special circumstances a process can change its persona and thus
16 change its access permissions.
18 Each file in the system also has a user ID and a group ID.  Access
19 control works by comparing the user and group IDs of the file with those
20 of the running process.
22 The system keeps a database of all the registered users, and another
23 database of all the defined groups.  There are library functions you
24 can use to examine these databases.
26 @menu
27 * User and Group IDs::          Each user has a unique numeric ID;
28                                  likewise for groups.
29 * Process Persona::             The user IDs and group IDs of a process.
30 * Why Change Persona::          Why a program might need to change
31                                  its user and/or group IDs.
32 * How Change Persona::          Changing the user and group IDs.
33 * Reading Persona::             How to examine the user and group IDs.
35 * Setting User ID::             Functions for setting the user ID.
36 * Setting Groups::              Functions for setting the group IDs.
38 * Enable/Disable Setuid::       Turning setuid access on and off.
39 * Setuid Program Example::      The pertinent parts of one sample program.
40 * Tips for Setuid::             How to avoid granting unlimited access.
42 * Who Logged In::               Getting the name of the user who logged in,
43                                  or of the real user ID of the current process.
45 * User Database::               Functions and data structures for
46                                  accessing the user database.
47 * Group Database::              Functions and data structures for
48                                  accessing the group database.
49 * Netgroup Database::           Functions for accessing the netgroup database.
50 * Database Example::            Example program showing use of database
51                                  inquiry functions.
52 @end menu
54 @node User and Group IDs, Process Persona, Users and Groups, Users and Groups
55 @section User and Group IDs
57 @cindex login name
58 @cindex user name
59 @cindex user ID
60 Each user account on a computer system is identified by a @dfn{user
61 name} (or @dfn{login name}) and @dfn{user ID}.  Normally, each user name
62 has a unique user ID, but it is possible for several login names to have
63 the same user ID.  The user names and corresponding user IDs are stored
64 in a data base which you can access as described in @ref{User Database}.
66 @cindex group name
67 @cindex group ID
68 Users are classified in @dfn{groups}.  Each user name also belongs to
69 one or more groups, and has one @dfn{default group}.  Users who are
70 members of the same group can share resources (such as files) that are
71 not accessible to users who are not a member of that group.  Each group
72 has a @dfn{group name} and @dfn{group ID}.  @xref{Group Database},
73 for how to find information about a group ID or group name.
75 @node Process Persona, Why Change Persona, User and Group IDs, Users and Groups
76 @section The Persona of a Process
77 @cindex persona
78 @cindex effective user ID
79 @cindex effective group ID
81 @c !!! bogus; not single ID.  set of effective group IDs (and, in GNU,
82 @c set of effective UIDs) determines privilege.  lying here and then
83 @c telling the truth below is confusing.
84 At any time, each process has a single user ID and a group ID which
85 determine the privileges of the process.  These are collectively called
86 the @dfn{persona} of the process, because they determine ``who it is''
87 for purposes of access control.  These IDs are also called the
88 @dfn{effective user ID} and @dfn{effective group ID} of the process.
90 Your login shell starts out with a persona which consists of your user
91 ID and your default group ID.
92 @c !!! also supplementary group IDs.
93 In normal circumstances, all your other processes inherit these values.
95 @cindex real user ID
96 @cindex real group ID
97 A process also has a @dfn{real user ID} which identifies the user who
98 created the process, and a @dfn{real group ID} which identifies that
99 user's default group.  These values do not play a role in access
100 control, so we do not consider them part of the persona.  But they are
101 also important.
103 Both the real and effective user ID can be changed during the lifetime
104 of a process.  @xref{Why Change Persona}.
106 @cindex supplementary group IDs
107 In addition, a user can belong to multiple groups, so the persona
108 includes @dfn{supplementary group IDs} that also contribute to access
109 permission.
111 For details on how a process's effective user IDs and group IDs affect
112 its permission to access files, see @ref{Access Permission}.
114 The user ID of a process also controls permissions for sending signals
115 using the @code{kill} function.  @xref{Signaling Another Process}.
117 @node Why Change Persona, How Change Persona, Process Persona, Users and Groups
118 @section Why Change the Persona of a Process?
120 The most obvious situation where it is necessary for a process to change
121 its user and/or group IDs is the @code{login} program.  When
122 @code{login} starts running, its user ID is @code{root}.  Its job is to
123 start a shell whose user and group IDs are those of the user who is
124 logging in.  (To accomplish this fully, @code{login} must set the real
125 user and group IDs as well as its persona.  But this is a special case.)
127 The more common case of changing persona is when an ordinary user
128 program needs access to a resource that wouldn't ordinarily be
129 accessible to the user actually running it.
131 For example, you may have a file that is controlled by your program but
132 that shouldn't be read or modified directly by other users, either
133 because it implements some kind of locking protocol, or because you want
134 to preserve the integrity or privacy of the information it contains.
135 This kind of restricted access can be implemented by having the program
136 change its effective user or group ID to match that of the resource.
138 Thus, imagine a game program that saves scores in a file.  The game
139 program itself needs to be able to update this file no matter who is
140 running it, but if users can write the file without going through the
141 game, they can give themselves any scores they like.  Some people
142 consider this undesirable, or even reprehensible.  It can be prevented
143 by creating a new user ID and login name (say, @code{games}) to own the
144 scores file, and make the file writable only by this user.  Then, when
145 the game program wants to update this file, it can change its effective
146 user ID to be that for @code{games}.  In effect, the program must
147 adopt the persona of @code{games} so it can write the scores file.
149 @node How Change Persona, Reading Persona, Why Change Persona, Users and Groups
150 @section How an Application Can Change Persona
151 @cindex @code{setuid} programs
153 The ability to change the persona of a process can be a source of
154 unintentional privacy violations, or even intentional abuse.  Because of
155 the potential for problems, changing persona is restricted to special
156 circumstances.
158 You can't arbitrarily set your user ID or group ID to anything you want;
159 only privileged processes can do that.  Instead, the normal way for a
160 program to change its persona is that it has been set up in advance to
161 change to a particular user or group.  This is the function of the setuid
162 and setgid bits of a file's access mode.  @xref{Permission Bits}.
164 When the setuid bit of an executable file is set, executing that file
165 automatically changes the effective user ID to the user that owns the
166 file.  Likewise, executing a file whose setgid bit is set changes the
167 effective group ID to the group of the file.  @xref{Executing a File}.
168 Creating a file that changes to a particular user or group ID thus
169 requires full access to that user or group ID.
171 @xref{File Attributes}, for a more general discussion of file modes and
172 accessibility.
174 A process can always change its effective user (or group) ID back to its
175 real ID.  Programs do this so as to turn off their special privileges
176 when they are not needed, which makes for more robustness.
178 @c !!! talk about _POSIX_SAVED_IDS
180 @node Reading Persona, Setting User ID, How Change Persona, Users and Groups
181 @section Reading the Persona of a Process
183 Here are detailed descriptions of the functions for reading the user and
184 group IDs of a process, both real and effective.  To use these
185 facilities, you must include the header files @file{sys/types.h} and
186 @file{unistd.h}.
187 @pindex unistd.h
188 @pindex sys/types.h
190 @comment sys/types.h
191 @comment POSIX.1
192 @deftp {Data Type} uid_t
193 This is an integer data type used to represent user IDs.  In the GNU
194 library, this is an alias for @code{unsigned int}.
195 @end deftp
197 @comment sys/types.h
198 @comment POSIX.1
199 @deftp {Data Type} gid_t
200 This is an integer data type used to represent group IDs.  In the GNU
201 library, this is an alias for @code{unsigned int}.
202 @end deftp
204 @comment unistd.h
205 @comment POSIX.1
206 @deftypefun uid_t getuid (void)
207 The @code{getuid} function returns the real user ID of the process.
208 @end deftypefun
210 @comment unistd.h
211 @comment POSIX.1
212 @deftypefun gid_t getgid (void)
213 The @code{getgid} function returns the real group ID of the process.
214 @end deftypefun
216 @comment unistd.h
217 @comment POSIX.1
218 @deftypefun uid_t geteuid (void)
219 The @code{geteuid} function returns the effective user ID of the process.
220 @end deftypefun
222 @comment unistd.h
223 @comment POSIX.1
224 @deftypefun gid_t getegid (void)
225 The @code{getegid} function returns the effective group ID of the process.
226 @end deftypefun
228 @comment unistd.h
229 @comment POSIX.1
230 @deftypefun int getgroups (int @var{count}, gid_t *@var{groups})
231 The @code{getgroups} function is used to inquire about the supplementary
232 group IDs of the process.  Up to @var{count} of these group IDs are
233 stored in the array @var{groups}; the return value from the function is
234 the number of group IDs actually stored.  If @var{count} is smaller than
235 the total number of supplementary group IDs, then @code{getgroups}
236 returns a value of @code{-1} and @code{errno} is set to @code{EINVAL}.
238 If @var{count} is zero, then @code{getgroups} just returns the total
239 number of supplementary group IDs.  On systems that do not support
240 supplementary groups, this will always be zero.
242 Here's how to use @code{getgroups} to read all the supplementary group
243 IDs:
245 @smallexample
246 @group
247 gid_t *
248 read_all_groups (void)
250   int ngroups = getgroups (0, NULL);
251   gid_t *groups
252     = (gid_t *) xmalloc (ngroups * sizeof (gid_t));
253   int val = getgroups (ngroups, groups);
254   if (val < 0)
255     @{
256       free (groups);
257       return NULL;
258     @}
259   return groups;
261 @end group
262 @end smallexample
263 @end deftypefun
265 @node Setting User ID, Setting Groups, Reading Persona, Users and Groups
266 @section Setting the User ID
268 This section describes the functions for altering the user ID (real
269 and/or effective) of a process.  To use these facilities, you must
270 include the header files @file{sys/types.h} and @file{unistd.h}.
271 @pindex unistd.h
272 @pindex sys/types.h
274 @comment unistd.h
275 @comment POSIX.1
276 @deftypefun int setuid (uid_t @var{newuid})
277 This function sets both the real and effective user ID of the process
278 to @var{newuid}, provided that the process has appropriate privileges.
279 @c !!! also sets saved-id
281 If the process is not privileged, then @var{newuid} must either be equal
282 to the real user ID or the saved user ID (if the system supports the
283 @code{_POSIX_SAVED_IDS} feature).  In this case, @code{setuid} sets only
284 the effective user ID and not the real user ID.
285 @c !!! xref to discussion of _POSIX_SAVED_IDS
287 The @code{setuid} function returns a value of @code{0} to indicate
288 successful completion, and a value of @code{-1} to indicate an error.
289 The following @code{errno} error conditions are defined for this
290 function:
292 @table @code
293 @item EINVAL
294 The value of the @var{newuid} argument is invalid.
296 @item EPERM
297 The process does not have the appropriate privileges; you do not
298 have permission to change to the specified ID.
299 @end table
300 @end deftypefun
302 @comment unistd.h
303 @comment BSD
304 @deftypefun int setreuid (uid_t @var{ruid}, uid_t @var{euid})
305 This function sets the real user ID of the process to @var{ruid} and the
306 effective user ID to @var{euid}.  If @var{ruid} is @code{-1}, it means
307 not to change the real user ID; likewise if @var{euid} is @code{-1}, it
308 means not to change the effective user ID.
310 The @code{setreuid} function exists for compatibility with 4.3 BSD Unix,
311 which does not support saved IDs.  You can use this function to swap the
312 effective and real user IDs of the process.  (Privileged processes are
313 not limited to this particular usage.)  If saved IDs are supported, you
314 should use that feature instead of this function.  @xref{Enable/Disable
315 Setuid}.
317 The return value is @code{0} on success and @code{-1} on failure.
318 The following @code{errno} error conditions are defined for this
319 function:
321 @table @code
322 @item EPERM
323 The process does not have the appropriate privileges; you do not
324 have permission to change to the specified ID.
325 @end table
326 @end deftypefun
328 @node Setting Groups, Enable/Disable Setuid, Setting User ID, Users and Groups
329 @section Setting the Group IDs
331 This section describes the functions for altering the group IDs (real
332 and effective) of a process.  To use these facilities, you must include
333 the header files @file{sys/types.h} and @file{unistd.h}.
334 @pindex unistd.h
335 @pindex sys/types.h
337 @comment unistd.h
338 @comment POSIX.1
339 @deftypefun int setgid (gid_t @var{newgid})
340 This function sets both the real and effective group ID of the process
341 to @var{newgid}, provided that the process has appropriate privileges.
342 @c !!! also sets saved-id
344 If the process is not privileged, then @var{newgid} must either be equal
345 to the real group ID or the saved group ID.  In this case, @code{setgid}
346 sets only the effective group ID and not the real group ID.
348 The return values and error conditions for @code{setgid} are the same
349 as those for @code{setuid}.
350 @end deftypefun
352 @comment unistd.h
353 @comment BSD
354 @deftypefun int setregid (gid_t @var{rgid}, fid_t @var{egid})
355 This function sets the real group ID of the process to @var{rgid} and
356 the effective group ID to @var{egid}.  If @var{rgid} is @code{-1}, it
357 means not to change the real group ID; likewise if @var{egid} is
358 @code{-1}, it means not to change the effective group ID.
360 The @code{setregid} function is provided for compatibility with 4.3 BSD
361 Unix, which does not support saved IDs.  You can use this function to
362 swap the effective and real group IDs of the process.  (Privileged
363 processes are not limited to this usage.)  If saved IDs are supported,
364 you should use that feature instead of using this function.
365 @xref{Enable/Disable Setuid}.
367 The return values and error conditions for @code{setregid} are the same
368 as those for @code{setreuid}.
369 @end deftypefun
371 The GNU system also lets privileged processes change their supplementary
372 group IDs.  To use @code{setgroups} or @code{initgroups}, your programs
373 should include the header file @file{grp.h}.
374 @pindex grp.h
376 @comment grp.h
377 @comment BSD
378 @deftypefun int setgroups (size_t @var{count}, gid_t *@var{groups})
379 This function sets the process's supplementary group IDs.  It can only
380 be called from privileged processes.  The @var{count} argument specifies
381 the number of group IDs in the array @var{groups}.
383 This function returns @code{0} if successful and @code{-1} on error.
384 The following @code{errno} error conditions are defined for this
385 function:
387 @table @code
388 @item EPERM
389 The calling process is not privileged.
390 @end table
391 @end deftypefun
393 @comment grp.h
394 @comment BSD
395 @deftypefun int initgroups (const char *@var{user}, gid_t @var{gid})
396 The @code{initgroups} function effectively calls @code{setgroups} to
397 set the process's supplementary group IDs to be the normal default for
398 the user name @var{user}.  The group ID @var{gid} is also included.
399 @c !!! explain that this works by reading the group file looking for
400 @c groups USER is a member of.
401 @end deftypefun
403 @node Enable/Disable Setuid, Setuid Program Example, Setting Groups, Users and Groups
404 @section Enabling and Disabling Setuid Access
406 A typical setuid program does not need its special access all of the
407 time.  It's a good idea to turn off this access when it isn't needed,
408 so it can't possibly give unintended access.
410 If the system supports the saved user ID feature, you can accomplish
411 this with @code{setuid}.  When the game program starts, its real user ID
412 is @code{jdoe}, its effective user ID is @code{games}, and its saved
413 user ID is also @code{games}.  The program should record both user ID
414 values once at the beginning, like this:
416 @smallexample
417 user_user_id = getuid ();
418 game_user_id = geteuid ();
419 @end smallexample
421 Then it can turn off game file access with
423 @smallexample
424 setuid (user_user_id);
425 @end smallexample
427 @noindent
428 and turn it on with
430 @smallexample
431 setuid (game_user_id);
432 @end smallexample
434 @noindent
435 Throughout this process, the real user ID remains @code{jdoe} and the
436 saved user ID remains @code{games}, so the program can always set its
437 effective user ID to either one.
439 On other systems that don't support the saved user ID feature, you can
440 turn setuid access on and off by using @code{setreuid} to swap the real
441 and effective user IDs of the process, as follows:
443 @smallexample
444 setreuid (geteuid (), getuid ());
445 @end smallexample
447 @noindent
448 This special case is always allowed---it cannot fail.
450 Why does this have the effect of toggling the setuid access?  Suppose a
451 game program has just started, and its real user ID is @code{jdoe} while
452 its effective user ID is @code{games}.  In this state, the game can
453 write the scores file.  If it swaps the two uids, the real becomes
454 @code{games} and the effective becomes @code{jdoe}; now the program has
455 only @code{jdoe} access.  Another swap brings @code{games} back to
456 the effective user ID and restores access to the scores file.
458 In order to handle both kinds of systems, test for the saved user ID
459 feature with a preprocessor conditional, like this:
461 @smallexample
462 #ifdef _POSIX_SAVED_IDS
463   setuid (user_user_id);
464 #else
465   setreuid (geteuid (), getuid ());
466 #endif
467 @end smallexample
469 @node Setuid Program Example, Tips for Setuid, Enable/Disable Setuid, Users and Groups
470 @section Setuid Program Example
472 Here's an example showing how to set up a program that changes its
473 effective user ID.
475 This is part of a game program called @code{caber-toss} that
476 manipulates a file @file{scores} that should be writable only by the game
477 program itself.  The program assumes that its executable
478 file will be installed with the set-user-ID bit set and owned by the
479 same user as the @file{scores} file.  Typically, a system
480 administrator will set up an account like @code{games} for this purpose.
482 The executable file is given mode @code{4755}, so that doing an
483 @samp{ls -l} on it produces output like:
485 @smallexample
486 -rwsr-xr-x   1 games    184422 Jul 30 15:17 caber-toss
487 @end smallexample
489 @noindent
490 The set-user-ID bit shows up in the file modes as the @samp{s}.
492 The scores file is given mode @code{644}, and doing an @samp{ls -l} on
493 it shows:
495 @smallexample
496 -rw-r--r--  1 games           0 Jul 31 15:33 scores
497 @end smallexample
499 Here are the parts of the program that show how to set up the changed
500 user ID.  This program is conditionalized so that it makes use of the
501 saved IDs feature if it is supported, and otherwise uses @code{setreuid}
502 to swap the effective and real user IDs.
504 @smallexample
505 #include <stdio.h>
506 #include <sys/types.h>
507 #include <unistd.h>
508 #include <stdlib.h>
511 /* @r{Save the effective and real UIDs.} */
513 static uid_t euid, ruid;
516 /* @r{Restore the effective UID to its original value.} */
518 void
519 do_setuid (void)
521   int status;
523 #ifdef _POSIX_SAVED_IDS
524   status = setuid (euid);
525 #else
526   status = setreuid (ruid, euid);
527 #endif
528   if (status < 0) @{
529     fprintf (stderr, "Couldn't set uid.\n");
530     exit (status);
531     @}
535 @group
536 /* @r{Set the effective UID to the real UID.} */
538 void
539 undo_setuid (void)
541   int status;
543 #ifdef _POSIX_SAVED_IDS
544   status = setuid (ruid);
545 #else
546   status = setreuid (euid, ruid);
547 #endif
548   if (status < 0) @{
549     fprintf (stderr, "Couldn't set uid.\n");
550     exit (status);
551     @}
553 @end group
555 /* @r{Main program.} */
558 main (void)
560   /* @r{Save the real and effective user IDs.}  */
561   ruid = getuid ();
562   euid = geteuid ();
563   undo_setuid ();
565   /* @r{Do the game and record the score.}  */
566   @dots{}
568 @end smallexample
570 Notice how the first thing the @code{main} function does is to set the
571 effective user ID back to the real user ID.  This is so that any other
572 file accesses that are performed while the user is playing the game use
573 the real user ID for determining permissions.  Only when the program
574 needs to open the scores file does it switch back to the original
575 effective user ID, like this:
577 @smallexample
578 /* @r{Record the score.} */
581 record_score (int score)
583   FILE *stream;
584   char *myname;
586   /* @r{Open the scores file.} */
587   do_setuid ();
588   stream = fopen (SCORES_FILE, "a");
589   undo_setuid ();
591 @group
592   /* @r{Write the score to the file.} */
593   if (stream)
594     @{
595       myname = cuserid (NULL);
596       if (score < 0)
597         fprintf (stream, "%10s: Couldn't lift the caber.\n", myname);
598       else
599         fprintf (stream, "%10s: %d feet.\n", myname, score);
600       fclose (stream);
601       return 0;
602     @}
603   else
604     return -1;
606 @end group
607 @end smallexample
609 @node Tips for Setuid, Who Logged In, Setuid Program Example, Users and Groups
610 @section Tips for Writing Setuid Programs
612 It is easy for setuid programs to give the user access that isn't
613 intended---in fact, if you want to avoid this, you need to be careful.
614 Here are some guidelines for preventing unintended access and
615 minimizing its consequences when it does occur:
617 @itemize @bullet
618 @item
619 Don't have @code{setuid} programs with privileged user IDs such as
620 @code{root} unless it is absolutely necessary.  If the resource is
621 specific to your particular program, it's better to define a new,
622 nonprivileged user ID or group ID just to manage that resource.
624 @item
625 Be cautious about using the @code{system} and @code{exec} functions in
626 combination with changing the effective user ID.  Don't let users of
627 your program execute arbitrary programs under a changed user ID.
628 Executing a shell is especially bad news.  Less obviously, the
629 @code{execlp} and @code{execvp} functions are a potential risk (since
630 the program they execute depends on the user's @code{PATH} environment
631 variable).
633 If you must @code{exec} another program under a changed ID, specify an
634 absolute file name (@pxref{File Name Resolution}) for the executable,
635 and make sure that the protections on that executable and @emph{all}
636 containing directories are such that ordinary users cannot replace it
637 with some other program.
639 @item
640 Only use the user ID controlling the resource in the part of the program
641 that actually uses that resource.  When you're finished with it, restore
642 the effective user ID back to the actual user's user ID.
643 @xref{Enable/Disable Setuid}.
645 @item
646 If the @code{setuid} part of your program needs to access other files
647 besides the controlled resource, it should verify that the real user
648 would ordinarily have permission to access those files.  You can use the
649 @code{access} function (@pxref{Access Permission}) to check this; it
650 uses the real user and group IDs, rather than the effective IDs.
651 @end itemize
653 @node Who Logged In, User Database, Tips for Setuid, Users and Groups
654 @section Identifying Who Logged In
655 @cindex login name, determining
656 @cindex user ID, determining
658 You can use the functions listed in this section to determine the login
659 name of the user who is running a process, and the name of the user who
660 logged in the current session.  See also the function @code{getuid} and
661 friends (@pxref{Reading Persona}).
663 The @code{getlogin} function is declared in @file{unistd.h}, while
664 @code{cuserid} and @code{L_cuserid} are declared in @file{stdio.h}.
665 @pindex stdio.h
666 @pindex unistd.h
668 @comment unistd.h
669 @comment POSIX.1
670 @deftypefun {char *} getlogin (void)
671 The @code{getlogin} function returns a pointer to a string containing the
672 name of the user logged in on the controlling terminal of the process,
673 or a null pointer if this information cannot be determined.  The string
674 is statically allocated and might be overwritten on subsequent calls to
675 this function or to @code{cuserid}.
676 @end deftypefun
678 @comment stdio.h
679 @comment POSIX.1
680 @deftypefun {char *} cuserid (char *@var{string})
681 The @code{cuserid} function returns a pointer to a string containing a
682 user name associated with the effective ID of the process.  If
683 @var{string} is not a null pointer, it should be an array that can hold
684 at least @code{L_cuserid} characters; the string is returned in this
685 array.  Otherwise, a pointer to a string in a static area is returned.
686 This string is statically allocated and might be overwritten on
687 subsequent calls to this function or to @code{getlogin}.
689 The use of this function is deprecated since it is marked to be
690 withdrawn in XPG4.2 and it is already removed in POSIX.1.
691 @end deftypefun
693 @comment stdio.h
694 @comment POSIX.1
695 @deftypevr Macro int L_cuserid
696 An integer constant that indicates how long an array you might need to
697 store a user name.
698 @end deftypevr
700 These functions let your program identify positively the user who is
701 running or the user who logged in this session.  (These can differ when
702 setuid programs are involved; @xref{Process Persona}.)  The user cannot
703 do anything to fool these functions.
705 For most purposes, it is more useful to use the environment variable
706 @code{LOGNAME} to find out who the user is.  This is more flexible
707 precisely because the user can set @code{LOGNAME} arbitrarily.
708 @xref{Standard Environment}.
710 @node User Database, Group Database, Who Logged In, Users and Groups
711 @section User Database
712 @cindex user database
713 @cindex password database
714 @pindex /etc/passwd
716 This section describes all about how to search and scan the database of
717 registered users.  The database itself is kept in the file
718 @file{/etc/passwd} on most systems, but on some systems a special
719 network server gives access to it.
721 @menu
722 * User Data Structure::         What each user record contains.
723 * Lookup User::                 How to look for a particular user.
724 * Scanning All Users::          Scanning the list of all users, one by one.
725 * Writing a User Entry::        How a program can rewrite a user's record.
726 @end menu
728 @node User Data Structure, Lookup User, User Database, User Database
729 @subsection The Data Structure that Describes a User
731 The functions and data structures for accessing the system user database
732 are declared in the header file @file{pwd.h}.
733 @pindex pwd.h
735 @comment pwd.h
736 @comment POSIX.1
737 @deftp {Data Type} {struct passwd}
738 The @code{passwd} data structure is used to hold information about
739 entries in the system user data base.  It has at least the following members:
741 @table @code
742 @item char *pw_name
743 The user's login name.
745 @item char *pw_passwd.
746 The encrypted password string.
748 @item uid_t pw_uid
749 The user ID number.
751 @item gid_t pw_gid
752 The user's default group ID number.
754 @item char *pw_gecos
755 A string typically containing the user's real name, and possibly other
756 information such as a phone number.
758 @item char *pw_dir
759 The user's home directory, or initial working directory.  This might be
760 a null pointer, in which case the interpretation is system-dependent.
762 @item char *pw_shell
763 The user's default shell, or the initial program run when the user logs in.
764 This might be a null pointer, indicating that the system default should
765 be used.
766 @end table
767 @end deftp
769 @node Lookup User, Scanning All Users, User Data Structure, User Database
770 @subsection Looking Up One User
771 @cindex converting user ID to user name
772 @cindex converting user name to user ID
774 You can search the system user database for information about a
775 specific user using @code{getpwuid} or @code{getpwnam}.  These
776 functions are declared in @file{pwd.h}.
778 @comment pwd.h
779 @comment POSIX.1
780 @deftypefun {struct passwd *} getpwuid (uid_t @var{uid})
781 This function returns a pointer to a statically-allocated structure
782 containing information about the user whose user ID is @var{uid}.  This
783 structure may be overwritten on subsequent calls to @code{getpwuid}.
785 A null pointer value indicates there is no user in the data base with
786 user ID @var{uid}.
787 @end deftypefun
789 @comment pwd.h
790 @comment POSIX.1c
791 @deftypefun int getpwuid_r (uid_t @var{uid}, struct passwd *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct passwd **@var{result})
792 This function is similar to @code{getpwuid} in that is returns
793 information about the user whose user ID is @var{uid}.  But the result
794 is not placed in a static buffer.  Instead the user supplied structure
795 pointed to by @var{result_buf} is filled with the information.  The
796 first @var{buflen} bytes of the additional buffer pointed to by
797 @var{buffer} are used to contain additional information, normally
798 strings which are pointed to by the elements of the result structure.
800 If the return value is @code{0} the pointer returned in @var{result}
801 points to the record which contains the wanted data (i.e., @var{result}
802 contains the value @var{result_buf}).  In case the return value is non
803 null there is no user in the data base with user ID @var{uid} or the
804 buffer @var{buffer} is too small to contain all the needed information.
805 In the later case the global @var{errno} variable is set to
806 @code{ERANGE}.
807 @end deftypefun
810 @comment pwd.h
811 @comment POSIX.1
812 @deftypefun {struct passwd *} getpwnam (const char *@var{name})
813 This function returns a pointer to a statically-allocated structure
814 containing information about the user whose user name is @var{name}.
815 This structure may be overwritten on subsequent calls to
816 @code{getpwnam}.
818 A null pointer value indicates there is no user named @var{name}.
819 @end deftypefun
821 @comment pwd.h
822 @comment POSIX.1c
823 @deftypefun int getpwnam_r (const char *@var{name}, struct passwd *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct passwd **@var{result})
824 This function is similar to @code{getpwnam} in that is returns
825 information about the user whose user name is @var{name}.  But the result
826 is not placed in a static buffer.  Instead the user supplied structure
827 pointed to by @var{result_buf} is filled with the information.  The
828 first @var{buflen} bytes of the additional buffer pointed to by
829 @var{buffer} are used to contain additional information, normally
830 strings which are pointed to by the elements of the result structure.
832 If the return value is @code{0} the pointer returned in @var{result}
833 points to the record which contains the wanted data (i.e., @var{result}
834 contains the value @var{result_buf}).  In case the return value is non
835 null there is no user in the data base with user name @var{name} or the
836 buffer @var{buffer} is too small to contain all the needed information.
837 In the later case the global @var{errno} variable is set to
838 @code{ERANGE}.
839 @end deftypefun
842 @node Scanning All Users, Writing a User Entry, Lookup User, User Database
843 @subsection Scanning the List of All Users
844 @cindex scanning the user list
846 This section explains how a program can read the list of all users in
847 the system, one user at a time.  The functions described here are
848 declared in @file{pwd.h}.
850 You can use the @code{fgetpwent} function to read user entries from a
851 particular file.
853 @comment pwd.h
854 @comment SVID
855 @deftypefun {struct passwd *} fgetpwent (FILE *@var{stream})
856 This function reads the next user entry from @var{stream} and returns a
857 pointer to the entry.  The structure is statically allocated and is
858 rewritten on subsequent calls to @code{fgetpwent}.  You must copy the
859 contents of the structure if you wish to save the information.
861 This stream must correspond to a file in the same format as the standard
862 password database file.  This function comes from System V.
863 @end deftypefun
865 @comment pwd.h
866 @comment GNU
867 @deftypefun int fgetpwent_r (FILE *@var{stream}, struct passwd *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct passwd **@var{result})
868 This function is similar to @code{fgetpwent} in that it reads the next
869 user entry from @var{stream}.  But the result is returned in the
870 structure pointed to by @var{result_buf}.  The
871 first @var{buflen} bytes of the additional buffer pointed to by
872 @var{buffer} are used to contain additional information, normally
873 strings which are pointed to by the elements of the result structure.
875 This stream must correspond to a file in the same format as the standard
876 password database file.
878 If the funciton returns null @var{result} points to the structure with
879 the wanted data (normally this is in @var{result_buf}).  If errors
880 occured the return value is non-null and @var{result} contains a null
881 pointer.
882 @end deftypefun
884 The way to scan all the entries in the user database is with
885 @code{setpwent}, @code{getpwent}, and @code{endpwent}.
887 @comment pwd.h
888 @comment SVID, BSD
889 @deftypefun void setpwent (void)
890 This function initializes a stream which @code{getpwent} and
891 @code{getpwent_r} use to read the user database.
892 @end deftypefun
894 @comment pwd.h
895 @comment POSIX.1
896 @deftypefun {struct passwd *} getpwent (void)
897 The @code{getpwent} function reads the next entry from the stream
898 initialized by @code{setpwent}.  It returns a pointer to the entry.  The
899 structure is statically allocated and is rewritten on subsequent calls
900 to @code{getpwent}.  You must copy the contents of the structure if you
901 wish to save the information.
903 A null pointer is returned in case no further entry is available.
904 @end deftypefun
906 @comment pwd.h
907 @comment GNU
908 @deftypefun int getpwent_r (struct passwd *@var{result_buf}, char *@var{buffer}, int @var{buflen}, struct passwd **@var{result})
909 This function is similar to @code{getpwent} in that it returns the next
910 entry from the stream initialized by @code{setpwent}.  But in contrast
911 to the @code{getpwent} function this function is reentrant since the
912 result is placed in the user supplied structure pointed to by
913 @var{result_buf}.  Additional data, normally the strings pointed to by
914 the elements of the result structure, are placed in the additional
915 buffer or length @var{buflen} starting at @var{buffer}.
917 If the function returns null @var{result} points to the structure with
918 the wanted data (normally this is in @var{result_buf}).  If errors
919 occured the return value is non-null and @var{result} contains a null
920 pointer.
921 @end deftypefun
923 @comment pwd.h
924 @comment SVID, BSD
925 @deftypefun void endpwent (void)
926 This function closes the internal stream used by @code{getpwent} or
927 @code{getpwent_r}.
928 @end deftypefun
930 @node Writing a User Entry,  , Scanning All Users, User Database
931 @subsection Writing a User Entry
933 @comment pwd.h
934 @comment SVID
935 @deftypefun int putpwent (const struct passwd *@var{p}, FILE *@var{stream})
936 This function writes the user entry @code{*@var{p}} to the stream
937 @var{stream}, in the format used for the standard user database
938 file.  The return value is zero on success and nonzero on failure.
940 This function exists for compatibility with SVID.  We recommend that you
941 avoid using it, because it makes sense only on the assumption that the
942 @code{struct passwd} structure has no members except the standard ones;
943 on a system which merges the traditional Unix data base with other
944 extended information about users, adding an entry using this function
945 would inevitably leave out much of the important information.
947 The function @code{putpwent} is declared in @file{pwd.h}.
948 @end deftypefun
950 @node Group Database, Netgroup Database, User Database, Users and Groups
951 @section Group Database
952 @cindex group database
953 @pindex /etc/group
955 This section describes all about how to search and scan the database of
956 registered groups.  The database itself is kept in the file
957 @file{/etc/group} on most systems, but on some systems a special network
958 service provides access to it.
960 @menu
961 * Group Data Structure::        What each group record contains.
962 * Lookup Group::                How to look for a particular group.
963 * Scanning All Groups::         Scanning the list of all groups.
964 @end menu
966 @node Group Data Structure, Lookup Group, Group Database, Group Database
967 @subsection The Data Structure for a Group
969 The functions and data structures for accessing the system group
970 database are declared in the header file @file{grp.h}.
971 @pindex grp.h
973 @comment grp.h
974 @comment POSIX.1
975 @deftp {Data Type} {struct group}
976 The @code{group} structure is used to hold information about an entry in
977 the system group database.  It has at least the following members:
979 @table @code
980 @item char *gr_name
981 The name of the group.
983 @item gid_t gr_gid
984 The group ID of the group.
986 @item char **gr_mem
987 A vector of pointers to the names of users in the group.  Each user name
988 is a null-terminated string, and the vector itself is terminated by a
989 null pointer.
990 @end table
991 @end deftp
993 @node Lookup Group, Scanning All Groups, Group Data Structure, Group Database
994 @subsection Looking Up One Group
995 @cindex converting group name to group ID
996 @cindex converting group ID to group name
998 You can search the group database for information about a specific
999 group using @code{getgrgid} or @code{getgrnam}.  These functions are
1000 declared in @file{grp.h}.
1002 @comment grp.h
1003 @comment POSIX.1
1004 @deftypefun {struct group *} getgrgid (gid_t @var{gid})
1005 This function returns a pointer to a statically-allocated structure
1006 containing information about the group whose group ID is @var{gid}.
1007 This structure may be overwritten by subsequent calls to
1008 @code{getgrgid}.
1010 A null pointer indicates there is no group with ID @var{gid}.
1011 @end deftypefun
1013 @comment grp.h
1014 @comment POSIX.1c
1015 @deftypefun int getgrgid_r (gid_t @var{gid}, struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1016 This function is similar to @code{getgrgid} in that is returns
1017 information about the group whose group ID is @var{gid}.  But the result
1018 is not placed in a static buffer.  Instead the user supplied structure
1019 pointed to by @var{result_buf} is filled with the information.  The
1020 first @var{buflen} bytes of the additional buffer pointed to by
1021 @var{buffer} are used to contain additional information, normally
1022 strings which are pointed to by the elements of the result structure.
1024 If the return value is @code{0} the pointer returned in @var{result}
1025 points to the record which contains the wanted data (i.e., @var{result}
1026 contains the value @var{result_buf}).  In case the return value is non
1027 null there is no group in the data base with group ID @var{gid} or the
1028 buffer @var{buffer} is too small to contain all the needed information.
1029 In the later case the global @var{errno} variable is set to
1030 @code{ERANGE}.
1031 @end deftypefun
1033 @comment grp.h
1034 @comment SVID, BSD
1035 @deftypefun {struct group *} getgrnam (const char *@var{name})
1036 This function returns a pointer to a statically-allocated structure
1037 containing information about the group whose group name is @var{name}.
1038 This structure may be overwritten by subsequent calls to
1039 @code{getgrnam}.
1041 A null pointer indicates there is no group named @var{name}.
1042 @end deftypefun
1044 @comment grp.h
1045 @comment POSIX.1c
1046 @deftypefun int getgrnam_r (const char *@var{name}, struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1047 This function is similar to @code{getgrnam} in that is returns
1048 information about the group whose group name is @var{name}.  But the result
1049 is not placed in a static buffer.  Instead the user supplied structure
1050 pointed to by @var{result_buf} is filled with the information.  The
1051 first @var{buflen} bytes of the additional buffer pointed to by
1052 @var{buffer} are used to contain additional information, normally
1053 strings which are pointed to by the elements of the result structure.
1055 If the return value is @code{0} the pointer returned in @var{result}
1056 points to the record which contains the wanted data (i.e., @var{result}
1057 contains the value @var{result_buf}).  In case the return value is non
1058 null there is no group in the data base with group name @var{name} or the
1059 buffer @var{buffer} is too small to contain all the needed information.
1060 In the later case the global @var{errno} variable is set to
1061 @code{ERANGE}.
1062 @end deftypefun
1064 @node Scanning All Groups,  , Lookup Group, Group Database
1065 @subsection Scanning the List of All Groups
1066 @cindex scanning the group list
1068 This section explains how a program can read the list of all groups in
1069 the system, one group at a time.  The functions described here are
1070 declared in @file{grp.h}.
1072 You can use the @code{fgetgrent} function to read group entries from a
1073 particular file.
1075 @comment grp.h
1076 @comment SVID
1077 @deftypefun {struct group *} fgetgrent (FILE *@var{stream})
1078 The @code{fgetgrent} function reads the next entry from @var{stream}.
1079 It returns a pointer to the entry.  The structure is statically
1080 allocated and is rewritten on subsequent calls to @code{fgetgrent}.  You
1081 must copy the contents of the structure if you wish to save the
1082 information.
1084 The stream must correspond to a file in the same format as the standard
1085 group database file.
1086 @end deftypefun
1088 @comment grp.h
1089 @comment GNU
1090 @deftypefun int fgetgrent_r (FILE *@var{stream}, struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1091 This function is similar to @code{fgetgrent} in that it reads the next
1092 user entry from @var{stream}.  But the result is returned in the
1093 structure pointed to by @var{result_buf}.  The
1094 first @var{buflen} bytes of the additional buffer pointed to by
1095 @var{buffer} are used to contain additional information, normally
1096 strings which are pointed to by the elements of the result structure.
1098 This stream must correspond to a file in the same format as the standard
1099 group database file.
1101 If the funciton returns null @var{result} points to the structure with
1102 the wanted data (normally this is in @var{result_buf}).  If errors
1103 occured the return value is non-null and @var{result} contains a null
1104 pointer.
1105 @end deftypefun
1107 The way to scan all the entries in the group database is with
1108 @code{setgrent}, @code{getgrent}, and @code{endgrent}.
1110 @comment grp.h
1111 @comment SVID, BSD
1112 @deftypefun void setgrent (void)
1113 This function initializes a stream for reading from the group data base.
1114 You use this stream by calling @code{getgrent} or @code{getgrent_r}.
1115 @end deftypefun
1117 @comment grp.h
1118 @comment SVID, BSD
1119 @deftypefun {struct group *} getgrent (void)
1120 The @code{getgrent} function reads the next entry from the stream
1121 initialized by @code{setgrent}.  It returns a pointer to the entry.  The
1122 structure is statically allocated and is rewritten on subsequent calls
1123 to @code{getgrent}.  You must copy the contents of the structure if you
1124 wish to save the information.
1125 @end deftypefun
1127 @comment grp.h
1128 @comment GNU
1129 @deftypefun int getgrent_r (struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1130 This function is similar to @code{getgrent} in that it returns the next
1131 entry from the stream initialized by @code{setgrent}.  But in contrast
1132 to the @code{getgrent} function this function is reentrant since the
1133 result is placed in the user supplied structure pointed to by
1134 @var{result_buf}.  Additional data, normally the strings pointed to by
1135 the elements of the result structure, are placed in the additional
1136 buffer or length @var{buflen} starting at @var{buffer}.
1138 If the function returns null @var{result} points to the structure with
1139 the wanted data (normally this is in @var{result_buf}).  If errors
1140 occured the return value is non-null and @var{result} contains a null
1141 pointer.
1142 @end deftypefun
1144 @comment grp.h
1145 @comment SVID, BSD
1146 @deftypefun void endgrent (void)
1147 This function closes the internal stream used by @code{getgrent} or
1148 @code{getgrent_r}.
1149 @end deftypefun
1151 @node Netgroup Database, Database Example, Group Database, Users and Groups
1152 @section Netgroup Database
1154 @menu
1155 * Netgroup Data::                  Data in the Netgroup database and where
1156                                    it comes from.
1157 * Lookup Netgroup::                How to look for a particular netgroup.
1158 * Netgroup Membership::            How to test for netgroup membership.
1159 @end menu
1161 @node Netgroup Data, Lookup Netgroup, Netgroup Database, Netgroup Database
1162 @subsection Netgroup Data
1164 @cindex Netgroup
1165 Sometimes it is useful group users according to other criterias like the
1166 ones used in the @xref{Group Database}.  E.g., it is useful to associate
1167 a certain group of users with a certain machine.  On the other hand
1168 grouping of host names is not supported so far.
1170 In Sun Microsystems SunOS appeared a new kind of database, the netgroup
1171 database.  It allows to group hosts, users, and domain freely, giving
1172 them individual names.  More concrete: a netgroup is a list of triples
1173 consisting of a host name, a user name, and a domain name, where any of
1174 the entries can be a wildcard entry, matching all inputs.  A last
1175 possibility is that names of other netgroups can also be given in the
1176 list specifying a netgroup.  So one can construct arbitrary hierachies
1177 without loops.
1179 Sun's implementation allows netgroups only for the @code{nis} or
1180 @code{nisplus} service @pxref{Services in the NSS configuration}.  The
1181 implementation in the GNU C library has no such restriction.  An entry
1182 in either of the input services must have the following form:
1184 @smallexample
1185 @var{groupname} ( @var{groupname} | @code{(}@var{hostname}@code{,}@var{username}@code{,}@code{domainname}@code{)} )+
1186 @end smallexample
1188 Any of the fields in the triple can be empty which means anything
1189 matches.  While describing te functions we will see that the opposite
1190 case is useful as well.  I.e., there shall be entries which will not
1191 match any input.  For entries like a name consisting of the single
1192 character @code{-} shall be used.
1194 @node Lookup Netgroup, Netgroup Membership, Netgroup Data, Netgroup Database
1195 @subsection Looking up one Netgroup
1197 The lookup functions for netgroups are a bit different to all other
1198 system database handling functions.  Since a single netgroup can contain
1199 many entries a two-step process is needed.  First a single netgroup is
1200 selected and then one can iterate over all entries in this netgroup.
1201 These functions are declared in @file{netdb.h}.
1203 @comment netdb.h
1204 @deftypefun int setnetgrent (const char *@var{netgroup})
1205 A call to this function initializes the internal state of the library to
1206 allow following calls of the @code{getnetgrent} iterate over all entries
1207 in the netgroup with name @var{netgroup}.
1209 When the call is successful (i.e., when a netgroup with this name exist)
1210 the return value is @code{1}.  When the return value is @code{0} no
1211 netgroup of this name is known or some other error occured.
1212 @end deftypefun
1214 It is important to remember that there is only one single state for
1215 iterating the netgroups.  Even if the programmer uses the
1216 @code{getnetgrent_r} function the result is not really reentrant since
1217 always only one single netgroup at a time can be processed.  If the
1218 program needs to process more than one netgroup simultaneously she
1219 must protect this by using external locking.  This problem was
1220 introduced in the original netgroups implementation in SunOS and since
1221 we must stay compatible it is not possible to change this.
1223 Some other functions also use the netgroups state.  Currently these are
1224 the @code{innetgr} function and parts of the implementation of the
1225 @code{compat} service part of the NSS implementation.
1227 @comment netdb.h
1228 @deftypefun int getnetgrent (char **@var{hostp}, char **@var{userp}, char **@var{domainp})
1229 This function returns the next unprocessed entry of the currently
1230 selected netgroup.  The string pointers, which addresses are passed in
1231 the arguments @var{hostp}, @var{userp}, and @var{domainp}, will contain
1232 after a successful call pointers to appropriate strings.  If the string
1233 in the next entry is empty the pointer has the value @code{NULL}.
1234 The returned string pointers are only valid unless no of the netgroup
1235 related functions are called.
1237 The return value is @code{1} if the next entry was successfully read.  A
1238 value of @code{0} means no further entry exist or internal errors occured.
1239 @end deftypefun
1241 @comment netdb.h
1242 @deftypefun int getnetgrent_r (char **@var{hostp}, char **@var{userp}, char **@var{domainp}, char *@var{buffer}, int @var{buflen})
1243 This function is similar to @code{getnetgrent} with only one exception:
1244 the strings the three string pointers @var{hostp}, @var{userp}, and
1245 @var{domainp} point to, are placed in the buffer of @var{buflen} bytes
1246 starting at @var{buffer}.  This means the returned values are valid
1247 even after other netgroup related functions are called.
1249 The return value is @code{1} if the next entry was successfully read and
1250 the buffer contains enough room to place the strings in it.  @code{0} is
1251 returned in case no more entries are found, the buffer is too small, or
1252 internal errors occured.
1254 This function is a GNU extension.  The original implementation in the
1255 SunOS libc does not provide this function.
1256 @end deftypefun
1258 @comment netdb.h
1259 @deftypefun void endnetgrent (void)
1260 This function free all buffers which were allocated to process the last
1261 selected netgroup.  As a result all string pointers returned by calls
1262 to @code{getnetgrent} are invalid afterwards.
1263 @end deftypefun
1265 @node Netgroup Membership,  , Lookup Netgroup, Netgroup Database
1266 @subsection Testing for Netgroup Membership
1268 It is often not necessary to scan the whole netgroup since often the
1269 only interesting question is whether a given entry is part of the
1270 selected netgroup.
1272 @comment netdb.h
1273 @deftypefun int innetgr (const char *@var{netgroup}, const char *@var{host}, const char *@var{user}, const char *@var{domain})
1274 This function tests whether the triple specified by the parameters
1275 @var{hostp}, @var{userp}, and @var{domainp} is part of the netgroup
1276 @var{netgroup}.  Using this function has the advantage that
1278 @enumerate
1279 @item
1280 no other netgroup function can use the global netgroup state since
1281 internal locking is used and
1282 @item
1283 the function is implemented more efficiently than successive calls
1284 to the other @code{set}/@code{get}/@code{endnetgrent} functions.
1285 @end enumerate
1287 Any of the pointers @var{hostp}, @var{userp}, and @var{domainp} can be
1288 @code{NULL} which means any value is excepted in this position.  This is
1289 also true for the name @code{-} which should not match any other string
1290 otherwise.
1292 The return value is @code{1} if an entry matching the given triple is
1293 found in the netgroup.  The return value is @code{0} is the netgroup
1294 itself is not found, the netgroup does not contain the triple or
1295 internal errors occured.
1296 @end deftypefun
1298 @node Database Example,  , Netgroup Database, Users and Groups
1299 @section User and Group Database Example
1301 Here is an example program showing the use of the system database inquiry
1302 functions.  The program prints some information about the user running
1303 the program.
1305 @smallexample
1306 @include db.c.texi
1307 @end smallexample
1309 Here is some output from this program:
1311 @smallexample
1312 I am Throckmorton Snurd.
1313 My login name is snurd.
1314 My uid is 31093.
1315 My home directory is /home/fsg/snurd.
1316 My default shell is /bin/sh.
1317 My default group is guest (12).
1318 The members of this group are:
1319   friedman
1320   tami
1321 @end smallexample