* libio/fileops.c (_IO_new_file_underflow): Set error indicator
[glibc/pb-stable.git] / manual / users.texi
blob7317f5efa20de4c8490230406ee60378cabf2902
1 @node Users and Groups, System Information, Name Service Switch, Top
2 @c %MENU% How users are identified and classified
3 @chapter Users and Groups
5 Every user who can log in on the system is identified by a unique number
6 called the @dfn{user ID}.  Each process has an effective user ID which
7 says which user's access permissions it has.
9 Users are classified into @dfn{groups} for access control purposes.  Each
10 process has one or more @dfn{group ID values} which say which groups the
11 process can use for access to files.
13 The effective user and group IDs of a process collectively form its
14 @dfn{persona}.  This determines which files the process can access.
15 Normally, a process inherits its persona from the parent process, but
16 under special circumstances a process can change its persona and thus
17 change its access permissions.
19 Each file in the system also has a user ID and a group ID.  Access
20 control works by comparing the user and group IDs of the file with those
21 of the running process.
23 The system keeps a database of all the registered users, and another
24 database of all the defined groups.  There are library functions you
25 can use to examine these databases.
27 @menu
28 * User and Group IDs::          Each user has a unique numeric ID;
29                                  likewise for groups.
30 * Process Persona::             The user IDs and group IDs of a process.
31 * Why Change Persona::          Why a program might need to change
32                                  its user and/or group IDs.
33 * How Change Persona::          Changing the user and group IDs.
34 * Reading Persona::             How to examine the user and group IDs.
36 * Setting User ID::             Functions for setting the user ID.
37 * Setting Groups::              Functions for setting the group IDs.
39 * Enable/Disable Setuid::       Turning setuid access on and off.
40 * Setuid Program Example::      The pertinent parts of one sample program.
41 * Tips for Setuid::             How to avoid granting unlimited access.
43 * Who Logged In::               Getting the name of the user who logged in,
44                                  or of the real user ID of the current process.
46 * User Accounting Database::    Keeping information about users and various
47                                  actions in databases.
49 * User Database::               Functions and data structures for
50                                  accessing the user database.
51 * Group Database::              Functions and data structures for
52                                  accessing the group database.
53 * Database Example::            Example program showing the use of database
54                                  inquiry functions.
55 * Netgroup Database::           Functions for accessing the netgroup database.
56 @end menu
58 @node User and Group IDs
59 @section User and Group IDs
61 @cindex login name
62 @cindex user name
63 @cindex user ID
64 Each user account on a computer system is identified by a @dfn{user
65 name} (or @dfn{login name}) and @dfn{user ID}.  Normally, each user name
66 has a unique user ID, but it is possible for several login names to have
67 the same user ID.  The user names and corresponding user IDs are stored
68 in a data base which you can access as described in @ref{User Database}.
70 @cindex group name
71 @cindex group ID
72 Users are classified in @dfn{groups}.  Each user name belongs to one
73 @dfn{default group} and may also belong to any number of
74 @dfn{supplementary groups}. Users who are members of the same group can
75 share resources (such as files) that are not accessible to users who are
76 not a member of that group.  Each group has a @dfn{group name} and
77 @dfn{group ID}.  @xref{Group Database}, for how to find information
78 about a group ID or group name.
80 @node Process Persona
81 @section The Persona of a Process
82 @cindex persona
83 @cindex effective user ID
84 @cindex effective group ID
85 @cindex supplementary group IDs
87 @c When Hurd is more widely used, explain multiple effective user IDs
88 @c here. -zw
89 At any time, each process has an @dfn{effective user ID}, a @dfn{effective
90 group ID}, and a set of @dfn{supplementary group IDs}.  These IDs
91 determine the privileges of the process.  They are collectively
92 called the @dfn{persona} of the process, because they determine ``who it
93 is'' for purposes of access control.
95 Your login shell starts out with a persona which consists of your user
96 ID, your default group ID, and your supplementary group IDs (if you are
97 in more than one group).  In normal circumstances, all your other processes
98 inherit these values.
100 @cindex real user ID
101 @cindex real group ID
102 A process also has a @dfn{real user ID} which identifies the user who
103 created the process, and a @dfn{real group ID} which identifies that
104 user's default group.  These values do not play a role in access
105 control, so we do not consider them part of the persona.  But they are
106 also important.
108 Both the real and effective user ID can be changed during the lifetime
109 of a process.  @xref{Why Change Persona}.
111 For details on how a process's effective user ID and group IDs affect
112 its permission to access files, see @ref{Access Permission}.
114 The effective user ID of a process also controls permissions for sending
115 signals using the @code{kill} function.  @xref{Signaling Another
116 Process}.
118 Finally, there are many operations which can only be performed by a
119 process whose effective user ID is zero.  A process with this user ID is
120 a @dfn{privileged process}.  Commonly the user name @code{root} is
121 associated with user ID 0, but there may be other user names with this
123 @c !!! should mention POSIX capabilities here.
125 @node Why Change Persona
126 @section Why Change the Persona of a Process?
128 The most obvious situation where it is necessary for a process to change
129 its user and/or group IDs is the @code{login} program.  When
130 @code{login} starts running, its user ID is @code{root}.  Its job is to
131 start a shell whose user and group IDs are those of the user who is
132 logging in.  (To accomplish this fully, @code{login} must set the real
133 user and group IDs as well as its persona.  But this is a special case.)
135 The more common case of changing persona is when an ordinary user
136 program needs access to a resource that wouldn't ordinarily be
137 accessible to the user actually running it.
139 For example, you may have a file that is controlled by your program but
140 that shouldn't be read or modified directly by other users, either
141 because it implements some kind of locking protocol, or because you want
142 to preserve the integrity or privacy of the information it contains.
143 This kind of restricted access can be implemented by having the program
144 change its effective user or group ID to match that of the resource.
146 Thus, imagine a game program that saves scores in a file.  The game
147 program itself needs to be able to update this file no matter who is
148 running it, but if users can write the file without going through the
149 game, they can give themselves any scores they like.  Some people
150 consider this undesirable, or even reprehensible.  It can be prevented
151 by creating a new user ID and login name (say, @code{games}) to own the
152 scores file, and make the file writable only by this user.  Then, when
153 the game program wants to update this file, it can change its effective
154 user ID to be that for @code{games}.  In effect, the program must
155 adopt the persona of @code{games} so it can write the scores file.
157 @node How Change Persona
158 @section How an Application Can Change Persona
159 @cindex @code{setuid} programs
160 @cindex saved set-user-ID
161 @cindex saved set-group-ID
162 @cindex @code{_POSIX_SAVED_IDS}
164 The ability to change the persona of a process can be a source of
165 unintentional privacy violations, or even intentional abuse.  Because of
166 the potential for problems, changing persona is restricted to special
167 circumstances.
169 You can't arbitrarily set your user ID or group ID to anything you want;
170 only privileged processes can do that.  Instead, the normal way for a
171 program to change its persona is that it has been set up in advance to
172 change to a particular user or group.  This is the function of the setuid
173 and setgid bits of a file's access mode.  @xref{Permission Bits}.
175 When the setuid bit of an executable file is on, executing that file
176 gives the process a third user ID: the @dfn{file user ID}.  This ID is
177 set to the owner ID of the file.  The system then changes the effective
178 user ID to the file user ID.  The real user ID remains as it was.
179 Likewise, if the setgid bit is on, the process is given a @dfn{file
180 group ID} equal to the group ID of the file, and its effective group ID
181 is changed to the file group ID.
183 If a process has a file ID (user or group), then it can at any time
184 change its effective ID to its real ID and back to its file ID.
185 Programs use this feature to relinquish their special privileges except
186 when they actually need them.  This makes it less likely that they can
187 be tricked into doing something inappropriate with their privileges.
189 @strong{Portability Note:} Older systems do not have file IDs.
190 To determine if a system has this feature, you can test the compiler
191 define @code{_POSIX_SAVED_IDS}.  (In the POSIX standard, file IDs are
192 known as saved IDs.)
194 @xref{File Attributes}, for a more general discussion of file modes and
195 accessibility.
197 @node Reading Persona
198 @section Reading the Persona of a Process
200 Here are detailed descriptions of the functions for reading the user and
201 group IDs of a process, both real and effective.  To use these
202 facilities, you must include the header files @file{sys/types.h} and
203 @file{unistd.h}.
204 @pindex unistd.h
205 @pindex sys/types.h
207 @comment sys/types.h
208 @comment POSIX.1
209 @deftp {Data Type} uid_t
210 This is an integer data type used to represent user IDs.  In the GNU
211 library, this is an alias for @code{unsigned int}.
212 @end deftp
214 @comment sys/types.h
215 @comment POSIX.1
216 @deftp {Data Type} gid_t
217 This is an integer data type used to represent group IDs.  In the GNU
218 library, this is an alias for @code{unsigned int}.
219 @end deftp
221 @comment unistd.h
222 @comment POSIX.1
223 @deftypefun uid_t getuid (void)
224 The @code{getuid} function returns the real user ID of the process.
225 @end deftypefun
227 @comment unistd.h
228 @comment POSIX.1
229 @deftypefun gid_t getgid (void)
230 The @code{getgid} function returns the real group ID of the process.
231 @end deftypefun
233 @comment unistd.h
234 @comment POSIX.1
235 @deftypefun uid_t geteuid (void)
236 The @code{geteuid} function returns the effective user ID of the process.
237 @end deftypefun
239 @comment unistd.h
240 @comment POSIX.1
241 @deftypefun gid_t getegid (void)
242 The @code{getegid} function returns the effective group ID of the process.
243 @end deftypefun
245 @comment unistd.h
246 @comment POSIX.1
247 @deftypefun int getgroups (int @var{count}, gid_t *@var{groups})
248 The @code{getgroups} function is used to inquire about the supplementary
249 group IDs of the process.  Up to @var{count} of these group IDs are
250 stored in the array @var{groups}; the return value from the function is
251 the number of group IDs actually stored.  If @var{count} is smaller than
252 the total number of supplementary group IDs, then @code{getgroups}
253 returns a value of @code{-1} and @code{errno} is set to @code{EINVAL}.
255 If @var{count} is zero, then @code{getgroups} just returns the total
256 number of supplementary group IDs.  On systems that do not support
257 supplementary groups, this will always be zero.
259 Here's how to use @code{getgroups} to read all the supplementary group
260 IDs:
262 @smallexample
263 @group
264 gid_t *
265 read_all_groups (void)
267   int ngroups = getgroups (0, NULL);
268   gid_t *groups
269     = (gid_t *) xmalloc (ngroups * sizeof (gid_t));
270   int val = getgroups (ngroups, groups);
271   if (val < 0)
272     @{
273       free (groups);
274       return NULL;
275     @}
276   return groups;
278 @end group
279 @end smallexample
280 @end deftypefun
282 @node Setting User ID
283 @section Setting the User ID
285 This section describes the functions for altering the user ID (real
286 and/or effective) of a process.  To use these facilities, you must
287 include the header files @file{sys/types.h} and @file{unistd.h}.
288 @pindex unistd.h
289 @pindex sys/types.h
291 @comment unistd.h
292 @comment POSIX.1
293 @deftypefun int seteuid (uid_t @var{neweuid})
294 This function sets the effective user ID of a process to @var{newuid},
295 provided that the process is allowed to change its effective user ID.  A
296 privileged process (effective user ID zero) can change its effective
297 user ID to any legal value.  An unprivileged process with a file user ID
298 can change its effective user ID to its real user ID or to its file user
299 ID.  Otherwise, a process may not change its effective user ID at all.
301 The @code{seteuid} function returns a value of @code{0} to indicate
302 successful completion, and a value of @code{-1} to indicate an error.
303 The following @code{errno} error conditions are defined for this
304 function:
306 @table @code
307 @item EINVAL
308 The value of the @var{newuid} argument is invalid.
310 @item EPERM
311 The process may not change to the specified ID.
312 @end table
314 Older systems (those without the @code{_POSIX_SAVED_IDS} feature) do not
315 have this function.
316 @end deftypefun
318 @comment unistd.h
319 @comment POSIX.1
320 @deftypefun int setuid (uid_t @var{newuid})
321 If the calling process is privileged, this function sets both the real
322 and effective user ID of the process to @var{newuid}.  It also deletes
323 the file user ID of the process, if any.  @var{newuid} may be any
324 legal value.  (Once this has been done, there is no way to recover the
325 old effective user ID.)
327 If the process is not privileged, and the system supports the
328 @code{_POSIX_SAVED_IDS} feature, then this function behaves like
329 @code{seteuid}.
331 The return values and error conditions are the same as for @code{seteuid}.
332 @end deftypefun
334 @comment unistd.h
335 @comment BSD
336 @deftypefun int setreuid (uid_t @var{ruid}, uid_t @var{euid})
337 This function sets the real user ID of the process to @var{ruid} and the
338 effective user ID to @var{euid}.  If @var{ruid} is @code{-1}, it means
339 not to change the real user ID; likewise if @var{euid} is @code{-1}, it
340 means not to change the effective user ID.
342 The @code{setreuid} function exists for compatibility with 4.3 BSD Unix,
343 which does not support file IDs.  You can use this function to swap the
344 effective and real user IDs of the process.  (Privileged processes are
345 not limited to this particular usage.)  If file IDs are supported, you
346 should use that feature instead of this function.  @xref{Enable/Disable
347 Setuid}.
349 The return value is @code{0} on success and @code{-1} on failure.
350 The following @code{errno} error conditions are defined for this
351 function:
353 @table @code
354 @item EPERM
355 The process does not have the appropriate privileges; you do not
356 have permission to change to the specified ID.
357 @end table
358 @end deftypefun
360 @node Setting Groups
361 @section Setting the Group IDs
363 This section describes the functions for altering the group IDs (real
364 and effective) of a process.  To use these facilities, you must include
365 the header files @file{sys/types.h} and @file{unistd.h}.
366 @pindex unistd.h
367 @pindex sys/types.h
369 @comment unistd.h
370 @comment POSIX.1
371 @deftypefun int setegid (gid_t @var{newgid})
372 This function sets the effective group ID of the process to
373 @var{newgid}, provided that the process is allowed to change its group
374 ID.  Just as with @code{seteuid}, if the process is privileged it may
375 change its effective group ID to any value; if it isn't, but it has a
376 file group ID, then it may change to its real group ID or file group ID;
377 otherwise it may not change its effective group ID.
379 Note that a process is only privileged if its effective @emph{user} ID
380 is zero.  The effective group ID only affects access permissions.
382 The return values and error conditions for @code{setegid} are the same
383 as those for @code{seteuid}.
385 This function is only present if @code{_POSIX_SAVED_IDS} is defined.
386 @end deftypefun
388 @comment unistd.h
389 @comment POSIX.1
390 @deftypefun int setgid (gid_t @var{newgid})
391 This function sets both the real and effective group ID of the process
392 to @var{newgid}, provided that the process is privileged.  It also
393 deletes the file group ID, if any.
395 If the process is not privileged, then @code{setgid} behaves like
396 @code{setegid}.
398 The return values and error conditions for @code{setgid} are the same
399 as those for @code{seteuid}.
400 @end deftypefun
402 @comment unistd.h
403 @comment BSD
404 @deftypefun int setregid (gid_t @var{rgid}, gid_t @var{egid})
405 This function sets the real group ID of the process to @var{rgid} and
406 the effective group ID to @var{egid}.  If @var{rgid} is @code{-1}, it
407 means not to change the real group ID; likewise if @var{egid} is
408 @code{-1}, it means not to change the effective group ID.
410 The @code{setregid} function is provided for compatibility with 4.3 BSD
411 Unix, which does not support file IDs.  You can use this function to
412 swap the effective and real group IDs of the process.  (Privileged
413 processes are not limited to this usage.)  If file IDs are supported,
414 you should use that feature instead of using this function.
415 @xref{Enable/Disable Setuid}.
417 The return values and error conditions for @code{setregid} are the same
418 as those for @code{setreuid}.
419 @end deftypefun
421 @code{setuid} and @code{setgid} behave differently depending on whether
422 the effective user ID at the time is zero.  If it is not zero, they
423 behave like @code{seteuid} and @code{setegid}.  If it is, they change
424 both effective and real IDs and delete the file ID.  To avoid confusion,
425 we recommend you always use @code{seteuid} and @code{setegid} except
426 when you know the effective user ID is zero and your intent is to change
427 the persona permanently.  This case is rare---most of the programs that
428 need it, such as @code{login} and @code{su}, have already been written.
430 Note that if your program is setuid to some user other than @code{root},
431 there is no way to drop privileges permanently.
433 The system also lets privileged processes change their supplementary
434 group IDs.  To use @code{setgroups} or @code{initgroups}, your programs
435 should include the header file @file{grp.h}.
436 @pindex grp.h
438 @comment grp.h
439 @comment BSD
440 @deftypefun int setgroups (size_t @var{count}, gid_t *@var{groups})
441 This function sets the process's supplementary group IDs.  It can only
442 be called from privileged processes.  The @var{count} argument specifies
443 the number of group IDs in the array @var{groups}.
445 This function returns @code{0} if successful and @code{-1} on error.
446 The following @code{errno} error conditions are defined for this
447 function:
449 @table @code
450 @item EPERM
451 The calling process is not privileged.
452 @end table
453 @end deftypefun
455 @comment grp.h
456 @comment BSD
457 @deftypefun int initgroups (const char *@var{user}, gid_t @var{gid})
458 The @code{initgroups} function sets the process's supplementary group
459 IDs to be the normal default for the user name @var{user}. If @var{gid}
460 is not -1, it includes that group also.
462 This function works by scanning the group database for all the groups
463 @var{user} belongs to.  It then calls @code{setgroups} with the list it
464 has constructed.
466 The return values and error conditions are the same as for
467 @code{setgroups}.
468 @end deftypefun
470 @node Enable/Disable Setuid
471 @section Enabling and Disabling Setuid Access
473 A typical setuid program does not need its special access all of the
474 time.  It's a good idea to turn off this access when it isn't needed,
475 so it can't possibly give unintended access.
477 If the system supports the @code{_POSIX_SAVED_IDS} feature, you can
478 accomplish this with @code{seteuid}.  When the game program starts, its
479 real user ID is @code{jdoe}, its effective user ID is @code{games}, and
480 its saved user ID is also @code{games}.  The program should record both
481 user ID values once at the beginning, like this:
483 @smallexample
484 user_user_id = getuid ();
485 game_user_id = geteuid ();
486 @end smallexample
488 Then it can turn off game file access with
490 @smallexample
491 seteuid (user_user_id);
492 @end smallexample
494 @noindent
495 and turn it on with
497 @smallexample
498 seteuid (game_user_id);
499 @end smallexample
501 @noindent
502 Throughout this process, the real user ID remains @code{jdoe} and the
503 file user ID remains @code{games}, so the program can always set its
504 effective user ID to either one.
506 On other systems that don't support file user IDs, you can
507 turn setuid access on and off by using @code{setreuid} to swap the real
508 and effective user IDs of the process, as follows:
510 @smallexample
511 setreuid (geteuid (), getuid ());
512 @end smallexample
514 @noindent
515 This special case is always allowed---it cannot fail.
517 Why does this have the effect of toggling the setuid access?  Suppose a
518 game program has just started, and its real user ID is @code{jdoe} while
519 its effective user ID is @code{games}.  In this state, the game can
520 write the scores file.  If it swaps the two uids, the real becomes
521 @code{games} and the effective becomes @code{jdoe}; now the program has
522 only @code{jdoe} access.  Another swap brings @code{games} back to
523 the effective user ID and restores access to the scores file.
525 In order to handle both kinds of systems, test for the saved user ID
526 feature with a preprocessor conditional, like this:
528 @smallexample
529 #ifdef _POSIX_SAVED_IDS
530   setuid (user_user_id);
531 #else
532   setreuid (geteuid (), getuid ());
533 #endif
534 @end smallexample
536 @node Setuid Program Example
537 @section Setuid Program Example
539 Here's an example showing how to set up a program that changes its
540 effective user ID.
542 This is part of a game program called @code{caber-toss} that manipulates
543 a file @file{scores} that should be writable only by the game program
544 itself.  The program assumes that its executable file will be installed
545 with the setuid bit set and owned by the same user as the @file{scores}
546 file.  Typically, a system administrator will set up an account like
547 @code{games} for this purpose.
549 The executable file is given mode @code{4755}, so that doing an
550 @samp{ls -l} on it produces output like:
552 @smallexample
553 -rwsr-xr-x   1 games    184422 Jul 30 15:17 caber-toss
554 @end smallexample
556 @noindent
557 The setuid bit shows up in the file modes as the @samp{s}.
559 The scores file is given mode @code{644}, and doing an @samp{ls -l} on
560 it shows:
562 @smallexample
563 -rw-r--r--  1 games           0 Jul 31 15:33 scores
564 @end smallexample
566 Here are the parts of the program that show how to set up the changed
567 user ID.  This program is conditionalized so that it makes use of the
568 file IDs feature if it is supported, and otherwise uses @code{setreuid}
569 to swap the effective and real user IDs.
571 @smallexample
572 #include <stdio.h>
573 #include <sys/types.h>
574 #include <unistd.h>
575 #include <stdlib.h>
578 /* @r{Remember the effective and real UIDs.} */
580 static uid_t euid, ruid;
583 /* @r{Restore the effective UID to its original value.} */
585 void
586 do_setuid (void)
588   int status;
590 #ifdef _POSIX_SAVED_IDS
591   status = seteuid (euid);
592 #else
593   status = setreuid (ruid, euid);
594 #endif
595   if (status < 0) @{
596     fprintf (stderr, "Couldn't set uid.\n");
597     exit (status);
598     @}
602 @group
603 /* @r{Set the effective UID to the real UID.} */
605 void
606 undo_setuid (void)
608   int status;
610 #ifdef _POSIX_SAVED_IDS
611   status = seteuid (ruid);
612 #else
613   status = setreuid (euid, ruid);
614 #endif
615   if (status < 0) @{
616     fprintf (stderr, "Couldn't set uid.\n");
617     exit (status);
618     @}
620 @end group
622 /* @r{Main program.} */
625 main (void)
627   /* @r{Remember the real and effective user IDs.}  */
628   ruid = getuid ();
629   euid = geteuid ();
630   undo_setuid ();
632   /* @r{Do the game and record the score.}  */
633   @dots{}
635 @end smallexample
637 Notice how the first thing the @code{main} function does is to set the
638 effective user ID back to the real user ID.  This is so that any other
639 file accesses that are performed while the user is playing the game use
640 the real user ID for determining permissions.  Only when the program
641 needs to open the scores file does it switch back to the file user ID,
642 like this:
644 @smallexample
645 /* @r{Record the score.} */
648 record_score (int score)
650   FILE *stream;
651   char *myname;
653   /* @r{Open the scores file.} */
654   do_setuid ();
655   stream = fopen (SCORES_FILE, "a");
656   undo_setuid ();
658 @group
659   /* @r{Write the score to the file.} */
660   if (stream)
661     @{
662       myname = cuserid (NULL);
663       if (score < 0)
664         fprintf (stream, "%10s: Couldn't lift the caber.\n", myname);
665       else
666         fprintf (stream, "%10s: %d feet.\n", myname, score);
667       fclose (stream);
668       return 0;
669     @}
670   else
671     return -1;
673 @end group
674 @end smallexample
676 @node Tips for Setuid
677 @section Tips for Writing Setuid Programs
679 It is easy for setuid programs to give the user access that isn't
680 intended---in fact, if you want to avoid this, you need to be careful.
681 Here are some guidelines for preventing unintended access and
682 minimizing its consequences when it does occur:
684 @itemize @bullet
685 @item
686 Don't have @code{setuid} programs with privileged user IDs such as
687 @code{root} unless it is absolutely necessary.  If the resource is
688 specific to your particular program, it's better to define a new,
689 nonprivileged user ID or group ID just to manage that resource.
690 It's better if you can write your program to use a special group than a
691 special user.
693 @item
694 Be cautious about using the @code{exec} functions in combination with
695 changing the effective user ID.  Don't let users of your program execute
696 arbitrary programs under a changed user ID.  Executing a shell is
697 especially bad news. Less obviously, the @code{execlp} and @code{execvp}
698 functions are a potential risk (since the program they execute depends
699 on the user's @code{PATH} environment variable).
701 If you must @code{exec} another program under a changed ID, specify an
702 absolute file name (@pxref{File Name Resolution}) for the executable,
703 and make sure that the protections on that executable and @emph{all}
704 containing directories are such that ordinary users cannot replace it
705 with some other program.
707 You should also check the arguments passed to the program to make sure
708 they do not have unexpected effects.  Likewise, you should examine the
709 environment variables.  Decide which arguments and variables are safe,
710 and reject all others.
712 You should never use @code{system} in a privileged program, because it
713 invokes a shell.
715 @item
716 Only use the user ID controlling the resource in the part of the program
717 that actually uses that resource.  When you're finished with it, restore
718 the effective user ID back to the actual user's user ID.
719 @xref{Enable/Disable Setuid}.
721 @item
722 If the @code{setuid} part of your program needs to access other files
723 besides the controlled resource, it should verify that the real user
724 would ordinarily have permission to access those files.  You can use the
725 @code{access} function (@pxref{Access Permission}) to check this; it
726 uses the real user and group IDs, rather than the effective IDs.
727 @end itemize
729 @node Who Logged In
730 @section Identifying Who Logged In
731 @cindex login name, determining
732 @cindex user ID, determining
734 You can use the functions listed in this section to determine the login
735 name of the user who is running a process, and the name of the user who
736 logged in the current session.  See also the function @code{getuid} and
737 friends (@pxref{Reading Persona}).  How this information is collected by
738 the system and how to control/add/remove information from the background
739 storage is described in @ref{User Accounting Database}.
741 The @code{getlogin} function is declared in @file{unistd.h}, while
742 @code{cuserid} and @code{L_cuserid} are declared in @file{stdio.h}.
743 @pindex stdio.h
744 @pindex unistd.h
746 @comment unistd.h
747 @comment POSIX.1
748 @deftypefun {char *} getlogin (void)
749 The @code{getlogin} function returns a pointer to a string containing the
750 name of the user logged in on the controlling terminal of the process,
751 or a null pointer if this information cannot be determined.  The string
752 is statically allocated and might be overwritten on subsequent calls to
753 this function or to @code{cuserid}.
754 @end deftypefun
756 @comment stdio.h
757 @comment POSIX.1
758 @deftypefun {char *} cuserid (char *@var{string})
759 The @code{cuserid} function returns a pointer to a string containing a
760 user name associated with the effective ID of the process.  If
761 @var{string} is not a null pointer, it should be an array that can hold
762 at least @code{L_cuserid} characters; the string is returned in this
763 array.  Otherwise, a pointer to a string in a static area is returned.
764 This string is statically allocated and might be overwritten on
765 subsequent calls to this function or to @code{getlogin}.
767 The use of this function is deprecated since it is marked to be
768 withdrawn in XPG4.2 and has already been removed from newer revisions of
769 POSIX.1.
770 @end deftypefun
772 @comment stdio.h
773 @comment POSIX.1
774 @deftypevr Macro int L_cuserid
775 An integer constant that indicates how long an array you might need to
776 store a user name.
777 @end deftypevr
779 These functions let your program identify positively the user who is
780 running or the user who logged in this session.  (These can differ when
781 setuid programs are involved; see @ref{Process Persona}.)  The user cannot
782 do anything to fool these functions.
784 For most purposes, it is more useful to use the environment variable
785 @code{LOGNAME} to find out who the user is.  This is more flexible
786 precisely because the user can set @code{LOGNAME} arbitrarily.
787 @xref{Standard Environment}.
790 @node User Accounting Database
791 @section The User Accounting Database
792 @cindex user accounting database
794 Most Unix-like operating systems keep track of logged in users by
795 maintaining a user accounting database.  This user accounting database
796 stores for each terminal, who has logged on, at what time, the process
797 ID of the user's login shell, etc., etc., but also stores information
798 about the run level of the system, the time of the last system reboot,
799 and possibly more.
801 The user accounting database typically lives in @file{/etc/utmp},
802 @file{/var/adm/utmp} or @file{/var/run/utmp}.  However, these files
803 should @strong{never} be accessed directly.  For reading information
804 from and writing information to the user accounting database, the
805 functions described in this section should be used.
808 @menu
809 * Manipulating the Database::   Scanning and modifying the user
810                                  accounting database.
811 * XPG Functions::               A standardized way for doing the same thing.
812 * Logging In and Out::          Functions from BSD that modify the user
813                                  accounting database.
814 @end menu
816 @node Manipulating the Database
817 @subsection Manipulating the User Accounting Database
819 These functions and the corresponding data structures are declared in
820 the header file @file{utmp.h}.
821 @pindex utmp.h
823 @comment utmp.h
824 @comment SVID
825 @deftp {Data Type} {struct exit_status}
826 The @code{exit_status} data structure is used to hold information about
827 the exit status of processes marked as @code{DEAD_PROCESS} in the user
828 accounting database.
830 @table @code
831 @item short int e_termination
832 The exit status of the process.
834 @item short int e_exit
835 The exit status of the process.
836 @end table
837 @end deftp
839 @deftp {Data Type} {struct utmp}
840 The @code{utmp} data structure is used to hold information about entries
841 in the user accounting database.  On the GNU system it has the following
842 members:
844 @table @code
845 @item short int ut_type
846 Specifies the type of login; one of @code{EMPTY}, @code{RUN_LVL},
847 @code{BOOT_TIME}, @code{OLD_TIME}, @code{NEW_TIME}, @code{INIT_PROCESS},
848 @code{LOGIN_PROCESS}, @code{USER_PROCESS}, @code{DEAD_PROCESS} or
849 @code{ACCOUNTING}.
851 @item pid_t ut_pid
852 The process ID number of the login process.
854 @item char ut_line[]
855 The device name of the tty (without @file{/dev/}).
857 @item char ut_id[]
858 The inittab ID of the process.
860 @item char ut_user[]
861 The user's login name.
863 @item char ut_host[]
864 The name of the host from which the user logged in.
866 @item struct exit_status ut_exit
867 The exit status of a process marked as @code{DEAD_PROCESS}.
869 @item long ut_session
870 The Session ID, used for windowing.
872 @item struct timeval ut_tv
873 Time the entry was made.  For entries of type @code{OLD_TIME} this is
874 the time when the system clock changed, and for entries of type
875 @code{NEW_TIME} this is the time the system clock was set to.
877 @item int32_t ut_addr_v6[4]
878 The Internet address of a remote host.
879 @end table
880 @end deftp
882 The @code{ut_type}, @code{ut_pid}, @code{ut_id}, @code{ut_tv}, and
883 @code{ut_host} fields are not available on all systems.  Portable
884 applications therefore should be prepared for these situations.  To help
885 doing this the @file{utmp.h} header provides macros
886 @code{_HAVE_UT_TYPE}, @code{_HAVE_UT_PID}, @code{_HAVE_UT_ID},
887 @code{_HAVE_UT_TV}, and @code{_HAVE_UT_HOST} if the respective field is
888 available.  The programmer can handle the situations by using
889 @code{#ifdef} in the program code.
891 The following macros are defined for use as values for the
892 @code{ut_type} member of the @code{utmp} structure.  The values are
893 integer constants.
895 @table @code
896 @comment utmp.h
897 @comment SVID
898 @vindex EMPTY
899 @item EMPTY
900 This macro is used to indicate that the entry contains no valid user
901 accounting information.
903 @comment utmp.h
904 @comment SVID
905 @vindex RUN_LVL
906 @item RUN_LVL
907 This macro is used to identify the systems runlevel.
909 @comment utmp.h
910 @comment SVID
911 @vindex BOOT_TIME
912 @item BOOT_TIME
913 This macro is used to identify the time of system boot.
915 @comment utmp.h
916 @comment SVID
917 @vindex OLD_TIME
918 @item OLD_TIME
919 This macro is used to identify the time when the system clock changed.
921 @comment utmp.h
922 @comment SVID
923 @vindex NEW_TIME
924 @item NEW_TIME
925 This macro is used to identify the time after the system changed.
927 @comment utmp.h
928 @comment SVID
929 @vindex INIT_PROCESS
930 @item INIT_PROCESS
931 This macro is used to identify a process spawned by the init process.
933 @comment utmp.h
934 @comment SVID
935 @vindex LOGIN_PROCESS
936 @item LOGIN_PROCESS
937 This macro is used to identify the session leader of a logged in user.
939 @comment utmp.h
940 @comment SVID
941 @vindex USER_PROCESS
942 @item USER_PROCESS
943 This macro is used to identify a user process.
945 @comment utmp.h
946 @comment SVID
947 @vindex DEAD_PROCESS
948 @item DEAD_PROCESS
949 This macro is used to identify a terminated process.
951 @comment utmp.h
952 @comment SVID
953 @vindex ACCOUNTING
954 @item ACCOUNTING
956 @end table
958 The size of the @code{ut_line}, @code{ut_id}, @code{ut_user} and
959 @code{ut_host} arrays can be found using the @code{sizeof} operator.
961 Many older systems have, instead of an @code{ut_tv} member, an
962 @code{ut_time} member, usually of type @code{time_t}, for representing
963 the time associated with the entry.  Therefore, for backwards
964 compatibility only, @file{utmp.h} defines @code{ut_time} as an alias for
965 @code{ut_tv.tv_sec}.
967 @comment utmp.h
968 @comment SVID
969 @deftypefun void setutent (void)
970 This function opens the user accounting database to begin scanning it.
971 You can then call @code{getutent}, @code{getutid} or @code{getutline} to
972 read entries and @code{pututline} to write entries.
974 If the database is already open, it resets the input to the beginning of
975 the database.
976 @end deftypefun
978 @comment utmp.h
979 @comment SVID
980 @deftypefun {struct utmp *} getutent (void)
981 The @code{getutent} function reads the next entry from the user
982 accounting database.  It returns a pointer to the entry, which is
983 statically allocated and may be overwritten by subsequent calls to
984 @code{getutent}.  You must copy the contents of the structure if you
985 wish to save the information or you can use the @code{getutent_r}
986 function which stores the data in a user-provided buffer.
988 A null pointer is returned in case no further entry is available.
989 @end deftypefun
991 @comment utmp.h
992 @comment SVID
993 @deftypefun void endutent (void)
994 This function closes the user accounting database.
995 @end deftypefun
997 @comment utmp.h
998 @comment SVID
999 @deftypefun {struct utmp *} getutid (const struct utmp *@var{id})
1000 This function searches forward from the current point in the database
1001 for an entry that matches @var{id}.  If the @code{ut_type} member of the
1002 @var{id} structure is one of @code{RUN_LVL}, @code{BOOT_TIME},
1003 @code{OLD_TIME} or @code{NEW_TIME} the entries match if the
1004 @code{ut_type} members are identical.  If the @code{ut_type} member of
1005 the @var{id} structure is @code{INIT_PROCESS}, @code{LOGIN_PROCESS},
1006 @code{USER_PROCESS} or @code{DEAD_PROCESS}, the entries match if the
1007 @code{ut_type} member of the entry read from the database is one of
1008 these four, and the @code{ut_id} members match.  However if the
1009 @code{ut_id} member of either the @var{id} structure or the entry read
1010 from the database is empty it checks if the @code{ut_line} members match
1011 instead.  If a matching entry is found, @code{getutid} returns a pointer
1012 to the entry, which is statically allocated, and may be overwritten by a
1013 subsequent call to @code{getutent}, @code{getutid} or @code{getutline}.
1014 You must copy the contents of the structure if you wish to save the
1015 information.
1017 A null pointer is returned in case the end of the database is reached
1018 without a match.
1020 The @code{getutid} function may cache the last read entry.  Therefore,
1021 if you are using @code{getutid} to search for multiple occurrences, it
1022 is necessary to zero out the static data after each call.  Otherwise
1023 @code{getutid} could just return a pointer to the same entry over and
1024 over again.
1025 @end deftypefun
1027 @comment utmp.h
1028 @comment SVID
1029 @deftypefun {struct utmp *} getutline (const struct utmp *@var{line})
1030 This function searches forward from the current point in the database
1031 until it finds an entry whose @code{ut_type} value is
1032 @code{LOGIN_PROCESS} or @code{USER_PROCESS}, and whose @code{ut_line}
1033 member matches the @code{ut_line} member of the @var{line} structure.
1034 If it finds such an entry, it returns a pointer to the entry which is
1035 statically allocated, and may be overwritten by a subsequent call to
1036 @code{getutent}, @code{getutid} or @code{getutline}.  You must copy the
1037 contents of the structure if you wish to save the information.
1039 A null pointer is returned in case the end of the database is reached
1040 without a match.
1042 The @code{getutline} function may cache the last read entry.  Therefore
1043 if you are using @code{getutline} to search for multiple occurrences, it
1044 is necessary to zero out the static data after each call.  Otherwise
1045 @code{getutline} could just return a pointer to the same entry over and
1046 over again.
1047 @end deftypefun
1049 @comment utmp.h
1050 @comment SVID
1051 @deftypefun {struct utmp *} pututline (const struct utmp *@var{utmp})
1052 The @code{pututline} function inserts the entry @code{*@var{utmp}} at
1053 the appropriate place in the user accounting database.  If it finds that
1054 it is not already at the correct place in the database, it uses
1055 @code{getutid} to search for the position to insert the entry, however
1056 this will not modify the static structure returned by @code{getutent},
1057 @code{getutid} and @code{getutline}.  If this search fails, the entry
1058 is appended to the database.
1060 The @code{pututline} function returns a pointer to a copy of the entry
1061 inserted in the user accounting database, or a null pointer if the entry
1062 could not be added.  The following @code{errno} error conditions are
1063 defined for this function:
1065 @table @code
1066 @item EPERM
1067 The process does not have the appropriate privileges; you cannot modify
1068 the user accounting database.
1069 @end table
1070 @end deftypefun
1072 All the @code{get*} functions mentioned before store the information
1073 they return in a static buffer.  This can be a problem in multi-threaded
1074 programs since the data return for the request is overwritten be the
1075 return value data in another thread.  Therefore the GNU C Library
1076 provides as extensions three more functions which return the data in a
1077 user-provided buffer.
1079 @comment utmp.h
1080 @comment GNU
1081 @deftypefun int getutent_r (struct utmp *@var{buffer}, struct utmp **@var{result})
1082 The @code{getutent_r} is equivalent to the @code{getutent} function.  It
1083 returns the next entry from the database.  But instead of storing the
1084 information in a static buffer it stores it in the buffer pointed to by
1085 the parameter @var{buffer}.
1087 If the call was successful, the function returns @code{0} and the
1088 pointer variable pointed to by the parameter @var{result} contains a
1089 pointer to the buffer which contains the result (this is most probably
1090 the same value as @var{buffer}).  If something went wrong during the
1091 execution of @code{getutent_r} the function returns @code{-1}.
1093 This function is a GNU extension.
1094 @end deftypefun
1096 @comment utmp.h
1097 @comment GNU
1098 @deftypefun int getutid_r (const struct utmp *@var{id}, struct utmp *@var{buffer}, struct utmp **@var{result})
1099 This function retrieves just like @code{getutid} the next entry matching
1100 the information stored in @var{id}.  But the result is stored in the
1101 buffer pointed to by the parameter @var{buffer}.
1103 If successful the function returns @code{0} and the pointer variable
1104 pointed to by the parameter @var{result} contains a pointer to the
1105 buffer with the result (probably the same as @var{result}.  If not
1106 successful the function return @code{-1}.
1108 This function is a GNU extension.
1109 @end deftypefun
1111 @comment utmp.h
1112 @comment GNU
1113 @deftypefun int getutline_r (const struct utmp *@var{line}, struct utmp *@var{buffer}, struct utmp **@var{result})
1114 This function retrieves just like @code{getutline} the next entry
1115 matching the information stored in @var{line}.  But the result is stored
1116 in the buffer pointed to by the parameter @var{buffer}.
1118 If successful the function returns @code{0} and the pointer variable
1119 pointed to by the parameter @var{result} contains a pointer to the
1120 buffer with the result (probably the same as @var{result}.  If not
1121 successful the function return @code{-1}.
1123 This function is a GNU extension.
1124 @end deftypefun
1127 In addition to the user accounting database, most systems keep a number
1128 of similar databases.  For example most systems keep a log file with all
1129 previous logins (usually in @file{/etc/wtmp} or @file{/var/log/wtmp}).
1131 For specifying which database to examine, the following function should
1132 be used.
1134 @comment utmp.h
1135 @comment SVID
1136 @deftypefun int utmpname (const char *@var{file})
1137 The @code{utmpname} function changes the name of the database to be
1138 examined to @var{file}, and closes any previously opened database.  By
1139 default @code{getutent}, @code{getutid}, @code{getutline} and
1140 @code{pututline} read from and write to the user accounting database.
1142 The following macros are defined for use as the @var{file} argument:
1144 @deftypevr Macro {char *} _PATH_UTMP
1145 This macro is used to specify the user accounting database.
1146 @end deftypevr
1148 @deftypevr Macro {char *} _PATH_WTMP
1149 This macro is used to specify the user accounting log file.
1150 @end deftypevr
1152 The @code{utmpname} function returns a value of @code{0} if the new name
1153 was successfully stored, and a value of @code{-1} to indicate an error.
1154 Note that @code{utmpname} does not try to open the database, and that
1155 therefore the return value does not say anything about whether the
1156 database can be successfully opened.
1157 @end deftypefun
1159 Specially for maintaining log-like databases the GNU C Library provides
1160 the following function:
1162 @comment utmp.h
1163 @comment SVID
1164 @deftypefun void updwtmp (const char *@var{wtmp_file}, const struct utmp *@var{utmp})
1165 The @code{updwtmp} function appends the entry *@var{utmp} to the
1166 database specified by @var{wtmp_file}.  For possible values for the
1167 @var{wtmp_file} argument see the @code{utmpname} function.
1168 @end deftypefun
1170 @strong{Portability Note:} Although many operating systems provide a
1171 subset of these functions, they are not standardized.  There are often
1172 subtle differences in the return types, and there are considerable
1173 differences between the various definitions of @code{struct utmp}.  When
1174 programming for the GNU system, it is probably best to stick
1175 with the functions described in this section.  If however, you want your
1176 program to be portable, consider using the XPG functions described in
1177 @ref{XPG Functions}, or take a look at the BSD compatible functions in
1178 @ref{Logging In and Out}.
1181 @node XPG Functions
1182 @subsection XPG User Accounting Database Functions
1184 These functions, described in the X/Open Portability Guide, are declared
1185 in the header file @file{utmpx.h}.
1186 @pindex utmpx.h
1188 @deftp {Data Type} {struct utmpx}
1189 The @code{utmpx} data structure contains at least the following members:
1191 @table @code
1192 @item short int ut_type
1193 Specifies the type of login; one of @code{EMPTY}, @code{RUN_LVL},
1194 @code{BOOT_TIME}, @code{OLD_TIME}, @code{NEW_TIME}, @code{INIT_PROCESS},
1195 @code{LOGIN_PROCESS}, @code{USER_PROCESS} or @code{DEAD_PROCESS}.
1197 @item pid_t ut_pid
1198 The process ID number of the login process.
1200 @item char ut_line[]
1201 The device name of the tty (without @file{/dev/}).
1203 @item char ut_id[]
1204 The inittab ID of the process.
1206 @item char ut_user[]
1207 The user's login name.
1209 @item struct timeval ut_tv
1210 Time the entry was made.  For entries of type @code{OLD_TIME} this is
1211 the time when the system clock changed, and for entries of type
1212 @code{NEW_TIME} this is the time the system clock was set to.
1213 @end table
1214 On the GNU system, @code{struct utmpx} is identical to @code{struct
1215 utmp} except for the fact that including @file{utmpx.h} does not make
1216 visible the declaration of @code{struct exit_status}.
1217 @end deftp
1219 The following macros are defined for use as values for the
1220 @code{ut_type} member of the @code{utmpx} structure.  The values are
1221 integer constants and are, on the GNU system, identical to the
1222 definitions in @file{utmp.h}.
1224 @table @code
1225 @comment utmpx.h
1226 @comment XPG4.2
1227 @vindex EMPTY
1228 @item EMPTY
1229 This macro is used to indicate that the entry contains no valid user
1230 accounting information.
1232 @comment utmpx.h
1233 @comment XPG4.2
1234 @vindex RUN_LVL
1235 @item RUN_LVL
1236 This macro is used to identify the systems runlevel.
1238 @comment utmpx.h
1239 @comment XPG4.2
1240 @vindex BOOT_TIME
1241 @item BOOT_TIME
1242 This macro is used to identify the time of system boot.
1244 @comment utmpx.h
1245 @comment XPG4.2
1246 @vindex OLD_TIME
1247 @item OLD_TIME
1248 This macro is used to identify the time when the system clock changed.
1250 @comment utmpx.h
1251 @comment XPG4.2
1252 @vindex NEW_TIME
1253 @item NEW_TIME
1254 This macro is used to identify the time after the system changed.
1256 @comment utmpx.h
1257 @comment XPG4.2
1258 @vindex INIT_PROCESS
1259 @item INIT_PROCESS
1260 This macro is used to identify a process spawned by the init process.
1262 @comment utmpx.h
1263 @comment XPG4.2
1264 @vindex LOGIN_PROCESS
1265 @item LOGIN_PROCESS
1266 This macro is used to identify the session leader of a logged in user.
1268 @comment utmpx.h
1269 @comment XPG4.2
1270 @vindex USER_PROCESS
1271 @item USER_PROCESS
1272 This macro is used to identify a user process.
1274 @comment utmpx.h
1275 @comment XPG4.2
1276 @vindex DEAD_PROCESS
1277 @item DEAD_PROCESS
1278 This macro is used to identify a terminated process.
1279 @end table
1281 The size of the @code{ut_line}, @code{ut_id} and @code{ut_user} arrays
1282 can be found using the @code{sizeof} operator.
1284 @comment utmpx.h
1285 @comment XPG4.2
1286 @deftypefun void setutxent (void)
1287 This function is similar to @code{setutent}.  On the GNU system it is
1288 simply an alias for @code{setutent}.
1289 @end deftypefun
1291 @comment utmpx.h
1292 @comment XPG4.2
1293 @deftypefun {struct utmpx *} getutxent (void)
1294 The @code{getutxent} function is similar to @code{getutent}, but returns
1295 a pointer to a @code{struct utmpx} instead of @code{struct utmp}.  On
1296 the GNU system it simply is an alias for @code{getutent}.
1297 @end deftypefun
1299 @comment utmpx.h
1300 @comment XPG4.2
1301 @deftypefun void endutxent (void)
1302 This function is similar to @code{endutent}.  On the GNU system it is
1303 simply an alias for @code{endutent}.
1304 @end deftypefun
1306 @comment utmpx.h
1307 @comment XPG4.2
1308 @deftypefun {struct utmpx *} getutxid (const struct utmpx *@var{id})
1309 This function is similar to @code{getutid}, but uses @code{struct utmpx}
1310 instead of @code{struct utmp}.  On the GNU system it is simply an alias
1311 for @code{getutid}.
1312 @end deftypefun
1314 @comment utmpx.h
1315 @comment XPG4.2
1316 @deftypefun {struct utmpx *} getutxline (const struct utmpx *@var{line})
1317 This function is similar to @code{getutid}, but uses @code{struct utmpx}
1318 instead of @code{struct utmp}.  On the GNU system it is simply an alias
1319 for @code{getutline}.
1320 @end deftypefun
1322 @comment utmpx.h
1323 @comment XPG4.2
1324 @deftypefun {struct utmpx *} pututxline (const struct utmpx *@var{utmp})
1325 The @code{pututxline} function provides functionality identical to
1326 @code{pututline}, but uses @code{struct utmpx} instead of @code{struct
1327 utmp}.  On the GNU system @code{pututxline} is simply an alias for
1328 @code{pututline}.
1329 @end deftypefun
1332 @node Logging In and Out
1333 @subsection Logging In and Out
1335 These functions, derived from BSD, are available in the separate
1336 @file{libutil} library, and declared in @file{utmp.h}.
1337 @pindex utmp.h
1339 Note that the @code{ut_user} member of @code{struct utmp} is called
1340 @code{ut_name} in BSD.  Therefore, @code{ut_name} is defined as an alias
1341 for @code{ut_user} in @file{utmp.h}.
1343 @comment utmp.h
1344 @comment BSD
1345 @deftypefun int login_tty (int @var{filedes})
1346 This function makes @var{filedes} the controlling terminal of the
1347 current process, redirects standard input, standard output and
1348 standard error output to this terminal, and closes @var{filedes}.
1350 This function returns @code{0} on successful completion, and @code{-1}
1351 on error.
1352 @end deftypefun
1354 @comment utmp.h
1355 @comment BSD
1356 @deftypefun void login (const struct utmp *@var{entry})
1357 The @code{login} functions inserts an entry into the user accounting
1358 database.  The @code{ut_line} member is set to the name of the terminal
1359 on standard input.  If standard input is not a terminal @code{login}
1360 uses standard output or standard error output to determine the name of
1361 the terminal.  If @code{struct utmp} has a @code{ut_type} member,
1362 @code{login} sets it to @code{USER_PROCESS}, and if there is an
1363 @code{ut_pid} member, it will be set to the process ID of the current
1364 process.  The remaining entries are copied from @var{entry}.
1366 A copy of the entry is written to the user accounting log file.
1367 @end deftypefun
1369 @comment utmp.h
1370 @comment BSD
1371 @deftypefun int logout (const char *@var{ut_line})
1372 This function modifies the user accounting database to indicate that the
1373 user on @var{ut_line} has logged out.
1375 The @code{logout} function returns @code{1} if the entry was successfully
1376 written to the database, or @code{0} on error.
1377 @end deftypefun
1379 @comment utmp.h
1380 @comment BSD
1381 @deftypefun void logwtmp (const char *@var{ut_line}, const char *@var{ut_name}, const char *@var{ut_host})
1382 The @code{logwtmp} function appends an entry to the user accounting log
1383 file, for the current time and the information provided in the
1384 @var{ut_line}, @var{ut_name} and @var{ut_host} arguments.
1385 @end deftypefun
1387 @strong{Portability Note:} The BSD @code{struct utmp} only has the
1388 @code{ut_line}, @code{ut_name}, @code{ut_host} and @code{ut_time}
1389 members.  Older systems do not even have the @code{ut_host} member.
1392 @node User Database
1393 @section User Database
1394 @cindex user database
1395 @cindex password database
1396 @pindex /etc/passwd
1398 This section describes how to search and scan the database of registered
1399 users.  The database itself is kept in the file @file{/etc/passwd} on
1400 most systems, but on some systems a special network server gives access
1401 to it.
1403 @menu
1404 * User Data Structure::         What each user record contains.
1405 * Lookup User::                 How to look for a particular user.
1406 * Scanning All Users::          Scanning the list of all users, one by one.
1407 * Writing a User Entry::        How a program can rewrite a user's record.
1408 @end menu
1410 @node User Data Structure
1411 @subsection The Data Structure that Describes a User
1413 The functions and data structures for accessing the system user database
1414 are declared in the header file @file{pwd.h}.
1415 @pindex pwd.h
1417 @comment pwd.h
1418 @comment POSIX.1
1419 @deftp {Data Type} {struct passwd}
1420 The @code{passwd} data structure is used to hold information about
1421 entries in the system user data base.  It has at least the following members:
1423 @table @code
1424 @item char *pw_name
1425 The user's login name.
1427 @item char *pw_passwd.
1428 The encrypted password string.
1430 @item uid_t pw_uid
1431 The user ID number.
1433 @item gid_t pw_gid
1434 The user's default group ID number.
1436 @item char *pw_gecos
1437 A string typically containing the user's real name, and possibly other
1438 information such as a phone number.
1440 @item char *pw_dir
1441 The user's home directory, or initial working directory.  This might be
1442 a null pointer, in which case the interpretation is system-dependent.
1444 @item char *pw_shell
1445 The user's default shell, or the initial program run when the user logs in.
1446 This might be a null pointer, indicating that the system default should
1447 be used.
1448 @end table
1449 @end deftp
1451 @node Lookup User
1452 @subsection Looking Up One User
1453 @cindex converting user ID to user name
1454 @cindex converting user name to user ID
1456 You can search the system user database for information about a
1457 specific user using @code{getpwuid} or @code{getpwnam}.  These
1458 functions are declared in @file{pwd.h}.
1460 @comment pwd.h
1461 @comment POSIX.1
1462 @deftypefun {struct passwd *} getpwuid (uid_t @var{uid})
1463 This function returns a pointer to a statically-allocated structure
1464 containing information about the user whose user ID is @var{uid}.  This
1465 structure may be overwritten on subsequent calls to @code{getpwuid}.
1467 A null pointer value indicates there is no user in the data base with
1468 user ID @var{uid}.
1469 @end deftypefun
1471 @comment pwd.h
1472 @comment POSIX.1c
1473 @deftypefun int getpwuid_r (uid_t @var{uid}, struct passwd *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct passwd **@var{result})
1474 This function is similar to @code{getpwuid} in that it returns
1475 information about the user whose user ID is @var{uid}.  However, it
1476 fills the user supplied structure pointed to by @var{result_buf} with
1477 the information instead of using a static buffer.  The first
1478 @var{buflen} bytes of the additional buffer pointed to by @var{buffer}
1479 are used to contain additional information, normally strings which are
1480 pointed to by the elements of the result structure.
1482 If a user with ID @var{uid} is found, the pointer returned in
1483 @var{result} points to the record which contains the wanted data (i.e.,
1484 @var{result} contains the value @var{result_buf}).  If no user is found
1485 or if an error occured, the pointer returned in @var{result} is a null
1486 pointer.  The function returns zero or an error code.  If the buffer
1487 @var{buffer} is too small to contain all the needed information, the
1488 error code @code{ERANGE} is returned and @var{errno} is set to
1489 @code{ERANGE}.
1490 @end deftypefun
1493 @comment pwd.h
1494 @comment POSIX.1
1495 @deftypefun {struct passwd *} getpwnam (const char *@var{name})
1496 This function returns a pointer to a statically-allocated structure
1497 containing information about the user whose user name is @var{name}.
1498 This structure may be overwritten on subsequent calls to
1499 @code{getpwnam}.
1501 A null pointer return indicates there is no user named @var{name}.
1502 @end deftypefun
1504 @comment pwd.h
1505 @comment POSIX.1c
1506 @deftypefun int getpwnam_r (const char *@var{name}, struct passwd *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct passwd **@var{result})
1507 This function is similar to @code{getpwnam} in that is returns
1508 information about the user whose user name is @var{name}.  However, like
1509 @code{getpwuid_r}, it fills the user supplied buffers in
1510 @var{result_buf} and @var{buffer} with the information instead of using
1511 a static buffer.
1513 The return values are the same as for @code{getpwuid_r}.
1514 @end deftypefun
1517 @node Scanning All Users
1518 @subsection Scanning the List of All Users
1519 @cindex scanning the user list
1521 This section explains how a program can read the list of all users in
1522 the system, one user at a time.  The functions described here are
1523 declared in @file{pwd.h}.
1525 You can use the @code{fgetpwent} function to read user entries from a
1526 particular file.
1528 @comment pwd.h
1529 @comment SVID
1530 @deftypefun {struct passwd *} fgetpwent (FILE *@var{stream})
1531 This function reads the next user entry from @var{stream} and returns a
1532 pointer to the entry.  The structure is statically allocated and is
1533 rewritten on subsequent calls to @code{fgetpwent}.  You must copy the
1534 contents of the structure if you wish to save the information.
1536 The stream must correspond to a file in the same format as the standard
1537 password database file.
1538 @end deftypefun
1540 @comment pwd.h
1541 @comment GNU
1542 @deftypefun int fgetpwent_r (FILE *@var{stream}, struct passwd *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct passwd **@var{result})
1543 This function is similar to @code{fgetpwent} in that it reads the next
1544 user entry from @var{stream}.  But the result is returned in the
1545 structure pointed to by @var{result_buf}.  The
1546 first @var{buflen} bytes of the additional buffer pointed to by
1547 @var{buffer} are used to contain additional information, normally
1548 strings which are pointed to by the elements of the result structure.
1550 The stream must correspond to a file in the same format as the standard
1551 password database file.
1553 If the function returns zero @var{result} points to the structure with
1554 the wanted data (normally this is in @var{result_buf}).  If errors
1555 occurred the return value is nonzero and @var{result} contains a null
1556 pointer.
1557 @end deftypefun
1559 The way to scan all the entries in the user database is with
1560 @code{setpwent}, @code{getpwent}, and @code{endpwent}.
1562 @comment pwd.h
1563 @comment SVID, BSD
1564 @deftypefun void setpwent (void)
1565 This function initializes a stream which @code{getpwent} and
1566 @code{getpwent_r} use to read the user database.
1567 @end deftypefun
1569 @comment pwd.h
1570 @comment POSIX.1
1571 @deftypefun {struct passwd *} getpwent (void)
1572 The @code{getpwent} function reads the next entry from the stream
1573 initialized by @code{setpwent}.  It returns a pointer to the entry.  The
1574 structure is statically allocated and is rewritten on subsequent calls
1575 to @code{getpwent}.  You must copy the contents of the structure if you
1576 wish to save the information.
1578 A null pointer is returned when no more entries are available.
1579 @end deftypefun
1581 @comment pwd.h
1582 @comment GNU
1583 @deftypefun int getpwent_r (struct passwd *@var{result_buf}, char *@var{buffer}, int @var{buflen}, struct passwd **@var{result})
1584 This function is similar to @code{getpwent} in that it returns the next
1585 entry from the stream initialized by @code{setpwent}.  Like
1586 @code{fgetpwent_r}, it uses the user-supplied buffers in
1587 @var{result_buf} and @var{buffer} to return the information requested.
1589 The return values are the same as for @code{fgetpwent_r}.
1591 @end deftypefun
1593 @comment pwd.h
1594 @comment SVID, BSD
1595 @deftypefun void endpwent (void)
1596 This function closes the internal stream used by @code{getpwent} or
1597 @code{getpwent_r}.
1598 @end deftypefun
1600 @node Writing a User Entry
1601 @subsection Writing a User Entry
1603 @comment pwd.h
1604 @comment SVID
1605 @deftypefun int putpwent (const struct passwd *@var{p}, FILE *@var{stream})
1606 This function writes the user entry @code{*@var{p}} to the stream
1607 @var{stream}, in the format used for the standard user database
1608 file.  The return value is zero on success and nonzero on failure.
1610 This function exists for compatibility with SVID.  We recommend that you
1611 avoid using it, because it makes sense only on the assumption that the
1612 @code{struct passwd} structure has no members except the standard ones;
1613 on a system which merges the traditional Unix data base with other
1614 extended information about users, adding an entry using this function
1615 would inevitably leave out much of the important information.
1616 @c Then how are programmers to modify the password file? -zw
1618 The function @code{putpwent} is declared in @file{pwd.h}.
1619 @end deftypefun
1621 @node Group Database
1622 @section Group Database
1623 @cindex group database
1624 @pindex /etc/group
1626 This section describes how to search and scan the database of
1627 registered groups.  The database itself is kept in the file
1628 @file{/etc/group} on most systems, but on some systems a special network
1629 service provides access to it.
1631 @menu
1632 * Group Data Structure::        What each group record contains.
1633 * Lookup Group::                How to look for a particular group.
1634 * Scanning All Groups::         Scanning the list of all groups.
1635 @end menu
1637 @node Group Data Structure
1638 @subsection The Data Structure for a Group
1640 The functions and data structures for accessing the system group
1641 database are declared in the header file @file{grp.h}.
1642 @pindex grp.h
1644 @comment grp.h
1645 @comment POSIX.1
1646 @deftp {Data Type} {struct group}
1647 The @code{group} structure is used to hold information about an entry in
1648 the system group database.  It has at least the following members:
1650 @table @code
1651 @item char *gr_name
1652 The name of the group.
1654 @item gid_t gr_gid
1655 The group ID of the group.
1657 @item char **gr_mem
1658 A vector of pointers to the names of users in the group.  Each user name
1659 is a null-terminated string, and the vector itself is terminated by a
1660 null pointer.
1661 @end table
1662 @end deftp
1664 @node Lookup Group
1665 @subsection Looking Up One Group
1666 @cindex converting group name to group ID
1667 @cindex converting group ID to group name
1669 You can search the group database for information about a specific
1670 group using @code{getgrgid} or @code{getgrnam}.  These functions are
1671 declared in @file{grp.h}.
1673 @comment grp.h
1674 @comment POSIX.1
1675 @deftypefun {struct group *} getgrgid (gid_t @var{gid})
1676 This function returns a pointer to a statically-allocated structure
1677 containing information about the group whose group ID is @var{gid}.
1678 This structure may be overwritten by subsequent calls to
1679 @code{getgrgid}.
1681 A null pointer indicates there is no group with ID @var{gid}.
1682 @end deftypefun
1684 @comment grp.h
1685 @comment POSIX.1c
1686 @deftypefun int getgrgid_r (gid_t @var{gid}, struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1687 This function is similar to @code{getgrgid} in that it returns
1688 information about the group whose group ID is @var{gid}.  However, it
1689 fills the user supplied structure pointed to by @var{result_buf} with
1690 the information instead of using a static buffer.  The first
1691 @var{buflen} bytes of the additional buffer pointed to by @var{buffer}
1692 are used to contain additional information, normally strings which are
1693 pointed to by the elements of the result structure.
1695 If a group with ID @var{gid} is found, the pointer returned in
1696 @var{result} points to the record which contains the wanted data (i.e.,
1697 @var{result} contains the value @var{result_buf}).  If no group is found
1698 or if an error occured, the pointer returned in @var{result} is a null
1699 pointer.  The function returns zero or an error code.  If the buffer
1700 @var{buffer} is too small to contain all the needed information, the
1701 error code @code{ERANGE} is returned and @var{errno} is set to
1702 @code{ERANGE}.
1703 @end deftypefun
1705 @comment grp.h
1706 @comment SVID, BSD
1707 @deftypefun {struct group *} getgrnam (const char *@var{name})
1708 This function returns a pointer to a statically-allocated structure
1709 containing information about the group whose group name is @var{name}.
1710 This structure may be overwritten by subsequent calls to
1711 @code{getgrnam}.
1713 A null pointer indicates there is no group named @var{name}.
1714 @end deftypefun
1716 @comment grp.h
1717 @comment POSIX.1c
1718 @deftypefun int getgrnam_r (const char *@var{name}, struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1719 This function is similar to @code{getgrnam} in that is returns
1720 information about the group whose group name is @var{name}.  Like
1721 @code{getgrgid_r}, it uses the user supplied buffers in
1722 @var{result_buf} and @var{buffer}, not a static buffer.
1724 The return values are the same as for @code{getgrgid_r}
1725 @code{ERANGE}.
1726 @end deftypefun
1728 @node Scanning All Groups
1729 @subsection Scanning the List of All Groups
1730 @cindex scanning the group list
1732 This section explains how a program can read the list of all groups in
1733 the system, one group at a time.  The functions described here are
1734 declared in @file{grp.h}.
1736 You can use the @code{fgetgrent} function to read group entries from a
1737 particular file.
1739 @comment grp.h
1740 @comment SVID
1741 @deftypefun {struct group *} fgetgrent (FILE *@var{stream})
1742 The @code{fgetgrent} function reads the next entry from @var{stream}.
1743 It returns a pointer to the entry.  The structure is statically
1744 allocated and is overwritten on subsequent calls to @code{fgetgrent}.  You
1745 must copy the contents of the structure if you wish to save the
1746 information.
1748 The stream must correspond to a file in the same format as the standard
1749 group database file.
1750 @end deftypefun
1752 @comment grp.h
1753 @comment GNU
1754 @deftypefun int fgetgrent_r (FILE *@var{stream}, struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1755 This function is similar to @code{fgetgrent} in that it reads the next
1756 user entry from @var{stream}.  But the result is returned in the
1757 structure pointed to by @var{result_buf}.  The first @var{buflen} bytes
1758 of the additional buffer pointed to by @var{buffer} are used to contain
1759 additional information, normally strings which are pointed to by the
1760 elements of the result structure.
1762 This stream must correspond to a file in the same format as the standard
1763 group database file.
1765 If the function returns zero @var{result} points to the structure with
1766 the wanted data (normally this is in @var{result_buf}).  If errors
1767 occurred the return value is non-zero and @var{result} contains a null
1768 pointer.
1769 @end deftypefun
1771 The way to scan all the entries in the group database is with
1772 @code{setgrent}, @code{getgrent}, and @code{endgrent}.
1774 @comment grp.h
1775 @comment SVID, BSD
1776 @deftypefun void setgrent (void)
1777 This function initializes a stream for reading from the group data base.
1778 You use this stream by calling @code{getgrent} or @code{getgrent_r}.
1779 @end deftypefun
1781 @comment grp.h
1782 @comment SVID, BSD
1783 @deftypefun {struct group *} getgrent (void)
1784 The @code{getgrent} function reads the next entry from the stream
1785 initialized by @code{setgrent}.  It returns a pointer to the entry.  The
1786 structure is statically allocated and is overwritten on subsequent calls
1787 to @code{getgrent}.  You must copy the contents of the structure if you
1788 wish to save the information.
1789 @end deftypefun
1791 @comment grp.h
1792 @comment GNU
1793 @deftypefun int getgrent_r (struct group *@var{result_buf}, char *@var{buffer}, size_t @var{buflen}, struct group **@var{result})
1794 This function is similar to @code{getgrent} in that it returns the next
1795 entry from the stream initialized by @code{setgrent}.  Like
1796 @code{fgetgrent_r}, it places the result in user-supplied buffers
1797 pointed to @var{result_buf} and @var{buffer}.
1799 If the function returns zero @var{result} contains a pointer to the data
1800 (normally equal to @var{result_buf}).  If errors occurred the return
1801 value is non-zero and @var{result} contains a null pointer.
1802 @end deftypefun
1804 @comment grp.h
1805 @comment SVID, BSD
1806 @deftypefun void endgrent (void)
1807 This function closes the internal stream used by @code{getgrent} or
1808 @code{getgrent_r}.
1809 @end deftypefun
1811 @node Database Example
1812 @section User and Group Database Example
1814 Here is an example program showing the use of the system database inquiry
1815 functions.  The program prints some information about the user running
1816 the program.
1818 @smallexample
1819 @include db.c.texi
1820 @end smallexample
1822 Here is some output from this program:
1824 @smallexample
1825 I am Throckmorton Snurd.
1826 My login name is snurd.
1827 My uid is 31093.
1828 My home directory is /home/fsg/snurd.
1829 My default shell is /bin/sh.
1830 My default group is guest (12).
1831 The members of this group are:
1832   friedman
1833   tami
1834 @end smallexample
1836 @node Netgroup Database
1837 @section Netgroup Database
1839 @menu
1840 * Netgroup Data::                  Data in the Netgroup database and where
1841                                    it comes from.
1842 * Lookup Netgroup::                How to look for a particular netgroup.
1843 * Netgroup Membership::            How to test for netgroup membership.
1844 @end menu
1846 @node Netgroup Data
1847 @subsection Netgroup Data
1849 @cindex Netgroup
1850 Sometimes it is useful to group users according to other criteria
1851 (@pxref{Group Database}).  E.g., it is useful to associate a certain
1852 group of users with a certain machine.  On the other hand grouping of
1853 host names is not supported so far.
1855 In Sun Microsystems SunOS appeared a new kind of database, the netgroup
1856 database.  It allows to group hosts, users, and domain freely, giving
1857 them individual names.  More concrete: a netgroup is a list of triples
1858 consisting of a host name, a user name, and a domain name, where any of
1859 the entries can be a wildcard entry, matching all inputs.  A last
1860 possibility is that names of other netgroups can also be given in the
1861 list specifying a netgroup.  So one can construct arbitrary hierarchies
1862 without loops.
1864 Sun's implementation allows netgroups only for the @code{nis} or
1865 @code{nisplus} service @pxref{Services in the NSS configuration}.  The
1866 implementation in the GNU C library has no such restriction.  An entry
1867 in either of the input services must have the following form:
1869 @smallexample
1870 @var{groupname} ( @var{groupname} | @code{(}@var{hostname}@code{,}@var{username}@code{,}@code{domainname}@code{)} )+
1871 @end smallexample
1873 Any of the fields in the triple can be empty which means anything
1874 matches.  While describing the functions we will see that the opposite
1875 case is useful as well.  I.e., there may be entries which will not
1876 match any input.  For entries like a name consisting of the single
1877 character @code{-} shall be used.
1879 @node Lookup Netgroup
1880 @subsection Looking up one Netgroup
1882 The lookup functions for netgroups are a bit different to all other
1883 system database handling functions.  Since a single netgroup can contain
1884 many entries a two-step process is needed.  First a single netgroup is
1885 selected and then one can iterate over all entries in this netgroup.
1886 These functions are declared in @file{netdb.h}.
1888 @comment netdb.h
1889 @comment BSD
1890 @deftypefun int setnetgrent (const char *@var{netgroup})
1891 A call to this function initializes the internal state of the library to
1892 allow following calls of the @code{getnetgrent} iterate over all entries
1893 in the netgroup with name @var{netgroup}.
1895 When the call is successful (i.e., when a netgroup with this name exist)
1896 the return value is @code{1}.  When the return value is @code{0} no
1897 netgroup of this name is known or some other error occurred.
1898 @end deftypefun
1900 It is important to remember that there is only one single state for
1901 iterating the netgroups.  Even if the programmer uses the
1902 @code{getnetgrent_r} function the result is not really reentrant since
1903 always only one single netgroup at a time can be processed.  If the
1904 program needs to process more than one netgroup simultaneously she
1905 must protect this by using external locking.  This problem was
1906 introduced in the original netgroups implementation in SunOS and since
1907 we must stay compatible it is not possible to change this.
1909 Some other functions also use the netgroups state.  Currently these are
1910 the @code{innetgr} function and parts of the implementation of the
1911 @code{compat} service part of the NSS implementation.
1913 @comment netdb.h
1914 @comment BSD
1915 @deftypefun int getnetgrent (char **@var{hostp}, char **@var{userp}, char **@var{domainp})
1916 This function returns the next unprocessed entry of the currently
1917 selected netgroup.  The string pointers, which addresses are passed in
1918 the arguments @var{hostp}, @var{userp}, and @var{domainp}, will contain
1919 after a successful call pointers to appropriate strings.  If the string
1920 in the next entry is empty the pointer has the value @code{NULL}.
1921 The returned string pointers are only valid unless no of the netgroup
1922 related functions are called.
1924 The return value is @code{1} if the next entry was successfully read.  A
1925 value of @code{0} means no further entries exist or internal errors occurred.
1926 @end deftypefun
1928 @comment netdb.h
1929 @comment GNU
1930 @deftypefun int getnetgrent_r (char **@var{hostp}, char **@var{userp}, char **@var{domainp}, char *@var{buffer}, int @var{buflen})
1931 This function is similar to @code{getnetgrent} with only one exception:
1932 the strings the three string pointers @var{hostp}, @var{userp}, and
1933 @var{domainp} point to, are placed in the buffer of @var{buflen} bytes
1934 starting at @var{buffer}.  This means the returned values are valid
1935 even after other netgroup related functions are called.
1937 The return value is @code{1} if the next entry was successfully read and
1938 the buffer contains enough room to place the strings in it.  @code{0} is
1939 returned in case no more entries are found, the buffer is too small, or
1940 internal errors occurred.
1942 This function is a GNU extension.  The original implementation in the
1943 SunOS libc does not provide this function.
1944 @end deftypefun
1946 @comment netdb.h
1947 @comment BSD
1948 @deftypefun void endnetgrent (void)
1949 This function free all buffers which were allocated to process the last
1950 selected netgroup.  As a result all string pointers returned by calls
1951 to @code{getnetgrent} are invalid afterwards.
1952 @end deftypefun
1954 @node Netgroup Membership
1955 @subsection Testing for Netgroup Membership
1957 It is often not necessary to scan the whole netgroup since often the
1958 only interesting question is whether a given entry is part of the
1959 selected netgroup.
1961 @comment netdb.h
1962 @comment BSD
1963 @deftypefun int innetgr (const char *@var{netgroup}, const char *@var{host}, const char *@var{user}, const char *@var{domain})
1964 This function tests whether the triple specified by the parameters
1965 @var{hostp}, @var{userp}, and @var{domainp} is part of the netgroup
1966 @var{netgroup}.  Using this function has the advantage that
1968 @enumerate
1969 @item
1970 no other netgroup function can use the global netgroup state since
1971 internal locking is used and
1972 @item
1973 the function is implemented more efficiently than successive calls
1974 to the other @code{set}/@code{get}/@code{endnetgrent} functions.
1975 @end enumerate
1977 Any of the pointers @var{hostp}, @var{userp}, and @var{domainp} can be
1978 @code{NULL} which means any value is excepted in this position.  This is
1979 also true for the name @code{-} which should not match any other string
1980 otherwise.
1982 The return value is @code{1} if an entry matching the given triple is
1983 found in the netgroup.  The return value is @code{0} if the netgroup
1984 itself is not found, the netgroup does not contain the triple or
1985 internal errors occurred.
1986 @end deftypefun