Magellan Linux

Diff of /trunk/mkinitrd-magellan/busybox/sysklogd/syslogd.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 532 by niro, Sat Sep 1 22:45:15 2007 UTC revision 816 by niro, Fri Apr 24 18:33:46 2009 UTC
# Line 13  Line 13 
13   * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.   * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
14   */   */
15    
16  #include "busybox.h"  /*
17     * Done in syslogd_and_logger.c:
18    #include "libbb.h"
19    #define SYSLOG_NAMES
20    #define SYSLOG_NAMES_CONST
21    #include <syslog.h>
22    */
23    
24  #include <paths.h>  #include <paths.h>
25  #include <sys/un.h>  #include <sys/un.h>
   
 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */  
 #define SYSLOG_NAMES  
 #include <sys/syslog.h>  
26  #include <sys/uio.h>  #include <sys/uio.h>
27    
28    #if ENABLE_FEATURE_REMOTE_LOG
29    #include <netinet/in.h>
30    #endif
31    
32    #if ENABLE_FEATURE_IPC_SYSLOG
33    #include <sys/ipc.h>
34    #include <sys/sem.h>
35    #include <sys/shm.h>
36    #endif
37    
38    
39  #define DEBUG 0  #define DEBUG 0
40    
41  /* Path to the unix socket */  /* MARK code is not very useful, is bloat, and broken:
42  static char *dev_log_name;   * can deadlock if alarmed to make MARK while writing to IPC buffer
43     * (semaphores are down but do_mark routine tries to down them again) */
44    #undef SYSLOGD_MARK
45    
46  /* Path for the file where all log messages are written */  enum {
47  static const char *logFilePath = "/var/log/messages";   MAX_READ = 256,
48  static int logFD = -1;   DNS_WAIT_SEC = 2 * 60,
49    };
50    
51  /* interval between marks in seconds */  /* Semaphore operation structures */
52  static int markInterval = 20 * 60;  struct shbuf_ds {
53     int32_t size;   /* size of data - 1 */
54     int32_t tail;   /* end of message list */
55     char data[1];   /* data/messages */
56    };
57    
58  /* level of messages to be locally logged */  /* Allows us to have smaller initializer. Ugly. */
59  static int logLevel = 8;  #define GLOBALS \
60     const char *logFilePath;                \
61     int logFD;                              \
62     /* interval between marks in seconds */ \
63     /*int markInterval;*/                   \
64     /* level of messages to be logged */    \
65     int logLevel;                           \
66    USE_FEATURE_ROTATE_LOGFILE( \
67     /* max size of file before rotation */  \
68     unsigned logFileSize;                   \
69     /* number of rotated message files */   \
70     unsigned logFileRotate;                 \
71     unsigned curFileSize;                   \
72     smallint isRegular;                     \
73    ) \
74    USE_FEATURE_REMOTE_LOG( \
75     /* udp socket for remote logging */     \
76     int remoteFD;                           \
77     len_and_sockaddr* remoteAddr;           \
78    ) \
79    USE_FEATURE_IPC_SYSLOG( \
80     int shmid; /* ipc shared memory id */   \
81     int s_semid; /* ipc semaphore id */     \
82     int shm_size;                           \
83     struct sembuf SMwup[1];                 \
84     struct sembuf SMwdn[3];                 \
85    )
86    
87  /* localhost's name */  struct init_globals {
88  static char localHostName[64];   GLOBALS
89    };
90    
91  #if ENABLE_FEATURE_ROTATE_LOGFILE  struct globals {
92  /* max size of message file before being rotated */   GLOBALS
93  static unsigned logFileSize = 200 * 1024;  
94  /* number of rotated message files */  #if ENABLE_FEATURE_REMOTE_LOG
95  static unsigned logFileRotate = 1;   unsigned last_dns_resolve;
96  static unsigned curFileSize;   char *remoteAddrStr;
 static smallint isRegular;  
97  #endif  #endif
98    
99    #if ENABLE_FEATURE_IPC_SYSLOG
100     struct shbuf_ds *shbuf;
101    #endif
102     time_t last_log_time;
103     /* localhost's name. We print only first 64 chars */
104     char *hostname;
105    
106     /* We recv into recvbuf... */
107     char recvbuf[MAX_READ * (1 + ENABLE_FEATURE_SYSLOGD_DUP)];
108     /* ...then copy to parsebuf, escaping control chars */
109     /* (can grow x2 max) */
110     char parsebuf[MAX_READ*2];
111     /* ...then sprintf into printbuf, adding timestamp (15 chars),
112     * host (64), fac.prio (20) to the message */
113     /* (growth by: 15 + 64 + 20 + delims = ~110) */
114     char printbuf[MAX_READ*2 + 128];
115    };
116    
117    static const struct init_globals init_data = {
118     .logFilePath = "/var/log/messages",
119     .logFD = -1,
120    #ifdef SYSLOGD_MARK
121     .markInterval = 20 * 60,
122    #endif
123     .logLevel = 8,
124    #if ENABLE_FEATURE_ROTATE_LOGFILE
125     .logFileSize = 200 * 1024,
126     .logFileRotate = 1,
127    #endif
128  #if ENABLE_FEATURE_REMOTE_LOG  #if ENABLE_FEATURE_REMOTE_LOG
129  #include <netinet/in.h>   .remoteFD = -1,
130  /* udp socket for logging to remote host */  #endif
131  static int remoteFD = -1;  #if ENABLE_FEATURE_IPC_SYSLOG
132  static len_and_sockaddr* remoteAddr;   .shmid = -1,
133  #endif   .s_semid = -1,
134     .shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024), // default shm size
135  /* We are using bb_common_bufsiz1 for buffering: */   .SMwup = { {1, -1, IPC_NOWAIT} },
136  enum { MAX_READ = (BUFSIZ/6) & ~0xf };   .SMwdn = { {0, 0}, {1, 0}, {1, +1} },
137  /* We recv into RECVBUF... (size: MAX_READ ~== BUFSIZ/6) */  #endif
138  #define RECVBUF  bb_common_bufsiz1  };
139  /* ...then copy to PARSEBUF, escaping control chars */  
140  /* (can grow x2 max ~== BUFSIZ/3) */  #define G (*ptr_to_globals)
141  #define PARSEBUF (bb_common_bufsiz1 + MAX_READ)  #define INIT_G() do { \
142  /* ...then sprintf into PRINTBUF, adding timestamp (15 chars),   SET_PTR_TO_GLOBALS(memcpy(xzalloc(sizeof(G)), &init_data, sizeof(init_data))); \
143   * host (64), fac.prio (20) to the message */  } while (0)
 /* (growth by: 15 + 64 + 20 + delims = ~110) */  
 #define PRINTBUF (bb_common_bufsiz1 + 3*MAX_READ)  
 /* totals: BUFSIZ == BUFSIZ/6 + BUFSIZ/3 + (BUFSIZ/3+BUFSIZ/6)  
  * -- we have BUFSIZ/6 extra at the ent of PRINTBUF  
  * which covers needed ~110 extra bytes (and much more) */  
