findInitPid() has been implemented and it seems to work.
[oweals/busybox.git] / syslogd.c
1 /*
2  * Mini syslogd implementation for busybox
3  *
4  * Copyright (C) 1999 by Lineo, inc.
5  * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 #include "internal.h"
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <unistd.h>
29 #include <time.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <netdb.h>
36 #include <sys/klog.h>
37 #include <errno.h>
38 #include <paths.h>
39
40 #define ksyslog klogctl
41 extern int ksyslog(int type, char *buf, int len);
42
43
44 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
45 #define SYSLOG_NAMES
46 #include <sys/syslog.h>
47
48 /* Path for the file where all log messages are written */
49 #define __LOG_FILE              "/var/log/messages"
50
51
52 static char* logFilePath = __LOG_FILE;
53 /* interval between marks in seconds */
54 static int MarkInterval = 20*60;
55 /* localhost's name */
56 static char LocalHostName[32];
57
58 static const char syslogd_usage[] =
59     "syslogd [OPTION]...\n\n"
60     "Linux system and kernel (provides klogd) logging utility.\n"
61     "Note that this version of syslogd/klogd ignores /etc/syslog.conf.\n\n"
62     "Options:\n"
63     "\t-m\tChange the mark timestamp interval. default=20min. 0=off\n"
64     "\t-n\tDo not fork into the background (for when run by init)\n"
65     "\t-O\tSpecify an alternate log file.  default=/var/log/messages\n";
66
67
68 /* try to open up the specified device */
69 static int device_open(char *device, int mode)
70 {
71     int m, f, fd = -1;
72
73     m = mode | O_NONBLOCK;
74
75     /* Retry up to 5 times */
76     for (f = 0; f < 5; f++)
77         if ((fd = open(device, m)) >= 0)
78             break;
79     if (fd < 0)
80         return fd;
81     /* Reset original flags. */
82     if (m != mode)
83         fcntl(fd, F_SETFL, mode);
84     return fd;
85 }
86
87 /* print a message to the log file */
88 static void message(char *fmt, ...)
89 {
90     int fd;
91     va_list arguments;
92
93     if ((fd = device_open(logFilePath, O_WRONLY|O_CREAT|O_NOCTTY|O_APPEND|O_NONBLOCK)) >= 0) {
94         va_start(arguments, fmt);
95         vdprintf(fd, fmt, arguments);
96         va_end(arguments);
97         close(fd);
98     } else {
99         /* Always send console messages to /dev/console so people will see them. */
100         if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NONBLOCK)) >= 0) {
101             va_start(arguments, fmt);
102             vdprintf(fd, fmt, arguments);
103             va_end(arguments);
104             close(fd);
105         } else {
106             fprintf(stderr, "Bummer, can't print: ");
107             va_start(arguments, fmt);
108             vfprintf(stderr, fmt, arguments);
109             fflush(stderr);
110             va_end(arguments);
111         }
112     }
113 }
114
115 static void logMessage( int pri, char* msg) 
116 {
117     time_t  now;
118     char *timestamp;
119     static char res[20];
120     CODE *c_pri, *c_fac;
121
122     for (c_fac=facilitynames; c_fac->c_name && !(c_fac->c_val==LOG_FAC(pri)<<3); c_fac++);
123     for (c_pri=prioritynames; c_pri->c_name && !(c_pri->c_val==LOG_PRI(pri)); c_pri++);
124     if (*c_fac->c_name=='\0' || *c_pri->c_name=='\0')
125         snprintf (res, sizeof(res), "<%d>", pri);
126     else
127         snprintf (res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
128
129     if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' || 
130             msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') 
131     {
132         time(&now);
133         timestamp = ctime(&now) + 4;
134         timestamp[15] = '\0';
135     } else {
136         timestamp = msg;
137         timestamp[15] = '\0';
138         msg += 16;
139     }
140
141     /* todo: supress duplicates */
142
143     /* now spew out the message to wherever it is supposed to go */
144     message( "%s %s %s %s\n", timestamp, LocalHostName, res, msg);
145 }
146
147 static void quit_signal(int sig)
148 {
149     logMessage(LOG_SYSLOG|LOG_INFO, "System log daemon exiting.");
150     unlink( _PATH_LOG);
151     exit( TRUE);
152 }
153
154 static void restart_signal(int sig)
155 {
156     /* pretend to restart */
157     logMessage(LOG_SYSLOG|LOG_INFO, "syslogd restarting");
158 }
159
160 static void domark(int sig)
161 {
162     if (MarkInterval > 0) {
163         logMessage(LOG_SYSLOG|LOG_INFO, "-- MARK --");
164         signal(SIGALRM, domark);
165         alarm(MarkInterval);
166     }
167 }
168
169 static void doSyslogd(void)
170 {
171     struct sockaddr_un sunx;
172     int fd, conn;
173     size_t addrLength;
174     char buf[1024];
175     char *q, *p = buf;
176     int readSize;
177
178     /* Remove any preexisting socket/file */
179     unlink(_PATH_LOG);
180
181     /* Set up sig handlers */
182     signal(SIGINT,  quit_signal);
183     signal(SIGTERM, quit_signal);
184     signal(SIGQUIT, quit_signal);
185     signal(SIGHUP,  restart_signal);
186     signal(SIGALRM, domark);
187     alarm(MarkInterval);
188
189
190     unlink( _PATH_LOG);
191     memset(&sunx, 0, sizeof(sunx));
192     sunx.sun_family = AF_UNIX;  /* Unix domain socket */
193     strncpy(sunx.sun_path, _PATH_LOG, sizeof(sunx.sun_path));
194     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 ) {
195         perror("Couldn't obtain descriptor for socket " _PATH_LOG);
196         exit( FALSE);
197     }
198
199     addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
200     if ( (bind(fd, (struct sockaddr *) &sunx, addrLength)) ||
201             (fchmod(fd, 0666) < 0) || (listen(fd, 5)) ) 
202     {
203         perror("Could not connect to socket " _PATH_LOG);
204         exit( FALSE);
205     }
206     
207     
208     logMessage(LOG_SYSLOG|LOG_INFO, "syslogd started: "
209             "BusyBox v" BB_VER " (" BB_BT ")");
210
211
212     while ((conn = accept(fd, (struct sockaddr *) &sunx, 
213                           &addrLength)) >= 0) 
214     {
215         while ((readSize=read(conn, buf, sizeof(buf))) > 0)
216         {
217             char line[1025];
218             unsigned char c;
219             int pri = (LOG_USER|LOG_NOTICE);
220
221             memset (line, 0, sizeof(line));
222             p = buf;
223             q = line;
224             while ( p && (c = *p) && q < &line[sizeof(line) - 1]) {
225                 if (c == '<') {
226                     /* Parse the magic priority number */
227                     pri = 0;
228                     while (isdigit(*(++p))) {
229                         pri = 10 * pri + (*p - '0');
230                     }
231                     if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
232                         pri = (LOG_USER|LOG_NOTICE);
233                 } else if (c == '\n') {
234                     *q++ = ' ';
235                 } else if (iscntrl(c)&&(c<0177)) {
236                     *q++ = '^';
237                     *q++ = c ^ 0100;
238                 } else {
239                     *q++ = c;
240                 }
241                 p++;
242             }
243             *q = '\0';
244
245             /* Now log it */
246             logMessage( pri, line);
247         }
248         close(conn);
249     }
250
251     close(fd);
252 }
253
254 static void klogd_signal(int sig)
255 {
256     ksyslog(7, NULL, 0);
257     ksyslog(0, 0, 0);
258     logMessage(LOG_SYSLOG|LOG_INFO, "Kernel log daemon exiting.");
259     exit( TRUE);
260 }
261
262
263 static void doKlogd(void)
264 {
265     int priority=LOG_INFO;
266     char log_buffer[4096];
267     char *logp;
268
269     /* Set up sig handlers */
270     signal(SIGINT,  klogd_signal);
271     signal(SIGKILL, klogd_signal);
272     signal(SIGTERM, klogd_signal);
273     signal(SIGHUP,  klogd_signal);
274     logMessage(LOG_SYSLOG|LOG_INFO, "klogd started: "
275             "BusyBox v" BB_VER " (" BB_BT ")");
276
277     ksyslog(1, NULL, 0);
278
279     while (1) {
280         /* Use kernel syscalls */
281         memset(log_buffer, '\0', sizeof(log_buffer));
282         if ( ksyslog(2, log_buffer, sizeof(log_buffer)) < 0 ) {
283             char message[80];
284             if ( errno == EINTR )
285                 continue;
286             snprintf(message, 79, "klogd: Error return from sys_sycall: " \
287                     "%d - %s.\n", errno, strerror(errno));
288             logMessage(LOG_SYSLOG|LOG_ERR, message);
289             exit(1);
290         }
291         logp=log_buffer;
292         if ( *log_buffer == '<' )
293         {
294             switch ( *(log_buffer+1) )
295             {
296                 case '0':
297                     priority = LOG_EMERG;
298                     break;
299                 case '1':
300                     priority = LOG_ALERT;
301                     break;
302                 case '2':
303                     priority = LOG_CRIT;
304                     break;
305                 case '3':
306                     priority = LOG_ERR;
307                     break;
308                 case '4':
309                     priority = LOG_WARNING;
310                     break;
311                 case '5':
312                     priority = LOG_NOTICE;
313                     break;
314                 case '6':
315                     priority = LOG_INFO;
316                     break;
317                 case '7':
318                 default:
319                     priority = LOG_DEBUG;
320             }
321             logp+=3;
322         }
323         logMessage(LOG_KERN|priority, logp);
324     }
325
326 }
327
328
329 extern int syslogd_main(int argc, char **argv)
330 {
331     int pid, klogd_pid;
332     int doFork = TRUE;
333     char *p;
334     char **argv1=argv;
335     
336     while (--argc > 0 && **(++argv1) == '-') {
337         while (*(++(*argv1))) {
338             switch (**argv1) {
339             case 'm':
340                 if (--argc == 0) {
341                     usage(syslogd_usage);
342                 }
343                 MarkInterval = atoi(*(++argv1))*60;
344                 break;
345             case 'n':
346                 doFork = FALSE;
347                 break;
348             case 'O':
349                 if (--argc == 0) {
350                     usage(syslogd_usage);
351                 }
352                 logFilePath = *(++argv1);
353                 break;
354             default:
355                 usage(syslogd_usage);
356             }
357         }
358     }
359     
360     /* Store away localhost's name before the fork */
361     gethostname(LocalHostName, sizeof(LocalHostName));
362     if ( (p = strchr(LocalHostName, '.')) ) {
363         *p++ = '\0';
364     }
365
366     if (doFork == TRUE) {
367         pid = fork();
368         if ( pid < 0 )
369             exit( pid);
370         else if ( pid == 0 ) {
371             strncpy(argv[0], "syslogd",strlen(argv[0]));
372             doSyslogd();
373         }
374     } else {
375         doSyslogd();
376     }
377
378     /* Start up the klogd process */
379     klogd_pid = fork();
380     if (klogd_pid == 0 ) {
381             strncpy(argv[0], "klogd", strlen(argv[0]));
382             doKlogd();
383     }
384
385     exit( TRUE);
386 }
387
388