log.c 27 KB

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