syslog.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 <libio/libioP.h>
  33. #include <paths.h>
  34. #include <stdarg.h>
  35. #include <stdlib.h>
  36. #include <stdio.h>
  37. #include <stdio_ext.h>
  38. #include <sys/socket.h>
  39. #include <sys/uio.h>
  40. #include <sys/un.h>
  41. #include <syslog.h>
  42. #include <limits.h>
  43. static int LogType = SOCK_DGRAM; /* type of socket connection */
  44. static int LogFile = -1; /* fd for log */
  45. static bool connected; /* have done connect */
  46. static int LogStat; /* status bits, set by openlog() */
  47. static const char *LogTag; /* string to tag the entry with */
  48. static int LogFacility = LOG_USER; /* default facility code */
  49. static int LogMask = 0xff; /* mask of priorities to be logged */
  50. extern char *__progname; /* Program name, from crt0. */
  51. /* Define the lock. */
  52. __libc_lock_define_initialized (static, syslog_lock)
  53. static void openlog_internal (const char *, int, int);
  54. static void closelog_internal (void);
  55. struct cleanup_arg
  56. {
  57. void *buf;
  58. struct sigaction *oldaction;
  59. };
  60. static void
  61. cancel_handler (void *ptr)
  62. {
  63. /* Restore the old signal handler. */
  64. struct cleanup_arg *clarg = (struct cleanup_arg *) ptr;
  65. if (clarg != NULL)
  66. /* Free the memstream buffer, */
  67. free (clarg->buf);
  68. /* Free the lock. */
  69. __libc_lock_unlock (syslog_lock);
  70. }
  71. /*
  72. * syslog, vsyslog --
  73. * print message on log file; output is intended for syslogd(8).
  74. */
  75. void
  76. __syslog (int pri, const char *fmt, ...)
  77. {
  78. va_list ap;
  79. va_start (ap, fmt);
  80. __vsyslog_internal (pri, fmt, ap, 0);
  81. va_end (ap);
  82. }
  83. ldbl_hidden_def (__syslog, syslog)
  84. ldbl_strong_alias (__syslog, syslog)
  85. void
  86. __vsyslog (int pri, const char *fmt, va_list ap)
  87. {
  88. __vsyslog_internal (pri, fmt, ap, 0);
  89. }
  90. ldbl_weak_alias (__vsyslog, vsyslog)
  91. void
  92. ___syslog_chk (int pri, int flag, const char *fmt, ...)
  93. {
  94. va_list ap;
  95. va_start (ap, fmt);
  96. __vsyslog_internal (pri, fmt, ap, (flag > 0) ? PRINTF_FORTIFY : 0);
  97. va_end (ap);
  98. }
  99. ldbl_hidden_def (___syslog_chk, __syslog_chk)
  100. ldbl_strong_alias (___syslog_chk, __syslog_chk)
  101. void
  102. ___vsyslog_chk (int pri, int flag, const char *fmt, va_list ap)
  103. {
  104. __vsyslog_internal (pri, fmt, ap, (flag > 0) ? PRINTF_FORTIFY : 0);
  105. }
  106. ldbl_hidden_def (___vsyslog_chk, __vsyslog_chk)
  107. ldbl_strong_alias (___vsyslog_chk, __vsyslog_chk)
  108. void
  109. __vsyslog_internal (int pri, const char *fmt, va_list ap,
  110. unsigned int mode_flags)
  111. {
  112. /* Try to use a static buffer as an optimization. */
  113. char bufs[1024];
  114. char *buf = bufs;
  115. size_t bufsize;
  116. int msgoff;
  117. int saved_errno = errno;
  118. #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
  119. /* Check for invalid bits. */
  120. if (pri & ~(LOG_PRIMASK | LOG_FACMASK))
  121. {
  122. syslog (INTERNALLOG, "syslog: unknown facility/priority: %x", pri);
  123. pri &= LOG_PRIMASK | LOG_FACMASK;
  124. }
  125. /* Prepare for multiple users. We have to take care: most syscalls we are
  126. using are cancellation points. */
  127. struct cleanup_arg clarg = { NULL, NULL };
  128. __libc_cleanup_push (cancel_handler, &clarg);
  129. __libc_lock_lock (syslog_lock);
  130. /* Check priority against setlogmask values. */
  131. if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
  132. goto out;
  133. /* Set default facility if none specified. */
  134. if ((pri & LOG_FACMASK) == 0)
  135. pri |= LogFacility;
  136. pid_t pid = LogStat & LOG_PID ? __getpid () : 0;
  137. /* "%b %e %H:%M:%S " */
  138. char timestamp[sizeof "MMM DD hh:mm:ss "];
  139. __time64_t now = time64_now ();
  140. struct tm now_tm;
  141. struct tm *now_tmp = __localtime64_r (&now, &now_tm);
  142. bool has_ts = now_tmp != NULL;
  143. /* In the unlikely case of localtime_r failure (tm_year out of int range)
  144. skip the hostname so the message is handled as valid PRI but without
  145. TIMESTAMP or invalid TIMESTAMP (which should force the relay to add the
  146. timestamp itself). */
  147. if (has_ts)
  148. __strftime_l (timestamp, sizeof timestamp, "%h %e %T ", now_tmp,
  149. _nl_C_locobj_ptr);
  150. #define SYSLOG_HEADER(__pri, __timestamp, __msgoff, pid) \
  151. "<%d>%s%n%s%s%.0d%s: ", \
  152. __pri, __timestamp, __msgoff, \
  153. LogTag == NULL ? __progname : LogTag, \
  154. &"["[pid == 0], pid, &"]"[pid == 0]
  155. #define SYSLOG_HEADER_WITHOUT_TS(__pri, __msgoff) \
  156. "<%d>: %n", __pri, __msgoff
  157. int l, vl;
  158. if (has_ts)
  159. l = __snprintf (bufs, sizeof bufs,
  160. SYSLOG_HEADER (pri, timestamp, &msgoff, pid));
  161. else
  162. l = __snprintf (bufs, sizeof bufs,
  163. SYSLOG_HEADER_WITHOUT_TS (pri, &msgoff));
  164. if (l < 0)
  165. goto out;
  166. char *pos;
  167. size_t len;
  168. if (l < sizeof bufs)
  169. {
  170. /* At this point, there is still a chance that we can print the
  171. remaining part of the log into bufs and use that. */
  172. pos = bufs + l;
  173. len = sizeof (bufs) - l;
  174. }
  175. else
  176. {
  177. buf = NULL;
  178. /* We already know that bufs is too small to use for this log message.
  179. The next vsnprintf into bufs is used only to calculate the total
  180. required buffer length. We will discard bufs contents and allocate
  181. an appropriately sized buffer later instead. */
  182. pos = bufs;
  183. len = sizeof (bufs);
  184. }
  185. {
  186. va_list apc;
  187. va_copy (apc, ap);
  188. /* Restore errno for %m format. */
  189. __set_errno (saved_errno);
  190. vl = __vsnprintf_internal (pos, len, fmt, apc, mode_flags);
  191. va_end (apc);
  192. if (vl < 0 || vl >= INT_MAX - l)
  193. goto out;
  194. if (vl >= len)
  195. buf = NULL;
  196. bufsize = l + vl;
  197. }
  198. if (buf == NULL)
  199. {
  200. buf = malloc ((bufsize + 1) * sizeof (char));
  201. if (buf != NULL)
  202. {
  203. /* Tell the cancellation handler to free this buffer. */
  204. clarg.buf = buf;
  205. int cl;
  206. if (has_ts)
  207. cl = __snprintf (buf, l + 1,
  208. SYSLOG_HEADER (pri, timestamp, &msgoff, pid));
  209. else
  210. cl = __snprintf (buf, l + 1,
  211. SYSLOG_HEADER_WITHOUT_TS (pri, &msgoff));
  212. if (cl != l)
  213. goto out;
  214. va_list apc;
  215. va_copy (apc, ap);
  216. cl = __vsnprintf_internal (buf + l, bufsize - l + 1, fmt, apc,
  217. mode_flags);
  218. va_end (apc);
  219. if (cl != vl)
  220. goto out;
  221. }
  222. else
  223. {
  224. int bl;
  225. /* Nothing much to do but emit an error message. */
  226. bl = __snprintf (bufs, sizeof bufs,
  227. "out of memory[%d]", __getpid ());
  228. if (bl < 0 || bl >= sizeof bufs)
  229. goto out;
  230. bufsize = bl;
  231. buf = bufs;
  232. msgoff = 0;
  233. }
  234. }
  235. /* Output to stderr if requested. */
  236. if (LogStat & LOG_PERROR)
  237. __dprintf (STDERR_FILENO, "%s%s", buf + msgoff,
  238. &"\n"[buf[bufsize - 1] == '\n']);
  239. /* Get connected, output the message to the local logger. */
  240. if (!connected)
  241. openlog_internal (NULL, LogStat | LOG_NDELAY, LogFacility);
  242. /* If we have a SOCK_STREAM connection, also send ASCII NUL as a record
  243. terminator. */
  244. if (LogType == SOCK_STREAM)
  245. ++bufsize;
  246. if (!connected || __send (LogFile, buf, bufsize, MSG_NOSIGNAL) < 0)
  247. {
  248. if (connected)
  249. {
  250. /* Try to reopen the syslog connection. Maybe it went down. */
  251. closelog_internal ();
  252. openlog_internal (NULL, LogStat | LOG_NDELAY, LogFacility);
  253. }
  254. if (!connected || __send (LogFile, buf, bufsize, MSG_NOSIGNAL) < 0)
  255. {
  256. closelog_internal (); /* attempt re-open next time */
  257. /*
  258. * Output the message to the console; don't worry
  259. * about blocking, if console blocks everything will.
  260. * Make sure the error reported is the one from the
  261. * syslogd failure.
  262. */
  263. int fd;
  264. if (LogStat & LOG_CONS &&
  265. (fd = __open (_PATH_CONSOLE, O_WRONLY | O_NOCTTY
  266. | O_CLOEXEC, 0)) >= 0)
  267. {
  268. __dprintf (fd, "%s\r\n", buf + msgoff);
  269. __close (fd);
  270. }
  271. }
  272. }
  273. out:
  274. /* End of critical section. */
  275. __libc_cleanup_pop (0);
  276. __libc_lock_unlock (syslog_lock);
  277. if (buf != bufs)
  278. free (buf);
  279. }
  280. /* AF_UNIX address of local logger */
  281. static const struct sockaddr_un SyslogAddr =
  282. {
  283. .sun_family = AF_UNIX,
  284. .sun_path = _PATH_LOG
  285. };
  286. static void
  287. openlog_internal (const char *ident, int logstat, int logfac)
  288. {
  289. if (ident != NULL)
  290. LogTag = ident;
  291. LogStat = logstat;
  292. if ((logfac & ~LOG_FACMASK) == 0)
  293. LogFacility = logfac;
  294. int retry = 0;
  295. while (retry < 2)
  296. {
  297. if (LogFile == -1)
  298. {
  299. if (LogStat & LOG_NDELAY)
  300. {
  301. LogFile = __socket (AF_UNIX, LogType | SOCK_CLOEXEC, 0);
  302. if (LogFile == -1)
  303. return;
  304. }
  305. }
  306. if (LogFile != -1 && !connected)
  307. {
  308. int old_errno = errno;
  309. if (__connect (LogFile, &SyslogAddr, sizeof (SyslogAddr)) == -1)
  310. {
  311. int saved_errno = errno;
  312. int fd = LogFile;
  313. LogFile = -1;
  314. __close (fd);
  315. __set_errno (old_errno);
  316. if (saved_errno == EPROTOTYPE)
  317. {
  318. /* retry with the other type: */
  319. LogType = LogType == SOCK_DGRAM ? SOCK_STREAM : SOCK_DGRAM;
  320. ++retry;
  321. continue;
  322. }
  323. }
  324. else
  325. connected = true;
  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. static void
  340. closelog_internal (void)
  341. {
  342. if (!connected)
  343. return;
  344. __close (LogFile);
  345. LogFile = -1;
  346. connected = false;
  347. }
  348. void
  349. closelog (void)
  350. {
  351. /* Protect against multiple users and cancellation. */
  352. __libc_cleanup_push (cancel_handler, NULL);
  353. __libc_lock_lock (syslog_lock);
  354. closelog_internal ();
  355. LogTag = NULL;
  356. LogType = SOCK_DGRAM; /* this is the default */
  357. /* Free the lock. */
  358. __libc_cleanup_pop (1);
  359. }
  360. /* setlogmask -- set the log mask level */
  361. int
  362. setlogmask (int pmask)
  363. {
  364. int omask;
  365. /* Protect against multiple users. */
  366. __libc_lock_lock (syslog_lock);
  367. omask = LogMask;
  368. if (pmask != 0)
  369. LogMask = pmask;
  370. __libc_lock_unlock (syslog_lock);
  371. return (omask);
  372. }