log.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file log.c
  8. * \brief Functions to send messages to log files or the console.
  9. **/
  10. #include "orconfig.h"
  11. #include <stdarg.h>
  12. #include <assert.h>
  13. // #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #ifdef HAVE_SYS_TIME_H
  17. #include <sys/time.h>
  18. #endif
  19. #ifdef HAVE_TIME_H
  20. #include <time.h>
  21. #endif
  22. #ifdef HAVE_UNISTD_H
  23. #include <unistd.h>
  24. #endif
  25. #ifdef HAVE_SYS_TYPES_H
  26. #include <sys/types.h>
  27. #endif
  28. #ifdef HAVE_FCNTL_H
  29. #include <fcntl.h>
  30. #endif
  31. #include "compat.h"
  32. #include "util.h"
  33. #define LOG_PRIVATE
  34. #include "torlog.h"
  35. #include "container.h"
  36. /** @{ */
  37. /** The string we stick at the end of a log message when it is too long,
  38. * and its length. */
  39. #define TRUNCATED_STR "[...truncated]"
  40. #define TRUNCATED_STR_LEN 14
  41. /** @} */
  42. /** Information for a single logfile; only used in log.c */
  43. typedef struct logfile_t {
  44. struct logfile_t *next; /**< Next logfile_t in the linked list. */
  45. char *filename; /**< Filename to open. */
  46. int fd; /**< fd to receive log messages, or -1 for none. */
  47. int seems_dead; /**< Boolean: true if the stream seems to be kaput. */
  48. int needs_close; /**< Boolean: true if the stream gets closed on shutdown. */
  49. int is_temporary; /**< Boolean: close after initializing logging subsystem.*/
  50. int is_syslog; /**< Boolean: send messages to syslog. */
  51. log_callback callback; /**< If not NULL, send messages to this function. */
  52. log_severity_list_t *severities; /**< Which severity of messages should we
  53. * log for each log domain? */
  54. } logfile_t;
  55. static void log_free(logfile_t *victim);
  56. /** Helper: map a log severity to descriptive string. */
  57. static INLINE const char *
  58. sev_to_string(int severity)
  59. {
  60. switch (severity) {
  61. case LOG_DEBUG: return "debug";
  62. case LOG_INFO: return "info";
  63. case LOG_NOTICE: return "notice";
  64. case LOG_WARN: return "warn";
  65. case LOG_ERR: return "err";
  66. default: /* Call assert, not tor_assert, since tor_assert
  67. * calls log on failure. */
  68. assert(0); return "UNKNOWN";
  69. }
  70. }
  71. /** Helper: decide whether to include the function name in the log message. */
  72. static INLINE int
  73. should_log_function_name(log_domain_mask_t domain, int severity)
  74. {
  75. switch (severity) {
  76. case LOG_DEBUG:
  77. case LOG_INFO:
  78. /* All debugging messages occur in interesting places. */
  79. return 1;
  80. case LOG_NOTICE:
  81. case LOG_WARN:
  82. case LOG_ERR:
  83. /* We care about places where bugs occur. */
  84. return (domain == LD_BUG);
  85. default:
  86. /* Call assert, not tor_assert, since tor_assert calls log on failure. */
  87. assert(0); return 0;
  88. }
  89. }
  90. /** A mutex to guard changes to logfiles and logging. */
  91. static tor_mutex_t log_mutex;
  92. /* DOCDOC log_mutex_initialized */
  93. static int log_mutex_initialized = 0;
  94. /** Linked list of logfile_t. */
  95. static logfile_t *logfiles = NULL;
  96. /** Boolean: do we report logging domains? */
  97. static int log_domains_are_logged = 0;
  98. #ifdef HAVE_SYSLOG_H
  99. /** The number of open syslog log handlers that we have. When this reaches 0,
  100. * we can close our connection to the syslog facility. */
  101. static int syslog_count = 0;
  102. #endif
  103. /** Represents a log message that we are going to send to callback-driven
  104. * loggers once we can do so in a non-reentrant way. */
  105. typedef struct pending_cb_message_t {
  106. int severity; /**< The severity of the message */
  107. log_domain_mask_t domain; /**< The domain of the message */
  108. char *msg; /**< The content of the message */
  109. } pending_cb_message_t;
  110. /** Log messages waiting to be replayed onto callback-based logs */
  111. static smartlist_t *pending_cb_messages = NULL;
  112. /** Lock the log_mutex to prevent others from changing the logfile_t list */
  113. #define LOCK_LOGS() STMT_BEGIN \
  114. tor_mutex_acquire(&log_mutex); \
  115. STMT_END
  116. /** Unlock the log_mutex */
  117. #define UNLOCK_LOGS() STMT_BEGIN tor_mutex_release(&log_mutex); STMT_END
  118. /** What's the lowest log level anybody cares about? Checking this lets us
  119. * bail out early from log_debug if we aren't debugging. */
  120. int _log_global_min_severity = LOG_NOTICE;
  121. static void delete_log(logfile_t *victim);
  122. static void close_log(logfile_t *victim);
  123. static char *domain_to_string(log_domain_mask_t domain,
  124. char *buf, size_t buflen);
  125. static INLINE char *format_msg(char *buf, size_t buf_len,
  126. log_domain_mask_t domain, int severity, const char *funcname,
  127. const char *format, va_list ap, size_t *msg_len_out)
  128. CHECK_PRINTF(6,0);
  129. static void logv(int severity, log_domain_mask_t domain, const char *funcname,
  130. const char *format, va_list ap)
  131. CHECK_PRINTF(4,0);
  132. /** Name of the application: used to generate the message we write at the
  133. * start of each new log. */
  134. static char *appname = NULL;
  135. /** Set the "application name" for the logs to <b>name</b>: we'll use this
  136. * name in the message we write when starting up, and at the start of each new
  137. * log.
  138. *
  139. * Tor uses this string to write the version number to the log file. */
  140. void
  141. log_set_application_name(const char *name)
  142. {
  143. tor_free(appname);
  144. appname = name ? tor_strdup(name) : NULL;
  145. }
  146. /** Log time granularity in milliseconds. */
  147. static int log_time_granularity = 1;
  148. /** Define log time granularity for all logs to be <b>granularity_msec</b>
  149. * milliseconds. */
  150. void
  151. set_log_time_granularity(int granularity_msec)
  152. {
  153. log_time_granularity = granularity_msec;
  154. }
  155. /** Helper: Write the standard prefix for log lines to a
  156. * <b>buf_len</b> character buffer in <b>buf</b>.
  157. */
  158. static INLINE size_t
  159. _log_prefix(char *buf, size_t buf_len, int severity)
  160. {
  161. time_t t;
  162. struct timeval now;
  163. struct tm tm;
  164. size_t n;
  165. int r, ms;
  166. tor_gettimeofday(&now);
  167. t = (time_t)now.tv_sec;
  168. ms = (int)now.tv_usec / 1000;
  169. if (log_time_granularity >= 1000) {
  170. t -= t % (log_time_granularity / 1000);
  171. ms = 0;
  172. } else {
  173. ms -= ((int)now.tv_usec / 1000) % log_time_granularity;
  174. }
  175. n = strftime(buf, buf_len, "%b %d %H:%M:%S", tor_localtime_r(&t, &tm));
  176. r = tor_snprintf(buf+n, buf_len-n, ".%.3i [%s] ", ms,
  177. sev_to_string(severity));
  178. if (r<0)
  179. return buf_len-1;
  180. else
  181. return n+r;
  182. }
  183. /** If lf refers to an actual file that we have just opened, and the file
  184. * contains no data, log an "opening new logfile" message at the top.
  185. *
  186. * Return -1 if the log is broken and needs to be deleted, else return 0.
  187. */
  188. static int
  189. log_tor_version(logfile_t *lf, int reset)
  190. {
  191. char buf[256];
  192. size_t n;
  193. int is_new;
  194. if (!lf->needs_close)
  195. /* If it doesn't get closed, it isn't really a file. */
  196. return 0;
  197. if (lf->is_temporary)
  198. /* If it's temporary, it isn't really a file. */
  199. return 0;
  200. is_new = lf->fd >= 0 && tor_fd_getpos(lf->fd) == 0;
  201. if (reset && !is_new)
  202. /* We are resetting, but we aren't at the start of the file; no
  203. * need to log again. */
  204. return 0;
  205. n = _log_prefix(buf, sizeof(buf), LOG_NOTICE);
  206. if (appname) {
  207. tor_snprintf(buf+n, sizeof(buf)-n,
  208. "%s opening %slog file.\n", appname, is_new?"new ":"");
  209. } else {
  210. tor_snprintf(buf+n, sizeof(buf)-n,
  211. "Tor %s opening %slog file.\n", VERSION, is_new?"new ":"");
  212. }
  213. if (write_all(lf->fd, buf, strlen(buf), 0) < 0) /* error */
  214. return -1; /* failed */
  215. return 0;
  216. }
  217. /** Helper: Format a log message into a fixed-sized buffer. (This is
  218. * factored out of <b>logv</b> so that we never format a message more
  219. * than once.) Return a pointer to the first character of the message
  220. * portion of the formatted string.
  221. */
  222. static INLINE char *
  223. format_msg(char *buf, size_t buf_len,
  224. log_domain_mask_t domain, int severity, const char *funcname,
  225. const char *format, va_list ap, size_t *msg_len_out)
  226. {
  227. size_t n;
  228. int r;
  229. char *end_of_prefix;
  230. char *buf_end;
  231. assert(buf_len >= 16); /* prevent integer underflow and general stupidity */
  232. buf_len -= 2; /* subtract 2 characters so we have room for \n\0 */
  233. buf_end = buf+buf_len; /* point *after* the last char we can write to */
  234. n = _log_prefix(buf, buf_len, severity);
  235. end_of_prefix = buf+n;
  236. if (log_domains_are_logged) {
  237. char *cp = buf+n;
  238. if (cp == buf_end) goto format_msg_no_room_for_domains;
  239. *cp++ = '{';
  240. if (cp == buf_end) goto format_msg_no_room_for_domains;
  241. cp = domain_to_string(domain, cp, (buf+buf_len-cp));
  242. if (cp == buf_end) goto format_msg_no_room_for_domains;
  243. *cp++ = '}';
  244. if (cp == buf_end) goto format_msg_no_room_for_domains;
  245. *cp++ = ' ';
  246. if (cp == buf_end) goto format_msg_no_room_for_domains;
  247. end_of_prefix = cp;
  248. n = cp-buf;
  249. format_msg_no_room_for_domains:
  250. /* This will leave end_of_prefix and n unchanged, and thus cause
  251. * whatever log domain string we had written to be clobbered. */
  252. ;
  253. }
  254. if (funcname && should_log_function_name(domain, severity)) {
  255. r = tor_snprintf(buf+n, buf_len-n, "%s(): ", funcname);
  256. if (r<0)
  257. n = strlen(buf);
  258. else
  259. n += r;
  260. }
  261. if (domain == LD_BUG && buf_len-n > 6) {
  262. memcpy(buf+n, "Bug: ", 6);
  263. n += 5;
  264. }
  265. r = tor_vsnprintf(buf+n,buf_len-n,format,ap);
  266. if (r < 0) {
  267. /* The message was too long; overwrite the end of the buffer with
  268. * "[...truncated]" */
  269. if (buf_len >= TRUNCATED_STR_LEN) {
  270. size_t offset = buf_len-TRUNCATED_STR_LEN;
  271. /* We have an extra 2 characters after buf_len to hold the \n\0,
  272. * so it's safe to add 1 to the size here. */
  273. strlcpy(buf+offset, TRUNCATED_STR, buf_len-offset+1);
  274. }
  275. /* Set 'n' to the end of the buffer, where we'll be writing \n\0.
  276. * Since we already subtracted 2 from buf_len, this is safe.*/
  277. n = buf_len;
  278. } else {
  279. n += r;
  280. }
  281. buf[n]='\n';
  282. buf[n+1]='\0';
  283. *msg_len_out = n+1;
  284. return end_of_prefix;
  285. }
  286. /** Helper: sends a message to the appropriate logfiles, at loglevel
  287. * <b>severity</b>. If provided, <b>funcname</b> is prepended to the
  288. * message. The actual message is derived as from tor_snprintf(format,ap).
  289. */
  290. static void
  291. logv(int severity, log_domain_mask_t domain, const char *funcname,
  292. const char *format, va_list ap)
  293. {
  294. char buf[10024];
  295. size_t msg_len = 0;
  296. int formatted = 0;
  297. logfile_t *lf;
  298. char *end_of_prefix=NULL;
  299. int callbacks_deferred = 0;
  300. /* Call assert, not tor_assert, since tor_assert calls log on failure. */
  301. assert(format);
  302. /* check that severity is sane. Overrunning the masks array leads to
  303. * interesting and hard to diagnose effects */
  304. assert(severity >= LOG_ERR && severity <= LOG_DEBUG);
  305. LOCK_LOGS();
  306. if ((! (domain & LD_NOCB)) && smartlist_len(pending_cb_messages))
  307. flush_pending_log_callbacks();
  308. lf = logfiles;
  309. while (lf) {
  310. if (! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  311. lf = lf->next;
  312. continue;
  313. }
  314. if (! (lf->fd >= 0 || lf->is_syslog || lf->callback)) {
  315. lf = lf->next;
  316. continue;
  317. }
  318. if (lf->seems_dead) {
  319. lf = lf->next;
  320. continue;
  321. }
  322. if (!formatted) {
  323. end_of_prefix =
  324. format_msg(buf, sizeof(buf), domain, severity, funcname, format, ap,
  325. &msg_len);
  326. formatted = 1;
  327. }
  328. if (lf->is_syslog) {
  329. #ifdef HAVE_SYSLOG_H
  330. char *m = end_of_prefix;
  331. #ifdef MAXLINE
  332. /* Some syslog implementations have limits on the length of what you can
  333. * pass them, and some very old ones do not detect overflow so well.
  334. * Regrettably, they call their maximum line length MAXLINE. */
  335. #if MAXLINE < 64
  336. #warn "MAXLINE is a very low number; it might not be from syslog.h after all"
  337. #endif
  338. if (msg_len >= MAXLINE)
  339. m = tor_strndup(end_of_prefix, MAXLINE-1);
  340. #endif
  341. syslog(severity, "%s", m);
  342. #ifdef MAXLINE
  343. if (m != end_of_prefix) {
  344. tor_free(m);
  345. }
  346. #endif
  347. #endif
  348. lf = lf->next;
  349. continue;
  350. } else if (lf->callback) {
  351. if (domain & LD_NOCB) {
  352. if (!callbacks_deferred && pending_cb_messages) {
  353. pending_cb_message_t *msg = tor_malloc(sizeof(pending_cb_message_t));
  354. msg->severity = severity;
  355. msg->domain = domain;
  356. msg->msg = tor_strdup(end_of_prefix);
  357. smartlist_add(pending_cb_messages, msg);
  358. callbacks_deferred = 1;
  359. }
  360. } else {
  361. lf->callback(severity, domain, end_of_prefix);
  362. }
  363. lf = lf->next;
  364. continue;
  365. }
  366. if (write_all(lf->fd, buf, msg_len, 0) < 0) { /* error */
  367. /* don't log the error! mark this log entry to be blown away, and
  368. * continue. */
  369. lf->seems_dead = 1;
  370. }
  371. lf = lf->next;
  372. }
  373. UNLOCK_LOGS();
  374. }
  375. /** Output a message to the log. It gets logged to all logfiles that
  376. * care about messages with <b>severity</b> in <b>domain</b>. The content
  377. * is formatted printf-style based on <b>format</b> and extra arguments.
  378. * */
  379. void
  380. tor_log(int severity, log_domain_mask_t domain, const char *format, ...)
  381. {
  382. va_list ap;
  383. if (severity > _log_global_min_severity)
  384. return;
  385. va_start(ap,format);
  386. logv(severity, domain, NULL, format, ap);
  387. va_end(ap);
  388. }
  389. /** Output a message to the log, prefixed with a function name <b>fn</b>. */
  390. #ifdef __GNUC__
  391. /** GCC-based implementation of the log_fn backend, used when we have
  392. * variadic macros. All arguments are as for log_fn, except for
  393. * <b>fn</b>, which is the name of the calling functions. */
  394. void
  395. _log_fn(int severity, log_domain_mask_t domain, const char *fn,
  396. const char *format, ...)
  397. {
  398. va_list ap;
  399. if (severity > _log_global_min_severity)
  400. return;
  401. va_start(ap,format);
  402. logv(severity, domain, fn, format, ap);
  403. va_end(ap);
  404. }
  405. #else
  406. /** @{ */
  407. /** Variant implementation of log_fn, log_debug, log_info,... for C compilers
  408. * without variadic macros. In this case, the calling function sets
  409. * _log_fn_function_name to the name of the function, then invokes the
  410. * appropriate _log_fn, _log_debug, etc. */
  411. const char *_log_fn_function_name=NULL;
  412. void
  413. _log_fn(int severity, log_domain_mask_t domain, const char *format, ...)
  414. {
  415. va_list ap;
  416. if (severity > _log_global_min_severity)
  417. return;
  418. va_start(ap,format);
  419. logv(severity, domain, _log_fn_function_name, format, ap);
  420. va_end(ap);
  421. _log_fn_function_name = NULL;
  422. }
  423. void
  424. _log_debug(log_domain_mask_t domain, const char *format, ...)
  425. {
  426. va_list ap;
  427. /* For GCC we do this check in the macro. */
  428. if (PREDICT_LIKELY(LOG_DEBUG > _log_global_min_severity))
  429. return;
  430. va_start(ap,format);
  431. logv(LOG_DEBUG, domain, _log_fn_function_name, format, ap);
  432. va_end(ap);
  433. _log_fn_function_name = NULL;
  434. }
  435. void
  436. _log_info(log_domain_mask_t domain, const char *format, ...)
  437. {
  438. va_list ap;
  439. if (LOG_INFO > _log_global_min_severity)
  440. return;
  441. va_start(ap,format);
  442. logv(LOG_INFO, domain, _log_fn_function_name, format, ap);
  443. va_end(ap);
  444. _log_fn_function_name = NULL;
  445. }
  446. void
  447. _log_notice(log_domain_mask_t domain, const char *format, ...)
  448. {
  449. va_list ap;
  450. if (LOG_NOTICE > _log_global_min_severity)
  451. return;
  452. va_start(ap,format);
  453. logv(LOG_NOTICE, domain, _log_fn_function_name, format, ap);
  454. va_end(ap);
  455. _log_fn_function_name = NULL;
  456. }
  457. void
  458. _log_warn(log_domain_mask_t domain, const char *format, ...)
  459. {
  460. va_list ap;
  461. if (LOG_WARN > _log_global_min_severity)
  462. return;
  463. va_start(ap,format);
  464. logv(LOG_WARN, domain, _log_fn_function_name, format, ap);
  465. va_end(ap);
  466. _log_fn_function_name = NULL;
  467. }
  468. void
  469. _log_err(log_domain_mask_t domain, const char *format, ...)
  470. {
  471. va_list ap;
  472. if (LOG_ERR > _log_global_min_severity)
  473. return;
  474. va_start(ap,format);
  475. logv(LOG_ERR, domain, _log_fn_function_name, format, ap);
  476. va_end(ap);
  477. _log_fn_function_name = NULL;
  478. }
  479. /** @} */
  480. #endif
  481. /** Free all storage held by <b>victim</b>. */
  482. static void
  483. log_free(logfile_t *victim)
  484. {
  485. if (!victim)
  486. return;
  487. tor_free(victim->severities);
  488. tor_free(victim->filename);
  489. tor_free(victim);
  490. }
  491. /** Close all open log files, and free other static memory. */
  492. void
  493. logs_free_all(void)
  494. {
  495. logfile_t *victim, *next;
  496. smartlist_t *messages;
  497. LOCK_LOGS();
  498. next = logfiles;
  499. logfiles = NULL;
  500. messages = pending_cb_messages;
  501. pending_cb_messages = NULL;
  502. UNLOCK_LOGS();
  503. while (next) {
  504. victim = next;
  505. next = next->next;
  506. close_log(victim);
  507. log_free(victim);
  508. }
  509. tor_free(appname);
  510. SMARTLIST_FOREACH(messages, pending_cb_message_t *, msg, {
  511. tor_free(msg->msg);
  512. tor_free(msg);
  513. });
  514. smartlist_free(messages);
  515. /* We _could_ destroy the log mutex here, but that would screw up any logs
  516. * that happened between here and the end of execution. */
  517. }
  518. /** Remove and free the log entry <b>victim</b> from the linked-list
  519. * logfiles (it is probably present, but it might not be due to thread
  520. * racing issues). After this function is called, the caller shouldn't
  521. * refer to <b>victim</b> anymore.
  522. *
  523. * Long-term, we need to do something about races in the log subsystem
  524. * in general. See bug 222 for more details.
  525. */
  526. static void
  527. delete_log(logfile_t *victim)
  528. {
  529. logfile_t *tmpl;
  530. if (victim == logfiles)
  531. logfiles = victim->next;
  532. else {
  533. for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
  534. // tor_assert(tmpl);
  535. // tor_assert(tmpl->next == victim);
  536. if (!tmpl)
  537. return;
  538. tmpl->next = victim->next;
  539. }
  540. log_free(victim);
  541. }
  542. /** Helper: release system resources (but not memory) held by a single
  543. * logfile_t. */
  544. static void
  545. close_log(logfile_t *victim)
  546. {
  547. if (victim->needs_close && victim->fd >= 0) {
  548. close(victim->fd);
  549. victim->fd = -1;
  550. } else if (victim->is_syslog) {
  551. #ifdef HAVE_SYSLOG_H
  552. if (--syslog_count == 0) {
  553. /* There are no other syslogs; close the logging facility. */
  554. closelog();
  555. }
  556. #endif
  557. }
  558. }
  559. /** Adjust a log severity configuration in <b>severity_out</b> to contain
  560. * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
  561. */
  562. void
  563. set_log_severity_config(int loglevelMin, int loglevelMax,
  564. log_severity_list_t *severity_out)
  565. {
  566. int i;
  567. tor_assert(loglevelMin >= loglevelMax);
  568. tor_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
  569. tor_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
  570. memset(severity_out, 0, sizeof(log_severity_list_t));
  571. for (i = loglevelMin; i >= loglevelMax; --i) {
  572. severity_out->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  573. }
  574. }
  575. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  576. * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
  577. static void
  578. add_stream_log_impl(const log_severity_list_t *severity,
  579. const char *name, int fd)
  580. {
  581. logfile_t *lf;
  582. lf = tor_malloc_zero(sizeof(logfile_t));
  583. lf->fd = fd;
  584. lf->filename = tor_strdup(name);
  585. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  586. lf->next = logfiles;
  587. logfiles = lf;
  588. _log_global_min_severity = get_min_log_level();
  589. }
  590. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  591. * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
  592. * not use it after calling this function. */
  593. void
  594. add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
  595. {
  596. LOCK_LOGS();
  597. add_stream_log_impl(severity, name, fd);
  598. UNLOCK_LOGS();
  599. }
  600. /** Initialize the global logging facility */
  601. void
  602. init_logging(void)
  603. {
  604. if (!log_mutex_initialized) {
  605. tor_mutex_init(&log_mutex);
  606. log_mutex_initialized = 1;
  607. }
  608. if (pending_cb_messages == NULL)
  609. pending_cb_messages = smartlist_new();
  610. }
  611. /** Set whether we report logging domains as a part of our log messages.
  612. */
  613. void
  614. logs_set_domain_logging(int enabled)
  615. {
  616. LOCK_LOGS();
  617. log_domains_are_logged = enabled;
  618. UNLOCK_LOGS();
  619. }
  620. /** Add a log handler to receive messages during startup (before the real
  621. * logs are initialized).
  622. */
  623. void
  624. add_temp_log(int min_severity)
  625. {
  626. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  627. set_log_severity_config(min_severity, LOG_ERR, s);
  628. LOCK_LOGS();
  629. add_stream_log_impl(s, "<temp>", fileno(stdout));
  630. tor_free(s);
  631. logfiles->is_temporary = 1;
  632. UNLOCK_LOGS();
  633. }
  634. /**
  635. * Add a log handler to send messages in <b>severity</b>
  636. * to the function <b>cb</b>.
  637. */
  638. int
  639. add_callback_log(const log_severity_list_t *severity, log_callback cb)
  640. {
  641. logfile_t *lf;
  642. lf = tor_malloc_zero(sizeof(logfile_t));
  643. lf->fd = -1;
  644. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  645. lf->filename = tor_strdup("<callback>");
  646. lf->callback = cb;
  647. lf->next = logfiles;
  648. LOCK_LOGS();
  649. logfiles = lf;
  650. _log_global_min_severity = get_min_log_level();
  651. UNLOCK_LOGS();
  652. return 0;
  653. }
  654. /** Adjust the configured severity of any logs whose callback function is
  655. * <b>cb</b>. */
  656. void
  657. change_callback_log_severity(int loglevelMin, int loglevelMax,
  658. log_callback cb)
  659. {
  660. logfile_t *lf;
  661. log_severity_list_t severities;
  662. set_log_severity_config(loglevelMin, loglevelMax, &severities);
  663. LOCK_LOGS();
  664. for (lf = logfiles; lf; lf = lf->next) {
  665. if (lf->callback == cb) {
  666. memcpy(lf->severities, &severities, sizeof(severities));
  667. }
  668. }
  669. _log_global_min_severity = get_min_log_level();
  670. UNLOCK_LOGS();
  671. }
  672. /** If there are any log messages that were generated with LD_NOCB waiting to
  673. * be sent to callback-based loggers, send them now. */
  674. void
  675. flush_pending_log_callbacks(void)
  676. {
  677. logfile_t *lf;
  678. smartlist_t *messages, *messages_tmp;
  679. LOCK_LOGS();
  680. if (0 == smartlist_len(pending_cb_messages)) {
  681. UNLOCK_LOGS();
  682. return;
  683. }
  684. messages = pending_cb_messages;
  685. pending_cb_messages = smartlist_new();
  686. do {
  687. SMARTLIST_FOREACH_BEGIN(messages, pending_cb_message_t *, msg) {
  688. const int severity = msg->severity;
  689. const int domain = msg->domain;
  690. for (lf = logfiles; lf; lf = lf->next) {
  691. if (! lf->callback || lf->seems_dead ||
  692. ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  693. continue;
  694. }
  695. lf->callback(severity, domain, msg->msg);
  696. }
  697. tor_free(msg->msg);
  698. tor_free(msg);
  699. } SMARTLIST_FOREACH_END(msg);
  700. smartlist_clear(messages);
  701. messages_tmp = pending_cb_messages;
  702. pending_cb_messages = messages;
  703. messages = messages_tmp;
  704. } while (smartlist_len(messages));
  705. smartlist_free(messages);
  706. UNLOCK_LOGS();
  707. }
  708. /** Close any log handlers added by add_temp_log() or marked by
  709. * mark_logs_temp(). */
  710. void
  711. close_temp_logs(void)
  712. {
  713. logfile_t *lf, **p;
  714. LOCK_LOGS();
  715. for (p = &logfiles; *p; ) {
  716. if ((*p)->is_temporary) {
  717. lf = *p;
  718. /* we use *p here to handle the edge case of the head of the list */
  719. *p = (*p)->next;
  720. close_log(lf);
  721. log_free(lf);
  722. } else {
  723. p = &((*p)->next);
  724. }
  725. }
  726. _log_global_min_severity = get_min_log_level();
  727. UNLOCK_LOGS();
  728. }
  729. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  730. * live again, and close all non-temporary logs. */
  731. void
  732. rollback_log_changes(void)
  733. {
  734. logfile_t *lf;
  735. LOCK_LOGS();
  736. for (lf = logfiles; lf; lf = lf->next)
  737. lf->is_temporary = ! lf->is_temporary;
  738. UNLOCK_LOGS();
  739. close_temp_logs();
  740. }
  741. /** Configure all log handles to be closed by close_temp_logs(). */
  742. void
  743. mark_logs_temp(void)
  744. {
  745. logfile_t *lf;
  746. LOCK_LOGS();
  747. for (lf = logfiles; lf; lf = lf->next)
  748. lf->is_temporary = 1;
  749. UNLOCK_LOGS();
  750. }
  751. /**
  752. * Add a log handler to send messages to <b>filename</b>. If opening the
  753. * logfile fails, -1 is returned and errno is set appropriately (by open(2)).
  754. */
  755. int
  756. add_file_log(const log_severity_list_t *severity, const char *filename)
  757. {
  758. int fd;
  759. logfile_t *lf;
  760. fd = tor_open_cloexec(filename, O_WRONLY|O_CREAT|O_APPEND, 0644);
  761. if (fd<0)
  762. return -1;
  763. if (tor_fd_seekend(fd)<0)
  764. return -1;
  765. LOCK_LOGS();
  766. add_stream_log_impl(severity, filename, fd);
  767. logfiles->needs_close = 1;
  768. lf = logfiles;
  769. _log_global_min_severity = get_min_log_level();
  770. if (log_tor_version(lf, 0) < 0) {
  771. delete_log(lf);
  772. }
  773. UNLOCK_LOGS();
  774. return 0;
  775. }
  776. #ifdef HAVE_SYSLOG_H
  777. /**
  778. * Add a log handler to send messages to they system log facility.
  779. */
  780. int
  781. add_syslog_log(const log_severity_list_t *severity)
  782. {
  783. logfile_t *lf;
  784. if (syslog_count++ == 0)
  785. /* This is the first syslog. */
  786. openlog("Tor", LOG_PID | LOG_NDELAY, LOGFACILITY);
  787. lf = tor_malloc_zero(sizeof(logfile_t));
  788. lf->fd = -1;
  789. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  790. lf->filename = tor_strdup("<syslog>");
  791. lf->is_syslog = 1;
  792. LOCK_LOGS();
  793. lf->next = logfiles;
  794. logfiles = lf;
  795. _log_global_min_severity = get_min_log_level();
  796. UNLOCK_LOGS();
  797. return 0;
  798. }
  799. #endif
  800. /** If <b>level</b> is a valid log severity, return the corresponding
  801. * numeric value. Otherwise, return -1. */
  802. int
  803. parse_log_level(const char *level)
  804. {
  805. if (!strcasecmp(level, "err"))
  806. return LOG_ERR;
  807. if (!strcasecmp(level, "warn"))
  808. return LOG_WARN;
  809. if (!strcasecmp(level, "notice"))
  810. return LOG_NOTICE;
  811. if (!strcasecmp(level, "info"))
  812. return LOG_INFO;
  813. if (!strcasecmp(level, "debug"))
  814. return LOG_DEBUG;
  815. return -1;
  816. }
  817. /** Return the string equivalent of a given log level. */
  818. const char *
  819. log_level_to_string(int level)
  820. {
  821. return sev_to_string(level);
  822. }
  823. /** NULL-terminated array of names for log domains such that domain_list[dom]
  824. * is a description of <b>dom</b>. */
  825. static const char *domain_list[] = {
  826. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  827. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  828. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", NULL
  829. };
  830. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  831. * or 0 if there is no such name. */
  832. static log_domain_mask_t
  833. parse_log_domain(const char *domain)
  834. {
  835. int i;
  836. for (i=0; domain_list[i]; ++i) {
  837. if (!strcasecmp(domain, domain_list[i]))
  838. return (1u<<i);
  839. }
  840. return 0;
  841. }
  842. /** Translate a bitmask of log domains to a string. */
  843. static char *
  844. domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
  845. {
  846. char *cp = buf;
  847. char *eos = buf+buflen;
  848. buf[0] = '\0';
  849. if (! domain)
  850. return buf;
  851. while (1) {
  852. const char *d;
  853. int bit = tor_log2(domain);
  854. size_t n;
  855. if (bit >= N_LOGGING_DOMAINS) {
  856. tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
  857. return buf+strlen(buf);
  858. }
  859. d = domain_list[bit];
  860. n = strlcpy(cp, d, eos-cp);
  861. if (n >= buflen) {
  862. tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
  863. return buf+strlen(buf);
  864. }
  865. cp += n;
  866. domain &= ~(1<<bit);
  867. if (domain == 0 || (eos-cp) < 2)
  868. return cp;
  869. memcpy(cp, ",", 2); /*Nul-terminated ,"*/
  870. cp++;
  871. }
  872. }
  873. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  874. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  875. * the parsed pattern. Return 0 on success, -1 on failure.
  876. *
  877. * The syntax for a SeverityPattern is:
  878. * <pre>
  879. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  880. * DomainSeverity = (DomainList SP)? SeverityRange
  881. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  882. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  883. * DomainSpec = "*" | Domain | "~" Domain
  884. * </pre>
  885. * A missing MaxSeverity defaults to ERR. Severities and domains are
  886. * case-insensitive. "~" indicates negation for a domain; negation happens
  887. * last inside a DomainList. Only one SeverityRange without a DomainList is
  888. * allowed per line.
  889. */
  890. int
  891. parse_log_severity_config(const char **cfg_ptr,
  892. log_severity_list_t *severity_out)
  893. {
  894. const char *cfg = *cfg_ptr;
  895. int got_anything = 0;
  896. int got_an_unqualified_range = 0;
  897. memset(severity_out, 0, sizeof(*severity_out));
  898. cfg = eat_whitespace(cfg);
  899. while (*cfg) {
  900. const char *dash, *space;
  901. char *sev_lo, *sev_hi;
  902. int low, high, i;
  903. log_domain_mask_t domains = ~0u;
  904. if (*cfg == '[') {
  905. int err = 0;
  906. char *domains_str;
  907. smartlist_t *domains_list;
  908. log_domain_mask_t neg_domains = 0;
  909. const char *closebracket = strchr(cfg, ']');
  910. if (!closebracket)
  911. return -1;
  912. domains = 0;
  913. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  914. domains_list = smartlist_new();
  915. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  916. -1);
  917. tor_free(domains_str);
  918. SMARTLIST_FOREACH(domains_list, const char *, domain,
  919. {
  920. if (!strcmp(domain, "*")) {
  921. domains = ~0u;
  922. } else {
  923. int d;
  924. int negate=0;
  925. if (*domain == '~') {
  926. negate = 1;
  927. ++domain;
  928. }
  929. d = parse_log_domain(domain);
  930. if (!d) {
  931. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  932. err = 1;
  933. } else {
  934. if (negate)
  935. neg_domains |= d;
  936. else
  937. domains |= d;
  938. }
  939. }
  940. });
  941. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  942. smartlist_free(domains_list);
  943. if (err)
  944. return -1;
  945. if (domains == 0 && neg_domains)
  946. domains = ~neg_domains;
  947. else
  948. domains &= ~neg_domains;
  949. cfg = eat_whitespace(closebracket+1);
  950. } else {
  951. ++got_an_unqualified_range;
  952. }
  953. if (!strcasecmpstart(cfg, "file") ||
  954. !strcasecmpstart(cfg, "stderr") ||
  955. !strcasecmpstart(cfg, "stdout") ||
  956. !strcasecmpstart(cfg, "syslog")) {
  957. goto done;
  958. }
  959. if (got_an_unqualified_range > 1)
  960. return -1;
  961. space = strchr(cfg, ' ');
  962. dash = strchr(cfg, '-');
  963. if (!space)
  964. space = strchr(cfg, '\0');
  965. if (dash && dash < space) {
  966. sev_lo = tor_strndup(cfg, dash-cfg);
  967. sev_hi = tor_strndup(dash+1, space-(dash+1));
  968. } else {
  969. sev_lo = tor_strndup(cfg, space-cfg);
  970. sev_hi = tor_strdup("ERR");
  971. }
  972. low = parse_log_level(sev_lo);
  973. high = parse_log_level(sev_hi);
  974. tor_free(sev_lo);
  975. tor_free(sev_hi);
  976. if (low == -1)
  977. return -1;
  978. if (high == -1)
  979. return -1;
  980. got_anything = 1;
  981. for (i=low; i >= high; --i)
  982. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  983. cfg = eat_whitespace(space);
  984. }
  985. done:
  986. *cfg_ptr = cfg;
  987. return got_anything ? 0 : -1;
  988. }
  989. /** Return the least severe log level that any current log is interested in. */
  990. int
  991. get_min_log_level(void)
  992. {
  993. logfile_t *lf;
  994. int i;
  995. int min = LOG_ERR;
  996. for (lf = logfiles; lf; lf = lf->next) {
  997. for (i = LOG_DEBUG; i > min; --i)
  998. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  999. min = i;
  1000. }
  1001. return min;
  1002. }
  1003. /** Switch all logs to output at most verbose level. */
  1004. void
  1005. switch_logs_debug(void)
  1006. {
  1007. logfile_t *lf;
  1008. int i;
  1009. LOCK_LOGS();
  1010. for (lf = logfiles; lf; lf=lf->next) {
  1011. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  1012. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  1013. }
  1014. _log_global_min_severity = get_min_log_level();
  1015. UNLOCK_LOGS();
  1016. }
  1017. #if 0
  1018. static void
  1019. dump_log_info(logfile_t *lf)
  1020. {
  1021. const char *tp;
  1022. if (lf->filename) {
  1023. printf("=== log into \"%s\" (%s-%s) (%stemporary)\n", lf->filename,
  1024. sev_to_string(lf->min_loglevel),
  1025. sev_to_string(lf->max_loglevel),
  1026. lf->is_temporary?"":"not ");
  1027. } else if (lf->is_syslog) {
  1028. printf("=== syslog (%s-%s) (%stemporary)\n",
  1029. sev_to_string(lf->min_loglevel),
  1030. sev_to_string(lf->max_loglevel),
  1031. lf->is_temporary?"":"not ");
  1032. } else {
  1033. printf("=== log (%s-%s) (%stemporary)\n",
  1034. sev_to_string(lf->min_loglevel),
  1035. sev_to_string(lf->max_loglevel),
  1036. lf->is_temporary?"":"not ");
  1037. }
  1038. }
  1039. void
  1040. describe_logs(void)
  1041. {
  1042. logfile_t *lf;
  1043. printf("==== BEGIN LOGS ====\n");
  1044. for (lf = logfiles; lf; lf = lf->next)
  1045. dump_log_info(lf);
  1046. printf("==== END LOGS ====\n");
  1047. }
  1048. #endif