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