2 * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file daemon.c Some helpers for programs that detach from the console. */
11 #include <sys/types.h> /* getgrnam() */
14 #include <sys/resource.h>
21 /** The internal state of the daemon. */
23 /** See \ref daemon_flags. */
25 /** Set by \ref daemon_set_logfile(). */
27 /** Current loglevel, see \ref daemon_set_loglevel(). */
29 /** Used by \ref server_uptime() and \ref uptime_str(). */
31 /** The file pointer if the logfile is open. */
33 /** Used by para_log() if \p DF_LOG_HOSTNAME is set. */
35 /** Used for colored log messages. */
36 char log_colors[NUM_LOGLEVELS][COLOR_MAXLEN];
39 static struct daemon the_daemon, *me = &the_daemon;
41 static void daemon_set_default_log_colors(void)
44 static const char *default_log_colors[NUM_LOGLEVELS] = {
45 [LL_DEBUG] = "normal",
47 [LL_NOTICE] = "normal",
48 [LL_WARNING] = "yellow",
50 [LL_CRIT] = "magenta bold",
51 [LL_EMERG] = "red bold",
53 for (i = 0; i < NUM_LOGLEVELS; i++)
54 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
58 * Set the color for one loglevel.
60 * \param arg Must be of the form "ll:[fg [bg]] [attr]".
62 void daemon_set_log_color_or_die(const char *arg)
64 char *p = strchr(arg, ':');
69 ret = get_loglevel_by_name(arg);
74 color_parse_or_die(p, me->log_colors[ll]);
77 PARA_EMERG_LOG("%s: invalid color argument\n", arg);
82 * Initialize color mode if necessary.
84 * \param color_arg The argument given to --color.
85 * \param color_arg_auto The value for automatic color detection.
86 * \param color_arg_no The value to disable colored log messages.
87 * \param logfile_given In auto mode colors are disabled if this value is true.
89 * If color_arg equals color_arg_no, color mode is disabled. That is, calls to
90 * para_log() will not produce colored output. If color_arg equals
91 * color_arg_auto, the function detects automatically whether to activate
92 * colors. Otherwise color mode is enabled.
94 * If color mode is to be enabled, the default colors are set for each
95 * loglevel. They can be overwritten by calling daemon_set_log_color_or_die().
97 * \return Whether colors have been enabled by the function.
99 bool daemon_init_colors_or_die(int color_arg, int color_arg_auto,
100 int color_arg_no, bool logfile_given)
102 if (color_arg == color_arg_no)
104 if (color_arg == color_arg_auto) {
107 if (!isatty(STDERR_FILENO))
110 daemon_set_flag(DF_COLOR_LOG);
111 daemon_set_default_log_colors();
116 * Init or change the name of the log file.
118 * \param logfile_name The full path of the logfile.
120 void daemon_set_logfile(const char *logfile_name)
122 free(me->logfile_name);
123 me->logfile_name = NULL;
125 me->logfile_name = para_strdup(logfile_name);
129 * Suppress log messages with severity lower than the given loglevel.
131 * \param loglevel The smallest level that should be logged.
133 void daemon_set_loglevel(const char *loglevel)
135 int ret = get_loglevel_by_name(loglevel);
142 * Set one of the daemon config flags.
144 * \param flag The flag to set.
146 * \sa \ref daemon_flags.
148 void daemon_set_flag(unsigned flag)
153 static bool daemon_test_flag(unsigned flag)
155 return me->flags & flag;
158 static void dummy_sighandler(__a_unused int s)
163 * Do the usual stuff to become a daemon.
165 * \param parent_waits Whether the parent process should pause before exit.
167 * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
168 * parent_waits is false, the parent process terminates immediately.
169 * Otherwise, it calls pause() to sleep until it receives \p SIGTERM or \p
170 * SIGCHLD and exits successfully thereafter. This behaviour is useful if the
171 * daemon process should not detach from the console until the child process
172 * has completed its setup.
174 * \sa fork(2), setsid(2), dup(2), pause(2).
176 void daemonize(bool parent_waits)
181 PARA_INFO_LOG("subsequent log messages go to %s\n", me->logfile_name?
182 me->logfile_name : "/dev/null");
188 signal(SIGTERM, dummy_sighandler);
189 signal(SIGCHLD, dummy_sighandler);
192 exit(EXIT_SUCCESS); /* parent exits */
194 /* become session leader */
199 null = open("/dev/null", O_RDWR);
202 if (dup2(null, STDIN_FILENO) < 0)
204 if (dup2(null, STDOUT_FILENO) < 0)
206 if (dup2(null, STDERR_FILENO) < 0)
211 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
216 * Close the log file of the daemon.
218 void daemon_close_log(void)
222 PARA_INFO_LOG("closing logfile\n");
228 * fopen() the logfile in append mode.
230 * \return Either succeeds or exits.
232 void daemon_open_log_or_die(void)
235 if (!me->logfile_name)
237 me->logfile = fopen(me->logfile_name, "a");
239 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
243 /* equivalent to setlinebuf(), but portable */
244 setvbuf(me->logfile, NULL, _IOLBF, 0);
248 * Log the startup message containing the paraslash version.
250 * \param name The name of the executable.
252 * First the given \a name is prefixed with the string "para_". Next the git
253 * version is appended. The resulting string is logged with priority "INFO".
255 void daemon_log_welcome(const char *name)
257 PARA_INFO_LOG("welcome to para_%s-" PACKAGE_VERSION " \n", name);
261 * Renice the calling process.
263 * \param prio The priority value to set.
265 * Errors are not considered fatal, but a warning message is logged if the
266 * underlying call to setpriority(2) fails.
268 void daemon_set_priority(int prio)
270 if (setpriority(PRIO_PROCESS, 0, prio) < 0)
271 PARA_WARNING_LOG("could not set priority to %d: %s\n", prio,
276 * Give up superuser privileges.
278 * \param username The user to switch to.
279 * \param groupname The group to switch to.
281 * This function returns immediately if not invoked with EUID zero. Otherwise,
282 * it tries to obtain the GID of \a groupname and the UID of \a username. On
283 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
284 * are all set accordingly. On errors, an appropriate message is logged and
285 * exit() is called to terminate the process.
287 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
289 void daemon_drop_privileges_or_die(const char *username, const char *groupname)
297 struct group *g = getgrnam(groupname);
299 PARA_EMERG_LOG("failed to get group %s: %s\n",
300 groupname, strerror(errno));
303 if (setgid(g->gr_gid) < 0) {
304 PARA_EMERG_LOG("failed to set group id %d: %s\n",
305 (int)g->gr_gid, strerror(errno));
310 PARA_EMERG_LOG("root privileges, but no user option given\n");
313 tmp = para_strdup(username);
317 PARA_EMERG_LOG("%s: no such user\n", username);
320 PARA_INFO_LOG("dropping root privileges\n");
321 if (setuid(p->pw_uid) < 0) {
322 PARA_EMERG_LOG("failed to set effective user ID (%s)",
326 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
330 * Set the startup time.
332 * This should be called once on startup. It sets the start time to the
333 * current time. The stored time is used for retrieving the server uptime.
335 * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
337 void daemon_set_start_time(void)
339 time(&me->startuptime);
345 * \param current_time The current time.
347 * The \a current_time pointer may be \p NULL. In this case the function
348 * obtains the current time from the system.
350 * \return This returns the server uptime in seconds, i.e. the difference
351 * between the current time and the value stored previously via \ref
352 * daemon_set_start_time().
354 time_t daemon_get_uptime(const struct timeval *current_time)
359 return current_time->tv_sec - me->startuptime;
361 return difftime(t, me->startuptime);
365 * Construct a string containing the current uptime.
367 * \param current_time See a \ref daemon_get_uptime().
369 * \return A dynamically allocated string of the form "days:hours:minutes".
373 __malloc char *daemon_get_uptime_str(const struct timeval *current_time)
375 long t = daemon_get_uptime(current_time);
376 return make_message("%li:%02li:%02li", t / 86400,
377 (t / 3600) % 24, (t / 60) % 60);
381 * The log function for para_server and para_audiod.
383 * \param ll The log level.
384 * \param fmt The format string describing the log message.
386 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
392 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
393 daemon_test_flag(DF_LOG_TIMING);
395 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
396 ll = PARA_MAX(ll, LL_DEBUG);
397 if (ll < me->loglevel)
400 fp = me->logfile? me->logfile : stderr;
401 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
403 fprintf(fp, "%s", color);
404 if (log_time || log_timing) {
406 clock_get_realtime(&tv);
407 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
408 time_t t1 = tv.tv_sec;
411 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
412 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
414 if (log_timing) /* print milliseconds */
415 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
417 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
419 me->hostname = para_hostname();
420 fprintf(fp, "%s ", me->hostname);
422 if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
423 fprintf(fp, "(%d) ", ll);
424 if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
425 pid_t mypid = getpid();
426 fprintf(fp, "(%d) ", (int)mypid);
429 vfprintf(fp, fmt, argp);
432 fprintf(fp, "%s", COLOR_RESET);