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() */
20 /** The internal state of the daemon. */
22 /** See \ref daemon_flags. */
24 /** Set by \ref daemon_set_logfile(). */
26 /** Current loglevel, see \ref daemon_set_loglevel(). */
28 /** Used by \ref server_uptime() and \ref uptime_str(). */
30 /** The file pointer if the logfile is open. */
32 /** Used by para_log() if \p DF_LOG_HOSTNAME is set. */
34 /** Used for colored log messages. */
35 char log_colors[NUM_LOGLEVELS][COLOR_MAXLEN];
38 static struct daemon the_daemon, *me = &the_daemon;
41 * Activate default log colors.
43 * This should be called early if color support is wanted.
45 void daemon_set_default_log_colors(void)
48 static const char *default_log_colors[NUM_LOGLEVELS] = {
49 [LL_DEBUG] = "normal",
51 [LL_NOTICE] = "normal",
52 [LL_WARNING] = "yellow",
54 [LL_CRIT] = "magenta bold",
55 [LL_EMERG] = "red bold",
57 for (i = 0; i < NUM_LOGLEVELS; i++)
58 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
62 * Set the color for one loglevel.
64 * \param arg The loglevel/color specifier.
66 * \a arg must be of the form "ll:[fg [bg]] [attr]".
68 void daemon_set_log_color_or_die(char const *arg)
70 char *p = strchr(arg, ':');
75 ret = get_loglevel_by_name(arg);
80 color_parse_or_die(p, me->log_colors[ll]);
83 PARA_EMERG_LOG("%s: color syntax error\n", arg);
88 * Init or change the name of the log file.
90 * \param logfile_name The full path of the logfile.
92 void daemon_set_logfile(char *logfile_name)
94 free(me->logfile_name);
95 me->logfile_name = NULL;
97 me->logfile_name = para_strdup(logfile_name);
101 * Suppress log messages with severity lower than the given loglevel.
103 * \param loglevel The smallest level that should be logged.
105 void daemon_set_loglevel(char *loglevel)
107 int ret = get_loglevel_by_name(loglevel);
114 * Set one of the daemon config flags.
116 * \param flag The flag to set.
118 * \sa \ref daemon_flags.
120 void daemon_set_flag(unsigned flag)
125 static bool daemon_test_flag(unsigned flag)
127 return me->flags & flag;
130 static void dummy_sighandler(__a_unused int s)
135 * Do the usual stuff to become a daemon.
137 * \param parent_waits Whether the parent process should pause before exit.
139 * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
140 * parent_waits is false, the parent process terminates immediately.
141 * Otherwise, it calls pause() to sleep until it receives \p SIGTERM or \p
142 * SIGCHLD and exits successfully thereafter. This behaviour is useful if the
143 * daemon process should not detach from the console until the child process
144 * has completed its setup.
146 * \sa fork(2), setsid(2), dup(2), pause(2).
148 void daemonize(bool parent_waits)
153 PARA_INFO_LOG("daemonizing\n");
159 signal(SIGTERM, dummy_sighandler);
160 signal(SIGCHLD, dummy_sighandler);
163 exit(EXIT_SUCCESS); /* parent exits */
165 /* become session leader */
170 null = open("/dev/null", O_RDONLY);
173 if (dup2(null, STDIN_FILENO) < 0)
175 if (dup2(null, STDOUT_FILENO) < 0)
177 if (dup2(null, STDERR_FILENO) < 0)
182 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
187 * Close the log file of the daemon.
189 void daemon_close_log(void)
193 PARA_INFO_LOG("closing logfile\n");
199 * fopen() the logfile in append mode.
201 * \return Either succeeds or exits.
203 void daemon_open_log_or_die(void)
206 if (!me->logfile_name)
208 me->logfile = fopen(me->logfile_name, "a");
210 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
214 /* equivalent to setlinebuf(), but portable */
215 setvbuf(me->logfile, NULL, _IOLBF, 0);
219 * Log the startup message containing the paraslash version.
221 void daemon_log_welcome(const char *whoami)
223 PARA_INFO_LOG("welcome to %s " PACKAGE_VERSION " ("BUILD_DATE")\n",
228 * Give up superuser privileges.
230 * \param username The user to switch to.
231 * \param groupname The group to switch to.
233 * This function returns immediately if not invoked with EUID zero. Otherwise,
234 * it tries to obtain the GID of \a groupname and the UID of \a username. On
235 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
236 * are all set accordingly. On errors, an appropriate message is logged and
237 * exit() is called to terminate the process.
239 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
241 void daemon_drop_privileges_or_die(const char *username, const char *groupname)
249 struct group *g = getgrnam(groupname);
251 PARA_EMERG_LOG("failed to get group %s: %s\n",
252 groupname, strerror(errno));
255 if (setgid(g->gr_gid) < 0) {
256 PARA_EMERG_LOG("failed to set group id %d: %s\n",
257 (int)g->gr_gid, strerror(errno));
262 PARA_EMERG_LOG("root privileges, but no user option given\n");
265 tmp = para_strdup(username);
269 PARA_EMERG_LOG("%s: no such user\n", username);
272 PARA_INFO_LOG("dropping root privileges\n");
273 if (setuid(p->pw_uid) < 0) {
274 PARA_EMERG_LOG("failed to set effective user ID (%s)",
278 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
282 * Set the startup time.
284 * This should be called once on startup. It sets the start time to the
285 * current time. The stored time is used for retrieving the server uptime.
287 * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
289 void daemon_set_start_time(void)
291 time(&me->startuptime);
297 * \param current_time The current time.
299 * The \a current_time pointer may be \p NULL. In this case the function
300 * obtains the current time from the system.
302 * \return This returns the server uptime in seconds, i.e. the difference
303 * between the current time and the value stored previously via \ref
304 * daemon_set_start_time().
306 time_t daemon_get_uptime(const struct timeval *current_time)
311 return current_time->tv_sec - me->startuptime;
313 return difftime(t, me->startuptime);
317 * Construct a string containing the current uptime.
319 * \param current_time See a \ref daemon_get_uptime().
321 * \return A dynamically allocated string of the form "days:hours:minutes".
325 __malloc char *daemon_get_uptime_str(const struct timeval *current_time)
327 long t = daemon_get_uptime(current_time);
328 return make_message("%li:%02li:%02li", t / 86400,
329 (t / 3600) % 24, (t / 60) % 60);
333 * The log function for para_server and para_audiod.
335 * \param ll The log level.
336 * \param fmt The format string describing the log message.
338 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
344 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
345 daemon_test_flag(DF_LOG_TIMING);
347 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
348 ll = PARA_MAX(ll, LL_DEBUG);
349 if (ll < me->loglevel)
352 fp = me->logfile? me->logfile : stderr;
353 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
355 fprintf(fp, "%s", color);
356 if (log_time || log_timing) {
358 clock_get_realtime(&tv);
359 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
360 time_t t1 = tv.tv_sec;
363 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
364 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
366 if (log_timing) /* print milliseconds */
367 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
369 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
371 me->hostname = para_hostname();
372 fprintf(fp, "%s ", me->hostname);
374 if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
375 fprintf(fp, "(%d) ", ll);
376 if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
377 pid_t mypid = getpid();
378 fprintf(fp, "(%d) ", (int)mypid);
381 vfprintf(fp, fmt, argp);
384 fprintf(fp, "%s", COLOR_RESET);