audiod: Increase default select timeout to 1s.
[paraslash.git] / daemon.c
1 /*
2  * Copyright (C) 1997-2009 Andre Noll <maan@systemlinux.org>
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
14 #include "para.h"
15 #include "daemon.h"
16 #include "string.h"
17 #include "color.h"
18
19 /** The internal state of the daemon. */
20 struct daemon {
21         /** See \ref daemon_flags. */
22         unsigned flags;
23         /** Set by \ref daemon_set_logfile(). */
24         char *logfile_name;
25         /** Current loglevel, see \ref daemon_set_loglevel(). */
26         int loglevel;
27
28         /** Used by \ref server_uptime() and \ref uptime_str(). */
29         time_t startuptime;
30         /** The file pointer if the logfile is open. */
31         FILE *logfile;
32         /** Used by para_log() if \p DF_LOG_HOSTNAME is set. */
33         char *hostname;
34         /** Used for colored log messages. */
35         char log_colors[NUM_LOGLEVELS][COLOR_MAXLEN];
36 };
37
38 static struct daemon the_daemon, *me = &the_daemon;
39
40 /**
41  * Activate default log colors.
42  *
43  * This should be called early if color support is wanted.
44  */
45 void daemon_set_default_log_colors(void)
46 {
47         int i;
48         static const char *default_log_colors[NUM_LOGLEVELS] = {
49                 [LL_DEBUG] = "normal",
50                 [LL_INFO] = "normal",
51                 [LL_NOTICE] = "normal",
52                 [LL_WARNING] = "yellow",
53                 [LL_ERROR] = "red",
54                 [LL_CRIT] = "magenta bold",
55                 [LL_EMERG] = "red bold",
56         };
57         for (i = 0; i < NUM_LOGLEVELS; i++) {
58                 int ret = color_parse(default_log_colors[i], me->log_colors[i]);
59                 assert(ret >= 0);
60         }
61 }
62
63 /**
64  * Set the color for one loglevel.
65  *
66  * \param arg The loglevel/color specifier.
67  *
68  * \a arg must be of the form "ll:[fg [bg]] [attr]".
69  *
70  * \return 1 On success, -1 on errors.
71  */
72 int daemon_set_log_color(char const *arg)
73 {
74         char *p = strchr(arg, ':');
75         int ret, ll;
76
77         if (!p)
78                 goto err;
79         ret = get_loglevel_by_name(arg);
80         if (ret < 0)
81                 goto err;
82         ll = ret;
83         p++;
84         ret = color_parse(p, me->log_colors[ll]);
85         if (ret < 0)
86                 goto err;
87         return 1;
88 err:
89         PARA_ERROR_LOG("%s: color syntax error\n", arg);
90         return -1;
91
92 }
93
94 /**
95  * Init or change the name of the log file.
96  *
97  * \param logfile_name The full path of the logfile.
98  */
99 void daemon_set_logfile(char *logfile_name)
100 {
101         free(me->logfile_name);
102         me->logfile_name = NULL;
103         if (logfile_name)
104                 me->logfile_name = para_strdup(logfile_name);
105 }
106
107 /**
108  * Supress log messages with severity lower than the given loglevel.
109  *
110  * \param loglevel The smallest level that should be logged.
111  */
112 void daemon_set_loglevel(char *loglevel)
113 {
114         int ret = get_loglevel_by_name(loglevel);
115
116         assert(ret >= 0);
117         me->loglevel = ret;
118 }
119
120 /**
121  * Set one of the daemon config flags.
122  *
123  * \param flag The flag to set.
124  *
125  * \sa \ref daemon_flags.
126  */
127 void daemon_set_flag(unsigned flag)
128 {
129         me->flags |= flag;
130 }
131
132 /**
133  * Clear one of the daemon config flags.
134  *
135  * \param flag The flag to clear.
136  *
137  * \sa \ref daemon_flags.
138  */
139 void daemon_clear_flag(unsigned flag)
140 {
141         me->flags &= ~flag;
142 }
143
144 static unsigned daemon_test_flag(unsigned flag)
145 {
146         return me->flags & flag;
147 }
148
149 /**
150  * Do the usual stuff to become a daemon.
151  *
152  * Fork, become session leader, dup fd 0, 1, 2 to /dev/null.
153  *
154  * \sa fork(2), setsid(2), dup(2).
155  */
156 void daemonize(void)
157 {
158         pid_t pid;
159         int null;
160
161         PARA_INFO_LOG("daemonizing\n");
162         pid = fork();
163         if (pid < 0)
164                 goto err;
165         if (pid)
166                 exit(EXIT_SUCCESS); /* parent exits */
167         /* become session leader */
168         if (setsid() < 0)
169                 goto err;
170         if (chdir("/") < 0)
171                 goto err;
172         umask(0);
173         null = open("/dev/null", O_RDONLY);
174         if (null < 0)
175                 goto err;
176         if (dup2(null, STDIN_FILENO) < 0)
177                 goto err;
178         if (dup2(null, STDOUT_FILENO) < 0)
179                 goto err;
180         if (dup2(null, STDERR_FILENO) < 0)
181                 goto err;
182         close(null);
183         return;
184 err:
185         PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
186         exit(EXIT_FAILURE);
187 }
188
189 /**
190  * Close the log file of the daemon.
191  */
192 void daemon_close_log(void)
193 {
194         if (!me->logfile)
195                 return;
196         PARA_INFO_LOG("closing logfile\n");
197         fclose(me->logfile);
198         me->logfile = NULL;
199 }
200
201 /**
202  * fopen() the logfile in append mode.
203  *
204  * \return Either succeeds or exits.
205  */
206 void daemon_open_log_or_die(void)
207 {
208         daemon_close_log();
209         if (!me->logfile_name)
210                 return;
211         me->logfile = fopen(me->logfile_name, "a");
212         if (!me->logfile) {
213                 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
214                         strerror(errno));
215                 exit(EXIT_FAILURE);
216         }
217         setlinebuf(me->logfile);
218 }
219
220 /**
221  * Log the startup message containing the paraslash version.
222  */
223 void log_welcome(const char *whoami)
224 {
225         PARA_INFO_LOG("welcome to %s " PACKAGE_VERSION " ("BUILD_DATE")\n",
226                 whoami);
227 }
228
229 /**
230  * Give up superuser privileges.
231  *
232  * \param username The user to switch to.
233  * \param groupname The group to switch to.
234  *
235  * This function returns immediately if not invoked with EUID zero. Otherwise,
236  * it tries to obtain the GID of \a groupname and the UID of \a username.  On
237  * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
238  * are all set accordingly. On errors, an appropriate message is logged and
239  * exit() is called to terminate the process.
240  *
241  * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
242  */
243 void drop_privileges_or_die(const char *username, const char *groupname)
244 {
245         struct passwd *p;
246         char *tmp;
247
248         if (geteuid())
249                 return;
250         if (groupname) {
251                 struct group *g = getgrnam(groupname);
252                 if (!g) {
253                         PARA_EMERG_LOG("failed to get group %s: %s\n",
254                                 groupname, strerror(errno));
255                         exit(EXIT_FAILURE);
256                 }
257                 if (setgid(g->gr_gid) < 0) {
258                         PARA_EMERG_LOG("failed to set group id %d: %s\n",
259                                 (int)g->gr_gid, strerror(errno));
260                         exit(EXIT_FAILURE);
261                 }
262         }
263         if (!username) {
264                 PARA_EMERG_LOG("root privileges, but no user option given\n");
265                 exit(EXIT_FAILURE);
266         }
267         tmp = para_strdup(username);
268         p = getpwnam(tmp);
269         free(tmp);
270         if (!p) {
271                 PARA_EMERG_LOG("%s: no such user\n", username);
272                 exit(EXIT_FAILURE);
273         }
274         PARA_INFO_LOG("dropping root privileges\n");
275         setuid(p->pw_uid);
276         PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
277 }
278
279 /**
280  * Set/get the server uptime.
281  *
282  * \param set_or_get Chose one of the two modes.
283  *
284  * This should be called at startup time with \a set_or_get equal to \p
285  * UPTIME_SET which sets the uptime to zero.  Subsequent calls with \a
286  * set_or_get equal to \p UPTIME_GET return the uptime.
287
288  * \return Zero if called with \a set_or_get equal to \p UPTIME_SET, the number
289  * of seconds ellapsed since the last reset otherwise.
290  *
291  * \sa time(2), difftime(3).
292  */
293 time_t server_uptime(enum uptime set_or_get)
294 {
295         time_t now;
296         double diff;
297
298         if (set_or_get == UPTIME_SET) {
299                 time(&me->startuptime);
300                 return 0;
301         }
302         time(&now);
303         diff = difftime(now, me->startuptime);
304         return (time_t) diff;
305 }
306
307 /**
308  * Construct string containing uptime.
309  *
310  * \return A dynamically allocated string of the form "days:hours:minutes".
311  *
312  * \sa server_uptime.
313  */
314 __malloc char *uptime_str(void)
315 {
316         long t = server_uptime(UPTIME_GET);
317         return make_message("%li:%02li:%02li", t / 86400,
318                 (t / 3600) % 24, (t / 60) % 60);
319 }
320
321 /**
322  * The log function for para_server and para_audiod.
323  *
324  * \param ll The log level.
325  * \param fmt The format string describing the log message.
326  */
327 __printf_2_3 void para_log(int ll, const char* fmt,...)
328 {
329         va_list argp;
330         FILE *fp;
331         struct tm *tm;
332         time_t t1;
333         char *color, str[MAXLINE] = "";
334
335         ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
336         ll = PARA_MAX(ll, LL_DEBUG);
337         if (ll < me->loglevel)
338                 return;
339
340         fp = me->logfile? me->logfile : stderr;
341         color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
342         if (color)
343                 fprintf(fp, "%s", color);
344         if (daemon_test_flag(DF_LOG_TIME)) {
345                 /* date and time */
346                 time(&t1);
347                 tm = localtime(&t1);
348                 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
349                 fprintf(fp, "%s ", str);
350         }
351         if (daemon_test_flag(DF_LOG_HOSTNAME)) {
352                 if (!me->hostname)
353                         me->hostname = para_hostname();
354                 fprintf(fp, "%s ", me->hostname);
355         }
356         if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
357                 fprintf(fp, "(%d) ", ll);
358         if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
359                 pid_t mypid = getpid();
360                 fprintf(fp, "(%d) ", (int)mypid);
361         }
362         va_start(argp, fmt);
363         vfprintf(fp, fmt, argp);
364         va_end(argp);
365         if (color)
366                 fprintf(fp, "%s", COLOR_RESET);
367 }