This is libc.info, produced by makeinfo version 4.0 from libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.10, last updated 2001-07-06, of `The GNU C Library
Reference Manual', for Version 2.2.x.

   Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002
Free Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software Needs Free Documentation" and
"GNU Lesser General Public License", the Front-Cover texts being (a)
(see below), and with the Back-Cover Texts being (b) (see below).  A
copy of the license is included in the section entitled "GNU Free
Documentation License".

   (a) The FSF's Front-Cover Text is:

   A GNU Manual

   (b) The FSF's Back-Cover Text is:

   You have freedom to copy and modify this GNU Manual, like GNU
software.  Copies published by the Free Software Foundation raise
funds for GNU development.


File: libc.info,  Node: Stopped and Terminated Jobs,  Next: Continuing Stopped Jobs,  Prev: Foreground and Background,  Up: Implementing a Shell

Stopped and Terminated Jobs
---------------------------

   When a foreground process is launched, the shell must block until
all of the processes in that job have either terminated or stopped.  It
can do this by calling the `waitpid' function; see *Note Process
Completion::.  Use the `WUNTRACED' option so that status is reported
for processes that stop as well as processes that terminate.

   The shell must also check on the status of background jobs so that it
can report terminated and stopped jobs to the user; this can be done by
calling `waitpid' with the `WNOHANG' option.  A good place to put a
such a check for terminated and stopped jobs is just before prompting
for a new command.

   The shell can also receive asynchronous notification that there is
status information available for a child process by establishing a
handler for `SIGCHLD' signals.  *Note Signal Handling::.

   In the sample shell program, the `SIGCHLD' signal is normally
ignored.  This is to avoid reentrancy problems involving the global data
structures the shell manipulates.  But at specific times when the shell
is not using these data structures--such as when it is waiting for
input on the terminal--it makes sense to enable a handler for
`SIGCHLD'.  The same function that is used to do the synchronous status
checks (`do_job_notification', in this case) can also be called from
within this handler.

   Here are the parts of the sample shell program that deal with
checking the status of jobs and reporting the information to the user.

     /* Store the status of the process PID that was returned by waitpid.
        Return 0 if all went well, nonzero otherwise.  */
     
     int
     mark_process_status (pid_t pid, int status)
     {
       job *j;
       process *p;
     
       if (pid > 0)
         {
           /* Update the record for the process.  */
           for (j = first_job; j; j = j->next)
             for (p = j->first_process; p; p = p->next)
               if (p->pid == pid)
                 {
                   p->status = status;
                   if (WIFSTOPPED (status))
                     p->stopped = 1;
                   else
                     {
                       p->completed = 1;
                       if (WIFSIGNALED (status))
                         fprintf (stderr, "%d: Terminated by signal %d.\n",
                                  (int) pid, WTERMSIG (p->status));
                     }
                   return 0;
                  }
           fprintf (stderr, "No child process %d.\n", pid);
           return -1;
         }
       else if (pid == 0 || errno == ECHILD)
         /* No processes ready to report.  */
         return -1;
       else {
         /* Other weird errors.  */
         perror ("waitpid");
         return -1;
       }
     }
     
     /* Check for processes that have status information available,
        without blocking.  */
     
     void
     update_status (void)
     {
       int status;
       pid_t pid;
     
       do
         pid = waitpid (WAIT_ANY, &status, WUNTRACED|WNOHANG);
       while (!mark_process_status (pid, status));
     }
     
     /* Check for processes that have status information available,
        blocking until all processes in the given job have reported.  */
     
     void
     wait_for_job (job *j)
     {
       int status;
       pid_t pid;
     
       do
         pid = waitpid (WAIT_ANY, &status, WUNTRACED);
       while (!mark_process_status (pid, status)
              && !job_is_stopped (j)
              && !job_is_completed (j));
     }
     
     /* Format information about job status for the user to look at.  */
     
     void
     format_job_info (job *j, const char *status)
     {
       fprintf (stderr, "%ld (%s): %s\n", (long)j->pgid, status, j->command);
     }
     
     /* Notify the user about stopped or terminated jobs.
        Delete terminated jobs from the active job list.  */
     
     void
     do_job_notification (void)
     {
       job *j, *jlast, *jnext;
       process *p;
     
       /* Update status information for child processes.  */
       update_status ();
     
       jlast = NULL;
       for (j = first_job; j; j = jnext)
         {
           jnext = j->next;
     
           /* If all processes have completed, tell the user the job has
              completed and delete it from the list of active jobs.  */
           if (job_is_completed (j)) {
             format_job_info (j, "completed");
             if (jlast)
               jlast->next = jnext;
             else
               first_job = jnext;
             free_job (j);
           }
     
           /* Notify the user about stopped jobs,
              marking them so that we won't do this more than once.  */
           else if (job_is_stopped (j) && !j->notified) {
             format_job_info (j, "stopped");
             j->notified = 1;
             jlast = j;
           }
     
           /* Don't say anything about jobs that are still running.  */
           else
             jlast = j;
         }
     }


