2 * Copyright (C) 1997-2011 Andre Noll <maan@systemlinux.org>
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() */
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;
42 * Activate default log colors.
44 * This should be called early if color support is wanted.
46 void daemon_set_default_log_colors(void)
49 static const char *default_log_colors[NUM_LOGLEVELS] = {
50 [LL_DEBUG] = "normal",
52 [LL_NOTICE] = "normal",
53 [LL_WARNING] = "yellow",
55 [LL_CRIT] = "magenta bold",
56 [LL_EMERG] = "red bold",
58 for (i = 0; i < NUM_LOGLEVELS; i++)
59 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
63 * Set the color for one loglevel.
65 * \param arg The loglevel/color specifier.
67 * \a arg must be of the form "ll:[fg [bg]] [attr]".
69 * \return 1 On success, -1 on errors.
71 void daemon_set_log_color_or_die(char const *arg)
73 char *p = strchr(arg, ':');
78 ret = get_loglevel_by_name(arg);
83 color_parse_or_die(p, me->log_colors[ll]);
86 PARA_EMERG_LOG("%s: color syntax error\n", arg);
91 * Init or change the name of the log file.
93 * \param logfile_name The full path of the logfile.
95 void daemon_set_logfile(char *logfile_name)
97 free(me->logfile_name);
98 me->logfile_name = NULL;
100 me->logfile_name = para_strdup(logfile_name);
104 * Suppress log messages with severity lower than the given loglevel.
106 * \param loglevel The smallest level that should be logged.
108 void daemon_set_loglevel(char *loglevel)
110 int ret = get_loglevel_by_name(loglevel);
117 * Set one of the daemon config flags.
119 * \param flag The flag to set.
121 * \sa \ref daemon_flags.
123 void daemon_set_flag(unsigned flag)
129 * Clear one of the daemon config flags.
131 * \param flag The flag to clear.
133 * \sa \ref daemon_flags.
135 void daemon_clear_flag(unsigned flag)
140 static bool daemon_test_flag(unsigned flag)
142 return me->flags & flag;
146 * Do the usual stuff to become a daemon.
148 * Fork, become session leader, dup fd 0, 1, 2 to /dev/null.
150 * \sa fork(2), setsid(2), dup(2).
157 PARA_INFO_LOG("daemonizing\n");
162 exit(EXIT_SUCCESS); /* parent exits */
163 /* become session leader */
168 null = open("/dev/null", O_RDONLY);
171 if (dup2(null, STDIN_FILENO) < 0)
173 if (dup2(null, STDOUT_FILENO) < 0)
175 if (dup2(null, STDERR_FILENO) < 0)
180 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
185 * Close the log file of the daemon.
187 void daemon_close_log(void)
191 PARA_INFO_LOG("closing logfile\n");
197 * fopen() the logfile in append mode.
199 * \return Either succeeds or exits.
201 void daemon_open_log_or_die(void)
204 if (!me->logfile_name)
206 me->logfile = fopen(me->logfile_name, "a");
208 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
212 setlinebuf(me->logfile);
216 * Log the startup message containing the paraslash version.
218 void log_welcome(const char *whoami)
220 PARA_INFO_LOG("welcome to %s " PACKAGE_VERSION " ("BUILD_DATE")\n",
225 * Give up superuser privileges.
227 * \param username The user to switch to.
228 * \param groupname The group to switch to.
230 * This function returns immediately if not invoked with EUID zero. Otherwise,
231 * it tries to obtain the GID of \a groupname and the UID of \a username. On
232 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
233 * are all set accordingly. On errors, an appropriate message is logged and
234 * exit() is called to terminate the process.
236 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
238 void drop_privileges_or_die(const char *username, const char *groupname)
246 struct group *g = getgrnam(groupname);
248 PARA_EMERG_LOG("failed to get group %s: %s\n",
249 groupname, strerror(errno));
252 if (setgid(g->gr_gid) < 0) {
253 PARA_EMERG_LOG("failed to set group id %d: %s\n",
254 (int)g->gr_gid, strerror(errno));
259 PARA_EMERG_LOG("root privileges, but no user option given\n");
262 tmp = para_strdup(username);
266 PARA_EMERG_LOG("%s: no such user\n", username);
269 PARA_INFO_LOG("dropping root privileges\n");
270 if (setuid(p->pw_uid) < 0) {
271 PARA_EMERG_LOG("failed to set effective user ID (%s)",
275 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
279 * Set the server startup time.
281 * \param startuptime The value to store as the server start time.
283 * This should be called once on startup with \a startuptime either NULL or a
284 * pointer to a struct timeval which contains the current time. If \a
285 * startuptime is NULL, the server start time is set to the current time.
287 * \sa time(2), difftime(3) \ref get_server_uptime(), \ref
288 * get_server_uptime_str().
290 void set_server_start_time(const struct timeval *startuptime)
293 me->startuptime = startuptime->tv_sec;
295 time(&me->startuptime);
299 * Get the server uptime.
301 * \param current_time The current time.
303 * The \a current_time pointer may be \p NULL. In this case the function
304 * obtains the current time from the system.
306 * \return This returns the server uptime in seconds, i.e. the difference
307 * between the current time and the value stored previously via \ref
308 * set_server_start_time().
310 time_t get_server_uptime(const struct timeval *current_time)
315 return current_time->tv_sec - me->startuptime;
317 return difftime(t, me->startuptime);
321 * Construct a string containing the current uptime.
323 * \param current_time See a \ref get_server_uptime().
325 * \return A dynamically allocated string of the form "days:hours:minutes".
329 __malloc char *get_server_uptime_str(const struct timeval *current_time)
331 long t = get_server_uptime(current_time);
332 return make_message("%li:%02li:%02li", t / 86400,
333 (t / 3600) % 24, (t / 60) % 60);
337 * The log function for para_server and para_audiod.
339 * \param ll The log level.
340 * \param fmt The format string describing the log message.
342 __printf_2_3 void para_log(int ll, const char* fmt,...)
348 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
349 daemon_test_flag(DF_LOG_TIMING);
351 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
352 ll = PARA_MAX(ll, LL_DEBUG);
353 if (ll < me->loglevel)
356 fp = me->logfile? me->logfile : stderr;
357 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
359 fprintf(fp, "%s", color);
360 if (log_time || log_timing) {
362 gettimeofday(&tv, NULL);
363 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
364 time_t t1 = tv.tv_sec;
367 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
368 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
370 if (log_timing) /* print milliseconds */
371 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
373 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
375 me->hostname = para_hostname();
376 fprintf(fp, "%s ", me->hostname);
378 if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
379 fprintf(fp, "(%d) ", ll);
380 if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
381 pid_t mypid = getpid();
382 fprintf(fp, "(%d) ", (int)mypid);
385 vfprintf(fp, fmt, argp);
388 fprintf(fp, "%s", COLOR_RESET);