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