File: libc.info,  Node: Continuing Stopped Jobs,  Next: Missing Pieces,  Prev: Stopped and Terminated Jobs,  Up: Implementing a Shell

Continuing Stopped Jobs
-----------------------

   The shell can continue a stopped job by sending a `SIGCONT' signal
to its process group.  If the job is being continued in the foreground,
the shell should first invoke `tcsetpgrp' to give the job access to the
terminal, and restore the saved terminal settings.  After continuing a
job in the foreground, the shell should wait for the job to stop or
complete, as if the job had just been launched in the foreground.

   The sample shell program handles both newly created and continued
jobs with the same pair of functions, `put_job_in_foreground' and
`put_job_in_background'.  The definitions of these functions were given
in *Note Foreground and Background::.  When continuing a stopped job, a
nonzero value is passed as the CONT argument to ensure that the
`SIGCONT' signal is sent and the terminal modes reset, as appropriate.

   This leaves only a function for updating the shell's internal
bookkeeping about the job being continued:

     /* Mark a stopped job J as being running again.  */
     
     void
     mark_job_as_running (job *j)
     {
       Process *p;
     
       for (p = j->first_process; p; p = p->next)
         p->stopped = 0;
       j->notified = 0;
     }
     
     /* Continue the job J.  */
     
     void
     continue_job (job *j, int foreground)
     {
       mark_job_as_running (j);
       if (foreground)
         put_job_in_foreground (j, 1);
       else
         put_job_in_background (j, 1);
     }


File: libc.info,  Node: Missing Pieces,  Prev: Continuing Stopped Jobs,  Up: Implementing a Shell

The Missing Pieces
------------------

   The code extracts for the sample shell included in this chapter are
only a part of the entire shell program.  In particular, nothing at all
has been said about how `job' and `program' data structures are
allocated and initialized.

   Most real shells provide a complex user interface that has support
for a command language; variables; abbreviations, substitutions, and
pattern matching on file names; and the like.  All of this is far too
complicated to explain here!  Instead, we have concentrated on showing
how to implement the core process creation and job control functions
that can be called from such a shell.

   Here is a table summarizing the major entry points we have presented:

`void init_shell (void)'
     Initialize the shell's internal state.  *Note Initializing the
     Shell::.

`void launch_job (job *J, int FOREGROUND)'
     Launch the job J as either a foreground or background job.  *Note
     Launching Jobs::.

`void do_job_notification (void)'
     Check for and report any jobs that have terminated or stopped.
     Can be called synchronously or within a handler for `SIGCHLD'
     signals.  *Note Stopped and Terminated Jobs::.

`void continue_job (job *J, int FOREGROUND)'
     Continue the job J.  *Note Continuing Stopped Jobs::.

   Of course, a real shell would also want to provide other functions
for managing jobs.  For example, it would be useful to have commands to
list all active jobs or to send a signal (such as `SIGKILL') to a job.


File: libc.info,  Node: Functions for Job Control,  Prev: Implementing a Shell,  Up: Job Control

Functions for Job Control
=========================

   This section contains detailed descriptions of the functions relating
to job control.

* Menu:

* Identifying the Terminal::    Determining the controlling terminal's name.
* Process Group Functions::     Functions for manipulating process groups.
* Terminal Access Functions::   Functions for controlling terminal access.


File: libc.info,  Node: Identifying the Terminal,  Next: Process Group Functions,  Up: Functions for Job Control

Identifying the Controlling Terminal
------------------------------------

   You can use the `ctermid' function to get a file name that you can
use to open the controlling terminal.  In the GNU library, it returns
the same string all the time: `"/dev/tty"'.  That is a special "magic"
file name that refers to the controlling terminal of the current
process (if it has one).  To find the name of the specific terminal
device, use `ttyname'; *note Is It a Terminal::.

   The function `ctermid' is declared in the header file `stdio.h'.

 - Function: char * ctermid (char *STRING)
     The `ctermid' function returns a string containing the file name of
     the controlling terminal for the current process.  If STRING is
     not a null pointer, it should be an array that can hold at least
     `L_ctermid' characters; the string is returned in this array.
     Otherwise, a pointer to a string in a static area is returned,
     which might get overwritten on subsequent calls to this function.

     An empty string is returned if the file name cannot be determined
     for any reason.  Even if a file name is returned, access to the
     file it represents is not guaranteed.

 - Macro: int L_ctermid
     The value of this macro is an integer constant expression that
     represents the size of a string large enough to hold the file name
     returned by `ctermid'.

   See also the `isatty' and `ttyname' functions, in *Note Is It a
Terminal::.


File: libc.info,  Node: Process Group Functions,  Next: Terminal Access Functions,  Prev: Identifying the Terminal,  Up: Functions for Job Control

Process Group Functions
-----------------------

   Here are descriptions of the functions for manipulating process