144    
145    
146  /* Options */  /* Options */
# Line 82  enum { Line 153  enum {
153   USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize   ,) // -s   USE_FEATURE_ROTATE_LOGFILE(OPTBIT_filesize   ,) // -s
154   USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt  ,) // -b   USE_FEATURE_ROTATE_LOGFILE(OPTBIT_rotatecnt  ,) // -b
155   USE_FEATURE_REMOTE_LOG(    OPTBIT_remote     ,) // -R   USE_FEATURE_REMOTE_LOG(    OPTBIT_remote     ,) // -R
156   USE_FEATURE_REMOTE_LOG(    OPTBIT_localtoo   ,) // -L   USE_FEATURE_REMOTE_LOG(    OPTBIT_locallog   ,) // -L
157   USE_FEATURE_IPC_SYSLOG(    OPTBIT_circularlog,) // -C   USE_FEATURE_IPC_SYSLOG(    OPTBIT_circularlog,) // -C
158     USE_FEATURE_SYSLOGD_DUP(   OPTBIT_dup        ,) // -D
159    
160   OPT_mark        = 1 << OPTBIT_mark    ,   OPT_mark        = 1 << OPTBIT_mark    ,
161   OPT_nofork      = 1 << OPTBIT_nofork  ,   OPT_nofork      = 1 << OPTBIT_nofork  ,
# Line 93  enum { Line 165  enum {
165   OPT_filesize    = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize   )) + 0,   OPT_filesize    = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_filesize   )) + 0,
166   OPT_rotatecnt   = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt  )) + 0,   OPT_rotatecnt   = USE_FEATURE_ROTATE_LOGFILE((1 << OPTBIT_rotatecnt  )) + 0,
167   OPT_remotelog   = USE_FEATURE_REMOTE_LOG(    (1 << OPTBIT_remote     )) + 0,   OPT_remotelog   = USE_FEATURE_REMOTE_LOG(    (1 << OPTBIT_remote     )) + 0,
168   OPT_locallog    = USE_FEATURE_REMOTE_LOG(    (1 << OPTBIT_localtoo   )) + 0,   OPT_locallog    = USE_FEATURE_REMOTE_LOG(    (1 << OPTBIT_locallog   )) + 0,
169   OPT_circularlog = USE_FEATURE_IPC_SYSLOG(    (1 << OPTBIT_circularlog)) + 0,   OPT_circularlog = USE_FEATURE_IPC_SYSLOG(    (1 << OPTBIT_circularlog)) + 0,
170     OPT_dup         = USE_FEATURE_SYSLOGD_DUP(   (1 << OPTBIT_dup        )) + 0,
171  };  };
172  #define OPTION_STR "m:nO:l:S" \  #define OPTION_STR "m:nO:l:S" \
173   USE_FEATURE_ROTATE_LOGFILE("s:" ) \   USE_FEATURE_ROTATE_LOGFILE("s:" ) \
174   USE_FEATURE_ROTATE_LOGFILE("b:" ) \   USE_FEATURE_ROTATE_LOGFILE("b:" ) \
175   USE_FEATURE_REMOTE_LOG(    "R:" ) \   USE_FEATURE_REMOTE_LOG(    "R:" ) \
176   USE_FEATURE_REMOTE_LOG(    "L"  ) \   USE_FEATURE_REMOTE_LOG(    "L"  ) \
177   USE_FEATURE_IPC_SYSLOG(    "C::")   USE_FEATURE_IPC_SYSLOG(    "C::") \
178     USE_FEATURE_SYSLOGD_DUP(   "D"  )
179  #define OPTION_DECL *opt_m, *opt_l \  #define OPTION_DECL *opt_m, *opt_l \
180   USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \   USE_FEATURE_ROTATE_LOGFILE(,*opt_s) \
181   USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \   USE_FEATURE_ROTATE_LOGFILE(,*opt_b) \
  USE_FEATURE_REMOTE_LOG(    ,*opt_R) \  
