log.c 27 KB

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