groups.  Your program should include the header files `sys/types.h' and
`unistd.h' to use these functions.

 - Function: pid_t setsid (void)
     The `setsid' function creates a new session.  The calling process
     becomes the session leader, and is put in a new process group whose
     process group ID is the same as the process ID of that process.
     There are initially no other processes in the new process group,
     and no other process groups in the new session.

     This function also makes the calling process have no controlling
     terminal.

     The `setsid' function returns the new process group ID of the
     calling process if successful.  A return value of `-1' indicates an
     error.  The following `errno' error conditions are defined for this
     function:

    `EPERM'
          The calling process is already a process group leader, or
          there is already another process group around that has the
          same process group ID.

 - Function: pid_t getsid (pid_t PID)
     The `getsid' function returns the process group ID of the session
     leader of the specified process.  If a PID is `0', the process
     group ID of the session leader of the current process is returned.

     In case of error `-1' is returned and `errno' is set.  The
     following `errno' error conditions are defined for this function:

    `ESRCH'
          There is no process with the given process ID PID.

    `EPERM'
          The calling process and the process specified by PID are in
          different sessions, and the implementation doesn't allow to
          access the process group ID of the session leader of the
          process with ID PID from the calling process.

   The `getpgrp' function has two definitions: one derived from BSD
Unix, and one from the POSIX.1 standard.  The feature test macros you
have selected (*note Feature Test Macros::) determine which definition
you get.  Specifically, you get the BSD version if you define
`_BSD_SOURCE'; otherwise, you get the POSIX version if you define
`_POSIX_SOURCE' or `_GNU_SOURCE'.  Programs written for old BSD systems
will not include `unistd.h', which defines `getpgrp' specially under
`_BSD_SOURCE'.  You must link such programs with the `-lbsd-compat'
option to get the BSD definition.

 - POSIX.1 Function: pid_t getpgrp (void)
     The POSIX.1 definition of `getpgrp' returns the process group ID of
     the calling process.

 - BSD Function: pid_t getpgrp (pid_t PID)
     The BSD definition of `getpgrp' returns the process group ID of the
     process PID.  You can supply a value of `0' for the PID argument
     to get information about the calling process.

 - System V Function: int getpgid (pid_t PID)
     `getpgid' is the same as the BSD function `getpgrp'.  It returns
     the process group ID of the process PID.  You can supply a value
     of `0' for the PID argument to get information about the calling
     process.

     In case of error `-1' is returned and `errno' is set.  The
     following `errno' error conditions are defined for this function:

    `ESRCH'
          There is no process with the given process ID PID.  The
          calling process and the process specified by PID are in
          different sessions, and the implementation doesn't allow to
          access the process group ID of the process with ID PID from
          the calling process.

 - Function: int setpgid (pid_t PID, pid_t PGID)
     The `setpgid' function puts the process PID into the process group
     PGID.  As a special case, either PID or PGID can be zero to
     indicate the process ID of the calling process.

     This function fails on a system that does not support job control.
     *Note Job Control is Optional::, for more information.

     If the operation is successful, `setpgid' returns zero.  Otherwise
     it returns `-1'.  The following `errno' error conditions are
     defined for this function:

    `EACCES'
          The child process named by PID has executed an `exec'
          function since it was forked.

    `EINVAL'
          The value of the PGID is not valid.

    `ENOSYS'
          The system doesn't support job control.

    `EPERM'
          The process indicated by the PID argument is a session leader,
          or is not in the same session as the calling process, or the
          value of the PGID argument doesn't match a process group ID
          in the same session as the calling process.

    `ESRCH'
          The process indicated by the PID argument is not the calling
          process or a child of the calling process.

 - Function: int setpgrp (pid_t PID, pid_t PGID)
     This is the BSD Unix name for `setpgid'.  Both functions do exactly
     the same thing.


File: libc.info,  Node: Terminal Access Functions,  Prev: Process Group Functions,  Up: Functions for Job Control

Functions for Controlling Terminal Access
-----------------------------------------

   These are the functions for reading or setting the foreground
process group of a terminal.  You should include the header files
`sys/types.h' and `unistd.h' in your application to use these functions.

   Although these functions take a file descriptor argument to specify
