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