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 one loglevel.
63 * \param arg Must be of the form "ll:[fg [bg]] [attr]".
65 void daemon_set_log_color_or_die(const char *arg
)
67 char *p
= strchr(arg
, ':');
72 ret
= get_loglevel_by_name(arg
);
77 color_parse_or_die(p
, me
->log_colors
[ll
]);
80 PARA_EMERG_LOG("%s: invalid color argument\n", arg
);
85 * Initialize color mode if necessary.
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.
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.
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().
100 * \return Whether colors have been enabled by the function.
102 bool daemon_init_colors_or_die(int color_arg
, int color_arg_auto
,
103 int color_arg_no
, bool logfile_given
)
105 if (color_arg
== color_arg_no
)
107 if (color_arg
== color_arg_auto
) {
110 if (!isatty(STDERR_FILENO
))
113 daemon_set_flag(DF_COLOR_LOG
);
114 daemon_set_default_log_colors();
119 * Init or change the name of the log file.
121 * \param logfile_name The full path of the logfile.
123 void daemon_set_logfile(const char *logfile_name
)
125 free(me
->logfile_name
);
126 me
->logfile_name
= NULL
;
129 if (me
->old_cwd
&& logfile_name
[0] != '/')
130 me
->logfile_name
= make_message("%s/%s", me
->old_cwd
,
133 me
->logfile_name
= para_strdup(logfile_name
);
137 * Suppress log messages with severity lower than the given loglevel.
139 * \param loglevel The smallest level that should be logged.
141 void daemon_set_loglevel(const char *loglevel
)
143 int ret
= get_loglevel_by_name(loglevel
);
149 void daemon_set_hooks(void (*pre_log_hook
)(void), void (*post_log_hook
)(void))
151 me
->pre_log_hook
= pre_log_hook
;
152 me
->post_log_hook
= post_log_hook
;
156 * Set one of the daemon config flags.
158 * \param flag The flag to set.
160 * \sa \ref daemon_flags.
162 void daemon_set_flag(unsigned flag
)
167 static bool daemon_test_flag(unsigned flag
)
169 return me
->flags
& flag
;
173 * Do the usual stuff to become a daemon.
175 * \param parent_waits Whether the parent process should pause before exit.
177 * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
178 * parent_waits is false, the parent process terminates immediately.
179 * Otherwise, a pipe is created prior to the fork() and the parent tries to
180 * read a single byte from the reading end of the pipe. The child is supposed
181 * to write to the writing end of the pipe after it completed its setup
182 * procedure successfully. This behaviour is useful to let the parent process
183 * die with an error if the child process aborts early, since in this case the
184 * read() will return non-positive.
186 * \return This function either succeeds or calls exit(3). If parent_waits is
187 * true, the return value is the file descriptor of the writing end of the
188 * pipe. Otherwise the function returns zero.
190 * \sa fork(2), setsid(2), dup(2), pause(2).
192 int daemonize(bool parent_waits
)
195 int null
, pipe_fd
[2];
197 if (parent_waits
&& pipe(pipe_fd
) < 0)
199 PARA_INFO_LOG("subsequent log messages go to %s\n", me
->logfile_name
?
200 me
->logfile_name
: "/dev/null");
204 if (pid
) { /* parent exits */
208 exit(read(pipe_fd
[0], &c
, 1) <= 0?
209 EXIT_FAILURE
: EXIT_SUCCESS
);
215 /* become session leader */
218 me
->old_cwd
= getcwd(NULL
, 0);
221 null
= open("/dev/null", O_RDWR
);
224 if (dup2(null
, STDIN_FILENO
) < 0)
226 if (dup2(null
, STDOUT_FILENO
) < 0)
228 if (dup2(null
, STDERR_FILENO
) < 0)
231 return parent_waits
? pipe_fd
[1] : 0;
233 PARA_EMERG_LOG("fatal: %s\n", strerror(errno
));
238 * Close the log file of the daemon.
240 void daemon_close_log(void)
244 PARA_INFO_LOG("closing logfile\n");
250 * fopen() the logfile in append mode.
252 * \return Either succeeds or exits.
254 void daemon_open_log_or_die(void)
258 if (!me
->logfile_name
)
260 new_log
= fopen(me
->logfile_name
, "a");
262 PARA_EMERG_LOG("can not open %s: %s\n", me
->logfile_name
,
267 me
->logfile
= new_log
;
268 /* equivalent to setlinebuf(), but portable */
269 setvbuf(me
->logfile
, NULL
, _IOLBF
, 0);
273 * Log the startup message containing the paraslash version.
275 * \param name The name of the executable.
277 * First the given \a name is prefixed with the string "para_". Next the git
278 * version is appended. The resulting string is logged with priority "INFO".
280 void daemon_log_welcome(const char *name
)
282 PARA_INFO_LOG("welcome to para_%s-" PACKAGE_VERSION
" \n", name
);
286 * Renice the calling process.
288 * \param prio The priority value to set.
290 * Errors are not considered fatal, but a warning message is logged if the
291 * underlying call to setpriority(2) fails.
293 void daemon_set_priority(int prio
)
295 if (setpriority(PRIO_PROCESS
, 0, prio
) < 0)
296 PARA_WARNING_LOG("could not set priority to %d: %s\n", prio
,
301 * Give up superuser privileges.
303 * \param username The user to switch to.
304 * \param groupname The group to switch to.
306 * This function returns immediately if not invoked with EUID zero. Otherwise,
307 * it tries to obtain the GID of \a groupname and the UID of \a username. On
308 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
309 * are all set accordingly. On errors, an appropriate message is logged and
310 * exit() is called to terminate the process.
312 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
314 void daemon_drop_privileges_or_die(const char *username
, const char *groupname
)
322 struct group
*g
= getgrnam(groupname
);
324 PARA_EMERG_LOG("failed to get group %s: %s\n",
325 groupname
, strerror(errno
));
328 if (setgid(g
->gr_gid
) < 0) {
329 PARA_EMERG_LOG("failed to set group id %d: %s\n",
330 (int)g
->gr_gid
, strerror(errno
));
335 PARA_EMERG_LOG("root privileges, but no user option given\n");
338 tmp
= para_strdup(username
);
342 PARA_EMERG_LOG("%s: no such user\n", username
);
345 PARA_INFO_LOG("dropping root privileges\n");
346 if (setuid(p
->pw_uid
) < 0) {
347 PARA_EMERG_LOG("failed to set effective user ID (%s)",
351 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
355 * Set the startup time.
357 * This should be called once on startup. It sets the start time to the
358 * current time. The stored time is used for retrieving the server uptime.
360 * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
362 void daemon_set_start_time(void)
364 time(&me
->startuptime
);
370 * \param current_time The current time.
372 * The \a current_time pointer may be \p NULL. In this case the function
373 * obtains the current time from the system.
375 * \return This returns the server uptime in seconds, i.e. the difference
376 * between the current time and the value stored previously via \ref
377 * daemon_set_start_time().
379 time_t daemon_get_uptime(const struct timeval
*current_time
)
384 return current_time
->tv_sec
- me
->startuptime
;
386 return difftime(t
, me
->startuptime
);
390 * Construct a string containing the current uptime.
392 * \param current_time See a \ref daemon_get_uptime().
394 * \return A dynamically allocated string of the form "days:hours:minutes".
396 __malloc
char *daemon_get_uptime_str(const struct timeval
*current_time
)
398 long t
= daemon_get_uptime(current_time
);
399 return make_message("%li:%02li:%02li", t
/ 86400,
400 (t
/ 3600) % 24, (t
/ 60) % 60);
404 * The log function for para_server and para_audiod.
406 * \param ll The log level.
407 * \param fmt The format string describing the log message.
409 __printf_2_3
void daemon_log(int ll
, const char* fmt
,...)
415 bool log_time
= daemon_test_flag(DF_LOG_TIME
), log_timing
=
416 daemon_test_flag(DF_LOG_TIMING
);
418 ll
= PARA_MIN(ll
, NUM_LOGLEVELS
- 1);
419 ll
= PARA_MAX(ll
, LL_DEBUG
);
420 if (ll
< me
->loglevel
)
423 fp
= me
->logfile
? me
->logfile
: stderr
;
424 if (me
->pre_log_hook
)
426 color
= daemon_test_flag(DF_COLOR_LOG
)? me
->log_colors
[ll
] : NULL
;
428 fprintf(fp
, "%s", color
);
429 if (log_time
|| log_timing
) {
431 clock_get_realtime(&tv
);
432 if (daemon_test_flag(DF_LOG_TIME
)) { /* print date and time */
433 time_t t1
= tv
.tv_sec
;
436 strftime(str
, sizeof(str
), "%b %d %H:%M:%S", tm
);
437 fprintf(fp
, "%s%s", str
, log_timing
? ":" : " ");
439 if (log_timing
) /* print milliseconds */
440 fprintf(fp
, "%04lu ", (long unsigned)tv
.tv_usec
/ 1000);
442 if (daemon_test_flag(DF_LOG_HOSTNAME
)) {
444 me
->hostname
= para_hostname();
445 fprintf(fp
, "%s ", me
->hostname
);
447 if (daemon_test_flag(DF_LOG_LL
)) /* log loglevel */
448 fprintf(fp
, "(%d) ", ll
);
449 if (daemon_test_flag(DF_LOG_PID
)) { /* log pid */
450 pid_t mypid
= getpid();
451 fprintf(fp
, "(%d) ", (int)mypid
);
454 vfprintf(fp
, fmt
, argp
);
457 fprintf(fp
, "%s", COLOR_RESET
);
458 if (me
->post_log_hook
)