the terminal device, the foreground job is associated with the terminal
file itself and not a particular open file descriptor.

 - Function: pid_t tcgetpgrp (int FILEDES)
     This function returns the process group ID of the foreground
     process group associated with the terminal open on descriptor
     FILEDES.

     If there is no foreground process group, the return value is a
     number greater than `1' that does not match the process group ID
     of any existing process group.  This can happen if all of the
     processes in the job that was formerly the foreground job have
     terminated, and no other job has yet been moved into the
     foreground.

     In case of an error, a value of `-1' is returned.  The following
     `errno' error conditions are defined for this function:

    `EBADF'
          The FILEDES argument is not a valid file descriptor.

    `ENOSYS'
          The system doesn't support job control.

    `ENOTTY'
          The terminal file associated with the FILEDES argument isn't
          the controlling terminal of the calling process.

 - Function: int tcsetpgrp (int FILEDES, pid_t PGID)
     This function is used to set a terminal's foreground process group
     ID.  The argument FILEDES is a descriptor which specifies the
     terminal; PGID specifies the process group.  The calling process
     must be a member of the same session as PGID and must have the same
     controlling terminal.

     For terminal access purposes, this function is treated as output.
     If it is called from a background process on its controlling
     terminal, normally all processes in the process group are sent a
     `SIGTTOU' signal.  The exception is if the calling process itself
     is ignoring or blocking `SIGTTOU' signals, in which case the
     operation is performed and no signal is sent.

     If successful, `tcsetpgrp' returns `0'.  A return value of `-1'
     indicates an error.  The following `errno' error conditions are
     defined for this function:

    `EBADF'
          The FILEDES argument is not a valid file descriptor.

    `EINVAL'
          The PGID argument is not valid.

    `ENOSYS'
          The system doesn't support job control.

    `ENOTTY'
          The FILEDES isn't the controlling terminal of the calling
          process.

    `EPERM'
          The PGID isn't a process group in the same session as the
          calling process.

 - Function: pid_t tcgetsid (int FILDES)
     This function is used to obtain the process group ID of the session
     for which the terminal specified by FILDES is the controlling
     terminal.  If the call is successful the group ID is returned.
     Otherwise the return value is `(pid_t) -1' and the global variable
     ERRNO is set to the following value:
    `EBADF'
          The FILEDES argument is not a valid file descriptor.

    `ENOTTY'
          The calling process does not have a controlling terminal, or
          the file is not the controlling terminal.


File: libc.info,  Node: Name Service Switch,  Next: Users and Groups,  Prev: Job Control,  Up: Top

System Databases and Name Service Switch
****************************************

   Various functions in the C Library need to be configured to work
correctly in the local environment.  Traditionally, this was done by
using files (e.g., `/etc/passwd'), but other nameservices (like the
Network Information Service (NIS) and the Domain Name Service (DNS))
became popular, and were hacked into the C library, usually with a fixed
search order (*note frobnicate: (jargon)frobnicate.).

   The GNU C Library contains a cleaner solution of this problem.  It is
designed after a method used by Sun Microsystems in the C library of
Solaris 2.  GNU C Library follows their name and calls this scheme
"Name Service Switch" (NSS).

   Though the interface might be similar to Sun's version there is no
common code.  We never saw any source code of Sun's implementation and
so the internal interface is incompatible.  This also manifests in the
file names we use as we will see later.

* Menu:

* NSS Basics::                  What is this NSS good for.
* NSS Configuration File::      Configuring NSS.
* NSS Module Internals::        How does it work internally.
* Extending NSS::               What to do to add services or databases.


File: libc.info,  Node: NSS Basics,  Next: NSS Configuration File,  Prev: Name Service Switch,  Up: Name Service Switch

NSS Basics
==========

   The basic idea is to put the implementation of the different services
offered to access the databases in separate modules.  This has some
advantages:

  1. Contributors can add new services without adding them to GNU C
     Library.

  2. The modules can be updated separately.

  3. The C library image is smaller.

   To fulfill the first goal above the ABI of the modules will be
described below.  For getting the implementation of a new service right
it is important to understand how the functions in the modules get
called.  They are in no way designed to be used by the programmer
directly.  Instead the programmer should only use the documented and
standardized functions to access the databases.

The databases available in the NSS are

`aliases'
     Mail aliases

`ethers'
     Ethernet numbers,

`group'
     Groups of users, *note Group Database::.

`hosts'
     Host names and numbers, *note Host Names::.

`netgroup'
     Network wide list of host and users, *note Netgroup Database::.

`networks'
     Network names and numbers, *note Networks Database::.

`protocols'
     Network protocols, *note Protocols Database::.

`passwd'
     User passwords, *note User Database::.

`rpc'
     Remote procedure call names and numbers,

`services'
     Network services, *note Services Database::.

`shadow'
     Shadow user passwords,

There will be some more added later (`automount', `bootparams',
`netmasks', and `publickey').


File: libc.info,  Node: NSS Configuration File,  Next: NSS Module Internals,  Prev: NSS Basics,  Up: Name Service Switch

The NSS Configuration File
==========================

   Somehow the NSS code must be told about the wishes of the user.  For
this reason there is the file `/etc/nsswitch.conf'.  For each database
this file contain a specification how the lookup process should work.
The file could look like this:

     # /etc/nsswitch.conf
     #
     # Name Service Switch configuration file.
     #
     
     passwd:     db files nis
     shadow:     files
     group:      db files nis
     
     hosts:      files nisplus nis dns
     networks:   nisplus [NOTFOUND=return] files
     
     ethers:     nisplus [NOTFOUND=return] db files
     protocols:  nisplus [NOTFOUND=return] db files
     rpc:        nisplus [NOTFOUND=return] db files
     services:   nisplus [NOTFOUND=return] db files

   The first column is the database as you can guess from the table
above.  The rest of the line specifies how the lookup process works.
Please note that you specify the way it works for each database
individually.  This cannot be done with the old way of a monolithic
implementation.

   The configuration specification for each database can contain two
different items:

   * the service specification like `files', `db', or `nis'.

   * the reaction on lookup result like `[NOTFOUND=return]'.

* Menu:

* Services in the NSS configuration::  Service names in the NSS configuration.
* Actions in the NSS configuration::  React appropriately to the lookup result.
* Notes on NSS Configuration File::  Things to take care about while
                                     configuring NSS.


