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