]> git.tuebingen.mpg.de Git - paraslash.git/blob - daemon.c
daemon: Kill get_loglevel_by_name().
[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 /**
159  * Register functions to be called before and after a message is logged.
160  *
161  * \param pre_log_hook Called before the message is logged.
162  * \param post_log_hook Called after the message is logged.
163  *
164  * The purpose of this function is to provide a primitive for multi-threaded
165  * applications to serialize the access to the log facility, preventing
166  * interleaving log messages. This can be achieved by having the pre-log hook
167  * acquire a lock which blocks the other threads on the attempt to log a
168  * message at the same time.  The post-log hook is responsible for releasing
169  * the lock.
170  *
171  * If these hooks are unnecessary, for example because the application is
172  * single-threaded, this function does not need to be called.
173  */
174 void daemon_set_hooks(void (*pre_log_hook)(void), void (*post_log_hook)(void))
175 {
176         me->pre_log_hook = pre_log_hook;
177         me->post_log_hook = post_log_hook;
178 }
179
180 /**
181  * Set one of the daemon config flags.
182  *
183  * \param flag The flag to set.
184  *
185  * \sa \ref daemon_flags.
186  */
187 void daemon_set_flag(unsigned flag)
188 {
189         me->flags |= flag;
190 }
191
192 static bool daemon_test_flag(unsigned flag)
193 {
194         return me->flags & flag;
195 }
196
197 /**
198  * Do the usual stuff to become a daemon.
199  *
200  * \param parent_waits Whether the parent process should pause before exit.
201  *
202  * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
203  * parent_waits is false, the parent process terminates immediately.
204  * Otherwise, a pipe is created prior to the fork() and the parent tries to
205  * read a single byte from the reading end of the pipe. The child is supposed
206  * to write to the writing end of the pipe after it completed its setup
207  * procedure successfully. This behaviour is useful to let the parent process
208  * die with an error if the child process aborts early, since in this case the
209  * read() will return non-positive.
210  *
211  * \return This function either succeeds or calls exit(3). If parent_waits is
212  * true, the return value is the file descriptor of the writing end of the
213  * pipe. Otherwise the function returns zero.
214  *
215  * \sa fork(2), setsid(2), dup(2), pause(2).
216  */
217 int daemonize(bool parent_waits)
218 {
219         pid_t pid;
220         int null, pipe_fd[2];
221
222         if (parent_waits && pipe(pipe_fd) < 0)
223                 goto err;
224         PARA_INFO_LOG("subsequent log messages go to %s\n", me->logfile_name?
225                  me->logfile_name : "/dev/null");
226         pid = fork();
227         if (pid < 0)
228                 goto err;
229         if (pid) { /* parent exits */
230                 if (parent_waits) {
231                         char c;
232                         close(pipe_fd[1]);
233                         exit(read(pipe_fd[0], &c, 1) <= 0?
234                                 EXIT_FAILURE : EXIT_SUCCESS);
235                 }
236                 exit(EXIT_SUCCESS);
237         }
238         if (parent_waits)
239                 close(pipe_fd[0]);
240         /* become session leader */
241         if (setsid() < 0)
242                 goto err;
243         me->old_cwd = getcwd(NULL, 0);
244         if (chdir("/") < 0)
245                 goto err;
246         null = open("/dev/null", O_RDWR);
247         if (null < 0)
248                 goto err;
249         if (dup2(null, STDIN_FILENO) < 0)
250                 goto err;
251         if (dup2(null, STDOUT_FILENO) < 0)
252                 goto err;
253         if (dup2(null, STDERR_FILENO) < 0)
254                 goto err;
255         close(null);
256         return parent_waits? pipe_fd[1] : 0;
257 err:
258         PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
259         exit(EXIT_FAILURE);
260 }
261
262 /**
263  * Close the log file of the daemon.
264  */
265 void daemon_close_log(void)
266 {
267         if (!me->logfile)
268                 return;
269         PARA_INFO_LOG("closing logfile\n");
270         fclose(me->logfile);
271         me->logfile = NULL;
272 }
273
274 /**
275  * fopen() the logfile in append mode.
276  *
277  * \return Either succeeds or exits.
278  */
279 void daemon_open_log_or_die(void)
280 {
281         FILE *new_log;
282
283         if (!me->logfile_name)
284                 return;
285         new_log = fopen(me->logfile_name, "a");
286         if (!new_log) {
287                 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
288                         strerror(errno));
289                 exit(EXIT_FAILURE);
290         }
291         daemon_close_log();
292         me->logfile = new_log;
293         /* equivalent to setlinebuf(), but portable */
294         setvbuf(me->logfile, NULL, _IOLBF, 0);
295 }
296
297 /**
298  * Log the startup message containing the paraslash version.
299  *
300  * \param name The name of the executable.
301  *
302  * First the given \a name is prefixed with the string "para_". Next the git
303  * version is appended. The resulting string is logged with priority "INFO".
304  */
305 void daemon_log_welcome(const char *name)
306 {
307         PARA_INFO_LOG("welcome to para_%s-" PACKAGE_VERSION " \n", name);
308 }
309
310 /**
311  * Renice the calling process.
312  *
313  * \param prio The priority value to set.
314  *
315  * Errors are not considered fatal, but a warning message is logged if the
316  * underlying call to setpriority(2) fails.
317  */
318 void daemon_set_priority(int prio)
319 {
320         if (setpriority(PRIO_PROCESS, 0, prio) < 0)
321                 PARA_WARNING_LOG("could not set priority to %d: %s\n", prio,
322                         strerror(errno));
323 }
324
325 /**
326  * Give up superuser privileges.
327  *
328  * \param username The user to switch to.
329  * \param groupname The group to switch to.
330  *
331  * This function returns immediately if not invoked with EUID zero. Otherwise,
332  * it tries to obtain the GID of \a groupname and the UID of \a username.  On
333  * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
334  * are all set accordingly. On errors, an appropriate message is logged and
335  * exit() is called to terminate the process.
336  *
337  * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
338  */
339 void daemon_drop_privileges_or_die(const char *username, const char *groupname)
340 {
341         struct passwd *p;
342         char *tmp;
343
344         if (geteuid())
345                 return;
346         if (groupname) {
347                 struct group *g = getgrnam(groupname);
348                 if (!g) {
349                         PARA_EMERG_LOG("failed to get group %s: %s\n",
350                                 groupname, strerror(errno));
351                         exit(EXIT_FAILURE);
352                 }
353                 if (setgid(g->gr_gid) < 0) {
354                         PARA_EMERG_LOG("failed to set group id %d: %s\n",
355                                 (int)g->gr_gid, strerror(errno));
356                         exit(EXIT_FAILURE);
357                 }
358         }
359         if (!username) {
360                 PARA_EMERG_LOG("root privileges, but no user option given\n");
361                 exit(EXIT_FAILURE);
362         }
363         tmp = para_strdup(username);
364         p = getpwnam(tmp);
365         free(tmp);
366         if (!p) {
367                 PARA_EMERG_LOG("%s: no such user\n", username);
368                 exit(EXIT_FAILURE);
369         }
370         PARA_INFO_LOG("dropping root privileges\n");
371         if (setuid(p->pw_uid) < 0) {
372                 PARA_EMERG_LOG("failed to set effective user ID (%s)",
373                         strerror(errno));
374                 exit(EXIT_FAILURE);
375         }
376         PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
377 }
378
379 /**
380  * Set the startup time.
381  *
382  * This should be called once on startup. It sets the start time to the
383  * current time. The stored time is used for retrieving the server uptime.
384  *
385  * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
386  */
387 void daemon_set_start_time(void)
388 {
389         time(&me->startuptime);
390 }
391
392 /**
393  * Get the uptime.
394  *
395  * \param current_time The current time.
396  *
397  * The \a current_time pointer may be \p NULL. In this case the function
398  * obtains the current time from the system.
399  *
400  * \return This returns the server uptime in seconds, i.e. the difference
401  * between the current time and the value stored previously via \ref
402  * daemon_set_start_time().
403  */
404 time_t daemon_get_uptime(const struct timeval *current_time)
405 {
406         time_t t;
407
408         if (current_time)
409                 return current_time->tv_sec - me->startuptime;
410         time(&t);
411         return difftime(t, me->startuptime);
412 }
413
414 /**
415  * Construct a string containing the current uptime.
416  *
417  * \param current_time See a \ref daemon_get_uptime().
418  *
419  * \return A dynamically allocated string of the form "days:hours:minutes".
420  */
421 __malloc char *daemon_get_uptime_str(const struct timeval *current_time)
422 {
423         long t = daemon_get_uptime(current_time);
424         return make_message("%li:%02li:%02li", t / 86400,
425                 (t / 3600) % 24, (t / 60) % 60);
426 }
427
428 /**
429  * The log function for para_server and para_audiod.
430  *
431  * \param ll The log level.
432  * \param fmt The format string describing the log message.
433  */
434 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
435 {
436         va_list argp;
437         FILE *fp;
438         struct tm *tm;
439         char *color;
440         bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
441                 daemon_test_flag(DF_LOG_TIMING);
442
443         ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
444         ll = PARA_MAX(ll, LL_DEBUG);
445         if (ll < me->loglevel)
446                 return;
447
448         fp = me->logfile? me->logfile : stderr;
449         if (me->pre_log_hook)
450                 me->pre_log_hook();
451         color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
452         if (color)
453                 fprintf(fp, "%s", color);
454         if (log_time || log_timing) {
455                 struct timeval tv;
456                 clock_get_realtime(&tv);
457                 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
458                         time_t t1 = tv.tv_sec;
459                         char str[100];
460                         tm = localtime(&t1);
461                         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
462                         fprintf(fp, "%s%s", str, log_timing? ":" : " ");
463                 }
464                 if (log_timing) /* print milliseconds */
465                         fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
466         }
467         if (daemon_test_flag(DF_LOG_HOSTNAME)) {
468                 if (!me->hostname)
469                         me->hostname = para_hostname();
470                 fprintf(fp, "%s ", me->hostname);
471         }
472         if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
473                 fprintf(fp, "(%d) ", ll);
474         if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
475                 pid_t mypid = getpid();
476                 fprintf(fp, "(%d) ", (int)mypid);
477         }
478         va_start(argp, fmt);
479         vfprintf(fp, fmt, argp);
480         va_end(argp);
481         if (color)
482                 fprintf(fp, "%s", COLOR_RESET);
483         if (me->post_log_hook)
484                 me->post_log_hook();
485 }