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