File: libc.info,  Node: Services in the NSS configuration,  Next: Actions in the NSS configuration,  Prev: NSS Configuration File,  Up: NSS Configuration File

Services in the NSS configuration File
--------------------------------------

   The above example file mentions four different services: `files',
`db', `nis', and `nisplus'.  This does not mean these services are
available on all sites and it does also not mean these are all the
services which will ever be available.

   In fact, these names are simply strings which the NSS code uses to
find the implicitly addressed functions.  The internal interface will be
described later.  Visible to the user are the modules which implement an
individual service.

   Assume the service NAME shall be used for a lookup.  The code for
this service is implemented in a module called `libnss_NAME'.  On a
system supporting shared libraries this is in fact a shared library
with the name (for example) `libnss_NAME.so.2'.  The number at the end
is the currently used version of the interface which will not change
frequently.  Normally the user should not have to be cognizant of these
files since they should be placed in a directory where they are found
automatically.  Only the names of all available services are important.


File: libc.info,  Node: Actions in the NSS configuration,  Next: Notes on NSS Configuration File,  Prev: Services in the NSS configuration,  Up: NSS Configuration File

Actions in the NSS configuration
--------------------------------

   The second item in the specification gives the user much finer
control on the lookup process.  Action items are placed between two
service names and are written within brackets.  The general form is

     `[' ( `!'? STATUS `=' ACTION )+ `]'

where

     STATUS => success | notfound | unavail | tryagain
     ACTION => return | continue

   The case of the keywords is insignificant.  The STATUS values are
the results of a call to a lookup function of a specific service.  They
mean

`success'
     No error occurred and the wanted entry is returned.  The default
     action for this is `return'.

`notfound'
     The lookup process works ok but the needed value was not found.
     The default action is `continue'.

`unavail'
     The service is permanently unavailable.  This can either mean the
     needed file is not available, or, for DNS, the server is not
     available or does not allow queries.  The default action is
     `continue'.

`tryagain'
     The service is temporarily unavailable.  This could mean a file is
     locked or a server currently cannot accept more connections.  The
     default action is `continue'.

If we have a line like

     ethers: nisplus [NOTFOUND=return] db files

this is equivalent to

     ethers: nisplus [SUCCESS=return NOTFOUND=return UNAVAIL=continue
                      TRYAGAIN=continue]
             db      [SUCCESS=return NOTFOUND=continue UNAVAIL=continue
                      TRYAGAIN=continue]
             files

(except that it would have to be written on one line).  The default
value for the actions are normally what you want, and only need to be
changed in exceptional cases.

   If the optional `!' is placed before the STATUS this means the
following action is used for all statuses but STATUS itself.  I.e., `!'
is negation as in the C language (and others).

   Before we explain the exception which makes this action item
necessary one more remark: obviously it makes no sense to add another
action item after the `files' service.  Since there is no other service
following the action _always_ is `return'.

   Now, why is this `[NOTFOUND=return]' action useful?  To understand
this we should know that the `nisplus' service is often complete; i.e.,
if an entry is not available in the NIS+ tables it is not available
anywhere else.  This is what is expressed by this action item: it is
useless to examine further services since they will not give us a
result.

   The situation would be different if the NIS+ service is not available
because the machine is booting.  In this case the return value of the
lookup function is not `notfound' but instead `unavail'.  And as you
can see in the complete form above: in this situation the `db' and
`files' services are used.  Neat, isn't it?  The system administrator
need not pay special care for the time the system is not completely
ready to work (while booting or shutdown or network problems).


File: libc.info,  Node: Notes on NSS Configuration File,  Prev: Actions in the NSS configuration,  Up: NSS Configuration File

Notes on the NSS Configuration File
-----------------------------------

   Finally a few more hints.  The NSS implementation is not completely
helpless if `/etc/nsswitch.conf' does not exist.  For all supported
databases there is a default value so it should normally be possible to
get the system running even if the file is corrupted or missing.

   For the `hosts' and `networks' databases the default value is `dns
[!UNAVAIL=return] files'.  I.e., the system is prepared for the DNS
service not to be available but if it is available the answer it
returns is definitive.

   The `passwd', `group', and `shadow' databases are traditionally
handled in a special way.  The appropriate files in the `/etc'
directory are read but if an entry with a name starting with a `+'
character is found NIS is used.  This kind of lookup remains possible
by using the special lookup service `compat' and the default value for
the three databases above is `compat [NOTFOUND=return] files'.

   For all other databases the default value is `nis [NOTFOUND=return]
files'.  This solution give the best chance to be correct since NIS and
file based lookup is used.

   A second point is that the user should try to optimize the lookup
process.  The different service have different response times.  A
simple file look up on a local file could be fast, but if the file is
long and the needed entry is near the end of the file this may take
quite some time.  In this case it might be better to use the `db'
service which allows fast local access to large data sets.

   Often the situation is that some global information like NIS must be
used.  So it is unavoidable to use service entries like `nis' etc.  But
one should avoid slow services like this if possible.


