log.c 26 KB

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