log.c 31 KB

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