log.c 33 KB

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