build: Rename command list variables.
[paraslash.git] / daemon.c
1 /*
2  * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file daemon.c Some helpers for programs that detach from the console. */
8
9 #include <regex.h>
10 #include <pwd.h>
11 #include <sys/types.h> /* getgrnam() */
12 #include <grp.h>
13 #include <signal.h>
14 #include <sys/resource.h>
15
16 #include "para.h"
17 #include "daemon.h"
18 #include "string.h"
19 #include "color.h"
20
21 /** The internal state of the daemon. */
22 struct daemon {
23         /** See \ref daemon_flags. */
24         unsigned flags;
25         /** Set by \ref daemon_set_logfile(). */
26         char *logfile_name;
27         /** Current loglevel, see \ref daemon_set_loglevel(). */
28         int loglevel;
29         /** Used by \ref server_uptime() and \ref uptime_str(). */
30         time_t startuptime;
31         /** The file pointer if the logfile is open. */
32         FILE *logfile;
33         /** Used by para_log() if \p DF_LOG_HOSTNAME is set. */
34         char *hostname;
35         /** Used for colored log messages. */
36         char log_colors[NUM_LOGLEVELS][COLOR_MAXLEN];
37 };
38
39 static struct daemon the_daemon, *me = &the_daemon;
40
41 static void daemon_set_default_log_colors(void)
42 {
43         int i;
44         static const char *default_log_colors[NUM_LOGLEVELS] = {
45                 [LL_DEBUG] = "normal",
46                 [LL_INFO] = "normal",
47                 [LL_NOTICE] = "normal",
48                 [LL_WARNING] = "yellow",
49                 [LL_ERROR] = "red",
50                 [LL_CRIT] = "magenta bold",
51                 [LL_EMERG] = "red bold",
52         };
53         for (i = 0; i < NUM_LOGLEVELS; i++)
54                 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
55 }
56
57 /**
58  * Set the color for one loglevel.
59  *
60  * \param arg Must be of the form "ll:[fg [bg]] [attr]".
61  */
62 void daemon_set_log_color_or_die(const char *arg)
63 {
64         char *p = strchr(arg, ':');
65         int ret, ll;
66
67         if (!p)
68                 goto err;
69         ret = get_loglevel_by_name(arg);
70         if (ret < 0)
71                 goto err;
72         ll = ret;
73         p++;
74         color_parse_or_die(p, me->log_colors[ll]);
75         return;
76 err:
77         PARA_EMERG_LOG("%s: invalid color argument\n", arg);
78         exit(EXIT_FAILURE);
79 }
80
81 /**
82  * Initialize color mode if necessary.
83  *
84  * \param color_arg The argument given to --color.
85  * \param color_arg_auto The value for automatic color detection.
86  * \param color_arg_no The value to disable colored log messages.
87  * \param logfile_given In auto mode colors are disabled if this value is true.
88  *
89  * If color_arg equals color_arg_no, color mode is disabled. That is, calls to
90  * para_log() will not produce colored output. If color_arg equals
91  * color_arg_auto, the function detects automatically whether to activate
92  * colors. Otherwise color mode is enabled.
93  *
94  * If color mode is to be enabled, the default colors are set for each
95  * loglevel. They can be overwritten by calling daemon_set_log_color_or_die().
96  *
97  * \return Whether colors have been enabled by the function.
98  */
99 bool daemon_init_colors_or_die(int color_arg, int color_arg_auto,
100                 int color_arg_no, bool logfile_given)
101 {
102         if (color_arg == color_arg_no)
103                 return false;
104         if (color_arg == color_arg_auto) {
105                 if (logfile_given)
106                         return false;
107                 if (!isatty(STDERR_FILENO))
108                         return false;
109         }
110         daemon_set_flag(DF_COLOR_LOG);
111         daemon_set_default_log_colors();
112         return true;
113 }
114
115 /**
116  * Init or change the name of the log file.
117  *
118  * \param logfile_name The full path of the logfile.
119  */
120 void daemon_set_logfile(const char *logfile_name)
121 {
122         free(me->logfile_name);
123         me->logfile_name = NULL;
124         if (logfile_name)
125                 me->logfile_name = para_strdup(logfile_name);
126 }
127
128 /**
129  * Suppress log messages with severity lower than the given loglevel.
130  *
131  * \param loglevel The smallest level that should be logged.
132  */
133 void daemon_set_loglevel(const char *loglevel)
134 {
135         int ret = get_loglevel_by_name(loglevel);
136
137         assert(ret >= 0);
138         me->loglevel = ret;
139 }
140
141 /**
142  * Set one of the daemon config flags.
143  *
144  * \param flag The flag to set.
145  *
146  * \sa \ref daemon_flags.
147  */
148 void daemon_set_flag(unsigned flag)
149 {
150         me->flags |= flag;
151 }
152
153 static bool daemon_test_flag(unsigned flag)
154 {
155         return me->flags & flag;
156 }
157
158 /**
159  * Do the usual stuff to become a daemon.
160  *
161  * \param parent_waits Whether the parent process should pause before exit.
162  *
163  * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
164  * parent_waits is false, the parent process terminates immediately.
165  * Otherwise, a pipe is created prior to the fork() and the parent tries to
166  * read a single byte from the reading end of the pipe. The child is supposed
167  * to write to the writing end of the pipe after it completed its setup
168  * procedure successfully. This behaviour is useful to let the parent process
169  * die with an error if the child process aborts early, since in this case the
170  * read() will return non-positive.
171  *
172  * \return This function either succeeds or calls exit(3). If parent_waits is
173  * true, the return value is the file descriptor of the writing end of the
174  * pipe. Otherwise the function returns zero.
175  *
176  * \sa fork(2), setsid(2), dup(2), pause(2).
177  */
178 int daemonize(bool parent_waits)
179 {
180         pid_t pid;
181         int null, pipe_fd[2];
182
183         if (parent_waits && pipe(pipe_fd) < 0)
184                 goto err;
185         PARA_INFO_LOG("subsequent log messages go to %s\n", me->logfile_name?
186                  me->logfile_name : "/dev/null");
187         pid = fork();
188         if (pid < 0)
189                 goto err;
190         if (pid) { /* parent exits */
191                 if (parent_waits) {
192                         char c;
193                         close(pipe_fd[1]);
194                         exit(read(pipe_fd[0], &c, 1) <= 0?
195                                 EXIT_FAILURE : EXIT_SUCCESS);
196                 }
197                 exit(EXIT_SUCCESS);
198         }
199         if (parent_waits)
200                 close(pipe_fd[0]);
201         /* become session leader */
202         if (setsid() < 0)
203                 goto err;
204         if (chdir("/") < 0)
205                 goto err;
206         null = open("/dev/null", O_RDWR);
207         if (null < 0)
208                 goto err;
209         if (dup2(null, STDIN_FILENO) < 0)
210                 goto err;
211         if (dup2(null, STDOUT_FILENO) < 0)
212                 goto err;
213         if (dup2(null, STDERR_FILENO) < 0)
214                 goto err;
215         close(null);
216         return parent_waits? pipe_fd[1] : 0;
217 err:
218         PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
219         exit(EXIT_FAILURE);
220 }
221
222 /**
223  * Close the log file of the daemon.
224  */
225 void daemon_close_log(void)
226 {
227         if (!me->logfile)
228                 return;
229         PARA_INFO_LOG("closing logfile\n");
230         fclose(me->logfile);
231         me->logfile = NULL;
232 }
233
234 /**
235  * fopen() the logfile in append mode.
236  *
237  * \return Either succeeds or exits.
238  */
239 void daemon_open_log_or_die(void)
240 {
241         daemon_close_log();
242         if (!me->logfile_name)
243                 return;
244         me->logfile = fopen(me->logfile_name, "a");
245         if (!me->logfile) {
246                 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
247                         strerror(errno));
248                 exit(EXIT_FAILURE);
249         }
250         /* equivalent to setlinebuf(), but portable */
251         setvbuf(me->logfile, NULL, _IOLBF, 0);
252 }
253
254 /**
255  * Log the startup message containing the paraslash version.
256  *
257  * \param name The name of the executable.
258  *
259  * First the given \a name is prefixed with the string "para_". Next the git
260  * version is appended. The resulting string is logged with priority "INFO".
261  */
262 void daemon_log_welcome(const char *name)
263 {
264         PARA_INFO_LOG("welcome to para_%s-" PACKAGE_VERSION " \n", name);
265 }
266
267 /**
268  * Renice the calling process.
269  *
270  * \param prio The priority value to set.
271  *
272  * Errors are not considered fatal, but a warning message is logged if the
273  * underlying call to setpriority(2) fails.
274  */
275 void daemon_set_priority(int prio)
276 {
277         if (setpriority(PRIO_PROCESS, 0, prio) < 0)
278                 PARA_WARNING_LOG("could not set priority to %d: %s\n", prio,
279                         strerror(errno));
280 }
281
282 /**
283  * Give up superuser privileges.
284  *
285  * \param username The user to switch to.
286  * \param groupname The group to switch to.
287  *
288  * This function returns immediately if not invoked with EUID zero. Otherwise,
289  * it tries to obtain the GID of \a groupname and the UID of \a username.  On
290  * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
291  * are all set accordingly. On errors, an appropriate message is logged and
292  * exit() is called to terminate the process.
293  *
294  * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
295  */
296 void daemon_drop_privileges_or_die(const char *username, const char *groupname)
297 {
298         struct passwd *p;
299         char *tmp;
300
301         if (geteuid())
302                 return;
303         if (groupname) {
304                 struct group *g = getgrnam(groupname);
305                 if (!g) {
306                         PARA_EMERG_LOG("failed to get group %s: %s\n",
307                                 groupname, strerror(errno));
308                         exit(EXIT_FAILURE);
309                 }
310                 if (setgid(g->gr_gid) < 0) {
311                         PARA_EMERG_LOG("failed to set group id %d: %s\n",
312                                 (int)g->gr_gid, strerror(errno));
313                         exit(EXIT_FAILURE);
314                 }
315         }
316         if (!username) {
317                 PARA_EMERG_LOG("root privileges, but no user option given\n");
318                 exit(EXIT_FAILURE);
319         }
320         tmp = para_strdup(username);
321         p = getpwnam(tmp);
322         free(tmp);
323         if (!p) {
324                 PARA_EMERG_LOG("%s: no such user\n", username);
325                 exit(EXIT_FAILURE);
326         }
327         PARA_INFO_LOG("dropping root privileges\n");
328         if (setuid(p->pw_uid) < 0) {
329                 PARA_EMERG_LOG("failed to set effective user ID (%s)",
330                         strerror(errno));
331                 exit(EXIT_FAILURE);
332         }
333         PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
334 }
335
336 /**
337  * Set the startup time.
338  *
339  * This should be called once on startup. It sets the start time to the
340  * current time. The stored time is used for retrieving the server uptime.
341  *
342  * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
343  */
344 void daemon_set_start_time(void)
345 {
346         time(&me->startuptime);
347 }
348
349 /**
350  * Get the uptime.
351  *
352  * \param current_time The current time.
353  *
354  * The \a current_time pointer may be \p NULL. In this case the function
355  * obtains the current time from the system.
356  *
357  * \return This returns the server uptime in seconds, i.e. the difference
358  * between the current time and the value stored previously via \ref
359  * daemon_set_start_time().
360  */
361 time_t daemon_get_uptime(const struct timeval *current_time)
362 {
363         time_t t;
364
365         if (current_time)
366                 return current_time->tv_sec - me->startuptime;
367         time(&t);
368         return difftime(t, me->startuptime);
369 }
370
371 /**
372  * Construct a string containing the current uptime.
373  *
374  * \param current_time See a \ref daemon_get_uptime().
375  *
376  * \return A dynamically allocated string of the form "days:hours:minutes".
377  *
378  * \sa server_uptime.
379  */
380 __malloc char *daemon_get_uptime_str(const struct timeval *current_time)
381 {
382         long t = daemon_get_uptime(current_time);
383         return make_message("%li:%02li:%02li", t / 86400,
384                 (t / 3600) % 24, (t / 60) % 60);
385 }
386
387 /**
388  * The log function for para_server and para_audiod.
389  *
390  * \param ll The log level.
391  * \param fmt The format string describing the log message.
392  */
393 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
394 {
395         va_list argp;
396         FILE *fp;
397         struct tm *tm;
398         char *color;
399         bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
400                 daemon_test_flag(DF_LOG_TIMING);
401
402         ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
403         ll = PARA_MAX(ll, LL_DEBUG);
404         if (ll < me->loglevel)
405                 return;
406
407         fp = me->logfile? me->logfile : stderr;
408         color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
409         if (color)
410                 fprintf(fp, "%s", color);
411         if (log_time || log_timing) {
412                 struct timeval tv;
413                 clock_get_realtime(&tv);
414                 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
415                         time_t t1 = tv.tv_sec;
416                         char str[100];
417                         tm = localtime(&t1);
418                         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
419                         fprintf(fp, "%s%s", str, log_timing? ":" : " ");
420                 }
421                 if (log_timing) /* print milliseconds */
422                         fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
423         }
424         if (daemon_test_flag(DF_LOG_HOSTNAME)) {
425                 if (!me->hostname)
426                         me->hostname = para_hostname();
427                 fprintf(fp, "%s ", me->hostname);
428         }
429         if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
430                 fprintf(fp, "(%d) ", ll);
431         if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
432                 pid_t mypid = getpid();
433                 fprintf(fp, "(%d) ", (int)mypid);
434         }
435         va_start(argp, fmt);
436         vfprintf(fp, fmt, argp);
437         va_end(argp);
438         if (color)
439                 fprintf(fp, "%s", COLOR_RESET);
440 }