File: libc.info,  Node: NSS Module Internals,  Next: Extending NSS,  Prev: NSS Configuration File,  Up: Name Service Switch

NSS Module Internals
====================

   Now it is time to describe what the modules look like.  The functions
contained in a module are identified by their names.  I.e., there is no
jump table or the like.  How this is done is of no interest here; those
interested in this topic should read about Dynamic Linking.

* Menu:

* NSS Module Names::            Construction of the interface function of
                                the NSS modules.
* NSS Modules Interface::       Programming interface in the NSS module
                                functions.


File: libc.info,  Node: NSS Module Names,  Next: NSS Modules Interface,  Prev: NSS Module Internals,  Up: NSS Module Internals

The Naming Scheme of the NSS Modules
------------------------------------

The name of each function consist of various parts:

            _nss_SERVICE_FUNCTION

   SERVICE of course corresponds to the name of the module this
function is found in.(1)  The FUNCTION part is derived from the
interface function in the C library itself.  If the user calls the
function `gethostbyname' and the service used is `files' the function

            _nss_files_gethostbyname_r

in the module

            libnss_files.so.2

is used.  You see, what is explained above in not the whole truth.  In
fact the NSS modules only contain reentrant versions of the lookup
functions.  I.e., if the user would call the `gethostbyname_r' function
this also would end in the above function.  For all user interface
functions the C library maps this call to a call to the reentrant
function.  For reentrant functions this is trivial since the interface
is (nearly) the same.  For the non-reentrant version The library keeps
internal buffers which are used to replace the user supplied buffer.

   I.e., the reentrant functions _can_ have counterparts.  No service
module is forced to have functions for all databases and all kinds to
access them.  If a function is not available it is simply treated as if
the function would return `unavail' (*note Actions in the NSS
configuration::).

   The file name `libnss_files.so.2' would be on a Solaris 2 system
`nss_files.so.2'.  This is the difference mentioned above.  Sun's NSS
modules are usable as modules which get indirectly loaded only.

   The NSS modules in the GNU C Library are prepared to be used as
normal libraries themselves.  This is _not_ true at the moment, though.
However,  the organization of the name space in the modules does not
make it impossible like it is for Solaris.  Now you can see why the
modules are still libraries.(2)

   ---------- Footnotes ----------

   (1) Now you might ask why this information is duplicated.  The
answer is that we want to make it possible to link directly with these
shared objects.

   (2) There is a second explanation: we were too lazy to change the
Makefiles to allow the generation of shared objects not starting with
`lib' but don't tell this to anybody.


File: libc.info,  Node: NSS Modules Interface,  Prev: NSS Module Names,  Up: NSS Module Internals

The Interface of the Function in NSS Modules
--------------------------------------------

   Now we know about the functions contained in the modules.  It is now
time to describe the types.  When we mentioned the reentrant versions of
the functions above, this means there are some additional arguments
(compared with the standard, non-reentrant version).  The prototypes for
the non-reentrant and reentrant versions of our function above are:

     struct hostent *gethostbyname (const char *name)
     
     int gethostbyname_r (const char *name, struct hostent *result_buf,
                          char *buf, size_t buflen, struct hostent **result,
                          int *h_errnop)

The actual prototype of the function in the NSS modules in this case is

     enum nss_status _nss_files_gethostbyname_r (const char *name,
                                                 struct hostent *result_buf,
                                                 char *buf, size_t buflen,
                                                 int *errnop, int *h_errnop)

   I.e., the interface function is in fact the reentrant function with
the change of the return value and the omission of the RESULT
parameter.  While the user-level function returns a pointer to the
result the reentrant function return an `enum nss_status' value:

`NSS_STATUS_TRYAGAIN'
     numeric value `-2'

`NSS_STATUS_UNAVAIL'
     numeric value `-1'

`NSS_STATUS_NOTFOUND'
     numeric value `0'

`NSS_STATUS_SUCCESS'
     numeric value `1'

Now you see where the action items of the `/etc/nsswitch.conf' file are
used.

   If you study the source code you will find there is a fifth value:
`NSS_STATUS_RETURN'.  This is an internal use only value, used by a few
functions in places where none of the above value can be used.  If
necessary the source code should be examined to learn about the details.

   In case the interface function has to return an error it is important
that the correct error code is stored in `*ERRNOP'.  Some return status
value have only one associated error code, others have more.

`NSS_STATUS_TRYAGAIN'   `EAGAIN'      One of the functions used ran
                                      temporarily out of resources or a
                                      service is currently not available.
                       `ERANGE'       The provided buffer is not large
                                      enough.  The function should be
                                      called again with a larger buffer.
`NSS_STATUS_UNAVAIL'    `ENOENT'      A necessary input file cannot be
                                      found.
`NSS_STATUS_NOTFOUND'   `ENOENT'      The requested entry is not
                                      available.

   These are proposed values.  There can be other error codes and the
described error codes can have different meaning.  *With one
exception:* when returning `NSS_STATUS_TRYAGAIN' the error code
`ERANGE' _must_ mean that the user provided buffer is too small.
Everything is non-critical.

   The above function has something special which is missing for almost
