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