/* * daemon - https://libslack.org/daemon * * Copyright (C) 1999-2004, 2010, 2020-2023 raf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * * 20230824 raf */ /* =head1 NAME I - turns other processes into daemons =head1 SYNOPSIS usage: daemon [options] [--] [cmd arg...] options: -h, --help - Print a help message then exit -V, --version - Print a version message then exit -v, --verbose[=level] - Set the verbosity level -d, --debug[=level] - Set the debugging level -C, --config=path - Specify the system configuration file -N, --noconfig - Bypass the system configuration file -n, --name=name - Guarantee a single named instance -X, --command="cmd" - Specify the client command as an option -P, --pidfiles=/dir - Override standard pidfile location -F, --pidfile=/path - Override standard pidfile name and location -u, --user=user[:[group]] - Run the client as user[:group] -R, --chroot=path - Run the client with path as root -D, --chdir=path - Run the client in directory path -m, --umask=umask - Run the client with the given umask -e, --env="var=val" - Set a client environment variable -i, --inherit - Inherit environment variables -U, --unsafe - Allow execution of unsafe executable -S, --safe - Disallow execution of unsafe executable -c, --core - Allow core file generation --nocore - Disallow core file generation (default) -r, --respawn - Respawn the client when it terminates -a, --acceptable=# - Minimum acceptable client duration (seconds) -A, --attempts=# - Respawn # times on error before delay -L, --delay=# - Delay between respawn attempt bursts (seconds) -M, --limit=# - Maximum number of respawn attempt bursts --idiot - Idiot mode (trust root with the above) -f, --foreground - Run the client in the foreground -p, --pty[=noecho] - Allocate a pseudo terminal for the client -B, --bind - Stop when the user's last logind session ends -l, --errlog=spec - Send daemon's error output to syslog or file -b, --dbglog=spec - Send daemon's debug output to syslog or file -o, --output=spec - Send client's output to syslog or file -O, --stdout=spec - Send client's stdout to syslog or file -E, --stderr=spec - Send client's stderr to syslog or file --ignore-eof - After SIGCHLD ignore any client output --read-eof - After SIGCHLD read any client output (default) --running - Check if a named daemon is running --restart - Restart a named daemon client --stop - Terminate a named daemon process --signal=signame - Send a signal to a named daemon --list - Print a list of named daemons =head1 DESCRIPTION I turns other processes into daemons. There are many tasks that need to be performed to correctly set up a daemon process. This can be tedious. I performs these tasks for other processes. The preparatory tasks that I performs for other processes are: =over 4 =item * First, revoke any setuid or setgid privileges that I may have been installed with (by system administrators who laugh in the face of danger). =item * Process command line options. =item * Change the root directory if the C<--chroot> option was supplied. =item * Change the process uid and gid if the C<--user> option was supplied. Only I can use this option. Note that the uid of I itself is changed, rather than just changing the uid of the client process. =item * Read the system configuration file(s) (C and C by default, or specified by the C<--config> option), unless the C<--noconfig> option was supplied. Then read the user's personal configuration file(s) (C<~/.daemonrc> and C<~/.daemonrc.d/*>), if any. Generic options that apply to all daemons are processed first, then options that are specific to the daemon with the given name. B nor C<--user> options may appear in the configuration file.> On I systems (except I), the system configuration file(s) are C and C by default. On I, when installed via I, the system configuration file(s) are C and C. =item * Disable core file generation to prevent leaking potentially sensitive information in daemons that are run by I (unless the C<--core> option was supplied). =item * Become a daemon process: =over 4 =item * If I was not invoked by I (i.e. parent process id 1) or I (i.e. C is a socket): =over 4 =item * Ignore C signals in case the current process session leader terminates while attached to a controlling terminal, causing us to receive a C signal before we start our own process session below. This can happen when I was invoked interactively via the shell builtin C. When this initial process terminates below, the terminal emulator that invoked the shell also terminates, so I need to protect itself from that. =item * Background the process to lose process group leadership. =item * Start a new process session. =item * Background the process again to lose process session leadership. Under I, this prevents the process from ever gaining a controlling terminal. This is only necessary under I, but is always done for simplicity. Note that ignoring C signals earlier means that when the newly created process session leader terminates, then even if it has a controlling terminal open, the newly backgrounded process won't receive the corresponding C signal that is sent to all processes in the process session's foreground process group, because it inherited signal dispositions from the initial process. =back =item * Change the current directory to the root directory so as not to hamper umounts. =item * Clear the I to enable explicit file creation modes. =item * Close all open file descriptors. If I was invoked by I, C, C and C are left open, because they are open to a socket. =item * Open C, C and C to C, in case something requires them to be open. Of course, this is not done if I was invoked by I. =item * If the C<--name> option was supplied, create and lock a file containing the process id of the I process. The presence of this locked file prevents two instances of a daemon with the same name from running at the same time. The default location of the pidfile is C for I (C on I, C on I when installed via I), and C for normal users. If the C<--pidfiles> option was supplied, its argument specifies the directory in which the pidfile will be placed. If the C<--pidfile> option was supplied, its argument specifies the name of the pidfile and the directory in which it will be placed. =back =item * If the C<--umask> option was supplied, set the I to its argument, which must be a valid three-digit octal mode. Otherwise, set the umask to C<022>, to prevent clients from accidentally creating group- or world-writable files. =item * Set the current directory if the C<--chdir> option was supplied. =item * Spawn the client command and wait for it to terminate. The client command can be specified as command line arguments, or as the argument of the C<--command> option. If both the C<--command> option and command line arguments are present, the client command is the result of appending the command line arguments to the argument of the C<--command> option. =item * If the C<--output>, C<--stdout> and/or C<--stderr> options were supplied, the client's standard output and/or standard error are captured by I, and are sent to the respective I destinations. =item * When the client terminates, I respawns it if the C<--respawn> option was supplied. If the client ran for less than C<300> seconds (or the value of the C<--acceptable> option), then I sees this as a failure. It will attempt to restart the client up to five times (or the value of the C<--attempts> option), before waiting for C<300> seconds (or the value of the C<--delay> option). This gives the system administrator the chance to correct whatever is preventing the client from running successfully without overloading system resources. If the C<--limit> option was supplied, I terminates after the specified number of respawn attempt bursts. The default is zero, which means never give up, never surrender. When the client terminates, and the C<--respawn> option wasn't supplied, I terminates as well. =item * If I receives a C signal (e.g. from a separate invocation of I with the C<--stop> option), it propagates the signal to the client and then terminates. =item * If I receives a C signal (from a separate invocation of I with the C<--restart> option), it sends a C signal to the client. If it was started with the C<--respawn> option, the client process will be restarted after it is terminated by the C signal. =item * If the C<--foreground> option was supplied, the client process is run as a foreground process, and is not turned into a daemon at all. If I is connected to a terminal, then the client process will also be connected to it. If I is not connected to a terminal, but the client needs to be connected to a terminal, use the C<--pty> option. =back =head1 OPTIONS =over 4 =item C<-h>, C<--help> Display a help message and exit. =item C<-V>, C<--version> Display a version message and exit. =item C<-v>I<[level]>, C<--verbose>I<[=level]> Set the message verbosity level to I (or 1 if I is not supplied). This only effects the C<--running> and C<--list> options. =item C<-d>I<[level]>, C<--debug>I<[=level]> Set the debug message level to I (or 1 if I is not supplied). Level 1 traces high-level function calls. Level 2 traces lower-level function calls and shows configuration information. Level 3 adds environment variables. Level 9 adds every return value from I. Debug messages are sent to the destination specified by the C<--dbglog> option (by default, the I facility, C). =item C<-C> I, C<--config=>I Specify the system configuration file to use. By default, C is the system configuration file, if it exists and is not group- or world-writable, and does not exist in a group- or world-writable directory. The configuration file lets you predefine options that apply to all clients, and to specifically named clients. As well as the system configuration file, additional configuration files will be read from the directory whose path matches the system configuration file with C<".d"> appended to it (e.g. C). Any file in that directory whose name starts with a dot character (C<".">) is ignored. The same checks as described above apply to these files as well. On I systems (except I), the system configuration file(s) are C and C by default. On I, when installed via I, the system configuration file(s) are C and C. =item C<-N>, C<--noconfig> Bypass the system configuration files, C and C. Only the user's C<~/.daemonrc> and C<~/.daemonrc.d/*> configuration files will be read (if they exist). =item C<-n> I, C<--name=>I Create and lock a pidfile (IC<.pid>), ensuring that only one daemon with the given I is active at the same time. The standard location of the pidfile is C for root (C on I, C on I when installed via I), and C for normal users. This location can be overridden with the I<--pidfiles> option. The name may only consist of the following characters: -._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 While a named daemon's client process is running, there will also be a separate pidfile to record the process id of the client process. Its filename will be the same as the I pidfile's, except that the filename extension will be C<.clientpid> rather than C<.pid>. The only reason that there should be a C<.pid> file, with no C<.clientpid> file, is during the delay between respawn attempts bursts. =item C<-X> I<"cmd">, C<--command=>I<"cmd"> Specify the client command as an option. If a command is specified along with its name in the configuration file, then a daemon can be invoked merely by mentioning its name: daemon --name ftumch B If the client command is specified with the C<--command> option, either in the configuration file, or on the command line, then any additional command line arguments on the I command line are appended to the client command that is specified with the C<--command> option. =item C<-P> I, C<--pidfiles=>I Override the standard pidfile location. The standard pidfile location is C for root (C on I, C on I when installed via I), and C for normal users. This option only affects the C<--name> and C<--list> options. Use this option if these standard locations are unacceptable, but make sure that you don't forget where you put your pidfiles. This option is best used in configuration files, or in shell scripts, rather than on an interactive command line. The pidfile location will be created automatically only if it is within the user's home directory. =item C<-F> I, C<--pidfile=>I Override the standard pidfile name and location. The standard pidfile location is described immediately above. The standard pidfile name is the argument of the C<--name> option followed by C<.pid>. Use this option if the standard pidfile name and location are unacceptable, but make sure that you don't forget where you put your pidfile. This option is best used in configuration files, or in shell scripts, rather than on an interactive command line. The pidfile location will be created automatically only if it is within the user's home directory. =item C<-u> I, C<--user=>I Run the client as a different user (and group). This only works for I. If the argument includes a I<:group> specifier, I will assume the specified group and no other. Otherwise, I will assume all groups that the specified user is in. For backwards compatibility, C<"."> may be used instead of C<":"> to separate the user and group but since C<"."> can appear in user and group names, ambiguities can arise such as using C<--user=>I when users I and I and group I all exist. With such an ambiguity, I will assume the user I and group I. Use C<--user=>I instead for the other interpretation. =item C<-R> I, C<--chroot=>I Change the root directory to I before running the client. On some systems, only I can do this. Note that the path to the client program and to the configuration file (if any) must be relative to the new root path. =item C<-D> I, C<--chdir=>I Change the current directory to I before running the client. The default current directory is the root directory (possibly after I). =item C<-m> I, C<--umask=>I Change the umask to I before running the client. I must be a valid octal mode. The default umask is C<022>. =item C<-e> I<"var=val">, C<--env=>I<"var=val"> Set an environment variable for the client process. This option can be used any number of times. If it is used, only the supplied environment variables are passed to the client process. Otherwise, the client process inherits the current set of environment variables. =item C<-i>, C<--inherit> Explicitly inherit environment variables. This is only needed when the C<--env> option is used. When this option is used, the C<--env> option adds to the inherited environment, rather than replacing it. =item C<-U>, C<--unsafe> Allow reading an unsafe configuration file, and allow the execution of an unsafe executable. A configuration file or executable is considered to be unsafe if it is group- or world-writable or is in a directory that is group- or world-writable (following symbolic links). If an executable is a script that is interpreted by another executable, then it is considered to be unsafe if the interpreter is unsafe. If the interpreter is C (with an argument that is a command name to be searched for in C<$PATH>), then that command must be safe. By default, I will refuse to read an unsafe configuration file or to execute an unsafe executable when run by I. This option overrides that behaviour and hence should never be used. =item C<-S>, C<--safe> Disallow reading an unsafe configuration file, and disallow the execution of an unsafe executable. By default, I will allow reading an unsafe configuration file, and allow the execution of an unsafe executable, when run by normal users. This option overrides that behaviour. =item C<-c>, C<--core> Allow the client to create a core file. This should only be used for debugging, as it could lead to security-related information disclosures by daemons run by I. =item C<--nocore> By default, clients are prevented from creating a core file. If the C<--core> option has been used in a configuration file to apply to all named daemons, then this option can be used to restore the default behaviour for specific named daemons. =item C<-r>, C<--respawn> Respawn the client when it terminates. Without this option, the termination of a client process causes I itself to terminate as well. =item C<-a> I<#>, C<--acceptable=>I<#> Specify the minimum acceptable duration of a client process, in seconds. This option can only be used with the C<--respawn> option. If a client process terminates before this threshold is reached, then it is considered to have failed. The default value is C<300> seconds. It cannot be set to less than C<10> seconds, except by I when used in conjunction with the C<--idiot> option. =item C<-A> I<#>, C<--attempts=>I<#> Specify the number of attempts to respawn before delaying. This option can only be used with the C<--respawn> option. The default value is C<5>. It cannot be set to more than C<100> attempts, except by I when used in conjunction with the C<--idiot> option. =item C<-L> I<#>, C<--delay=>I<#> Specify the delay in seconds between each burst of respawn attempts. This option can only be used with the C<--respawn> option. The default value is C<300> seconds. It cannot be set to less than C<10> seconds except by I when used in conjunction with the C<--idiot> option. =item C<-M> I<#>, C<--limit=>I<#> Specify a limit to the number of respawn attempt bursts. This option can only be used with the C<--respawn> option. The default value is C<0>, which means no limit. =item C<--idiot> Turn on idiot mode in which I will not enforce the minimum or maximum values normally imposed on the C<--acceptable>, C<--attempts> and C<--delay> options. The C<--idiot> option must appear before any of these options. Only the I user may use this option, because it can turn a slight misconfiguration into a lot of wasted CPU energy and log messages, somewhat akin to a self-inflicted denial of service. Idiot mode also allows the I user to expand environment variable notation (e.g. C<$VAR> and C<${VAR}>) in command line option arguments, and in configuration files. By default, internal environment variable expansion is only performed for normal users. Note that this doesn't apply to any such expansion performed earlier by the shell that invokes I. See the C section below for more details. =item C<-f>, C<--foreground> Run the client in the foreground. The client is not turned into a daemon. =item C<-p>I<[noecho]>, C<--pty>I<[=noecho]> Connect the client to a pseudo terminal. This option can only be used with the C<--foreground> option. This is the default when the C<--foreground> option is supplied and I's standard input is connected to a terminal. This option is only necessary when the client process must be connected to a controlling terminal, but I itself has been run without a controlling terminal (e.g. from I or a pipeline). If the C argument is supplied with this option, the client's side of the pseudo terminal will be set to C mode. Use this only if there really is a terminal involved and input is being echoed twice. =item C<-B>, C<--bind> Automatically terminate the client process (and I itself) as soon as the user has no I (or I) user sessions. In other words, automatically terminate when the user logs out. If the user has no sessions to start with, the client process will be terminated immediately. This option is only available on I systems that have either I (e.g. I) or I (e.g. I). On systems with I, you could instead use a I user service, particularly if your user account is not allowed to have user services that I. =item C<-l> I, C<--errlog=>I Send I's standard output and standard error to the syslog destination or file that is specified by I. If I is a syslog destination of the form C<"facility.priority">, then output is sent to I. Otherwise, output is appended to the file whose path is given in I. By default, output is sent to the syslog destination, C. See the C section below for more details. =item C<-b> I, C<--dbglog=>I Send I's debug output to the syslog destination or file that is specified by I. If I is a syslog destination of the form C<"facility.priority">, then output is sent to I. Otherwise, output is appended to the file whose path is given in I. By default, output is sent to the syslog destination C. See the C section below for more details. =item C<-o> I, C<--output=>I Capture the client's standard output and standard error, and send it to the syslog destination or file that is specified by I. If I is a syslog destination of the form C<"facility.priority">, then output is sent to I. Otherwise, output is appended to the file whose path is given in I. By default, output is discarded unless the C<--foreground> option is present, in which case, the client's stdout and stderr are propagated to I's stdout and stderr, respectively. See the C section below for more details. =item C<-O> I, C<--stdout=>I Capture the client's standard output, and send it to the syslog destination or file that is specified by I. If I is a syslog destination of the form C<"facility.priority">, then output is sent to I. Otherwise, stdout is appended to the file whose path is given in I. By default, stdout is discarded unless the C<--foreground> option is present, in which case, the client's stdout is propagated to I's stdout. See the C section below for more details. =item C<-E> I, C<--stderr=>I Capture the client's standard error, and send it to the syslog destination or file that is specified by I. If I is a syslog destination of the form C<"facility.priority">, then stderr is sent to I. Otherwise, stderr is appended to the file whose path is given in I. By default, stderr is discarded unless the C<--foreground> option is present, in which case, the client's stderr is propagated to I's stderr. See the C section below for more details. =item C<--ignore-eof> After receiving a C signal due to a stopped or restarted client process, don't bother reading the client's output until the end-of-file is reached before reaping the client process's termination status with I. Normally, there will be little or no output after the C signal, because the client process has just terminated. However, the client process might have its own child processes keeping its output open long after its own termination. When this happens, by default, the client process remains as a zombie process until its child processes terminate and close the output. Waiting for the client's child processes to terminate before considering the client stopped, and before restarting a new invocation, might be desirable. If not, this option can be used to consider the client process as being terminated as soon as the C signal has been received, and reaping its termination status with I immediately. =item C<--read-eof> After receiving a C signal due to a stopped or restarted client process, continue reading the client's output until the end-of-file is reached before reaping the client process's termination status with I. This is the default behaviour. Normally, there will be little or no output after the C signal, because the client process has just terminated. However, the client process might have its own child processes keeping its output open long after its own termination. When this happens, the client process remains as a zombie process until its child processes terminate and close the output. Waiting for the client's child processes to terminate before considering the client stopped, and before restarting a new invocation, might be desirable. If so, but the C<--ignore-eof> option has been used in a configuration file to apply to all named daemons, then this option can be used to restore the default behaviour for specific named daemons. =item C<--running> Check whether or not a named daemon is running, then I with C if the named daemon is running or C if it isn't. If the C<--verbose> option is supplied, print a message before exiting. If both the named daemon and its client process are running, the output will look like this, showing both process IDs: daemon: name is running (pid 7455) (clientpid 7457) If the named daemon is running but its client process is not (there might be a delay between respawn attempt bursts), the output will look like this, showing only the daemon process's ID: daemon: name is running (pid 7455) (client is not running) If the named daemon is not running at all, the output will look like this: daemon: name is not running This option can only be used with the C<--name> option. Note that the C<--chroot>, C<--user>, C<--name>, C<--pidfiles> and C<--pidfile> (and possibly C<--config>) options must be the same as for the target daemon. =item C<--restart> Instruct a named daemon to terminate and restart its client process, by sending it a C signal. This will cause the named daemon to send its client process a C signal to stop it. If the named daemon had been started with the C<--restart> option, the named daemon will then restart its client process. Otherwise, this has the same effect as the C<--stop> option, and the named daemon's client process is not restarted. This option can only be used with the C<--name> option. Note that the C<--chroot>, C<--user>, C<--name>, C<--pidfiles> and C<--pidfile> (and possibly C<--config>) options must be the same as for the target daemon. =item C<--stop> Stop a named daemon by sending it a C signal. This will cause the named daemon to send its client process a C option and then exit. This option can only be used with the C<--name> option. Note that the C<--chroot>, C<--user>, C<--name>, C<--pidfiles> and C<--pidfile> (and possibly C<--config>) options must be the same as for the target daemon. =item C<--signal=>I Send the given signal to a named daemon's client process. The signal can be specified either by number or by name (with or without the "sig" prefix). Any signal may be sent. However, the named daemon's client process might be ignoring some signals. For example, C will be ignored by default unless the client process has installed a signal handler for it. The known list of signals are: C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C and C. Not all of them are available on all platforms. =item C<--list> Print a list of the currently running named daemons whose pidfiles are in the applicable pidfile directory which will either be the default (i.e. C for I (C on I, C on I when installed via I), and C for normal users), or it will be specified by the C<--pidfiles> option. Then exit. Without the C<--verbose> option, this will only list the names of daemons whose pidfiles are locked, as this implies that the corresponding daemon must still be running. Note that pidfiles for daemons that were not started by I might not be locked. An unlocked pidfile might indicate that I has died unexpectedly, or it might just be a pidfile for a daemon that was not started by I. If this might lead to confusion, you might want to consider using a dedicated pidfiles directory for named daemons started by I, and leave the default pidfiles directories for other daemons that were started independently of I. With the C<--verbose> option, the items in the list will look like the output of the C<--running> option with C<--verbose>, but with more detail. If there are no pidfiles at all, the output will look like this: No named daemons are running If a pidfile is locked, and there is a corresponding client pidfile, that indicates that the named daemon and its client are both running, and the output will look like this, showing both process IDs: name is running (pid ####) (client pid ####) If a pidfile is locked, but there is no client pidfile, that indicates that the named daemon is running, but its client is not (e.g. during a delay between respawn attempt bursts when the client is failing to start successfully), and the output will look like one of the following three options: When we can tell that the pidfile is for a process whose executable name is I: name is running (pid ####) (client is not running) When we can tell that the pidfile is for a process whose executable name is something other than I (i.e. is independent of I): name is running (pid ####) (independent) When it's not possible to determine the name of the executable associated with the I (i.e. On systems other than I without a C file system): name is running (pid ####) (client is not running or is independent) If a pidfile is not locked, and the applicable pidfiles directory is the default, that indicates either that the daemon has unexpectedly terminated, or just that the pidfile is for a daemon that was not started by I, and the output will look like this: name is not running (or is independent) If a pidfile is not locked, and the applicable pidfiles directory is not the default, then it is assumed that all pidfiles are for daemons that were started by I, and the output will look like this: name is not running =back As with all other programs, a C<--> argument signifies the end of options. Any options that appear on the command line after C<--> are part of the client command. =head1 EXPANSION Some simple shell-like expansion is performed internally on the arguments of the command line options with a text argument (but not the options with a numeric argument). Environment variable notation, such as C<$VAR> or C<${VAR}>, is expanded. Then user home directory notation, such as C<~> or C<~user>, is expanded. File name expansion (i.e. globbing) is NOT performed internally. Neither are any of your login shell's other wonderful expansions. This is very basic. This might not be of much use on the command line, since I is normally invoked via a shell, which will first perform all of its usual expansions. It might even be undesirable to perform expansion internally after the shell has already done so (e.g. if you refer to any directory names that actually contain the C<'$'> character, or if you use any environment variables whose values contain the C<'$'> character, which is unlikely). But it can be useful in configuration files. See the C section below for more details. It can also be useful when I is invoked directly by another program without the use of a shell. By default, environment variable expansion is not performed for the I user, even if the environment variable was defined in the configuration files. The C<--idiot> option can be used to change this behaviour, and allow the expansion of environment variables for the I user. Home directory notation expansion is performed for all users. =head1 FILES C, C - system-wide default options C, C - system-wide default options on I systems (except I). C, C - system-wide default options on I when installed via I. C<~/.daemonrc>, C<~/.daemonrc.d/*> - user-specific default options Each line of the configuration file is either an environment variable definition, or a configuration directive. Environment variable definitions consist of the variable name, followed immediately by C<'='> and the value of the variable. They look like they do in shell, except that there is no quoting or other shell syntax. Environment variable values can include simple environment variable notation (e.g. C<$VAR> or C<${VAR}>), and user home directory notation (e.g. C<~> or C<~user>). These will be expanded internally by I. See the C section above for more details. Note that any environment variables that are defined in the configuration file, which are subsequently used explicitly in another environment variable definition or in an option argument, will have these expansions performed multiple times. Avoid environment variables whose values can change again if expansion is performed multiple times. Example: PATH=/usr/bin:/usr/sbin:$HOME/bin:~app/bin PIDFILES=~/.run Configuration directives consist of a client name (for options that apply to a single client), or C<'*'> (for generic options that apply to all clients), followed by spaces and/or tabs, followed by a comma-separated list of options. Any option arguments must not contain any commas. The commas that separate options can have spaces and tabs before and after them. Option arguments that are text (but not numbers) can include simple environment variable notation (e.g. C<$VAR> or C<${VAR}>), and user home directory notation (e.g. C<~> or C<~user>). These will be expanded internally by I. See the C section above for more details. Blank lines and comments (C<'#'> to end of the line) are ignored. Lines can be continued with a C<'\'> character at the end of the line. Example: * errlog=daemon.err,output=local0.err,core test1 syslog=local0.debug,debug=9,verbose=9,respawn test2 syslog=local0.debug,debug=9, \ verbose=9,respawn, \ pidfiles=$PIDFILES The command line options are processed first, to look for a C<--config> option. If no C<--config> option was supplied, the default configuration files, C and C, are used. On I systems (except I), the default configuration files are C and C. On I when installed via I, the default configuration files are C and C. If the user has their own configuration files, C<~/.daemonrc> and C<~/.daemonrc.d/*>, they are also used. If the configuration files contain any generic (C<'*'>) entries, their options are applied in order of appearance. If the C<--name> option was supplied, and the configuration files contain any entries for the given name, those options are then applied in order of appearance. Finally, the command line options are applied again. This ensures that any generic options apply to all clients by default. Client-specific options override generic options. User options override system-wide options. Command line options override everything else. Note that the configuration files are not opened and read until after any C<--chroot> and/or C<--user> command line options are processed. This means that the configuration file paths and the client's file path must be relative to the C<--chroot> argument. It also means that the configuration files and the client executable must be readable/executable by the user specified by the C<--user> argument. It also means that the C<--chroot> and C<--user> options must not appear in the configuration file. Also note that the C<--name> option must not appear on the right hand side in the configuration file either. =head1 MESSAGING The C<--errlog>, C<--dbglog>, C<--output>, C<--stdout> and C<--stderr> options all take an argument that can be either a syslog destination of the form C<"facility.priority"> or the path to a file. Here are the lists of syslog facilities and priorities: Facilities: kern, user, mail, daemon, auth, syslog, lpr, news, uucp, cron, local0, local1, local2, local3, local4, local5, local6, local7. Priorities: emerg, alert, crit, err, warning, notice (on some systems), info, debug. If the path to a file is supplied instead, bear in mind the fact that I changes to the root directory by default, and so the file path should be an absolute path (or relative to the C<--chroot> and/or C<--chdir> option argument). Otherwise, I will attempt to create the file relative to its current directory. You might not have permissions to do that, or want to even if you do. =head1 CAVEAT Clients can only be restarted if they were started with the C<--respawn> option. Using C<--restart> on a non-respawning daemon client is equivalent to using C<--stop>. If you try to restart a named daemon, and it stops instead, then it probably wasn't started with the C<--respawn> option. Clients that are run in the foreground with a pseudo terminal don't respond to job control (i.e. suspending with Control-Z doesn't work). This is because the client belongs to an orphaned process group (it starts in its own process session), so the kernel won't send it C signals. However, if the client is a shell that supports job control, then its subprocesses can be suspended. In KDE, if you use C<"exec daemon"> (or just C<"exec"> without C) in a shell, to run a KDE application, you might find that the KDE application sometimes doesn't run. This problem has only been seen with I, but it might happen with other KDE applications as well. Capturing the standard error of the KDE application might show something like: unnamed app(9697): KUniqueApplication: Registering failed! unnamed app(9697): Communication problem with "konsole" , it probably crashed. Error message was: "org.freedesktop.DBus.Error.ServiceUnknown" : " "The name org.kde.konsole was not provided by any .service files" A workaround seems to be to delay the termination of the initial I process by at least 0.4 seconds. To make this happen, set the environment variable C to the number of milliseconds by which to delay. For example: C. Or you could just avoid using C when starting I applications. On I systems that have I or I, you might find that your I processes and their client processes are terminated when you logout, even though they are in a different process session, and so should be unaffected. This is because I has the ability to terminate all of your processes when you logout. Luckily, this feature is turned off by default in some I distributions. However, if it is on, you can turn it off by adding the following line to C (or C): KillUserProcesses=no =head1 SEE ALSO I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I =head1 AUTHOR 20230824 raf =cut */ #ifndef _BSD_SOURCE #define _BSD_SOURCE /* For SIGWINCH and CEOF on OpenBSD-4.7 */ #endif #ifndef _DEFAULT_SOURCE #define _DEFAULT_SOURCE /* New name for _BSD_SOURCE */ #endif #ifndef __BSD_VISIBLE #define __BSD_VISIBLE 1 /* For SIGWINCH on FreeBSD-8.0 */ #endif #ifndef _NETBSD_SOURCE #define _NETBSD_SOURCE /* For CEOF, chroot() on NetBSD-5.0.2 */ #endif #include #include #include #include #include #ifdef _POSIX_SOURCE #undef _POSIX_SOURCE /* For CEOF on FreeBSD-8.0 */ #define _RESTORE_POSIX_SOURCE #endif #include #ifdef _RESTORE_POSIX_SOURCE #define _POSIX_SOURCE #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "config.h" #ifdef HAVE_LOGIND #include #endif #ifdef HAVE_SYS_TTYDEFAULTS_H /* For CEOF in musl libc (Linux only) */ #include #endif /* Configuration file entries */ typedef struct Config Config; struct Config { char *name; List *options; }; #ifndef RESPAWN_ACCEPTABLE #define RESPAWN_ACCEPTABLE 300 #endif #ifndef RESPAWN_ACCEPTABLE_MIN #define RESPAWN_ACCEPTABLE_MIN 10 #endif #ifndef RESPAWN_ATTEMPTS #define RESPAWN_ATTEMPTS 5 #endif #ifndef RESPAWN_ATTEMPTS_MIN #define RESPAWN_ATTEMPTS_MIN 0 #endif #ifndef RESPAWN_ATTEMPTS_MAX #define RESPAWN_ATTEMPTS_MAX 100 #endif #ifndef RESPAWN_DELAY #define RESPAWN_DELAY 300 #endif #ifndef RESPAWN_DELAY_MIN #define RESPAWN_DELAY_MIN 10 #endif #ifndef RESPAWN_LIMIT #define RESPAWN_LIMIT 0 #endif #ifndef RESPAWN_LIMIT_MIN #define RESPAWN_LIMIT_MIN 0 #endif #ifndef PTY_DEVICE_NAME_SIZE #define PTY_DEVICE_NAME_SIZE 64 #endif #ifndef CONFIG_PATH #define CONFIG_PATH "/etc/daemon.conf" #endif #ifndef CONFIG_DIR_PATH_SUFFIX #define CONFIG_DIR_PATH_SUFFIX ".d" #endif #ifndef CONFIG_PATH_USER #define CONFIG_PATH_USER ".daemonrc" #endif #ifndef STATUS_BUFLEN #define STATUS_BUFLEN 64 #endif #ifndef DEFAULT_ROOT_PATH #define DEFAULT_ROOT_PATH "/bin:/usr/bin" #endif #ifndef DEFAULT_USER_PATH #define DEFAULT_USER_PATH ":/bin:/usr/bin" #endif /* Global variables */ extern char **environ; static struct { int ac; /* number of command line arguments */ char **av; /* the command line arguments */ char **cmd; /* command vector to execute (prefixed by name) */ char *cmdpath; /* executable command path (execve filename argument) */ char *name; /* the daemon's name to use for the locked pidfile */ char *daemon_init_name; /* the name argument for daemon_init() */ char *pidfiles; /* location of the pidfile */ char *pidfile; /* absolute path for the pidfile */ char *user; /* name of user to run as */ char *group; /* name of group to run as */ char userbuf[BUFSIZ]; /* buffer to store the user name */ char groupbuf[BUFSIZ]; /* buffer to store the group name */ char *chroot; /* name of root directory to run under */ char *chdir; /* name of directory to change to */ char *command; /* the client command as a string */ mode_t umask; /* set umask to this */ int init_groups; /* initgroups(3) if group not specified */ uid_t initial_uid; /* the uid when the program started */ uid_t uid; /* run the client as this user */ gid_t gid; /* run the client as this group */ List *env; /* client environment variables */ char **environ; /* client environment */ int inherit; /* inherit environment variables? */ int respawn; /* respawn the client process when it terminates? */ int acceptable; /* minimum acceptable client duration in seconds */ int attempts; /* number of times to attempt respawning before delay */ int delay; /* delay in seconds between respawn attempt bursts */ int limit; /* number of respawn attempt bursts */ int idiot; /* idiot mode */ int attempt; /* spawn attempt counter */ int burst; /* respawn attempt burst counter */ int foreground; /* run the client in the foreground? */ int pty; /* allocate a pseudo terminal for the client? */ int noecho; /* set client pty to noecho mode? */ int bind; /* bind the daemon to the user's logind session? */ #ifdef HAVE_LOGIND sd_login_monitor *logind_monitor; /* The systemd-logind/elogind monitor object */ int logind_monitor_fd; /* The systemd-logind/elogind monitor file descriptor */ #endif int core; /* do we allow core file generation? */ int unsafe; /* executable unsafe executables as root? */ int safe; /* do not execute unsafe executables? */ char *client_out; /* syslog/file spec for client stdout */ char *client_err; /* syslog/file spec for client stderr */ char *daemon_err; /* syslog/file spec for daemon output */ char *daemon_dbg; /* syslog/file spec for daemon debug output */ int client_outlog; /* syslog facility for client stdout */ int client_errlog; /* syslog facility for client stderr */ int daemon_errlog; /* syslog facility for daemon output */ int daemon_dbglog; /* syslog facility for daemon debug output */ int client_outfd; /* file descriptor for client stdout */ int client_errfd; /* file descriptor for client stderr */ char *config; /* name of the config file to use - /etc/daemon.conf */ int noconfig; /* bypass the system configuration file? */ int read_eof; /* read_eof mode (after SIGCHLD) */ pid_t pid; /* the pid of the client process to run as a daemon */ dev_t pid_dev; /* the device that the clientpid file is on */ ino_t pid_inode; /* the inode of the clientpid file */ int in; /* file descriptor for client stdin */ int out; /* file descriptor for client stdout */ int err; /* file descriptor for client stderr */ int pty_user_fd; /* user side of the pseudo terminal */ char pty_device_name[PTY_DEVICE_NAME_SIZE]; /* pseudo terminal device name */ size_t pty_device_name_size; /* size of g.pty_device_name */ int stop; /* stop a named daemon? */ int running; /* check whether or not a named daemon is running? */ int restart; /* restart a named daemon? */ time_t spawn_time; /* when did we last spawn the client? */ int done_name; /* have we already set the name? */ int done_chroot; /* have we already set the root directory? */ int done_user; /* have we already set the user id? */ int done_config; /* have we already processed the configuration file? */ struct termios stdin_termios; /* stdin's terminal attributes */ struct winsize stdin_winsize; /* stdin's terminal window size */ int stdin_isatty; /* is stdin a terminal? */ int stdin_eof; /* has stdin received eof? */ int terminated; /* have we received a term signal? */ int received_sigchld; /* have we received a chld signal? */ char *signame; /* name of the signal to send */ int signo; /* number of the signal to send */ int list; /* are we listing all currently running daemons? */ } g = { 0, /* ac */ null, /* av */ null, /* cmd */ null, /* cmdpath */ null, /* name */ null, /* daemon_init_name */ null, /* pidfiles */ null, /* pidfile */ null, /* user */ null, /* group */ { 0 }, /* userbuf */ { 0 }, /* groupbuf */ null, /* chroot */ null, /* chdir */ null, /* command */ S_IWGRP | S_IWOTH, /* umask */ 0, /* init_groups */ 0, /* initial_uid */ 0, /* uid */ 0, /* gid */ null, /* env */ null, /* environ */ 0, /* inherit */ 0, /* respawn */ RESPAWN_ACCEPTABLE, /* acceptable */ RESPAWN_ATTEMPTS, /* attempts */ RESPAWN_DELAY, /* delay */ RESPAWN_LIMIT, /* limit */ 0, /* idiot */ 0, /* attempt */ 0, /* burst */ 0, /* foreground */ 0, /* pty */ 0, /* noecho */ 0, /* bind */ #ifdef HAVE_LOGIND null, /* logind_monitor */ -1, /* logind_monitor_fd */ #endif 0, /* core */ 0, /* unsafe */ 0, /* safe */ null, /* client_out */ null, /* client_err */ null, /* daemon_err */ null, /* daemon_dbg */ 0, /* client_outlog */ 0, /* client_errlog */ LOG_DAEMON | LOG_ERR, /* daemon_errlog */ LOG_DAEMON | LOG_DEBUG, /* daemon_dbglog */ -1, /* client_outfd */ -1, /* client_errfd */ null, /* config */ 0, /* noconfig */ 1, /* read_eof */ (pid_t)0, /* pid */ (dev_t)0, /* pid_dev */ (ino_t)0, /* pid_inode */ -1, /* in */ -1, /* out */ -1, /* err */ -1, /* pty_user_fd */ { 0 }, /* pty_device_name */ PTY_DEVICE_NAME_SIZE, /* pty_device_name_size */ 0, /* stop */ 0, /* running */ 0, /* restart */ (time_t)0, /* spawn_time */ 0, /* done_name */ 0, /* done_chroot */ 0, /* done_user */ 0, /* done_config */ { 0 }, /* stdin_termios */ { 0 }, /* stdin_winsize */ 0, /* stdin_isatty */ 0, /* stdin_eof */ 0, /* terminated */ 0, /* received_sigchld */ null, /* signame */ 0, /* signo */ 0 /* list */ }; #define is_space(c) isspace((int)(unsigned char)(c)) /* C Returns a dynamically allocated string containing the contents of the C string with simple environment variables replaced with their values (e.g. C<$VARNAME> or C<${VARNAME}>) and shell-style user home directory notation (e.g. C<~> and C<~username>) replaced with the path to the home directory. It is the caller's responsibility to deallocate it with I or I or I. It is strongly recommended to use I, because it also sets the pointer variable to C. */ static char *expand(const char *input) { char *expanding = null; char *expanded = null; int i, len; /* Check arguments */ if (!input) return set_errnull(EINVAL); /* Replace simple environment variables: $VARNAME or ${VARNAME} */ expanding = mem_strdup(input); len = strlen(expanding); /* But not for root, unless --idiot */ if (g.idiot || (getuid() && geteuid())) { for (i = 0; i < len; ++i) { if (expanding[i] == '$') { int braces; size_t varnamelen; char *varname = null; char *varvalue = null; size_t valuelen; braces = (expanding[i + 1] == '{') ? 1 : 0; varnamelen = strspn(expanding + i + 1 + braces, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"); if (varnamelen == 0) continue; if (asprintf(&varname, "%.*s", (int)varnamelen, expanding + i + 1 + braces) == -1) fatalsys("failed to expand"); varvalue = getenv(varname); debug((2, "getenv %s=%s", varname, varvalue)) mem_destroy(&varname); if (!varvalue) varvalue = ""; if (asprintf(&expanded, "%.*s%s%s", i, expanding, varvalue, expanding + i + 1 + braces + varnamelen + braces) == -1) fatalsys("failed to expand"); free(expanding); expanding = expanded; expanded = null; valuelen = strlen(varvalue); len -= 1 + braces + varnamelen + braces; len += valuelen; i += valuelen - 1; } } } /* Replace home directory notation: ~ or ~username */ for (i = 0; i < len; ++i) { if (expanding[i] == '~' && (i == 0 || is_space(expanding[i - 1]) || expanding[i - 1] == ':' || expanding[i - 1] == '=')) { size_t usernamelen = strcspn(expanding + i + 1, ":/ \t"); struct passwd *pwd; if (usernamelen) { char *username = null; if (asprintf(&username, "%.*s", (int)usernamelen, expanding + i + 1) == -1) fatalsys("failed to expand"); pwd = getpwnam(username); free(username); } else { uid_t uid = g.uid ? g.uid : getuid(); pwd = getpwuid(uid); } if (pwd) { size_t homedirlen; if (asprintf(&expanded, "%.*s%s%s", i, expanding, pwd->pw_dir, expanding + i + 1 + usernamelen) == -1) fatalsys("failed to expand"); free(expanding); expanding = expanded; expanded = null; homedirlen = strlen(pwd->pw_dir); len -= 1 + usernamelen; len += homedirlen; i += homedirlen - 1; } } } return expanding; } /* C If C refers to a directory within the user's home directory that doesn't exist yet, create it. */ static void prepare_pidfiles(const char *path) { struct stat status[1]; struct passwd *pwd; const char *homedir; size_t homelen; char *dir = null; const char *start, *end; debug((1, "prepare_pidfiles(%s)", path)) /* Does path already exist? */ if (stat(path, status) == 0) return; /* Get the user's home directory */ if (!(pwd = getpwuid(g.uid ? g.uid : getuid()))) return; homedir = pwd->pw_dir; homelen = strlen(homedir); /* Is path within it? */ if (!(strncmp(path, homedir, homelen) == 0 && path[homelen] == '/')) return; /* Create it */ for (start = path + homelen + 1;; start = end + 1) { if ((end = strchr(start, PATH_SEP))) { if (asprintf(&dir, "%.*s", (int)(end - path), path) == -1) fatalsys("failed to prepare pidfiles location"); } else { if (!(dir = mem_strdup(path))) fatalsys("failed to prepare pidfiles location"); } debug((2, "dir %s", dir)) if (stat(dir, status) == -1) { debug((2, "mkdir %s", dir)) if (mkdir(dir, S_IRUSR | S_IWUSR | S_IXUSR) == -1) fatalsys("failed to create directory %s", dir); } free(dir); if (!end) break; } } /* C Store the C<--config> option argument, C. */ static void handle_config_option(const char *spec) { debug((1, "handle_config_option(spec = %s)", spec)) g.config = expand(spec); debug((2, "config = %s", g.config)) } /* C Store the C<--name> option argument, C. */ #ifndef ACCEPT_NAME #define ACCEPT_NAME "-._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" #endif #ifndef ACCEPT_PATH #define ACCEPT_PATH ACCEPT_NAME "/" #endif static void handle_name_option(const char *spec) { debug((1, "handle_name_option(spec = %s)", spec)) if (g.done_config) return; if (g.done_name) prog_usage_msg("Misplaced option: --name=%s in config file (Must be on the command line)", spec); spec = expand(spec); if (strspn(spec, ACCEPT_NAME) != strlen(spec)) prog_usage_msg("Invalid --name argument: '%s' (Must consist entirely of [-._a-zA-Z0-9])", spec); g.name = (char *)spec; debug((2, "name = %s", g.name)) } /* C Store the C<--command> option argument, C. */ static void handle_command_option(const char *spec) { debug((1, "handle_command_option(spec = %s)", spec)) g.command = expand(spec); debug((2, "command = %s", g.command)) } /* C Store the C<--pidfiles> option argument, C. */ static void handle_pidfiles_option(const char *spec) { struct stat status[1]; debug((1, "handle_pidfiles_option(spec = %s)", spec)) spec = expand(spec); if (strspn(spec, ACCEPT_PATH) != strlen(spec)) prog_usage_msg("Invalid --pidfiles argument: '%s' (Must consist entirely of [-._a-zA-Z0-9/])", spec); if (*spec != PATH_SEP) prog_usage_msg("Invalid --pidfiles argument: '%s' (Must be an absolute directory path)", spec); prepare_pidfiles(spec); if (stat(spec, status) == -1 || !S_ISDIR(status->st_mode)) prog_usage_msg("Invalid --pidfiles argument: '%s' (Directory does not exist)", spec); /* Check directory writability later in sanity_check() after all options have been seen */ g.pidfiles = (char *)spec; debug((2, "pidfiles = %s", g.pidfiles)) } /* C Store the C<--pidfile> option argument, C. */ static void handle_pidfile_option(const char *spec) { struct stat status[1]; char *buf; size_t size; debug((1, "handle_pidfile_option(spec = %s)", spec)) spec = expand(spec); if (strspn(spec, ACCEPT_PATH) != strlen(spec)) prog_usage_msg("Invalid --pidfile argument: '%s' (Must consist entirely of [-._a-zA-Z0-9/])", spec); if (*spec != PATH_SEP || (stat(spec, status) == 0 && S_ISDIR(status->st_mode))) prog_usage_msg("Invalid --pidfile argument: '%s' (Must be an absolute file path)", spec); if ((size = strrchr(spec, PATH_SEP) - spec + 1) == 1) ++size; if (!(buf = mem_create(size, char))) fatalsys("out of memory"); snprintf(buf, size, "%.*s", (int)size - 1, spec); prepare_pidfiles(buf); if (stat(buf, status) == -1 || !S_ISDIR(status->st_mode)) prog_usage_msg("Invalid --pidfile argument: '%s' (Parent directory does not exist)", spec); mem_release(buf); /* Check parent directory writability later in sanity_check() after all options have been seen */ g.pidfile = (char *)spec; debug((2, "pidfile = %s", g.pidfile)) } /* C Parse and store the client C<--user[:group]> option argument, C. */ static void handle_user_option(const char *spec) { struct passwd *pwd; struct group *grp; char **member; char *pos; debug((1, "handle_user_option(spec = %s)", spec)) if (g.done_config) return; if (g.done_user) prog_usage_msg("Misplaced option: --user=%s in config file (Must be on the command line)", spec); if (getuid() || geteuid()) prog_usage_msg("Invalid option: --user (Only works for root)"); spec = expand(spec); debug((2, "user = %s", spec)) if ((pos = strchr(spec, ':')) || (pos = strchr(spec, '.'))) { if (pos > spec) snprintf(g.user = g.userbuf, BUFSIZ, "%*.*s", (int)(pos - spec), (int)(pos - spec), spec); if (*++pos) snprintf(g.group = g.groupbuf, BUFSIZ, "%s", pos); } else { snprintf(g.user = g.userbuf, BUFSIZ, "%s", spec); } g.init_groups = (g.group == null); if (!g.user) prog_usage_msg("Invalid --user argument: '%s' (No user name)", spec); if (!(pwd = getpwnam(g.user))) prog_usage_msg("Invalid --user argument: '%s' (Unknown user %s)", spec, g.user); g.uid = pwd->pw_uid; g.gid = pwd->pw_gid; if (g.group) { if (!(grp = getgrnam(g.group))) prog_usage_msg("Invalid --user argument: '%s' (Unknown group %s)", spec, g.group); if (grp->gr_gid != pwd->pw_gid) { for (member = grp->gr_mem; *member; ++member) if (!strcmp(*member, g.user)) break; if (!*member) prog_usage_msg("Invalid --user argument: '%s' (User %s is not in group %s)", spec, g.user, g.group); } g.gid = grp->gr_gid; } } /* C Store the C<--chroot> option argument, C. */ static void handle_chroot_option(const char *spec) { debug((1, "handle_chroot_option(spec = %s)", spec)) if (g.done_config) return; if (g.done_chroot) prog_usage_msg("Misplaced option: --chroot=%s in config file (Must be on the command line)", spec); g.chroot = expand(spec); debug((2, "chroot = %s", g.chroot)) } /* C Store the C<--chdir> option argument, C. */ static void handle_chdir_option(const char *spec) { debug((1, "handle_chdir_option(spec = %s)", spec)) g.chdir = expand(spec); debug((2, "chdir = %s", g.chdir)) } /* C Parse and store the C<--umask> option argument, C. */ static void handle_umask_option(const char *spec) { char *end; long val; debug((1, "handle_umask_option(spec = %s)", spec)) spec = expand(spec); val = strtol(spec, &end, 8); if (end == spec || *end || val < 0 || val > 0777) prog_usage_msg("Invalid --umask argument: '%s' (Must be a valid octal mode)", spec); g.umask = val; debug((2, "umask = %03o", g.umask)) } /* C Store the C<--env> option argument, C. */ static void handle_env_option(const char *var) { debug((1, "handle_env_option(spec = %s)", var)) if (g.env == null && !(g.env = list_create(null))) fatalsys("failed to create environment list"); var = expand(var); if (!list_append(g.env, (void *)var)) fatalsys("failed to add '%s' to environment list", var); debug((2, "env += %s", var)) } /* C Process the C<--inherit> option. Add the contents of C to the list of environment variables to be used by the client. */ static void handle_inherit_option(void) { char **env; debug((1, "handle_inherit_option()")) if (g.env == null && !(g.env = list_create(null))) fatalsys("failed to create environment list"); for (env = environ; *env; ++env) if (!list_append(g.env, *env)) fatalsys("failed to add '%s' to environment list", env); g.inherit = 1; } /* C Allow core file generation. */ static void handle_core_option(void) { debug((1, "handle_core_option()")) g.core = 1; } /* C Disallow core file generation (default). */ static void handle_nocore_option(void) { debug((1, "handle_nocore_option()")) g.core = 0; } /* C Store the C<--acceptable> option argument, C. */ static void handle_acceptable_option(int acceptable) { debug((1, "handle_acceptable_option(acceptable = %d)", acceptable)) if (!g.idiot && acceptable < RESPAWN_ACCEPTABLE_MIN) prog_usage_msg("Invalid --acceptable argument: %d (Less than %d)\n", acceptable, RESPAWN_ACCEPTABLE_MIN); g.acceptable = acceptable; } /* C Store the C<--attempts> option argument, C. */ static void handle_attempts_option(int attempts) { debug((1, "handle_attempts_option(attempts = %d)", attempts)) if (!g.idiot && (attempts < RESPAWN_ATTEMPTS_MIN || attempts > RESPAWN_ATTEMPTS_MAX)) prog_usage_msg("Invalid --attempts argument: %d (Not between %d and %d)", attempts, RESPAWN_ATTEMPTS_MIN, RESPAWN_ATTEMPTS_MAX); g.attempts = attempts; } /* C Store the C<--delay> option argument, C. */ static void handle_delay_option(int delay) { debug((1, "handle_delay_option(delay = %d)", delay)) if (!g.idiot && delay < RESPAWN_DELAY_MIN) prog_usage_msg("Invalid --delay argument: %d (Less than %d)\n", delay, RESPAWN_DELAY_MIN); g.delay = delay; } /* C Store the C<--limit> option argument, C. */ static void handle_limit_option(int limit) { debug((1, "handle_limit_option(limit = %d)", limit)) if (limit < RESPAWN_LIMIT_MIN) prog_usage_msg("Invalid --limit argument: %d (Less than %d)\n", limit, RESPAWN_LIMIT_MIN); g.limit = limit; } /* C Store the C<--idiot> option argument if allowed. */ static void handle_idiot_option(void) { debug((1, "handle_idiot_option()")) if (g.initial_uid) prog_usage_msg("Invalid option: --idiot (Only for root)"); g.idiot = 1; } /* C Store the C<--pty> option argument, C. */ static void handle_pty_option(const char *arg) { debug((1, "handle_pty_option(arg = %s)", (arg) ? arg : "")) g.pty = 1; if (arg) { arg = expand(arg); debug((2, "pty %s", arg)) if (strcmp(arg, "noecho")) prog_usage_msg("Invalid --pty argument: '%s' (Only 'noecho' is supported)", arg); g.noecho = 1; } } /* C Parse the syslog target, C. Store C in C<*str> and store the parsed facility and priority in C<*var>. */ static void store_syslog(const char *option, const char *spec, char **str, int *var) { int facility; int priority; debug((1, "store_syslog(spec = %s)", spec)) if (syslog_parse(spec, &facility, &priority) == -1) { *str = (char *)spec; /* Must be a file */ *var = 0; /* Erase default syslog */ return; } *str = (char *)spec; *var = facility | priority; } /* C Parse and store the C<--errlog> option argument, C. */ static void handle_errlog_option(const char *spec) { debug((1, "handle_errlog_option(spec = %s)", spec)) spec = expand(spec); store_syslog("errlog", spec, &g.daemon_err, &g.daemon_errlog); debug((2, "errlog %s", spec)) } /* C Parse and store the C<--dbglog> option argument, C. */ static void handle_dbglog_option(const char *spec) { debug((1, "handle_dbglog_option(spec = %s)", spec)) spec = expand(spec); store_syslog("dbglog", spec, &g.daemon_dbg, &g.daemon_dbglog); debug((2, "dbglog %s", spec)) } /* C Parse and store the C<--output> option argument, C. */ static void handle_output_option(const char *spec) { debug((1, "handle_output_option(spec = %s)", spec)) spec = expand(spec); store_syslog("output", spec, &g.client_out, &g.client_outlog); store_syslog("output", spec, &g.client_err, &g.client_errlog); debug((2, "output %s", spec)) } /* C Parse and store the C<--stdout> option argument, C. */ static void handle_stdout_option(const char *spec) { debug((1, "handle_stdout_option(spec = %s)", spec)) spec = expand(spec); store_syslog("stdout", spec, &g.client_out, &g.client_outlog); debug((2, "stdout %s", spec)) } /* C Parse and store the C<--stderr> option argument, C. */ static void handle_stderr_option(const char *spec) { debug((1, "handle_stderr_option(spec = %s)", spec)) spec = expand(spec); store_syslog("stderr", spec, &g.client_err, &g.client_errlog); debug((2, "stderr %s", spec)) } /* C Turn off I mode. */ static void handle_ignore_eof_option(void) { debug((1, "handle_ignore_eof_option()")) g.read_eof = 0; } /* C Restore I mode. */ static void handle_read_eof_option(void) { debug((1, "handle_read_eof_option()")) g.read_eof = 1; } /* C Store the C<--signal> option argument, C. */ #ifdef NSIG #define SIG_MAX NSIG #else #ifdef _NSIG #define SIG_MAX _NSIG #else #define SIG_MAX 32 #endif #endif typedef struct sigmap_t sigmap_t; struct sigmap_t { char *signame; int signo; }; static sigmap_t signames[] = { #ifdef SIGHUP { "hup", SIGHUP }, #endif #ifdef SIGINT { "int", SIGINT }, #endif #ifdef SIGQUIT { "quit", SIGQUIT }, #endif #ifdef SIGILL { "ill", SIGILL }, #endif #ifdef SIGTRAP { "trap", SIGTRAP }, #endif #ifdef SIGABRT { "abrt", SIGABRT }, #endif #ifdef SIGIOT { "iot", SIGIOT }, #endif #ifdef SIGBUS { "bus", SIGBUS }, #endif #ifdef SIGFPE { "fpe", SIGFPE }, #endif #ifdef SIGKILL { "kill", SIGKILL }, #endif #ifdef SIGUSR1 { "usr1", SIGUSR1 }, #endif #ifdef SIGSEGV { "segv", SIGSEGV }, #endif #ifdef SIGUSR2 { "usr2", SIGUSR2 }, #endif #ifdef SIGPIPE { "pipe", SIGPIPE }, #endif #ifdef SIGALRM { "alrm", SIGALRM }, #endif #ifdef SIGTERM { "term", SIGTERM }, #endif #ifdef SIGSTKFLT { "stkflt", SIGSTKFLT }, #endif #ifdef SIGCLD { "cld", SIGCLD }, #endif #ifdef SIGCHLD { "chld", SIGCHLD }, #endif #ifdef SIGCONT { "cont", SIGCONT }, #endif #ifdef SIGSTOP { "stop", SIGSTOP }, #endif #ifdef SIGTSTP { "tstp", SIGTSTP }, #endif #ifdef SIGTTIN { "ttin", SIGTTIN }, #endif #ifdef SIGTTOU { "ttou", SIGTTOU }, #endif #ifdef SIGURG { "urg", SIGURG }, #endif #ifdef SIGXCPU { "xcpu", SIGXCPU }, #endif #ifdef SIGXFSZ { "xfsz", SIGXFSZ }, #endif #ifdef SIGVTALRM { "vtalrm", SIGVTALRM }, #endif #ifdef SIGPROF { "prof", SIGPROF }, #endif #ifdef SIGWINCH { "winch", SIGWINCH }, #endif #ifdef SIGPOLL { "poll", SIGPOLL }, #endif #ifdef SIGIO { "io", SIGIO }, #endif #ifdef SIGPWR { "pwr", SIGPWR }, #endif #ifdef SIGSYS { "sys", SIGSYS }, #endif #ifdef SIGEMT { "emt", SIGEMT }, #endif #ifdef SIGINFO { "info", SIGINFO }, #endif { null, 0 } }; static void handle_signal_option(const char *signame) { long int signo; char *endptr = null; int i; debug((1, "handle_signal_option(signame = %s)", signame)) errno = 0; signame = expand(signame); signo = strtol(signame, &endptr, 10); debug((2, "signal %s", signame)) if (errno == 0 && *signame && !*endptr && signo > 0 && signo < SIG_MAX) { g.signame = (char *)signame; g.signo = (int)signo; for (i = 0; signames[i].signame; ++i) if (signames[i].signo == g.signo) break; if (signames[i].signame) g.signame = signames[i].signame; } else { const char *start = signame; if (strncasecmp(start, "sig", 3) == 0) start += 3; for (i = 0; signames[i].signame; ++i) if (strcasecmp(start, signames[i].signame) == 0) break; if (!signames[i].signame) prog_usage_msg("Invalid --signal argument: '%s' (Must be a signal name or number)", signame); g.signame = (char *)signame; g.signo = signames[i].signo; } } /* C