all the other module functions.  There is an argument H_ERRNOP.  This
points to a variable which will be filled with the error code in case
the execution of the function fails for some reason.  The reentrant
function cannot use the global variable H_ERRNO; `gethostbyname' calls
`gethostbyname_r' with the last argument set to `&h_errno'.

   The `getXXXbyYYY' functions are the most important functions in the
NSS modules.  But there are others which implement the other ways to
access system databases (say for the password database, there are
`setpwent', `getpwent', and `endpwent').  These will be described in
more detail later.  Here we give a general way to determine the
signature of the module function:

   * the return value is `int';

   * the name is as explained in *note NSS Module Names::;

   * the first arguments are identical to the arguments of the
     non-reentrant function;

   * the next three arguments are:

    `STRUCT_TYPE *result_buf'
          pointer to buffer where the result is stored.  `STRUCT_TYPE'
          is normally a struct which corresponds to the database.

    `char *buffer'
          pointer to a buffer where the function can store additional
          data for the result etc.

    `size_t buflen'
          length of the buffer pointed to by BUFFER.

   * possibly a last argument H_ERRNOP, for the host name and network
     name lookup functions.

This table is correct for all functions but the `set...ent' and
`end...ent' functions.


File: libc.info,  Node: Extending NSS,  Prev: NSS Module Internals,  Up: Name Service Switch

Extending NSS
=============

   One of the advantages of NSS mentioned above is that it can be
extended quite easily.  There are two ways in which the extension can
happen: adding another database or adding another service.  The former
is normally done only by the C library developers.  It is here only
important to remember that adding another database is independent from
adding another service because a service need not support all databases
or lookup functions.

   A designer/implementor of a new service is therefore free to choose
the databases s/he is interested in and leave the rest for later (or
completely aside).

* Menu:

* Adding another Service to NSS::  What is to do to add a new service.
* NSS Module Function Internals::  Guidelines for writing new NSS
                                        service functions.


File: libc.info,  Node: Adding another Service to NSS,  Next: NSS Module Function Internals,  Prev: Extending NSS,  Up: Extending NSS

Adding another Service to NSS
-----------------------------

   The sources for a new service need not (and should not) be part of
the GNU C Library itself.  The developer retains complete control over
the sources and its development.  The links between the C library and
the new service module consists solely of the interface functions.

   Each module is designed following a specific interface specification.
For now the version is 2 (the interface in version 1 was not adequate)
and this manifests in the version number of the shared library object of
the NSS modules: they have the extension `.2'.  If the interface
changes again in an incompatible way, this number will be increased.
Modules using the old interface will still be usable.

   Developers of a new service will have to make sure that their module
is created using the correct interface number.  This means the file
itself must have the correct name and on ELF systems the "soname"
(Shared Object Name) must also have this number.  Building a module
from a bunch of object files on an ELF system using GNU CC could be
done like this:

     gcc -shared -o libnss_NAME.so.2 -Wl,-soname,libnss_NAME.so.2 OBJECTS

*Note Options for Linking: (gcc)Link Options, to learn more about this
command line.

   To use the new module the library must be able to find it.  This can
be achieved by using options for the dynamic linker so that it will
search the directory where the binary is placed.  For an ELF system
this could be done by adding the wanted directory to the value of
`LD_LIBRARY_PATH'.

   But this is not always possible since some programs (those which run
under IDs which do not belong to the user) ignore this variable.
Therefore the stable version of the module should be placed into a
directory which is searched by the dynamic linker.  Normally this should
be the directory `$prefix/lib', where `$prefix' corresponds to the
value given to configure using the `--prefix' option.  But be careful:
this should only be done if it is clear the module does not cause any
harm.  System administrators should be careful.


File: libc.info,  Node: NSS Module Function Internals,  Prev: Adding another Service to NSS,  Up: Extending NSS

Internals of the NSS Module Functions
-------------------------------------

   Until now we only provided the syntactic interface for the functions
in the NSS module.  In fact there is not much more we can say since the
implementation obviously is different for each function.  But a few
general rules must be followed by all functions.

   In fact there are four kinds of different functions which may appear
in the interface.  All derive from the traditional ones for system
databases.  DB in the following table is normally an abbreviation for
the database (e.g., it is `pw' for the password database).

`enum nss_status _nss_DATABASE_setDBent (void)'
     This function prepares the service for following operations.  For a
     simple file based lookup this means files could be opened, for
     other services this function simply is a noop.

     One special case for this function is that it takes an additional
     argument for some DATABASEs (i.e., the interface is `int setDBent
     (int)').  *Note Host Names::, which describes the `sethostent'
     function.

     The return value should be NSS_STATUS_SUCCESS or according to the
     table above in case of an error (*note NSS Modules Interface::).

