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