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