182   USE_FEATURE_IPC_SYSLOG(    ,*opt_C = NULL)   USE_FEATURE_IPC_SYSLOG(    ,*opt_C = NULL)
183  #define OPTION_PARAM &opt_m, &logFilePath, &opt_l \  #define OPTION_PARAM &opt_m, &G.logFilePath, &opt_l \
184   USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \   USE_FEATURE_ROTATE_LOGFILE(,&opt_s) \
185   USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \   USE_FEATURE_ROTATE_LOGFILE(,&opt_b) \
186   USE_FEATURE_REMOTE_LOG(    ,&opt_R) \   USE_FEATURE_REMOTE_LOG(    ,&G.remoteAddrStr) \
187   USE_FEATURE_IPC_SYSLOG(    ,&opt_C)   USE_FEATURE_IPC_SYSLOG(    ,&opt_C)
188    
189    
190  /* circular buffer variables/structures */  /* circular buffer variables/structures */
191  #if ENABLE_FEATURE_IPC_SYSLOG  #if ENABLE_FEATURE_IPC_SYSLOG
192    
   
193  #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4  #if CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE < 4
194  #error Sorry, you must set the syslogd buffer size to at least 4KB.  #error Sorry, you must set the syslogd buffer size to at least 4KB.
195  #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE  #error Please check CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE
196  #endif  #endif
197    
198  #include <sys/ipc.h>  /* our shared key (syslogd.c and logread.c must be in sync) */
199  #include <sys/sem.h>  enum { KEY_ID = 0x414e4547 }; /* "GENA" */
 #include <sys/shm.h>  
   
 /* our shared key */  
 #define KEY_ID ((long)0x414e4547) /* "GENA" */  
   
 // Semaphore operation structures  
 static struct shbuf_ds {  
  int32_t size;   // size of data written  
  int32_t head;   // start of message list  
  int32_t tail;   // end of message list  
  char data[1];   // data/messages  
 } *shbuf;               // shared memory pointer  
   
 static int shmid = -1;   // ipc shared memory id  
 static int s_semid = -1; // ipc semaphore id  
 static int shm_size = ((CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE)*1024); // default shm size  
