syslog.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (c) 1983, 1988, 1993
  3. * The Regents of the University of California. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 4. Neither the name of the University nor the names of its contributors
  14. * may be used to endorse or promote products derived from this software
  15. * without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  18. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  23. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  24. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  25. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  26. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  27. * SUCH DAMAGE.
  28. */
  29. #if defined(LIBC_SCCS) && !defined(lint)
  30. static char sccsid[] = "@(#)syslog.c 8.4 (Berkeley) 3/18/94";
  31. #endif /* LIBC_SCCS and not lint */
  32. #include <sys/types.h>
  33. #include <sys/socket.h>
  34. #include <sys/syslog.h>
  35. #include <sys/uio.h>
  36. #include <sys/un.h>
  37. #include <netdb.h>
  38. #include <errno.h>
  39. #include <fcntl.h>
  40. #include <paths.h>
  41. #include <stdio.h>
  42. #include <stdio_ext.h>
  43. #include <string.h>
  44. #include <time.h>
  45. #include <unistd.h>
  46. #include <stdlib.h>
  47. #include <libc-lock.h>
  48. #include <signal.h>
  49. #include <locale.h>
  50. #include <stdarg.h>
  51. #include <libio/libioP.h>
  52. #include <math_ldbl_opt.h>
  53. #include <kernel-features.h>
  54. #define ftell(s) _IO_ftell (s)
  55. static int LogType = SOCK_DGRAM; /* type of socket connection */
  56. static int LogFile = -1; /* fd for log */
  57. static int connected; /* have done connect */
  58. static int LogStat; /* status bits, set by openlog() */
  59. static const char *LogTag; /* string to tag the entry with */
  60. static int LogFacility = LOG_USER; /* default facility code */
  61. static int LogMask = 0xff; /* mask of priorities to be logged */
  62. extern char *__progname; /* Program name, from crt0. */
  63. /* Define the lock. */
  64. __libc_lock_define_initialized (static, syslog_lock)
  65. static void openlog_internal(const char *, int, int);
  66. static void closelog_internal(void);
  67. #ifndef NO_SIGPIPE
  68. static void sigpipe_handler (int);
  69. #endif
  70. #ifndef send_flags
  71. # define send_flags 0
  72. #endif
  73. struct cleanup_arg
  74. {
  75. void *buf;
  76. struct sigaction *oldaction;
  77. };
  78. static void
  79. cancel_handler (void *ptr)
  80. {
  81. #ifndef NO_SIGPIPE
  82. /* Restore the old signal handler. */
  83. struct cleanup_arg *clarg = (struct cleanup_arg *) ptr;
  84. if (clarg != NULL && clarg->oldaction != NULL)
  85. __sigaction (SIGPIPE, clarg->oldaction, NULL);
  86. #endif
  87. /* Free the lock. */
  88. __libc_lock_unlock (syslog_lock);
  89. }
  90. /*
  91. * syslog, vsyslog --
  92. * print message on log file; output is intended for syslogd(8).
  93. */
  94. void
  95. __syslog(int pri, const char *fmt, ...)
  96. {
  97. va_list ap;
  98. va_start(ap, fmt);
  99. __vsyslog_internal(pri, fmt, ap, 0);
  100. va_end(ap);
  101. }
  102. ldbl_hidden_def (__syslog, syslog)
  103. ldbl_strong_alias (__syslog, syslog)
  104. void
  105. __vsyslog(int pri, const char *fmt, va_list ap)
  106. {
  107. __vsyslog_internal(pri, fmt, ap, 0);
  108. }
  109. ldbl_weak_alias (__vsyslog, vsyslog)
  110. void
  111. __syslog_chk(int pri, int flag, const char *fmt, ...)
  112. {
  113. va_list ap;
  114. va_start(ap, fmt);
  115. __vsyslog_internal(pri, fmt, ap, (flag > 0) ? PRINTF_FORTIFY : 0);
  116. va_end(ap);
  117. }
  118. void
  119. __vsyslog_chk(int pri, int flag, const char *fmt, va_list ap)
  120. {
  121. __vsyslog_internal(pri, fmt, ap, (flag > 0) ? PRINTF_FORTIFY : 0);
  122. }
  123. void
  124. __vsyslog_internal(int pri, const char *fmt, va_list ap,
  125. unsigned int mode_flags)
  126. {
  127. struct tm now_tm;
  128. time_t now;
  129. int fd;
  130. FILE *f;
  131. char *buf = 0;
  132. size_t bufsize = 0;
  133. size_t msgoff;
  134. #ifndef NO_SIGPIPE
  135. struct sigaction action, oldaction;
  136. int sigpipe;
  137. #endif
  138. int saved_errno = errno;
  139. char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
  140. #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
  141. /* Check for invalid bits. */
  142. if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
  143. syslog(INTERNALLOG,
  144. "syslog: unknown facility/priority: %x", pri);
  145. pri &= LOG_PRIMASK|LOG_FACMASK;
  146. }
  147. /* Check priority against setlogmask values. */
  148. if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
  149. return;
  150. /* Set default facility if none specified. */
  151. if ((pri & LOG_FACMASK) == 0)
  152. pri |= LogFacility;
  153. /* Build the message in a memory-buffer stream. */
  154. f = __open_memstream (&buf, &bufsize);
  155. if (f == NULL)
  156. {
  157. /* We cannot get a stream. There is not much we can do but
  158. emitting an error messages. */
  159. char numbuf[3 * sizeof (pid_t)];
  160. char *nump;
  161. char *endp = __stpcpy (failbuf, "out of memory [");
  162. pid_t pid = __getpid ();
  163. nump = numbuf + sizeof (numbuf);
  164. /* The PID can never be zero. */
  165. do
  166. *--nump = '0' + pid % 10;
  167. while ((pid /= 10) != 0);
  168. endp = __mempcpy (endp, nump, (numbuf + sizeof (numbuf)) - nump);
  169. *endp++ = ']';
  170. *endp = '\0';
  171. buf = failbuf;
  172. bufsize = endp - failbuf;
  173. msgoff = 0;
  174. }
  175. else
  176. {
  177. __fsetlocking (f, FSETLOCKING_BYCALLER);
  178. fprintf (f, "<%d>", pri);
  179. (void) time (&now);
  180. f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
  181. f->_IO_write_end
  182. - f->_IO_write_ptr,
  183. "%h %e %T ",
  184. __localtime_r (&now, &now_tm),
  185. _nl_C_locobj_ptr);
  186. msgoff = ftell (f);
  187. if (LogTag == NULL)
  188. LogTag = __progname;
  189. if (LogTag != NULL)
  190. __fputs_unlocked (LogTag, f);
  191. if (LogStat & LOG_PID)
  192. fprintf (f, "[%d]", (int) __getpid ());
  193. if (LogTag != NULL)
  194. {
  195. __putc_unlocked (':', f);
  196. __putc_unlocked (' ', f);
  197. }
  198. /* Restore errno for %m format. */
  199. __set_errno (saved_errno);
  200. /* We have the header. Print the user's format into the
  201. buffer. */
  202. __vfprintf_internal (f, fmt, ap, mode_flags);
  203. /* Close the memory stream; this will finalize the data
  204. into a malloc'd buffer in BUF. */
  205. fclose (f);
  206. }
  207. /* Output to stderr if requested. */
  208. if (LogStat & LOG_PERROR) {
  209. struct iovec iov[2];
  210. struct iovec *v = iov;
  211. v->iov_base = buf + msgoff;
  212. v->iov_len = bufsize - msgoff;
  213. /* Append a newline if necessary. */
  214. if (buf[bufsize - 1] != '\n')
  215. {
  216. ++v;
  217. v->iov_base = (char *) "\n";
  218. v->iov_len = 1;
  219. }
  220. __libc_cleanup_push (free, buf == failbuf ? NULL : buf);
  221. /* writev is a cancellation point. */
  222. (void)__writev(STDERR_FILENO, iov, v - iov + 1);
  223. __libc_cleanup_pop (0);
  224. }
  225. /* Prepare for multiple users. We have to take care: open and
  226. write are cancellation points. */
  227. struct cleanup_arg clarg;
  228. clarg.buf = buf;
  229. clarg.oldaction = NULL;
  230. __libc_cleanup_push (cancel_handler, &clarg);
  231. __libc_lock_lock (syslog_lock);
  232. #ifndef NO_SIGPIPE
  233. /* Prepare for a broken connection. */
  234. memset (&action, 0, sizeof (action));
  235. action.sa_handler = sigpipe_handler;
  236. sigemptyset (&action.sa_mask);
  237. sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
  238. if (sigpipe == 0)
  239. clarg.oldaction = &oldaction;
  240. #endif
  241. /* Get connected, output the message to the local logger. */
  242. if (!connected)
  243. openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
  244. /* If we have a SOCK_STREAM connection, also send ASCII NUL as
  245. a record terminator. */
  246. if (LogType == SOCK_STREAM)
  247. ++bufsize;
  248. if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
  249. {
  250. if (connected)
  251. {
  252. /* Try to reopen the syslog connection. Maybe it went
  253. down. */
  254. closelog_internal ();
  255. openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
  256. }
  257. if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
  258. {
  259. closelog_internal (); /* attempt re-open next time */
  260. /*
  261. * Output the message to the console; don't worry
  262. * about blocking, if console blocks everything will.
  263. * Make sure the error reported is the one from the
  264. * syslogd failure.
  265. */
  266. if (LogStat & LOG_CONS &&
  267. (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
  268. {
  269. __dprintf (fd, "%s\r\n", buf + msgoff);
  270. (void)__close(fd);
  271. }
  272. }
  273. }
  274. #ifndef NO_SIGPIPE
  275. if (sigpipe == 0)
  276. __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
  277. #endif
  278. /* End of critical section. */
  279. __libc_cleanup_pop (0);
  280. __libc_lock_unlock (syslog_lock);
  281. if (buf != failbuf)
  282. free (buf);
  283. }
  284. static struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
  285. static void
  286. openlog_internal(const char *ident, int logstat, int logfac)
  287. {
  288. if (ident != NULL)
  289. LogTag = ident;
  290. LogStat = logstat;
  291. if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
  292. LogFacility = logfac;
  293. int retry = 0;
  294. while (retry < 2) {
  295. if (LogFile == -1) {
  296. SyslogAddr.sun_family = AF_UNIX;
  297. (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
  298. sizeof(SyslogAddr.sun_path));
  299. if (LogStat & LOG_NDELAY) {
  300. LogFile = __socket(AF_UNIX, LogType | SOCK_CLOEXEC, 0);
  301. if (LogFile == -1)
  302. return;
  303. }
  304. }
  305. if (LogFile != -1 && !connected)
  306. {
  307. int old_errno = errno;
  308. if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
  309. == -1)
  310. {
  311. int saved_errno = errno;
  312. int fd = LogFile;
  313. LogFile = -1;
  314. (void)__close(fd);
  315. __set_errno (old_errno);
  316. if (saved_errno == EPROTOTYPE)
  317. {
  318. /* retry with the other type: */
  319. LogType = (LogType == SOCK_DGRAM
  320. ? SOCK_STREAM : SOCK_DGRAM);
  321. ++retry;
  322. continue;
  323. }
  324. } else
  325. connected = 1;
  326. }
  327. break;
  328. }
  329. }
  330. void
  331. openlog (const char *ident, int logstat, int logfac)
  332. {
  333. /* Protect against multiple users and cancellation. */
  334. __libc_cleanup_push (cancel_handler, NULL);
  335. __libc_lock_lock (syslog_lock);
  336. openlog_internal (ident, logstat, logfac);
  337. __libc_cleanup_pop (1);
  338. }
  339. #ifndef NO_SIGPIPE
  340. static void
  341. sigpipe_handler (int signo)
  342. {
  343. closelog_internal ();
  344. }
  345. #endif
  346. static void
  347. closelog_internal (void)
  348. {
  349. if (!connected)
  350. return;
  351. __close (LogFile);
  352. LogFile = -1;
  353. connected = 0;
  354. }
  355. void
  356. closelog (void)
  357. {
  358. /* Protect against multiple users and cancellation. */
  359. __libc_cleanup_push (cancel_handler, NULL);
  360. __libc_lock_lock (syslog_lock);
  361. closelog_internal ();
  362. LogTag = NULL;
  363. LogType = SOCK_DGRAM; /* this is the default */
  364. /* Free the lock. */
  365. __libc_cleanup_pop (1);
  366. }
  367. /* setlogmask -- set the log mask level */
  368. int
  369. setlogmask (int pmask)
  370. {
  371. int omask;
  372. omask = LogMask;
  373. if (pmask != 0)
  374. LogMask = pmask;
  375. return (omask);
  376. }