1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file daemon.c Some helpers for programs that detach from the console. */
7 #include <sys/types.h> /* getgrnam() */
10 #include <sys/resource.h>
17 /** The internal state of the daemon. */
19 /** See \ref daemon_flags. */
21 /** Set by \ref daemon_set_logfile(). */
23 /** Current loglevel, see \ref daemon_set_loglevel(). */
25 /** Used by \ref server_uptime() and \ref uptime_str(). */
27 /** The file pointer if the logfile is open. */
29 /** Used by para_log() if \p DF_LOG_HOSTNAME is set. */
31 /** Used for colored log messages. */
32 char log_colors[NUM_LOGLEVELS][COLOR_MAXLEN];
35 * If these pointers are non-NULL, the functions are called from
36 * daemon_log() before and after writing each log message.
38 void (*pre_log_hook)(void);
39 void (*post_log_hook)(void);
42 static struct daemon the_daemon, *me = &the_daemon;
44 static void daemon_set_default_log_colors(void)
47 static const char *default_log_colors[NUM_LOGLEVELS] = {
48 [LL_DEBUG] = "normal",
50 [LL_NOTICE] = "normal",
51 [LL_WARNING] = "yellow",
53 [LL_CRIT] = "magenta bold",
54 [LL_EMERG] = "red bold",
56 for (i = 0; i < NUM_LOGLEVELS; i++)
57 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
61 * Set the color for log messages of the given severity level.
63 * \param arg Must be of the form "severity:[fg [bg]] [attr]".
65 void daemon_set_log_color_or_die(const char *arg)
68 const char * const sev[] = {SEVERITIES};
69 char *p = strchr(arg, ':');
73 for (ll = 0; ll < NUM_LOGLEVELS; ll++) {
74 const char *name = sev[ll];
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
81 if (strncasecmp(arg, name, strlen(name)))
83 return color_parse_or_die(p + 1, me->log_colors[ll]);
86 PARA_EMERG_LOG("%s: invalid color argument\n", arg);
91 * Initialize color mode if necessary.
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.
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.
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().
106 * \return Whether colors have been enabled by the function.
108 bool daemon_init_colors_or_die(int color_arg, int color_arg_auto,
109 int color_arg_no, bool logfile_given)
111 if (color_arg == color_arg_no)
113 if (color_arg == color_arg_auto) {
116 if (!isatty(STDERR_FILENO))
119 daemon_set_flag(DF_COLOR_LOG);
120 daemon_set_default_log_colors();
125 * Init or change the name of the log file.
127 * \param logfile_name The full path of the logfile.
129 void daemon_set_logfile(const char *logfile_name)
131 free(me->logfile_name);
132 me->logfile_name = NULL;
135 if (me->old_cwd && logfile_name[0] != '/')
136 me->logfile_name = make_message("%s/%s", me->old_cwd,
139 me->logfile_name = para_strdup(logfile_name);
143 * Control the verbosity for logging.
145 * This instructs the daemon to not log subsequent messages whose severity is
146 * lower than the given value.
148 * \param loglevel The new log level.
150 void daemon_set_loglevel(int loglevel)
152 assert(loglevel >= 0);
153 assert(loglevel < NUM_LOGLEVELS);
154 me->loglevel = loglevel;
158 * Get the current log level of the daemon.
160 * \return Greater or equal than zero and less than NUM_LOGLEVELS. This
161 * function never fails.
163 int daemon_get_loglevel(void)
169 * Register functions to be called before and after a message is logged.
171 * \param pre_log_hook Called before the message is logged.
172 * \param post_log_hook Called after the message is logged.
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
181 * If these hooks are unnecessary, for example because the application is
182 * single-threaded, this function does not need to be called.
184 void daemon_set_hooks(void (*pre_log_hook)(void), void (*post_log_hook)(void))
186 me->pre_log_hook = pre_log_hook;
187 me->post_log_hook = post_log_hook;
191 * Set one of the daemon config flags.
193 * \param flag The flag to set.
195 * \sa \ref daemon_flags.
197 void daemon_set_flag(unsigned flag)
202 static bool daemon_test_flag(unsigned flag)
204 return me->flags & flag;
208 * Do the usual stuff to become a daemon.
210 * \param parent_waits Whether the parent process should pause before exit.
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.
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.
225 * \sa fork(2), setsid(2), dup(2), pause(2).
227 int daemonize(bool parent_waits)
230 int null, pipe_fd[2];
232 if (parent_waits && pipe(pipe_fd) < 0)
234 PARA_INFO_LOG("subsequent log messages go to %s\n", me->logfile_name?
235 me->logfile_name : "/dev/null");
239 if (pid) { /* parent exits */
243 exit(read(pipe_fd[0], &c, 1) <= 0?
244 EXIT_FAILURE : EXIT_SUCCESS);
250 /* become session leader */
253 me->old_cwd = getcwd(NULL, 0);
256 null = open("/dev/null", O_RDWR);
259 if (dup2(null, STDIN_FILENO) < 0)
261 if (dup2(null, STDOUT_FILENO) < 0)
263 if (dup2(null, STDERR_FILENO) < 0)
266 return parent_waits? pipe_fd[1] : 0;
268 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
273 * Close the log file of the daemon.
275 void daemon_close_log(void)
279 PARA_INFO_LOG("closing logfile\n");
285 * Open the logfile in append mode.
287 * This function either succeeds or exits.
289 void daemon_open_log_or_die(void)
293 if (!me->logfile_name)
295 new_log = fopen(me->logfile_name, "a");
297 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
302 me->logfile = new_log;
303 /* equivalent to setlinebuf(), but portable */
304 setvbuf(me->logfile, NULL, _IOLBF, 0);
308 * Log the startup message containing the paraslash version.
310 * \param name The name of the executable.
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".
315 void daemon_log_welcome(const char *name)
317 PARA_INFO_LOG("welcome to para_%s-" PACKAGE_VERSION " \n", name);
321 * Renice the calling process.
323 * \param prio The priority value to set.
325 * Errors are not considered fatal, but a warning message is logged if the
326 * underlying call to setpriority(2) fails.
328 void daemon_set_priority(int prio)
330 if (setpriority(PRIO_PROCESS, 0, prio) < 0)
331 PARA_WARNING_LOG("could not set priority to %d: %s\n", prio,
336 * Give up superuser privileges.
338 * \param username The user to switch to.
339 * \param groupname The group to switch to.
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.
347 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
349 void daemon_drop_privileges_or_die(const char *username, const char *groupname)
357 struct group *g = getgrnam(groupname);
359 PARA_EMERG_LOG("failed to get group %s: %s\n",
360 groupname, strerror(errno));
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));
370 PARA_EMERG_LOG("root privileges, but no user option given\n");
373 tmp = para_strdup(username);
377 PARA_EMERG_LOG("%s: no such user\n", username);
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)",
386 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
390 * Set the startup time.
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.
395 * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
397 void daemon_set_start_time(void)
399 time(&me->startuptime);
405 * \param current_time The current time.
407 * The \a current_time pointer may be \p NULL. In this case the function
408 * obtains the current time from the system.
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().
414 time_t daemon_get_uptime(const struct timeval *current_time)
419 return current_time->tv_sec - me->startuptime;
421 return difftime(t, me->startuptime);
425 * Construct a string containing the current uptime.
427 * \param current_time See a \ref daemon_get_uptime().
429 * \return A dynamically allocated string of the form "days:hours:minutes".
431 __malloc char *daemon_get_uptime_str(const struct timeval *current_time)
433 long t = daemon_get_uptime(current_time);
434 return make_message("%li:%02li:%02li", t / 86400,
435 (t / 3600) % 24, (t / 60) % 60);
439 * The log function for para_server and para_audiod.
441 * \param ll The log level.
442 * \param fmt The format string describing the log message.
444 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
450 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
451 daemon_test_flag(DF_LOG_TIMING);
453 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
454 ll = PARA_MAX(ll, LL_DEBUG);
455 if (ll < me->loglevel)
458 fp = me->logfile? me->logfile : stderr;
459 if (me->pre_log_hook)
461 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
463 fprintf(fp, "%s", color);
464 if (log_time || log_timing) {
466 clock_get_realtime(&tv);
467 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
468 time_t t1 = tv.tv_sec;
471 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
472 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
474 if (log_timing) /* print milliseconds */
475 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
477 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
479 me->hostname = para_hostname();
480 fprintf(fp, "%s ", me->hostname);
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);
489 vfprintf(fp, fmt, argp);
492 fprintf(fp, "%s", COLOR_RESET);
493 if (me->post_log_hook)