200    
201  static void ipcsyslog_cleanup(void)  static void ipcsyslog_cleanup(void)
202  {  {
203   if (shmid != -1) {   if (G.shmid != -1) {
204   shmdt(shbuf);   shmdt(G.shbuf);
205   }   }
206   if (shmid != -1) {   if (G.shmid != -1) {
207   shmctl(shmid, IPC_RMID, NULL);   shmctl(G.shmid, IPC_RMID, NULL);
208   }   }
209   if (s_semid != -1) {   if (G.s_semid != -1) {
210   semctl(s_semid, 0, IPC_RMID, 0);   semctl(G.s_semid, 0, IPC_RMID, 0);
211   }   }
212  }  }
213    
214  static void ipcsyslog_init(void)  static void ipcsyslog_init(void)
215  {  {
216   if (DEBUG)   if (DEBUG)
217   printf("shmget(%lx, %d,...)\n", KEY_ID, shm_size);   printf("shmget(%x, %d,...)\n", (int)KEY_ID, G.shm_size);
218    
219   shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023);   G.shmid = shmget(KEY_ID, G.shm_size, IPC_CREAT | 0644);
220   if (shmid == -1) {   if (G.shmid == -1) {
221   bb_perror_msg_and_die("shmget");   bb_perror_msg_and_die("shmget");
222   }   }
223    
224   shbuf = shmat(shmid, NULL, 0);   G.shbuf = shmat(G.shmid, NULL, 0);
225   if (!shbuf) {   if (G.shbuf == (void*) -1L) { /* shmat has bizarre error return */
226   bb_perror_msg_and_die("shmat");   bb_perror_msg_and_die("shmat");
227   }   }
228    
229   shbuf->size = shm_size - offsetof(struct shbuf_ds, data);   memset(G.shbuf, 0, G.shm_size);
230   shbuf->head = shbuf->tail = 0;   G.shbuf->size = G.shm_size - offsetof(struct shbuf_ds, data) - 1;
231     /*G.shbuf->tail = 0;*/
232    
233   // we'll trust the OS to set initial semval to 0 (let's hope)   // we'll trust the OS to set initial semval to 0 (let's hope)
234   s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);   G.s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023);
235   if (s_semid == -1) {   if (G.s_semid == -1) {
236   if (errno == EEXIST) {   if (errno == EEXIST) {
237   s_semid = semget(KEY_ID, 2, 0);   G.s_semid = semget(KEY_ID, 2, 0);
238   if (s_semid != -1)   if (G.s_semid != -1)
239   return;   return;
240   }   }
241   bb_perror_msg_and_die("semget");   bb_perror_msg_and_die("semget");
# Line 188  static void ipcsyslog_init(void) Line 245  static void ipcsyslog_init(void)
245  /* Write message to shared mem buffer */  /* Write message to shared mem buffer */
246  static void log_to_shmem(const char *msg, int len)  static void log_to_shmem(const char *msg, int len)
247  {  {
  /* Why libc insists on these being rw? */  
  static struct sembuf SMwup[1] = { {1, -1, IPC_NOWAIT} };  
  static struct sembuf SMwdn[3] = { {0, 0}, {1, 0}, {1, +1} };  
   
248   int old_tail, new_tail;   int old_tail, new_tail;
  char *c;  
249    
250   if (semop(s_semid, SMwdn, 3) == -1) {   if (semop(G.s_semid, G.SMwdn, 3) == -1) {
251   bb_perror_msg_and_die("SMwdn");   bb_perror_msg_and_die("SMwdn");
252   }   }
253    
254   /* Circular Buffer Algorithm:   /* Circular Buffer Algorithm:
255   * --------------------------   * --------------------------
256   * tail == position where to store next syslog message.   * tail == position where to store next syslog message.
257   * head == position of next message to retrieve ("print").   * tail's max value is (shbuf->size - 1)
258   * if head == tail, there is no "unprinted" messages left.   * Last byte of buffer is never used and remains NUL.
  * head is typically advanced by separate "reader" program,  
  * but if there isn't one, we have to do it ourself.  
  * messages are NUL-separated.  
259   */   */
260   len++; /* length with NUL included */   len++; /* length with NUL included */
261   again:   again:
262   old_tail = shbuf->tail;   old_tail = G.shbuf->tail;
263   new_tail = old_tail + len;   new_tail = old_tail + len;
264   if (new_tail < shbuf->size) {   if (new_tail < G.shbuf->size) {
  /* No need to move head if shbuf->head <= old_tail,  
  * else... */  
  if (old_tail < shbuf->head && shbuf->head <= new_tail) {  
  /* ...need to move head forward */  
  c = memchr(shbuf->data + new_tail, '\0',  
    shbuf->size - new_tail);  
  if (!c) /* no NUL ahead of us, wrap around */  
  c = memchr(shbuf->data, '\0', old_tail);  
  if (!c) { /* still nothing? point to this msg... */  
  shbuf->head = old_tail;  
  } else {  
  /* convert pointer to offset + skip NUL */  
  shbuf->head = c - shbuf->data + 1;  
  }  
  }  
265   /* store message, set new tail */   /* store message, set new tail */
266   memcpy(shbuf->data + old_tail, msg, len);   memcpy(G.shbuf->data + old_tail, msg, len);
267   shbuf->tail = new_tail;   G.shbuf->tail = new_tail;
268   } else {   } else {
  /* we need to break up the message and wrap it around */  
269   /* k == available buffer space ahead of old tail */   /* k == available buffer space ahead of old tail */
270   int k = shbuf->size - old_tail - 1;   int k = G.shbuf->size - old_tail;
  if (shbuf->head > old_tail) {  
  /* we are going to overwrite head, need to  
  * move it out of the way */  
  c = memchr(shbuf->data, '\0', old_tail);  
  if (!c) { /* nothing? point to this msg... */  
  shbuf->head = old_tail;  
  } else { /* convert pointer to offset + skip NUL */  
  shbuf->head = c - shbuf->data + 1;  
  }  
  }  
271   /* copy what fits to the end of buffer, and repeat */   /* copy what fits to the end of buffer, and repeat */
272   memcpy(shbuf->data + old_tail, msg, k);   memcpy(G.shbuf->data + old_tail, msg, k);
273   msg += k;   msg += k;
274   len -= k;   len -= k;
275   shbuf->tail = 0;   G.shbuf->tail = 0;
276   goto again;   goto again;
277   }   }
278   if (semop(s_semid, SMwup, 1) == -1) {   if (semop(G.s_semid, G.SMwup, 1) == -1) {
279   bb_perror_msg_and_die("SMwup");   bb_perror_msg_and_die("SMwup");
280   }   }
281   if (DEBUG)   if (DEBUG)
282   printf("head:%d tail:%d\n", shbuf->head, shbuf->tail);   printf("tail:%d\n", G.shbuf->tail);
283  }  }
284  #else  #else
285  void ipcsyslog_cleanup(void);  void ipcsyslog_cleanup(void);
# Line 266  void log_to_shmem(const char *msg); Line 289  void log_to_shmem(const char *msg);
289    
290    
291  /* Print a message to the log file. */  /* Print a message to the log file. */
292  static void log_locally(char *msg)  static void log_locally(time_t now, char *msg)
293  {  {
  static time_t last;  
294   struct flock fl;   struct flock fl;
295   int len = strlen(msg);   int len = strlen(msg);
296    
297  #if ENABLE_FEATURE_IPC_SYSLOG  #if ENABLE_FEATURE_IPC_SYSLOG
298   if ((option_mask32 & OPT_circularlog) && shbuf) {   if ((option_mask32 & OPT_circularlog) && G.shbuf) {
299   log_to_shmem(msg, len);   log_to_shmem(msg, len);
300   return;   return;
301   }   }
302  #endif  #endif
303   if (logFD >= 0) {   if (G.logFD >= 0) {
304   time_t cur;   /* Reopen log file every second. This allows admin
305   time(&cur);   * to delete the file and not worry about restarting us.
306   if (last != cur) {   * This costs almost nothing since it happens
307   last = cur; /* reopen log file every second */   * _at most_ once a second.
308   close(logFD);   */
309     if (!now)
310     now = time(NULL);
311     if (G.last_log_time != now) {
312     G.last_log_time = now;
313     close(G.logFD);
314   goto reopen;   goto reopen;
315   }   }
316   } else {   } else {
317   reopen:   reopen:
318   logFD = device_open(logFilePath, O_WRONLY | O_CREAT   G.logFD = open(G.logFilePath, O_WRONLY | O_CREAT
319   | O_NOCTTY | O_APPEND | O_NONBLOCK);   | O_NOCTTY | O_APPEND | O_NONBLOCK,
320   if (logFD < 0) {   0666);
321     if (G.logFD < 0) {
322   /* cannot open logfile? - print to /dev/console then */   /* cannot open logfile? - print to /dev/console then */
323   int fd = device_open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);   int fd = device_open(DEV_CONSOLE, O_WRONLY | O_NOCTTY | O_NONBLOCK);
324   if (fd < 0)   if (fd < 0)
325   fd = 2; /* then stderr, dammit */   fd = 2; /* then stderr, dammit */
326   full_write(fd, msg, len);   full_write(fd, msg, len);
# Line 302  static void log_locally(char *msg) Line 330  static void log_locally(char *msg)
330   }   }
331  #if ENABLE_FEATURE_ROTATE_LOGFILE  #if ENABLE_FEATURE_ROTATE_LOGFILE
332   {   {
333   struct stat statf;   struct stat statf;
334     G.isRegular = (fstat(G.logFD, &statf) == 0 && S_ISREG(statf.st_mode));
335   isRegular = (fstat(logFD, &statf) == 0 && (statf.st_mode & S_IFREG));   /* bug (mostly harmless): can wrap around if file > 4gb */
336   /* bug (mostly harmless): can wrap around if file > 4gb */   G.curFileSize = statf.st_size;
  curFileSize = statf.st_size;  
337   }   }
338  #endif  #endif
339   }   }
# Line 315  static void log_locally(char *msg) Line 342  static void log_locally(char *msg)
342   fl.l_start = 0;   fl.l_start = 0;
343   fl.l_len = 1;   fl.l_len = 1;
344   fl.l_type = F_WRLCK;   fl.l_type = F_WRLCK;
345   fcntl(logFD, F_SETLKW, &fl);   fcntl(G.logFD, F_SETLKW, &fl);
346    
347  #if ENABLE_FEATURE_ROTATE_LOGFILE  #if ENABLE_FEATURE_ROTATE_LOGFILE
348   if (logFileSize && isRegular && curFileSize > logFileSize) {   if (G.logFileSize && G.isRegular && G.curFileSize > G.logFileSize) {
349   if (logFileRotate) { /* always 0..99 */   if (G.logFileRotate) { /* always 0..99 */
350   int i = strlen(logFilePath) + 3 + 1;   int i = strlen(G.logFilePath) + 3 + 1;
351   char oldFile[i];   char oldFile[i];
352   char newFile[i];   char newFile[i];
353   i = logFileRotate - 1;   i = G.logFileRotate - 1;
354   /* rename: f.8 -> f.9; f.7 -> f.8; ... */   /* rename: f.8 -> f.9; f.7 -> f.8; ... */
355   while (1) {   while (1) {
356   sprintf(newFile, "%s.%d", logFilePath, i);   sprintf(newFile, "%s.%d", G.logFilePath, i);
357   if (i == 0) break;   if (i == 0) break;
358   sprintf(oldFile, "%s.%d", logFilePath, --i);   sprintf(oldFile, "%s.%d", G.logFilePath, --i);
359     /* ignore errors - file might be missing */
360   rename(oldFile, newFile);   rename(oldFile, newFile);
361   }   }
362   /* newFile == "f.0" now */   /* newFile == "f.0" now */
363   rename(logFilePath, newFile);   rename(G.logFilePath, newFile);
364   fl.l_type = F_UNLCK;   fl.l_type = F_UNLCK;
365   fcntl(logFD, F_SETLKW, &fl);   fcntl(G.logFD, F_SETLKW, &fl);
366   close(logFD);   close(G.logFD);
367   goto reopen;   goto reopen;
368   }   }
369   ftruncate(logFD, 0);   ftruncate(G.logFD, 0);
370   }   }
371   curFileSize +=   G.curFileSize +=
372  #endif  #endif
373                  full_write(logFD, msg, len);   full_write(G.logFD, msg, len);
374   fl.l_type = F_UNLCK;   fl.l_type = F_UNLCK;
375   fcntl(logFD, F_SETLKW, &fl);   fcntl(G.logFD, F_SETLKW, &fl);
376  }  }
377    
378  static void parse_fac_prio_20(int pri, char *res20)  static void parse_fac_prio_20(int pri, char *res20)
379  {  {
380   CODE *c_pri, *c_fac;   const CODE *c_pri, *c_fac;
381    
382   if (pri != 0) {   if (pri != 0) {
383   c_fac = facilitynames;   c_fac = facilitynames;
384   while (c_fac->c_name) {   while (c_fac->c_name) {
385   if (c_fac->c_val != (LOG_FAC(pri) << 3)) {   if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
386   c_fac++; continue;   c_fac++;
387     continue;
388   }   }
389   /* facility is found, look for prio */   /* facility is found, look for prio */
390   c_pri = prioritynames;   c_pri = prioritynames;
391   while (c_pri->c_name) {   while (c_pri->c_name) {
392   if (c_pri->c_val != LOG_PRI(pri)) {   if (c_pri->c_val != LOG_PRI(pri)) {
393   c_pri++; continue;   c_pri++;
394     continue;
395   }   }
396   snprintf(res20, 20, "%s.%s",   snprintf(res20, 20, "%s.%s",
397   c_fac->c_name, c_pri->c_name);   c_fac->c_name, c_pri->c_name);
# Line 375  static void parse_fac_prio_20(int pri, c Line 405  static void parse_fac_prio_20(int pri, c
405  }  }
406    
407  /* len parameter is used only for "is there a timestamp?" check.  /* len parameter is used only for "is there a timestamp?" check.
408   * NB: some callers cheat and supply 0 when they know   * NB: some callers cheat and supply len==0 when they know
409   * that there is no timestamp, short-cutting the test. */   * that there is no timestamp, short-circuiting the test. */
410  static void timestamp_and_log(int pri, char *msg, int len)  static void timestamp_and_log(int pri, char *msg, int len)
411  {  {
412   char *timestamp;   char *timestamp;
413     time_t now;
414    
415   if (len < 16 || msg[3] != ' ' || msg[6] != ' '   if (len < 16 || msg[3] != ' ' || msg[6] != ' '
416   || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '   || msg[9] != ':' || msg[12] != ':' || msg[15] != ' '
417   ) {   ) {
  time_t now;  
418   time(&now);   time(&now);
419   timestamp = ctime(&now) + 4;   timestamp = ctime(&now) + 4; /* skip day of week */
420   } else {   } else {
421     now = 0;
422   timestamp = msg;   timestamp = msg;
423   msg += 16;   msg += 16;
424   }   }
425   timestamp[15] = '\0';   timestamp[15] = '\0';
426    
427   /* Log message locally (to file or shared mem) */   if (option_mask32 & OPT_small)
428   if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {   sprintf(G.printbuf, "%s %s\n", timestamp, msg);
429   if (LOG_PRI(pri) < logLevel) {   else {
430   if (option_mask32 & OPT_small)   char res[20];
431   sprintf(PRINTBUF, "%s %s\n", timestamp, msg);   parse_fac_prio_20(pri, res);
432   else {   sprintf(G.printbuf, "%s %.64s %s %s\n", timestamp, G.hostname, res, msg);
  char res[20];  
  parse_fac_prio_20(pri, res);  
  sprintf(PRINTBUF, "%s %s %s %s\n", timestamp, localHostName, res, msg);  
  }  
  log_locally(PRINTBUF);  
  }  
433   }   }
434    
435     /* Log message locally (to file or shared mem) */
436     log_locally(now, G.printbuf);
437  }  }
438    
439    static void timestamp_and_log_internal(const char *msg)
440    {
441     if (ENABLE_FEATURE_REMOTE_LOG && !(option_mask32 & OPT_locallog))
442     return;
443     timestamp_and_log(LOG_SYSLOG | LOG_INFO, (char*)msg, 0);
444    }
445    
446    /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
447     * embedded NULs. Split messages on each of these NULs, parse prio,
448     * escape control chars and log each locally. */
449  static void split_escape_and_log(char *tmpbuf, int len)  static void split_escape_and_log(char *tmpbuf, int len)
450  {  {
451   char *p = tmpbuf;   char *p = tmpbuf;
# Line 415  static void split_escape_and_log(char *t Line 453  static void split_escape_and_log(char *t
453   tmpbuf += len;   tmpbuf += len;
454   while (p < tmpbuf) {   while (p < tmpbuf) {
455   char c;   char c;
456   char *q = PARSEBUF;   char *q = G.parsebuf;
457   int pri = (LOG_USER | LOG_NOTICE);   int pri = (LOG_USER | LOG_NOTICE);
458    
459   if (*p == '<') {   if (*p == '<') {
460   /* Parse the magic priority number */   /* Parse the magic priority number */
461   pri = bb_strtou(p + 1, &p, 10);   pri = bb_strtou(p + 1, &p, 10);
462   if (*p == '>') p++;   if (*p == '>')
463   if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) {   p++;
464     if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
465   pri = (LOG_USER | LOG_NOTICE);   pri = (LOG_USER | LOG_NOTICE);
  }  
466   }   }
467    
468   while ((c = *p++)) {   while ((c = *p++)) {
469   if (c == '\n')   if (c == '\n')
470   c = ' ';   c = ' ';
471   if (!(c & ~0x1f)) {   if (!(c & ~0x1f) && c != '\t') {
472   *q++ = '^';   *q++ = '^';
473   c += '@'; /* ^@, ^A, ^B... */   c += '@'; /* ^@, ^A, ^B... */
474   }   }
475   *q++ = c;   *q++ = c;
476   }   }
477   *q = '\0';   *q = '\0';
478    
479   /* Now log it */   /* Now log it */
480   timestamp_and_log(pri, PARSEBUF, q - PARSEBUF);   if (LOG_PRI(pri) < G.logLevel)
481     timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
482   }   }
483  }  }
484    
485  static void quit_signal(int sig)  static void quit_signal(int sig)
486  {  {
487   timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd exiting", 0);   timestamp_and_log_internal("syslogd exiting");
488   puts("syslogd exiting");   puts("syslogd exiting");
  unlink(dev_log_name);  
489   if (ENABLE_FEATURE_IPC_SYSLOG)   if (ENABLE_FEATURE_IPC_SYSLOG)
490   ipcsyslog_cleanup();   ipcsyslog_cleanup();
491   exit(1);   kill_myself_with_sig(sig);
492  }  }
493    
494    #ifdef SYSLOGD_MARK
495  static void do_mark(int sig)  static void do_mark(int sig)
496  {  {
497   if (markInterval) {   if (G.markInterval) {
498   timestamp_and_log(LOG_SYSLOG | LOG_INFO, "-- MARK --", 0);   timestamp_and_log_internal("-- MARK --");
499   alarm(markInterval);   alarm(G.markInterval);
500   }   }
501  }  }
502    #endif
503    
504  static void do_syslogd(void) ATTRIBUTE_NORETURN;  /* Don't inline: prevent struct sockaddr_un to take up space on stack
505  static void do_syslogd(void)   * permanently */
506    static NOINLINE int create_socket(void)
507  {  {
508   struct sockaddr_un sunx;   struct sockaddr_un sunx;
  socklen_t addr_len;  
509   int sock_fd;   int sock_fd;
510   fd_set fds;   char *dev_log_name;
   
  /* Set up signal handlers */  
  signal(SIGINT, quit_signal);  
  signal(SIGTERM, quit_signal);  
  signal(SIGQUIT, quit_signal);  
  signal(SIGHUP, SIG_IGN);  
  signal(SIGCHLD, SIG_IGN);  
 #ifdef SIGCLD  
  signal(SIGCLD, SIG_IGN);  
 #endif  
  signal(SIGALRM, do_mark);  
  alarm(markInterval);  
   
  dev_log_name = xmalloc_realpath(_PATH_LOG);  
  if (!dev_log_name)  
  dev_log_name = _PATH_LOG;  
   
  /* Unlink old /dev/log (or object it points to) */  
  unlink(dev_log_name);  
511    
512   memset(&sunx, 0, sizeof(sunx));   memset(&sunx, 0, sizeof(sunx));
513   sunx.sun_family = AF_UNIX;   sunx.sun_family = AF_UNIX;
514   strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));  
515     /* Unlink old /dev/log or object it points to. */
516     /* (if it exists, bind will fail) */
517     strcpy(sunx.sun_path, "/dev/log");
518     dev_log_name = xmalloc_follow_symlinks("/dev/log");
519     if (dev_log_name) {
520     safe_strncpy(sunx.sun_path, dev_log_name, sizeof(sunx.sun_path));
521     free(dev_log_name);
522     }
523     unlink(sunx.sun_path);
524    
525   sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);   sock_fd = xsocket(AF_UNIX, SOCK_DGRAM, 0);
526   addr_len = sizeof(sunx.sun_family) + strlen(sunx.sun_path);   xbind(sock_fd, (struct sockaddr *) &sunx, sizeof(sunx));
527   xbind(sock_fd, (struct sockaddr *) &sunx, addr_len);   chmod("/dev/log", 0666);
528    
529     return sock_fd;
530    }
531    
532    #if ENABLE_FEATURE_REMOTE_LOG
533    static int try_to_resolve_remote(void)
534    {
535     if (!G.remoteAddr) {
536     unsigned now = monotonic_sec();
537    
538   if (chmod(dev_log_name, 0666) < 0) {   /* Don't resolve name too often - DNS timeouts can be big */
539   bb_perror_msg_and_die("cannot set permission on %s", dev_log_name);   if ((now - G.last_dns_resolve) < DNS_WAIT_SEC)
540     return -1;
541     G.last_dns_resolve = now;
542     G.remoteAddr = host2sockaddr(G.remoteAddrStr, 514);
543     if (!G.remoteAddr)
544     return -1;
545   }   }
546     return socket(G.remoteAddr->u.sa.sa_family, SOCK_DGRAM, 0);
547    }
548    #endif
549    
550    static void do_syslogd(void) NORETURN;
551    static void do_syslogd(void)
552    {
553     int sock_fd;
554    #if ENABLE_FEATURE_SYSLOGD_DUP
555     int last_sz = -1;
556     char *last_buf;
557     char *recvbuf = G.recvbuf;
558    #else
559    #define recvbuf (G.recvbuf)
560    #endif
561    
562     /* Set up signal handlers */
563     bb_signals(0
564     + (1 << SIGINT)
565     + (1 << SIGTERM)
566     + (1 << SIGQUIT)
567     , quit_signal);
568     signal(SIGHUP, SIG_IGN);
569     /* signal(SIGCHLD, SIG_IGN); - why? */
570    #ifdef SYSLOGD_MARK
571     signal(SIGALRM, do_mark);
572     alarm(G.markInterval);
573    #endif
574     sock_fd = create_socket();
575    
576   if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {   if (ENABLE_FEATURE_IPC_SYSLOG && (option_mask32 & OPT_circularlog)) {
577   ipcsyslog_init();   ipcsyslog_init();
578   }   }
579    
580   timestamp_and_log(LOG_SYSLOG | LOG_INFO, "syslogd started: BusyBox v" BB_VER, 0);   timestamp_and_log_internal("syslogd started: BusyBox v" BB_VER);
581    
582   for (;;) {   for (;;) {
583   FD_ZERO(&fds);   ssize_t sz;
  FD_SET(sock_fd, &fds);  
584    
585   if (select(sock_fd + 1, &fds, NULL, NULL, NULL) < 0) {  #if ENABLE_FEATURE_SYSLOGD_DUP
586   if (errno == EINTR) {   last_buf = recvbuf;
587   /* alarm may have happened */   if (recvbuf == G.recvbuf)
588     recvbuf = G.recvbuf + MAX_READ;
589     else
590     recvbuf = G.recvbuf;
591    #endif
592     read_again:
593     sz = safe_read(sock_fd, recvbuf, MAX_READ - 1);
594     if (sz < 0)
595     bb_perror_msg_and_die("read from /dev/log");
596    
597     /* Drop trailing '\n' and NULs (typically there is one NUL) */
598     while (1) {
599     if (sz == 0)
600     goto read_again;
601     /* man 3 syslog says: "A trailing newline is added when needed".
602     * However, neither glibc nor uclibc do this:
603     * syslog(prio, "test")   sends "test\0" to /dev/log,
604     * syslog(prio, "test\n") sends "test\n\0".
605     * IOW: newline is passed verbatim!
606     * I take it to mean that it's syslogd's job
607     * to make those look identical in the log files. */
608     if (recvbuf[sz-1] != '\0' && recvbuf[sz-1] != '\n')
609     break;
610     sz--;
611     }
612    #if ENABLE_FEATURE_SYSLOGD_DUP
613     if ((option_mask32 & OPT_dup) && (sz == last_sz))
614     if (memcmp(last_buf, recvbuf, sz) == 0)
615   continue;   continue;
616   }   last_sz = sz;
617   bb_perror_msg_and_die("select");  #endif
  }  
   
  if (FD_ISSET(sock_fd, &fds)) {  
  int i;  
  i = recv(sock_fd, RECVBUF, MAX_READ - 1, 0);  
  if (i <= 0)  
  bb_perror_msg_and_die("UNIX socket error");  
  /* TODO: maybe suppress duplicates? */  
618  #if ENABLE_FEATURE_REMOTE_LOG  #if ENABLE_FEATURE_REMOTE_LOG
619   /* We are not modifying log messages in any way before send */   /* We are not modifying log messages in any way before send */
620   /* Remote site cannot trust _us_ anyway and need to do validation again */   /* Remote site cannot trust _us_ anyway and need to do validation again */
621   if (remoteAddr) {   if (G.remoteAddrStr) {
622   if (-1 == remoteFD) {   if (-1 == G.remoteFD) {
623   remoteFD = socket(remoteAddr->sa.sa_family, SOCK_DGRAM, 0);   G.remoteFD = try_to_resolve_remote();
624   }   if (-1 == G.remoteFD)
625   if (-1 != remoteFD) {   goto no_luck;
  /* send message to remote logger, ignore possible error */  
  sendto(remoteFD, RECVBUF, i, MSG_DONTWAIT,  
  &remoteAddr->sa, remoteAddr->len);  
  }  
626   }   }
627  #endif   /* Stock syslogd sends it '\n'-terminated
628   RECVBUF[i] = '\0';   * over network, mimic that */
629   split_escape_and_log(RECVBUF, i);   recvbuf[sz] = '\n';
630   } /* FD_ISSET() */   /* send message to remote logger, ignore possible error */
631   } /* for */   /* TODO: on some errors, close and set G.remoteFD to -1
632     * so that DNS resolution and connect is retried? */
633     sendto(G.remoteFD, recvbuf, sz+1, MSG_DONTWAIT,
634        &G.remoteAddr->u.sa, G.remoteAddr->len);
635     no_luck: ;
636     }
637    #endif
638     if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
639     recvbuf[sz] = '\0'; /* ensure it *is* NUL terminated */
640     split_escape_and_log(recvbuf, sz);
641     }
642     } /* for (;;) */
643    #undef recvbuf
644  }  }
645    
646  int syslogd_main(int argc, char **argv)  int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
647    int syslogd_main(int argc UNUSED_PARAM, char **argv)
648  {  {
649   char OPTION_DECL;   char OPTION_DECL;
650   char *p;  
651     INIT_G();
652    #if ENABLE_FEATURE_REMOTE_LOG
653     G.last_dns_resolve = monotonic_sec() - DNS_WAIT_SEC - 1;
654    #endif
655    
656   /* do normal option parsing */   /* do normal option parsing */
657   opt_complementary = "=0"; /* no non-option params */   opt_complementary = "=0"; /* no non-option params */
658   getopt32(argc, argv, OPTION_STR, OPTION_PARAM);   getopt32(argv, OPTION_STR, OPTION_PARAM);
659    #ifdef SYSLOGD_MARK
660   if (option_mask32 & OPT_mark) // -m   if (option_mask32 & OPT_mark) // -m
661   markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;   G.markInterval = xatou_range(opt_m, 0, INT_MAX/60) * 60;
662    #endif
663   //if (option_mask32 & OPT_nofork) // -n   //if (option_mask32 & OPT_nofork) // -n
664   //if (option_mask32 & OPT_outfile) // -O   //if (option_mask32 & OPT_outfile) // -O
665   if (option_mask32 & OPT_loglevel) // -l   if (option_mask32 & OPT_loglevel) // -l
666   logLevel = xatou_range(opt_l, 1, 8);   G.logLevel = xatou_range(opt_l, 1, 8);
667   //if (option_mask32 & OPT_small) // -S   //if (option_mask32 & OPT_small) // -S
668  #if ENABLE_FEATURE_ROTATE_LOGFILE  #if ENABLE_FEATURE_ROTATE_LOGFILE
669   if (option_mask32 & OPT_filesize) // -s   if (option_mask32 & OPT_filesize) // -s
670   logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;   G.logFileSize = xatou_range(opt_s, 0, INT_MAX/1024) * 1024;
671   if (option_mask32 & OPT_rotatecnt) // -b   if (option_mask32 & OPT_rotatecnt) // -b
672   logFileRotate = xatou_range(opt_b, 0, 99);   G.logFileRotate = xatou_range(opt_b, 0, 99);
 #endif  
 #if ENABLE_FEATURE_REMOTE_LOG  
  if (option_mask32 & OPT_remotelog) { // -R  
  remoteAddr = host2sockaddr(opt_R, 514);  
  }  
  //if (option_mask32 & OPT_locallog) // -L  
673  #endif  #endif
674  #if ENABLE_FEATURE_IPC_SYSLOG  #if ENABLE_FEATURE_IPC_SYSLOG
675   if (opt_C) // -Cn   if (opt_C) // -Cn
676   shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;   G.shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024;
677  #endif  #endif
678    
679   /* If they have not specified remote logging, then log locally */   /* If they have not specified remote logging, then log locally */
# Line 578  int syslogd_main(int argc, char **argv) Line 681  int syslogd_main(int argc, char **argv)
681   option_mask32 |= OPT_locallog;   option_mask32 |= OPT_locallog;
682    
683   /* Store away localhost's name before the fork */   /* Store away localhost's name before the fork */
684   gethostname(localHostName, sizeof(localHostName));   G.hostname = safe_gethostname();
685   p = strchr(localHostName, '.');   *strchrnul(G.hostname, '.') = '\0';
  if (p) {  
  *p = '\0';  
  }  
686    
687   if (!(option_mask32 & OPT_nofork)) {   if (!(option_mask32 & OPT_nofork)) {
688  #ifdef BB_NOMMU   bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
  vfork_daemon_rexec(0, 1, argc, argv, "-n");  
 #else  
  bb_daemonize();  
 #endif  
689   }   }
690   umask(0);   umask(0);
691     write_pidfile("/var/run/syslogd.pid");
692   do_syslogd();   do_syslogd();
693   /* return EXIT_SUCCESS; */   /* return EXIT_SUCCESS; */
694  }  }
695    
696    /* Clean up. Needed because we are included from syslogd_and_logger.c */
697    #undef G
698    #undef GLOBALS
699    #undef INIT_G
700    #undef OPTION_STR
701    #undef OPTION_DECL
702    #undef OPTION_PARAM

Legend:
Removed from v.532  
changed lines
  Added in v.816