Allow switching between different log methods at runtime.
[paraslash.git] / daemon.c
1 /*
2 * Copyright (C) 1997-2011 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 #include <signal.h>
16
17 #include "para.h"
18 #include "daemon.h"
19 #include "string.h"
20 #include "color.h"
21
22 /** The internal state of the daemon. */
23 struct daemon {
24 /** See \ref daemon_flags. */
25 unsigned flags;
26 /** Set by \ref daemon_set_logfile(). */
27 char *logfile_name;
28 /** Current loglevel, see \ref daemon_set_loglevel(). */
29 int loglevel;
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 color_parse_or_die(default_log_colors[i], me->log_colors[i]);
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 void daemon_set_log_color_or_die(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 color_parse_or_die(p, me->log_colors[ll]);
85 return;
86 err:
87 PARA_EMERG_LOG("%s: color syntax error\n", arg);
88 exit(EXIT_FAILURE);
89 }
90
91 /**
92 * Init or change the name of the log file.
93 *
94 * \param logfile_name The full path of the logfile.
95 */
96 void daemon_set_logfile(char *logfile_name)
97 {
98 free(me->logfile_name);
99 me->logfile_name = NULL;
100 if (logfile_name)
101 me->logfile_name = para_strdup(logfile_name);
102 }
103
104 /**
105 * Suppress log messages with severity lower than the given loglevel.
106 *
107 * \param loglevel The smallest level that should be logged.
108 */
109 void daemon_set_loglevel(char *loglevel)
110 {
111 int ret = get_loglevel_by_name(loglevel);
112
113 assert(ret >= 0);
114 me->loglevel = ret;
115 }
116
117 /**
118 * Set one of the daemon config flags.
119 *
120 * \param flag The flag to set.
121 *
122 * \sa \ref daemon_flags.
123 */
124 void daemon_set_flag(unsigned flag)
125 {
126 me->flags |= flag;
127 }
128
129 /**
130 * Clear one of the daemon config flags.
131 *
132 * \param flag The flag to clear.
133 *
134 * \sa \ref daemon_flags.
135 */
136 void daemon_clear_flag(unsigned flag)
137 {
138 me->flags &= ~flag;
139 }
140
141 static bool daemon_test_flag(unsigned flag)
142 {
143 return me->flags & flag;
144 }
145
146 static void dummy_sighandler(__a_unused int s)
147 {
148 }
149
150 /**
151 * Do the usual stuff to become a daemon.
152 *
153 * \param parent_waits Whether the parent process should pause before exit.
154 *
155 * Fork, become session leader, cd to /, and dup fd 0, 1, 2 to /dev/null. If \a
156 * parent_waits is false, the parent process terminates immediately.
157 * Otherwise, it calls pause() to sleep until it receives \p SIGTERM or \p
158 * SIGCHLD and exits successfully thereafter. This behaviour is useful if the
159 * daemon process should not detach from the console until the child process
160 * has completed its setup.
161 *
162 * \sa fork(2), setsid(2), dup(2), pause(2).
163 */
164 void daemonize(bool parent_waits)
165 {
166 pid_t pid;
167 int null;
168
169 PARA_INFO_LOG("daemonizing\n");
170 pid = fork();
171 if (pid < 0)
172 goto err;
173 if (pid) {
174 if (parent_waits) {
175 signal(SIGTERM, dummy_sighandler);
176 signal(SIGCHLD, dummy_sighandler);
177 pause();
178 }
179 exit(EXIT_SUCCESS); /* parent exits */
180 }
181 /* become session leader */
182 if (setsid() < 0)
183 goto err;
184 if (chdir("/") < 0)
185 goto err;
186 null = open("/dev/null", O_RDONLY);
187 if (null < 0)
188 goto err;
189 if (dup2(null, STDIN_FILENO) < 0)
190 goto err;
191 if (dup2(null, STDOUT_FILENO) < 0)
192 goto err;
193 if (dup2(null, STDERR_FILENO) < 0)
194 goto err;
195 close(null);
196 return;
197 err:
198 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
199 exit(EXIT_FAILURE);
200 }
201
202 /**
203 * Close the log file of the daemon.
204 */
205 void daemon_close_log(void)
206 {
207 if (!me->logfile)
208 return;
209 PARA_INFO_LOG("closing logfile\n");
210 fclose(me->logfile);
211 me->logfile = NULL;
212 }
213
214 /**
215 * fopen() the logfile in append mode.
216 *
217 * \return Either succeeds or exits.
218 */
219 void daemon_open_log_or_die(void)
220 {
221 daemon_close_log();
222 if (!me->logfile_name)
223 return;
224 me->logfile = fopen(me->logfile_name, "a");
225 if (!me->logfile) {
226 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
227 strerror(errno));
228 exit(EXIT_FAILURE);
229 }
230 setlinebuf(me->logfile);
231 }
232
233 /**
234 * Log the startup message containing the paraslash version.
235 */
236 void log_welcome(const char *whoami)
237 {
238 PARA_INFO_LOG("welcome to %s " PACKAGE_VERSION " ("BUILD_DATE")\n",
239 whoami);
240 }
241
242 /**
243 * Give up superuser privileges.
244 *
245 * \param username The user to switch to.
246 * \param groupname The group to switch to.
247 *
248 * This function returns immediately if not invoked with EUID zero. Otherwise,
249 * it tries to obtain the GID of \a groupname and the UID of \a username. On
250 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
251 * are all set accordingly. On errors, an appropriate message is logged and
252 * exit() is called to terminate the process.
253 *
254 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
255 */
256 void drop_privileges_or_die(const char *username, const char *groupname)
257 {
258 struct passwd *p;
259 char *tmp;
260
261 if (geteuid())
262 return;
263 if (groupname) {
264 struct group *g = getgrnam(groupname);
265 if (!g) {
266 PARA_EMERG_LOG("failed to get group %s: %s\n",
267 groupname, strerror(errno));
268 exit(EXIT_FAILURE);
269 }
270 if (setgid(g->gr_gid) < 0) {
271 PARA_EMERG_LOG("failed to set group id %d: %s\n",
272 (int)g->gr_gid, strerror(errno));
273 exit(EXIT_FAILURE);
274 }
275 }
276 if (!username) {
277 PARA_EMERG_LOG("root privileges, but no user option given\n");
278 exit(EXIT_FAILURE);
279 }
280 tmp = para_strdup(username);
281 p = getpwnam(tmp);
282 free(tmp);
283 if (!p) {
284 PARA_EMERG_LOG("%s: no such user\n", username);
285 exit(EXIT_FAILURE);
286 }
287 PARA_INFO_LOG("dropping root privileges\n");
288 if (setuid(p->pw_uid) < 0) {
289 PARA_EMERG_LOG("failed to set effective user ID (%s)",
290 strerror(errno));
291 exit(EXIT_FAILURE);
292 }
293 PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
294 }
295
296 /**
297 * Set the server startup time.
298 *
299 * \param startuptime The value to store as the server start time.
300 *
301 * This should be called once on startup with \a startuptime either NULL or a
302 * pointer to a struct timeval which contains the current time. If \a
303 * startuptime is NULL, the server start time is set to the current time.
304 *
305 * \sa time(2), difftime(3) \ref get_server_uptime(), \ref
306 * get_server_uptime_str().
307 */
308 void set_server_start_time(const struct timeval *startuptime)
309 {
310 if (startuptime)
311 me->startuptime = startuptime->tv_sec;
312 else
313 time(&me->startuptime);
314 }
315
316 /**
317 * Get the server uptime.
318 *
319 * \param current_time The current time.
320 *
321 * The \a current_time pointer may be \p NULL. In this case the function
322 * obtains the current time from the system.
323 *
324 * \return This returns the server uptime in seconds, i.e. the difference
325 * between the current time and the value stored previously via \ref
326 * set_server_start_time().
327 */
328 time_t get_server_uptime(const struct timeval *current_time)
329 {
330 time_t t;
331
332 if (current_time)
333 return current_time->tv_sec - me->startuptime;
334 time(&t);
335 return difftime(t, me->startuptime);
336 }
337
338 /**
339 * Construct a string containing the current uptime.
340 *
341 * \param current_time See a \ref get_server_uptime().
342 *
343 * \return A dynamically allocated string of the form "days:hours:minutes".
344 *
345 * \sa server_uptime.
346 */
347 __malloc char *get_server_uptime_str(const struct timeval *current_time)
348 {
349 long t = get_server_uptime(current_time);
350 return make_message("%li:%02li:%02li", t / 86400,
351 (t / 3600) % 24, (t / 60) % 60);
352 }
353
354 /**
355 * The log function for para_server and para_audiod.
356 *
357 * \param ll The log level.
358 * \param fmt The format string describing the log message.
359 */
360 __printf_2_3 void daemon_log(int ll, const char* fmt,...)
361 {
362 va_list argp;
363 FILE *fp;
364 struct tm *tm;
365 char *color;
366 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
367 daemon_test_flag(DF_LOG_TIMING);
368
369 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
370 ll = PARA_MAX(ll, LL_DEBUG);
371 if (ll < me->loglevel)
372 return;
373
374 fp = me->logfile? me->logfile : stderr;
375 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
376 if (color)
377 fprintf(fp, "%s", color);
378 if (log_time || log_timing) {
379 struct timeval tv;
380 gettimeofday(&tv, NULL);
381 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
382 time_t t1 = tv.tv_sec;
383 char str[100];
384 tm = localtime(&t1);
385 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
386 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
387 }
388 if (log_timing) /* print milliseconds */
389 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
390 }
391 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
392 if (!me->hostname)
393 me->hostname = para_hostname();
394 fprintf(fp, "%s ", me->hostname);
395 }
396 if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
397 fprintf(fp, "(%d) ", ll);
398 if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
399 pid_t mypid = getpid();
400 fprintf(fp, "(%d) ", (int)mypid);
401 }
402 va_start(argp, fmt);
403 vfprintf(fp, fmt, argp);
404 va_end(argp);
405 if (color)
406 fprintf(fp, "%s", COLOR_RESET);
407 }