NEWS update.
[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
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 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 /**
147 * Do the usual stuff to become a daemon.
148 *
149 * Fork, become session leader, dup fd 0, 1, 2 to /dev/null.
150 *
151 * \sa fork(2), setsid(2), dup(2).
152 */
153 void daemonize(void)
154 {
155 pid_t pid;
156 int null;
157
158 PARA_INFO_LOG("daemonizing\n");
159 pid = fork();
160 if (pid < 0)
161 goto err;
162 if (pid)
163 exit(EXIT_SUCCESS); /* parent exits */
164 /* become session leader */
165 if (setsid() < 0)
166 goto err;
167 if (chdir("/") < 0)
168 goto err;
169 null = open("/dev/null", O_RDONLY);
170 if (null < 0)
171 goto err;
172 if (dup2(null, STDIN_FILENO) < 0)
173 goto err;
174 if (dup2(null, STDOUT_FILENO) < 0)
175 goto err;
176 if (dup2(null, STDERR_FILENO) < 0)
177 goto err;
178 close(null);
179 return;
180 err:
181 PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
182 exit(EXIT_FAILURE);
183 }
184
185 /**
186 * Close the log file of the daemon.
187 */
188 void daemon_close_log(void)
189 {
190 if (!me->logfile)
191 return;
192 PARA_INFO_LOG("closing logfile\n");
193 fclose(me->logfile);
194 me->logfile = NULL;
195 }
196
197 /**
198 * fopen() the logfile in append mode.
199 *
200 * \return Either succeeds or exits.
201 */
202 void daemon_open_log_or_die(void)
203 {
204 daemon_close_log();
205 if (!me->logfile_name)
206 return;
207 me->logfile = fopen(me->logfile_name, "a");
208 if (!me->logfile) {
209 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
210 strerror(errno));
211 exit(EXIT_FAILURE);
212 }
213 setlinebuf(me->logfile);
214 }
215
216 /**
217 * Log the startup message containing the paraslash version.
218 */
219 void log_welcome(const char *whoami)
220 {
221 PARA_INFO_LOG("welcome to %s " PACKAGE_VERSION " ("BUILD_DATE")\n",
222 whoami);
223 }
224
225 /**
226 * Give up superuser privileges.
227 *
228 * \param username The user to switch to.
229 * \param groupname The group to switch to.
230 *
231 * This function returns immediately if not invoked with EUID zero. Otherwise,
232 * it tries to obtain the GID of \a groupname and the UID of \a username. On
233 * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
234 * are all set accordingly. On errors, an appropriate message is logged and
235 * exit() is called to terminate the process.
236 *
237 * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
238 */
239 void drop_privileges_or_die(const char *username, const char *groupname)
240 {
241 struct passwd *p;
242 char *tmp;
243
244 if (geteuid())
245 return;
246 if (groupname) {
247 struct group *g = getgrnam(groupname);
248 if (!g) {
249 PARA_EMERG_LOG("failed to get group %s: %s\n",
250 groupname, strerror(errno));
251 exit(EXIT_FAILURE);
252 }
253 if (setgid(g->gr_gid) < 0) {
254 PARA_EMERG_LOG("failed to set group id %d: %s\n",
255 (int)g->gr_gid, strerror(errno));
256 exit(EXIT_FAILURE);
257 }
258 }
259 if (!username) {
260 PARA_EMERG_LOG("root privileges, but no user option given\n");
261 exit(EXIT_FAILURE);
262 }
263 tmp = para_strdup(username);
264 p = getpwnam(tmp);
265 free(tmp);
266 if (!p) {
267 PARA_EMERG_LOG("%s: no such user\n", username);
268 exit(EXIT_FAILURE);
269 }
270 PARA_INFO_LOG("dropping root privileges\n");
271 if (setuid(p->pw_uid) < 0) {
272 PARA_EMERG_LOG("failed to set effective user ID (%s)",
273 strerror(errno));
274 exit(EXIT_FAILURE);
275 }
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 elapsed 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 char *color;
333 bool log_time = daemon_test_flag(DF_LOG_TIME), log_timing =
334 daemon_test_flag(DF_LOG_TIMING);
335
336 ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
337 ll = PARA_MAX(ll, LL_DEBUG);
338 if (ll < me->loglevel)
339 return;
340
341 fp = me->logfile? me->logfile : stderr;
342 color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
343 if (color)
344 fprintf(fp, "%s", color);
345 if (log_time || log_timing) {
346 struct timeval tv;
347 gettimeofday(&tv, NULL);
348 if (daemon_test_flag(DF_LOG_TIME)) { /* print date and time */
349 time_t t1 = tv.tv_sec;
350 char str[100];
351 tm = localtime(&t1);
352 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
353 fprintf(fp, "%s%s", str, log_timing? ":" : " ");
354 }
355 if (log_timing) /* print milliseconds */
356 fprintf(fp, "%04lu ", (long unsigned)tv.tv_usec / 1000);
357 }
358 if (daemon_test_flag(DF_LOG_HOSTNAME)) {
359 if (!me->hostname)
360 me->hostname = para_hostname();
361 fprintf(fp, "%s ", me->hostname);
362 }
363 if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
364 fprintf(fp, "(%d) ", ll);
365 if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
366 pid_t mypid = getpid();
367 fprintf(fp, "(%d) ", (int)mypid);
368 }
369 va_start(argp, fmt);
370 vfprintf(fp, fmt, argp);
371 va_end(argp);
372 if (color)
373 fprintf(fp, "%s", COLOR_RESET);
374 }