syslogd.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini syslogd implementation for busybox
  4. *
  5. * Copyright (C) 1999,2000 by Lineo, inc. and Erik Andersen
  6. * Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
  7. *
  8. * Copyright (C) 2000 by Karl M. Hegbloom <karlheg@debian.org>
  9. *
  10. * "circular buffer" Copyright (C) 2001 by Gennady Feldman <gfeldman@cachier.com>
  11. *
  12. * Maintainer: Gennady Feldman <gena01@cachier.com> as of Mar 12, 2001
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 2 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  22. * General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program; if not, write to the Free Software
  26. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  27. *
  28. */
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <ctype.h>
  32. #include <errno.h>
  33. #include <fcntl.h>
  34. #include <netdb.h>
  35. #include <paths.h>
  36. #include <signal.h>
  37. #include <stdarg.h>
  38. #include <time.h>
  39. #include <string.h>
  40. #include <unistd.h>
  41. #include <sys/socket.h>
  42. #include <sys/types.h>
  43. #include <sys/un.h>
  44. #include <sys/param.h>
  45. #include "busybox.h"
  46. /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
  47. #define SYSLOG_NAMES
  48. #include <sys/syslog.h>
  49. #include <sys/uio.h>
  50. /* Path for the file where all log messages are written */
  51. #define __LOG_FILE "/var/log/messages"
  52. /* Path to the unix socket */
  53. static char lfile[MAXPATHLEN];
  54. static char *logFilePath = __LOG_FILE;
  55. /* interval between marks in seconds */
  56. static int MarkInterval = 20 * 60;
  57. /* localhost's name */
  58. static char LocalHostName[64];
  59. #ifdef BB_FEATURE_REMOTE_LOG
  60. #include <netinet/in.h>
  61. /* udp socket for logging to remote host */
  62. static int remotefd = -1;
  63. /* where do we log? */
  64. static char *RemoteHost;
  65. /* what port to log to? */
  66. static int RemotePort = 514;
  67. /* To remote log or not to remote log, that is the question. */
  68. static int doRemoteLog = FALSE;
  69. static int local_logging = FALSE;
  70. #endif
  71. #define MAXLINE 1024 /* maximum line length */
  72. /* circular buffer variables/structures */
  73. #ifdef BB_FEATURE_IPC_SYSLOG
  74. #if __GNU_LIBRARY__ < 5
  75. #error Sorry. Looks like you are using libc5.
  76. #error libc5 shm support isnt good enough.
  77. #error Please disable BB_FEATURE_IPC_SYSLOG
  78. #endif
  79. #include <sys/ipc.h>
  80. #include <sys/sem.h>
  81. #include <sys/shm.h>
  82. /* our shared key */
  83. static const long KEY_ID = 0x414e4547; /*"GENA"*/
  84. // Semaphore operation structures
  85. static struct shbuf_ds {
  86. int size; // size of data written
  87. int head; // start of message list
  88. int tail; // end of message list
  89. char data[1]; // data/messages
  90. } *buf = NULL; // shared memory pointer
  91. static struct sembuf SMwup[1] = {{1, -1, IPC_NOWAIT}}; // set SMwup
  92. static struct sembuf SMwdn[3] = {{0, 0}, {1, 0}, {1, +1}}; // set SMwdn
  93. static int shmid = -1; // ipc shared memory id
  94. static int s_semid = -1; // ipc semaphore id
  95. int data_size = 16000; // data size
  96. int shm_size = 16000 + sizeof(*buf); // our buffer size
  97. static int circular_logging = FALSE;
  98. /*
  99. * sem_up - up()'s a semaphore.
  100. */
  101. static inline void sem_up(int semid)
  102. {
  103. if ( semop(semid, SMwup, 1) == -1 )
  104. perror_msg_and_die("semop[SMwup]");
  105. }
  106. /*
  107. * sem_down - down()'s a semaphore
  108. */
  109. static inline void sem_down(int semid)
  110. {
  111. if ( semop(semid, SMwdn, 3) == -1 )
  112. perror_msg_and_die("semop[SMwdn]");
  113. }
  114. void ipcsyslog_cleanup(void){
  115. printf("Exiting Syslogd!\n");
  116. if (shmid != -1)
  117. shmdt(buf);
  118. if (shmid != -1)
  119. shmctl(shmid, IPC_RMID, NULL);
  120. if (s_semid != -1)
  121. semctl(s_semid, 0, IPC_RMID, 0);
  122. }
  123. void ipcsyslog_init(void){
  124. if (buf == NULL){
  125. if ((shmid = shmget(KEY_ID, shm_size, IPC_CREAT | 1023)) == -1)
  126. perror_msg_and_die("shmget");
  127. if ((buf = shmat(shmid, NULL, 0)) == NULL)
  128. perror_msg_and_die("shmat");
  129. buf->size=data_size;
  130. buf->head=buf->tail=0;
  131. // we'll trust the OS to set initial semval to 0 (let's hope)
  132. if ((s_semid = semget(KEY_ID, 2, IPC_CREAT | IPC_EXCL | 1023)) == -1){
  133. if (errno == EEXIST){
  134. if ((s_semid = semget(KEY_ID, 2, 0)) == -1)
  135. perror_msg_and_die("semget");
  136. }else
  137. perror_msg_and_die("semget");
  138. }
  139. }else{
  140. printf("Buffer already allocated just grab the semaphore?");
  141. }
  142. }
  143. /* write message to buffer */
  144. void circ_message(const char *msg){
  145. int l=strlen(msg)+1; /* count the whole message w/ '\0' included */
  146. sem_down(s_semid);
  147. /*
  148. * Circular Buffer Algorithm:
  149. * --------------------------
  150. *
  151. * Start-off w/ empty buffer of specific size SHM_SIZ
  152. * Start filling it up w/ messages. I use '\0' as separator to break up messages.
  153. * This is also very handy since we can do printf on message.
  154. *
  155. * Once the buffer is full we need to get rid of the first message in buffer and
  156. * insert the new message. (Note: if the message being added is >1 message then
  157. * we will need to "remove" >1 old message from the buffer). The way this is done
  158. * is the following:
  159. * When we reach the end of the buffer we set a mark and start from the beginning.
  160. * Now what about the beginning and end of the buffer? Well we have the "head"
  161. * index/pointer which is the starting point for the messages and we have "tail"
  162. * index/pointer which is the ending point for the messages. When we "display" the
  163. * messages we start from the beginning and continue until we reach "tail". If we
  164. * reach end of buffer, then we just start from the beginning (offset 0). "head" and
  165. * "tail" are actually offsets from the beginning of the buffer.
  166. *
  167. * Note: This algorithm uses Linux IPC mechanism w/ shared memory and semaphores to provide
  168. * a threasafe way of handling shared memory operations.
  169. */
  170. if ( (buf->tail + l) < buf->size ){
  171. /* before we append the message we need to check the HEAD so that we won't
  172. overwrite any of the message that we still need and adjust HEAD to point
  173. to the next message! */
  174. if ( buf->tail < buf->head){
  175. if ( (buf->tail + l) >= buf->head ){
  176. /* we need to move the HEAD to point to the next message
  177. * Theoretically we have enough room to add the whole message to the
  178. * buffer, because of the first outer IF statement, so we don't have
  179. * to worry about overflows here!
  180. */
  181. int k= buf->tail + l - buf->head; /* we need to know how many bytes
  182. we are overwriting to make
  183. enough room */
  184. char *c=memchr(buf->data+buf->head + k,'\0',buf->size - (buf->head + k));
  185. if (c != NULL) {/* do a sanity check just in case! */
  186. buf->head = c - buf->data + 1; /* we need to convert pointer to
  187. offset + skip the '\0' since
  188. we need to point to the beginning
  189. of the next message */
  190. /* Note: HEAD is only used to "retrieve" messages, it's not used
  191. when writing messages into our buffer */
  192. }else{ /* show an error message to know we messed up? */
  193. printf("Weird! Can't find the terminator token??? \n");
  194. buf->head=0;
  195. }
  196. }
  197. } /* in other cases no overflows have been done yet, so we don't care! */
  198. /* we should be ok to append the message now */
  199. strncpy(buf->data + buf->tail,msg,l); /* append our message */
  200. buf->tail+=l; /* count full message w/ '\0' terminating char */
  201. }else{
  202. /* we need to break up the message and "circle" it around */
  203. char *c;
  204. int k=buf->tail + l - buf->size; /* count # of bytes we don't fit */
  205. /* We need to move HEAD! This is always the case since we are going
  206. * to "circle" the message.
  207. */
  208. c=memchr(buf->data + k ,'\0', buf->size - k);
  209. if (c != NULL) /* if we don't have '\0'??? weird!!! */{
  210. /* move head pointer*/
  211. buf->head=c-buf->data+1;
  212. /* now write the first part of the message */
  213. strncpy(buf->data + buf->tail, msg, l - k - 1);
  214. /* ALWAYS terminate end of buffer w/ '\0' */
  215. buf->data[buf->size-1]='\0';
  216. /* now write out the rest of the string to the beginning of the buffer */
  217. strcpy(buf->data, &msg[l-k-1]);
  218. /* we need to place the TAIL at the end of the message */
  219. buf->tail = k + 1;
  220. }else{
  221. printf("Weird! Can't find the terminator token from the beginning??? \n");
  222. buf->head = buf->tail = 0; /* reset buffer, since it's probably corrupted */
  223. }
  224. }
  225. sem_up(s_semid);
  226. }
  227. #endif /* BB_FEATURE_IPC_SYSLOG */
  228. /* Note: There is also a function called "message()" in init.c */
  229. /* Print a message to the log file. */
  230. static void message (char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
  231. static void message (char *fmt, ...)
  232. {
  233. int fd;
  234. struct flock fl;
  235. va_list arguments;
  236. fl.l_whence = SEEK_SET;
  237. fl.l_start = 0;
  238. fl.l_len = 1;
  239. #ifdef BB_FEATURE_IPC_SYSLOG
  240. if ((circular_logging == TRUE) && (buf != NULL)){
  241. char b[1024];
  242. va_start (arguments, fmt);
  243. vsnprintf (b, sizeof(b)-1, fmt, arguments);
  244. va_end (arguments);
  245. circ_message(b);
  246. }else
  247. #endif
  248. if ((fd = device_open (logFilePath,
  249. O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
  250. O_NONBLOCK)) >= 0) {
  251. fl.l_type = F_WRLCK;
  252. fcntl (fd, F_SETLKW, &fl);
  253. va_start (arguments, fmt);
  254. vdprintf (fd, fmt, arguments);
  255. va_end (arguments);
  256. fl.l_type = F_UNLCK;
  257. fcntl (fd, F_SETLKW, &fl);
  258. close (fd);
  259. } else {
  260. /* Always send console messages to /dev/console so people will see them. */
  261. if ((fd = device_open (_PATH_CONSOLE,
  262. O_WRONLY | O_NOCTTY | O_NONBLOCK)) >= 0) {
  263. va_start (arguments, fmt);
  264. vdprintf (fd, fmt, arguments);
  265. va_end (arguments);
  266. close (fd);
  267. } else {
  268. fprintf (stderr, "Bummer, can't print: ");
  269. va_start (arguments, fmt);
  270. vfprintf (stderr, fmt, arguments);
  271. fflush (stderr);
  272. va_end (arguments);
  273. }
  274. }
  275. }
  276. static void logMessage (int pri, char *msg)
  277. {
  278. time_t now;
  279. char *timestamp;
  280. static char res[20] = "";
  281. CODE *c_pri, *c_fac;
  282. if (pri != 0) {
  283. for (c_fac = facilitynames;
  284. c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
  285. for (c_pri = prioritynames;
  286. c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
  287. if (c_fac->c_name == NULL || c_pri->c_name == NULL)
  288. snprintf(res, sizeof(res), "<%d>", pri);
  289. else
  290. snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
  291. }
  292. if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
  293. msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
  294. time(&now);
  295. timestamp = ctime(&now) + 4;
  296. timestamp[15] = '\0';
  297. } else {
  298. timestamp = msg;
  299. timestamp[15] = '\0';
  300. msg += 16;
  301. }
  302. /* todo: supress duplicates */
  303. #ifdef BB_FEATURE_REMOTE_LOG
  304. /* send message to remote logger */
  305. if ( -1 != remotefd){
  306. static const int IOV_COUNT = 2;
  307. struct iovec iov[IOV_COUNT];
  308. struct iovec *v = iov;
  309. memset(&res, 0, sizeof(res));
  310. snprintf(res, sizeof(res), "<%d>", pri);
  311. v->iov_base = res ;
  312. v->iov_len = strlen(res);
  313. v++;
  314. v->iov_base = msg;
  315. v->iov_len = strlen(msg);
  316. writev_retry:
  317. if ( -1 == writev(remotefd,iov, IOV_COUNT)){
  318. if (errno == EINTR) goto writev_retry;
  319. error_msg_and_die("cannot write to remote file handle on"
  320. "%s:%d",RemoteHost,RemotePort);
  321. }
  322. }
  323. if (local_logging == TRUE)
  324. #endif
  325. /* now spew out the message to wherever it is supposed to go */
  326. message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
  327. }
  328. static void quit_signal(int sig)
  329. {
  330. logMessage(LOG_SYSLOG | LOG_INFO, "System log daemon exiting.");
  331. unlink(lfile);
  332. #ifdef BB_FEATURE_IPC_SYSLOG
  333. ipcsyslog_cleanup();
  334. #endif
  335. exit(TRUE);
  336. }
  337. static void domark(int sig)
  338. {
  339. if (MarkInterval > 0) {
  340. logMessage(LOG_SYSLOG | LOG_INFO, "-- MARK --");
  341. alarm(MarkInterval);
  342. }
  343. }
  344. /* This must be a #define, since when DODEBUG and BUFFERS_GO_IN_BSS are
  345. * enabled, we otherwise get a "storage size isn't constant error. */
  346. static int serveConnection (char* tmpbuf, int n_read)
  347. {
  348. char *p = tmpbuf;
  349. while (p < tmpbuf + n_read) {
  350. int pri = (LOG_USER | LOG_NOTICE);
  351. int num_lt = 0;
  352. char line[ MAXLINE + 1 ];
  353. unsigned char c;
  354. char *q = line;
  355. while ( (c = *p) && q < &line[ sizeof (line) - 1 ]) {
  356. if (c == '<' && num_lt == 0) {
  357. /* Parse the magic priority number. */
  358. num_lt++;
  359. pri = 0;
  360. while (isdigit (*(++p))) {
  361. pri = 10 * pri + (*p - '0');
  362. }
  363. if (pri & ~(LOG_FACMASK | LOG_PRIMASK)){
  364. pri = (LOG_USER | LOG_NOTICE);
  365. }
  366. } else if (c == '\n') {
  367. *q++ = ' ';
  368. } else if (iscntrl (c) && (c < 0177)) {
  369. *q++ = '^';
  370. *q++ = c ^ 0100;
  371. } else {
  372. *q++ = c;
  373. }
  374. p++;
  375. }
  376. *q = '\0';
  377. p++;
  378. /* Now log it */
  379. logMessage (pri, line);
  380. }
  381. return n_read;
  382. }
  383. #ifdef BB_FEATURE_REMOTE_LOG
  384. static void init_RemoteLog (void)
  385. {
  386. struct sockaddr_in remoteaddr;
  387. struct hostent *hostinfo;
  388. int len = sizeof(remoteaddr);
  389. memset(&remoteaddr, 0, len);
  390. remotefd = socket(AF_INET, SOCK_DGRAM, 0);
  391. if (remotefd < 0) {
  392. error_msg_and_die("cannot create socket");
  393. }
  394. hostinfo = xgethostbyname(RemoteHost);
  395. remoteaddr.sin_family = AF_INET;
  396. remoteaddr.sin_addr = *(struct in_addr *) *hostinfo->h_addr_list;
  397. remoteaddr.sin_port = htons(RemotePort);
  398. /*
  399. Since we are using UDP sockets, connect just sets the default host and port
  400. for future operations
  401. */
  402. if ( 0 != (connect(remotefd, (struct sockaddr *) &remoteaddr, len))){
  403. error_msg_and_die("cannot connect to remote host %s:%d", RemoteHost, RemotePort);
  404. }
  405. }
  406. #endif
  407. static void doSyslogd (void) __attribute__ ((noreturn));
  408. static void doSyslogd (void)
  409. {
  410. struct sockaddr_un sunx;
  411. socklen_t addrLength;
  412. int sock_fd;
  413. fd_set fds;
  414. /* Set up signal handlers. */
  415. signal (SIGINT, quit_signal);
  416. signal (SIGTERM, quit_signal);
  417. signal (SIGQUIT, quit_signal);
  418. signal (SIGHUP, SIG_IGN);
  419. signal (SIGCHLD, SIG_IGN);
  420. #ifdef SIGCLD
  421. signal (SIGCLD, SIG_IGN);
  422. #endif
  423. signal (SIGALRM, domark);
  424. alarm (MarkInterval);
  425. /* Create the syslog file so realpath() can work. */
  426. if (realpath (_PATH_LOG, lfile) != NULL)
  427. unlink (lfile);
  428. memset (&sunx, 0, sizeof (sunx));
  429. sunx.sun_family = AF_UNIX;
  430. strncpy (sunx.sun_path, lfile, sizeof (sunx.sun_path));
  431. if ((sock_fd = socket (AF_UNIX, SOCK_DGRAM, 0)) < 0)
  432. perror_msg_and_die ("Couldn't get file descriptor for socket " _PATH_LOG);
  433. addrLength = sizeof (sunx.sun_family) + strlen (sunx.sun_path);
  434. if (bind(sock_fd, (struct sockaddr *) &sunx, addrLength) < 0)
  435. perror_msg_and_die ("Could not connect to socket " _PATH_LOG);
  436. if (chmod (lfile, 0666) < 0)
  437. perror_msg_and_die ("Could not set permission on " _PATH_LOG);
  438. #ifdef BB_FEATURE_IPC_SYSLOG
  439. if (circular_logging == TRUE ){
  440. ipcsyslog_init();
  441. }
  442. #endif
  443. #ifdef BB_FEATURE_REMOTE_LOG
  444. if (doRemoteLog == TRUE){
  445. init_RemoteLog();
  446. }
  447. #endif
  448. logMessage (LOG_SYSLOG | LOG_INFO, "syslogd started: " BB_BANNER);
  449. for (;;) {
  450. FD_ZERO (&fds);
  451. FD_SET (sock_fd, &fds);
  452. if (select (sock_fd+1, &fds, NULL, NULL, NULL) < 0) {
  453. if (errno == EINTR) {
  454. /* alarm may have happened. */
  455. continue;
  456. }
  457. perror_msg_and_die ("select error");
  458. }
  459. if (FD_ISSET (sock_fd, &fds)) {
  460. int i;
  461. RESERVE_BB_BUFFER(tmpbuf, MAXLINE + 1);
  462. memset(tmpbuf, '\0', MAXLINE+1);
  463. if ( (i = recv(sock_fd, tmpbuf, MAXLINE, 0)) > 0) {
  464. serveConnection(tmpbuf, i);
  465. } else {
  466. perror_msg_and_die ("UNIX socket error");
  467. }
  468. RELEASE_BB_BUFFER (tmpbuf);
  469. }/* FD_ISSET() */
  470. } /* for main loop */
  471. }
  472. extern int syslogd_main(int argc, char **argv)
  473. {
  474. int opt;
  475. #if ! defined(__uClinux__)
  476. int doFork = TRUE;
  477. #endif
  478. char *p;
  479. /* do normal option parsing */
  480. while ((opt = getopt(argc, argv, "m:nO:R:LC")) > 0) {
  481. switch (opt) {
  482. case 'm':
  483. MarkInterval = atoi(optarg) * 60;
  484. break;
  485. #if ! defined(__uClinux__)
  486. case 'n':
  487. doFork = FALSE;
  488. break;
  489. #endif
  490. case 'O':
  491. logFilePath = xstrdup(optarg);
  492. break;
  493. #ifdef BB_FEATURE_REMOTE_LOG
  494. case 'R':
  495. RemoteHost = xstrdup(optarg);
  496. if ( (p = strchr(RemoteHost, ':'))){
  497. RemotePort = atoi(p+1);
  498. *p = '\0';
  499. }
  500. doRemoteLog = TRUE;
  501. break;
  502. case 'L':
  503. local_logging = TRUE;
  504. break;
  505. #endif
  506. #ifdef BB_FEATURE_IPC_SYSLOG
  507. case 'C':
  508. circular_logging = TRUE;
  509. break;
  510. #endif
  511. default:
  512. show_usage();
  513. }
  514. }
  515. #ifdef BB_FEATURE_REMOTE_LOG
  516. /* If they have not specified remote logging, then log locally */
  517. if (doRemoteLog == FALSE)
  518. local_logging = TRUE;
  519. #endif
  520. /* Store away localhost's name before the fork */
  521. gethostname(LocalHostName, sizeof(LocalHostName));
  522. if ((p = strchr(LocalHostName, '.'))) {
  523. *p++ = '\0';
  524. }
  525. umask(0);
  526. #if ! defined(__uClinux__)
  527. if (doFork == TRUE) {
  528. if (daemon(0, 1) < 0)
  529. perror_msg_and_die("daemon");
  530. }
  531. #endif
  532. doSyslogd();
  533. return EXIT_SUCCESS;
  534. }
  535. /*
  536. Local Variables
  537. c-file-style: "linux"
  538. c-basic-offset: 4
  539. tab-width: 4
  540. End:
  541. */