Add new prebuffer filter.
[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  * Supress 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         umask(0);
171         null = open("/dev/null", O_RDONLY);
172         if (null < 0)
173                 goto err;
174         if (dup2(null, STDIN_FILENO) < 0)
175                 goto err;
176         if (dup2(null, STDOUT_FILENO) < 0)
177                 goto err;
178         if (dup2(null, STDERR_FILENO) < 0)
179                 goto err;
180         close(null);
181         return;
182 err:
183         PARA_EMERG_LOG("fatal: %s\n", strerror(errno));
184         exit(EXIT_FAILURE);
185 }
186
187 /**
188  * Close the log file of the daemon.
189  */
190 void daemon_close_log(void)
191 {
192         if (!me->logfile)
193                 return;
194         PARA_INFO_LOG("closing logfile\n");
195         fclose(me->logfile);
196         me->logfile = NULL;
197 }
198
199 /**
200  * fopen() the logfile in append mode.
201  *
202  * \return Either succeeds or exits.
203  */
204 void daemon_open_log_or_die(void)
205 {
206         daemon_close_log();
207         if (!me->logfile_name)
208                 return;
209         me->logfile = fopen(me->logfile_name, "a");
210         if (!me->logfile) {
211                 PARA_EMERG_LOG("can not open %s: %s\n", me->logfile_name,
212                         strerror(errno));
213                 exit(EXIT_FAILURE);
214         }
215         setlinebuf(me->logfile);
216 }
217
218 /**
219  * Log the startup message containing the paraslash version.
220  */
221 void log_welcome(const char *whoami)
222 {
223         PARA_INFO_LOG("welcome to %s " PACKAGE_VERSION " ("BUILD_DATE")\n",
224                 whoami);
225 }
226
227 /**
228  * Give up superuser privileges.
229  *
230  * \param username The user to switch to.
231  * \param groupname The group to switch to.
232  *
233  * This function returns immediately if not invoked with EUID zero. Otherwise,
234  * it tries to obtain the GID of \a groupname and the UID of \a username.  On
235  * success, effective and real GID/UID and the saved set-group-ID/set-user-ID
236  * are all set accordingly. On errors, an appropriate message is logged and
237  * exit() is called to terminate the process.
238  *
239  * \sa getpwnam(3), getuid(2), setuid(2), getgrnam(2), setgid(2)
240  */
241 void drop_privileges_or_die(const char *username, const char *groupname)
242 {
243         struct passwd *p;
244         char *tmp;
245
246         if (geteuid())
247                 return;
248         if (groupname) {
249                 struct group *g = getgrnam(groupname);
250                 if (!g) {
251                         PARA_EMERG_LOG("failed to get group %s: %s\n",
252                                 groupname, strerror(errno));
253                         exit(EXIT_FAILURE);
254                 }
255                 if (setgid(g->gr_gid) < 0) {
256                         PARA_EMERG_LOG("failed to set group id %d: %s\n",
257                                 (int)g->gr_gid, strerror(errno));
258                         exit(EXIT_FAILURE);
259                 }
260         }
261         if (!username) {
262                 PARA_EMERG_LOG("root privileges, but no user option given\n");
263                 exit(EXIT_FAILURE);
264         }
265         tmp = para_strdup(username);
266         p = getpwnam(tmp);
267         free(tmp);
268         if (!p) {
269                 PARA_EMERG_LOG("%s: no such user\n", username);
270                 exit(EXIT_FAILURE);
271         }
272         PARA_INFO_LOG("dropping root privileges\n");
273         setuid(p->pw_uid);
274         PARA_DEBUG_LOG("uid: %d, euid: %d\n", (int)getuid(), (int)geteuid());
275 }
276
277 /**
278  * Set/get the server uptime.
279  *
280  * \param set_or_get Chose one of the two modes.
281  *
282  * This should be called at startup time with \a set_or_get equal to \p
283  * UPTIME_SET which sets the uptime to zero.  Subsequent calls with \a
284  * set_or_get equal to \p UPTIME_GET return the uptime.
285
286  * \return Zero if called with \a set_or_get equal to \p UPTIME_SET, the number
287  * of seconds ellapsed since the last reset otherwise.
288  *
289  * \sa time(2), difftime(3).
290  */
291 time_t server_uptime(enum uptime set_or_get)
292 {
293         time_t now;
294         double diff;
295
296         if (set_or_get == UPTIME_SET) {
297                 time(&me->startuptime);
298                 return 0;
299         }
300         time(&now);
301         diff = difftime(now, me->startuptime);
302         return (time_t) diff;
303 }
304
305 /**
306  * Construct string containing uptime.
307  *
308  * \return A dynamically allocated string of the form "days:hours:minutes".
309  *
310  * \sa server_uptime.
311  */
312 __malloc char *uptime_str(void)
313 {
314         long t = server_uptime(UPTIME_GET);
315         return make_message("%li:%02li:%02li", t / 86400,
316                 (t / 3600) % 24, (t / 60) % 60);
317 }
318
319 /**
320  * The log function for para_server and para_audiod.
321  *
322  * \param ll The log level.
323  * \param fmt The format string describing the log message.
324  */
325 __printf_2_3 void para_log(int ll, const char* fmt,...)
326 {
327         va_list argp;
328         FILE *fp;
329         struct tm *tm;
330         time_t t1;
331         char *color, str[MAXLINE] = "";
332
333         ll = PARA_MIN(ll, NUM_LOGLEVELS - 1);
334         ll = PARA_MAX(ll, LL_DEBUG);
335         if (ll < me->loglevel)
336                 return;
337
338         fp = me->logfile? me->logfile : stderr;
339         color = daemon_test_flag(DF_COLOR_LOG)? me->log_colors[ll] : NULL;
340         if (color)
341                 fprintf(fp, "%s", color);
342         if (daemon_test_flag(DF_LOG_TIME)) {
343                 /* date and time */
344                 time(&t1);
345                 tm = localtime(&t1);
346                 strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
347                 fprintf(fp, "%s ", str);
348         }
349         if (daemon_test_flag(DF_LOG_HOSTNAME)) {
350                 if (!me->hostname)
351                         me->hostname = para_hostname();
352                 fprintf(fp, "%s ", me->hostname);
353         }
354         if (daemon_test_flag(DF_LOG_LL)) /* log loglevel */
355                 fprintf(fp, "(%d) ", ll);
356         if (daemon_test_flag(DF_LOG_PID)) { /* log pid */
357                 pid_t mypid = getpid();
358                 fprintf(fp, "(%d) ", (int)mypid);
359         }
360         va_start(argp, fmt);
361         vfprintf(fp, fmt, argp);
362         va_end(argp);
363         if (color)
364                 fprintf(fp, "%s", COLOR_RESET);
365 }