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