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