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