`enum nss_status _nss_DATABASE_endDBent (void)'
     This function simply closes all files which are still open or
     removes buffer caches.  If there are no files or buffers to remove
     this is again a simple noop.

     There normally is no return value different to NSS_STATUS_SUCCESS.

`enum nss_status _nss_DATABASE_getDBent_r (STRUCTURE *result, char *buffer, size_t buflen, int *errnop)'
     Since this function will be called several times in a row to
     retrieve one entry after the other it must keep some kind of
     state.  But this also means the functions are not really
     reentrant.  They are reentrant only in that simultaneous calls to
     this function will not try to write the retrieved data in the same
     place (as it would be the case for the non-reentrant functions);
     instead, it writes to the structure pointed to by the RESULT
     parameter.  But the calls share a common state and in the case of
     a file access this means they return neighboring entries in the
     file.

     The buffer of length BUFLEN pointed to by BUFFER can be used for
     storing some additional data for the result.  It is _not_
     guaranteed that the same buffer will be passed for the next call
     of this function.  Therefore one must not misuse this buffer to
     save some state information from one call to another.

     Before the function returns the implementation should store the
     value of the local ERRNO variable in the variable pointed to be
     ERRNOP.  This is important to guarantee the module working in
     statically linked programs.

     As explained above this function could also have an additional last
     argument.  This depends on the database used; it happens only for
     `host' and `networks'.

     The function shall return `NSS_STATUS_SUCCESS' as long as there are
     more entries.  When the last entry was read it should return
     `NSS_STATUS_NOTFOUND'.  When the buffer given as an argument is too
     small for the data to be returned `NSS_STATUS_TRYAGAIN' should be
     returned.  When the service was not formerly initialized by a call
     to `_nss_DATABASE_setDBent' all return value allowed for this
     function can also be returned here.

`enum nss_status _nss_DATABASE_getDBbyXX_r (PARAMS, STRUCTURE *result, char *buffer, size_t buflen, int *errnop)'
     This function shall return the entry from the database which is
     addressed by the PARAMS.  The type and number of these arguments
     vary.  It must be individually determined by looking to the
     user-level interface functions.  All arguments given to the
     non-reentrant version are here described by PARAMS.

     The result must be stored in the structure pointed to by RESULT.
     If there is additional data to return (say strings, where the
     RESULT structure only contains pointers) the function must use the
     BUFFER or length BUFLEN.  There must not be any references to
     non-constant global data.

     The implementation of this function should honor the STAYOPEN flag
     set by the `setDBent' function whenever this makes sense.

     Before the function returns the implementation should store the
     value of the local ERRNO variable in the variable pointed to be
     ERRNOP.  This is important to guarantee the module working in
     statically linked programs.

     Again, this function takes an additional last argument for the
     `host' and `networks' database.

     The return value should as always follow the rules given above
     (*note NSS Modules Interface::).


File: libc.info,  Node: Users and Groups,  Next: System Management,  Prev: Name Service Switch,  Up: Top

Users and Groups
****************

   Every user who can log in on the system is identified by a unique
number called the "user ID".  Each process has an effective user ID
which says which user's access permissions it has.

   Users are classified into "groups" for access control purposes.  Each
process has one or more "group ID values" which say which groups the
process can use for access to files.

   The effective user and group IDs of a process collectively form its
"persona".  This determines which files the process can access.
Normally, a process inherits its persona from the parent process, but
under special circumstances a process can change its persona and thus
change its access permissions.

   Each file in the system also has a user ID and a group ID.  Access
control works by comparing the user and group IDs of the file with those
of the running process.

   The system keeps a database of all the registered users, and another
database of all the defined groups.  There are library functions you
can use to examine these databases.

* Menu:

* User and Group IDs::          Each user has a unique numeric ID;
				 likewise for groups.
* Process Persona::             The user IDs and group IDs of a process.
* Why Change Persona::          Why a program might need to change
				 its user and/or group IDs.
* How Change Persona::          Changing the user and group IDs.
* Reading Persona::             How to examine the user and group IDs.

* Setting User ID::             Functions for setting the user ID.
* Setting Groups::              Functions for setting the group IDs.

* Enable/Disable Setuid::       Turning setuid access on and off.
* Setuid Program Example::      The pertinent parts of one sample program.
* Tips for Setuid::             How to avoid granting unlimited access.

* Who Logged In::               Getting the name of the user who logged in,
				 or of the real user ID of the current process.

* User Accounting Database::    Keeping information about users and various
                                 actions in databases.

* User Database::               Functions and data structures for
                        	 accessing the user database.
* Group Database::              Functions and data structures for
                        	 accessing the group database.
* Database Example::            Example program showing the use of database
				 inquiry functions.
* Netgroup Database::           Functions for accessing the netgroup database.


File: libc.info,  Node: User and Group IDs,  Next: Process Persona,  Up: Users and Groups

User and Group IDs
==================

   Each user account on a computer system is identified by a "user
name" (or "login name") and "user ID".  Normally, each user name has a
unique user ID, but it is possible for several login names to have the
same user ID.  The user names and corresponding user IDs are stored in
a data base which you can access as described in *Note User Database::.

   Users are classified in "groups".  Each user name belongs to one
"default group" and may also belong to any number of "supplementary
groups". Users who are members of the same group can share resources
(such as files) that are not accessible to users who are not a member
of that group.  Each group has a "group name" and "group ID".  *Note
Group Database::, for how to find information about a group ID or group
name.

