Merge branch 'refs/heads/t/para_play_fixes'
[paraslash.git] / daemon.c
1 /*
2 * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file daemon.c Some helpers for programs that detach from the console. */
8
9 #include <regex.h>
10 #include <pwd.h>
11 #include <sys/types.h> /* getgrnam() */
12 #include <grp.h>
13 #include <signal.h>
14 #include <sys/resource.h>
15
16 #include "para.h"
17 #include "daemon.h"
18 #include "string.h"
19 #include "color.h"
20
21 /** The internal state of the daemon. */
22 struct daemon {
23 /** See \ref daemon_flags. */
24 unsigned flags;
25 /** Set by \ref daemon_set_logfile(). */
26 char *logfile_name;
27 /** Current loglevel, see \ref daemon_set_loglevel(). */
28 int loglevel;
29 /** Used by \ref server_uptime() and \ref uptime_str(). */
30 time_t startuptime;
31 /** The file pointer if the logfile is open. */
32 FILE *logfile;
33 /** Used by para_log() if \p DF_LOG_HOSTNAME is set. */
34 char *hostname;
35 /** Used for colored log messages. */
36 char log_colors[NUM_LOGLEVELS][COLOR_MAXLEN];
37 };
38
39 static struct daemon the_daemon, *me = &the_daemon;
40
41 static void daemon_set_default_log_colors(void)
42 {
43 int i;
44 static const char *default_log_colors[NUM_LOGLEVELS] = {
45 [LL_DEBUG] = "normal",
46 [LL_INFO] = "normal",
47 [LL_NOTICE] = "normal",
48 [LL_WARNING] = "yellow",
49 [LL_ERROR] = "red",
50 [LL_CRIT] = "magenta bold",
51 [LL_EMERG] = "red bold",
52 };
53 for (i = 0; i < NUM_LOGLEVELS; i++)
54 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
55 }
56
57 /*
58 * Set the color for one loglevel.
59 *
60 * arg must be of the form "ll:[fg [bg]] [attr]".
61 */
62 static void daemon_set_log_color_or_die(char const *arg)
63 {
64 char *p = strchr(arg, ':');
65 int ret, ll;
66
67 if (!p)
68 goto err;
69 ret = get_loglevel_by_name(arg);
70 if (ret < 0)
71 goto err;
72 ll = ret;
73 p++;
74 color_parse_or_die(p, me->log_colors[ll]);
75 return;
76 err:
77 PARA_EMERG_LOG("%s: color syntax error\n", arg);
78 exit(EXIT_FAILURE);
79 }
80
81 /**
82 * Initialize color mode if necessary.
83 *
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.
88 * \param log_color_argv Color specifiers given to --log-color.
89 * \param argc Number of color specifiers in \a log_color_argv.
90 *
91 * If \a color_arg equals \a color_arg_no, color mode is disabled, i.e., calls
92 * to \a para_log() will not produce colored output. If \a color_arg == \a
93 * color_arg_auto, the function autodetects whether to activate colors.
94 * Otherwise color mode is enabled.
95 *
96 * If color mode is to be enabled, the strings in \a log_color_argv are parsed
97 * and the color scheme is updated accordingly. For each loglevel, the default
98 * colors apply if there is no log_color_argv for this loglevel.
99 */
100 void daemon_init_colors_or_die(int color_arg, int color_arg_auto,
101 int color_arg_no, bool logfile_given, char **log_color_argv,
102 int argc)
103 {
104 int i;
105
106 if (color_arg == color_arg_no)
107 return;
108 if (color_arg == color_arg_auto) {
109 if (logfile_given)
110 return;
111 if (!isatty(STDERR_FILENO))
112 return;
113 }
114 daemon_set_flag(DF_COLOR_LOG);
115 daemon_set_default_log_colors();
116 for (i = 0; i < argc; i++)
117 daemon_set_log_color_or_die(log_color_argv[i]);
118 }
119
120 /**
121 * Init or change the name of the log file.
122 *
123 * \param logfile_name The full path of the logfile.
124 */
125 void daemon_set_logfile(char *logfile_name)
126 {
127 free(me->logfile_name);
128 me->logfile_name = NULL;
129 if (logfile_name)
130 me->logfile_name = para_strdup(logfile_name);
131 }
132
133 /**
134 * Suppress log messages with severity lower than the given loglevel.
135 *
136 * \param loglevel The smallest level that should be logged.
137 */
138 void daemon_set_loglevel(char *loglevel)
139 {
140 int ret = get_loglevel_by_name(loglevel);
141
142 assert(ret >= 0);
143 me->loglevel = ret;
144 }
145
146 /**
147 * Set one of the daemon config flags.
148 *
149 * \param flag The flag to set.
150 *
151 * \sa \ref daemon_flags.
152 */
153 void daemon_set_flag(unsigned flag)
154 {
155 me->flags |= flag;
156 }
157
158 static bool daemon_test_flag(unsigned flag)
159 {
160 return me->flags & flag;
161 }
162
163 static void dummy_sighandler(__a_unused int s)
164 {
165 }
166
167 /**
168 * Do the usual stuff to become a daemon.
169 *
170 * \param parent_waits Whether the parent process should pause before exit.
171 *
172 * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
173 * parent_waits is false, the parent process terminates immediately.
174 * Otherwise, it calls pause() to sleep until it receives \p SIGTERM or \p
175 * SIGCHLD and exits successfully thereafter. This behaviour is useful if the
176 * daemon process should not detach from the console until the child process
177 * has completed its setup.
178 *
179 * \sa fork(2), setsid(2), dup(2), pause(2).
180 */
181 void daemonize(bool parent_waits)
182 {
183 pid_t pid;
184 int null;
185
186 PARA_INFO_LOG("daemonizing\n");
187 pid = fork();
188 if (pid < 0)
189 goto err;
190 if (pid) {
191 if (parent_waits) {
192 signal(SIGTERM, dummy_sighandler);
193 signal(SIGCHLD, dummy_sighandler);
194 pause();
195 }
196 exit(EXIT_SUCCESS); /* parent exits */
197 }
198 /* become session leader */
199 if (setsid() < 0)
200 goto err;
201 if (chdir("/") < 0)
202 goto err;
203 null = open("/dev/null", O_RDWR);
204 if (null < 0)
205 goto err;
206 if (dup2(null, STDIN_FILENO) < 0)
207 goto err;
208 if (dup2(null, STDOUT_FILENO) < 0)
209 goto err;
210 if (dup2(null, STDERR_FILENO) < 0)
211 goto err;
212 close(null);
213 return;
214 err:
215 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
216 exit(EXIT_FAILURE);
217 }
218
219 /**
220 * Close the log file of the daemon.
221 */
222 void daemon_close_log(void)
223 {
224 if (!me->logfile)
225 return;
226 PARA_INFO_LOG("closing logfile\n");
227 fclose(me->logfile);
228 me->logfile = NULL;
229 }
230
231 /**
232 * fopen() the logfile in append mode.
233 *
234 * \return Either succeeds or exits.
235 */
236 void daemon_open_log_or_die(void)
237 {
238 daemon_close_log();
239 if (!me->logfile_name)
240 return;
241 me->logfile = fopen(me->logfile_name, "a");
242 if (!me->logfile) {
243 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
244 strerror(errno));
245 exit(EXIT_FAILURE);
246 }
247 /* equivalent to setlinebuf(), but portable */
248 setvbuf(me->logfile, NULL, _IOLBF, 0);
249 }
250
251 /**
252 * Log the startup message containing the paraslash version.
253 *
254 * \param name The name of the executable.
255 *
256 * First the given \a name is prefixed with the string "para_". Next the git
257 * version is appended. The resulting string is logged with priority "INFO".
258 */
259 void daemon_log_welcome(const char *name)
260 {
261 PARA_INFO_LOG("welcome to para_%s-" PACKAGE_VERSION " \n", name);
262 }
263
264 /**
265 * Renice the calling process.
266 *
267 * \param prio The priority value to set.
268 *
269 * Errors are not considered fatal, but a warning message is logged if the
270 * underlying call to setpriority(2) fails.
271 */
272 void daemon_set_priority(int prio)
273 {
274 if (setpriority(PRIO_PROCESS, 0, prio) < 0)
275 PARA_WARNING_LOG("could not set priority to %d: %s\n", prio,
276 strerror(errno));
277 }
278
279 /**
280 * Give up superuser privileges.
281 *
282 * \param username The user to switch to.
283 * \param groupname The group to switch to.
284 *
285 * This function returns immediately if not invoked with EUID zero. Otherwise,
286 * it tries to obtain the GID of \a groupname and the UID of \a username. On
287 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
288 * are all set accordingly. On errors, an appropriate message is logged and
289 * exit() is called to terminate the process.
290 *
291 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
292 */
293 void daemon_drop_privileges_or_die(const char *username, const char *groupname)
294 {
295 struct passwd *p;
296 char *tmp;
297
298 if (geteuid())
299 return;
300 if (groupname) {
301 struct group *g = getgrnam(groupname);
302 if (!g) {
303 PARA_EMERG_LOG("failed to get group %s: %s\n",
304 groupname, strerror(errno));
305 exit(EXIT_FAILURE);
306 }
307 if (setgid(g->gr_gid) < 0) {
308 PARA_EMERG_LOG("failed to set group id %d: %s\n",
309 (int)g->gr_gid, strerror(errno));
310 exit(EXIT_FAILURE);
311 }
312 }
313 if (!username) {
314 PARA_EMERG_LOG("root privileges, but no user option given\n");
315 exit(EXIT_FAILURE);
316 }
317 tmp = para_strdup(username);
318 p = getpwnam(tmp);
319 free(tmp);
320 if (!p) {
321 PARA_EMERG_LOG("%s: no such user\n", username);
322 exit(EXIT_FAILURE);
323 }
324 PARA_INFO_LOG("dropping root privileges\n");
325 if (setuid(p->pw_uid) < 0) {
326 PARA_EMERG_LOG("failed to set effective user ID (%s)",
327 strerror(errno));
328 exit(EXIT_FAILURE);
329 }
330 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
331 }
332
333 /**
334 * Set the startup time.
335 *
336 * This should be called once on startup. It sets the start time to the
337 * current time. The stored time is used for retrieving the server uptime.
338 *
339 * \sa time(2), \ref daemon_get_uptime(), \ref daemon_get_uptime_str().
340 */
341 void daemon_set_start_time(void)
342 {
343 time(&me->startuptime);
344 }
345
346 /**
347 * Get the uptime.
348 *
349 * \param current_time The current time.
350 *
351 * The \a current_time pointer may be \p NULL. In this case the function
352 * obtains the current time from the system.
353 *
354 * \return This returns the server uptime in seconds, i.e. the difference
355 * between the current time and the value stored previously via \ref
356 * daemon_set_start_time().
357 */
358 time_t daemon_get_uptime(const struct timeval *current_time)
359 {
360 time_t t;
361
362 if (current_time)
363 return current_time->tv_sec - me->startuptime;
364 time(&t);
365 return difftime(t, me->startuptime);
366 }
367
368 /**
369 * Construct a string containing the current uptime.
370 *
371 * \param current_time See a \ref daemon_get_uptime().
372 *
373 * \return A dynamically allocated string of the form "days:hours:minutes".
374 *
375 * \sa server_uptime.
376 */
377 __malloc char *daemon_get_uptime_str(const struct timeval *current_time)
378 {
379 long t = daemon_get_uptime(current_time);
380 return make_message("%li:%02li:%02li", t / 86400,
381 (t / 3600) % 24, (t / 60) % 60);
382 }
383
384 /**
385 * The log function for para_server and para_audiod.
386 *
387 * \param ll The log level.
388 * \param fmt The format string describing the log message.
389 */
390 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
391 {
392 va_list argp;
393 FILE *fp;
394 struct tm *tm;
395 char *color;
396 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
397 daemon_test_flag(DF_LOG_TIMING);
398
399 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
400 ll = PARA_MAX(ll, LL_DEBUG);
401 if (ll < me->loglevel)
402 return;
403
404 fp = me->logfile? me->logfile : stderr;
405 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
406 if (color)
407 fprintf(fp, "%s", color);
408 if (log_time || log_timing) {
409 struct timeval tv;
410 clock_get_realtime(&tv);
411 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
412 time_t t1 = tv.tv_sec;
413 char str[100];
414 tm = localtime(&t1);
415 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
416 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
417 }
418 if (log_timing) /* print milliseconds */
419 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
420 }
421 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
422 if (!me->hostname)
423 me->hostname = para_hostname();
424 fprintf(fp, "%s ", me->hostname);
425 }
426 if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
427 fprintf(fp, "(%d) ", ll);
428 if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
429 pid_t mypid = getpid();
430 fprintf(fp, "(%d) ", (int)mypid);
431 }
432 va_start(argp, fmt);
433 vfprintf(fp, fmt, argp);
434 va_end(argp);
435 if (color)
436 fprintf(fp, "%s", COLOR_RESET);
437 }