log.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. }
  402. /** Remove and free the log entry <b>victim</b> from the linked-list
  403. * logfiles (it is probably present, but it might not be due to thread
  404. * racing issues). After this function is called, the caller shouldn't
  405. * refer to <b>victim</b> anymore.
  406. *
  407. * Long-term, we need to do something about races in the log subsystem
  408. * in general. See bug 222 for more details.
  409. */
  410. static void
  411. delete_log(logfile_t *victim)
  412. {
  413. logfile_t *tmpl;
  414. if (victim == logfiles)
  415. logfiles = victim->next;
  416. else {
  417. for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
  418. // tor_assert(tmpl);
  419. // tor_assert(tmpl->next == victim);
  420. if (!tmpl)
  421. return;
  422. tmpl->next = victim->next;
  423. }
  424. log_free(victim);
  425. }
  426. /** Helper: release system resources (but not memory) held by a single
  427. * logfile_t. */
  428. static void
  429. close_log(logfile_t *victim)
  430. {
  431. if (victim->needs_close && victim->file) {
  432. fclose(victim->file);
  433. } else if (victim->is_syslog) {
  434. #ifdef HAVE_SYSLOG_H
  435. if (--syslog_count == 0) {
  436. /* There are no other syslogs; close the logging facility. */
  437. closelog();
  438. }
  439. #endif
  440. }
  441. }
  442. /** Adjust a log severity configuration in <b>severity_out</b> to contain
  443. * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
  444. */
  445. void
  446. set_log_severity_config(int loglevelMin, int loglevelMax,
  447. log_severity_list_t *severity_out)
  448. {
  449. int i;
  450. tor_assert(loglevelMin >= loglevelMax);
  451. tor_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
  452. tor_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
  453. memset(severity_out, 0, sizeof(log_severity_list_t));
  454. for (i = loglevelMin; i >= loglevelMax; --i) {
  455. severity_out->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  456. }
  457. }
  458. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  459. * to <b>stream</b>. Copies <b>severity</b>. Helper: does no locking. */
  460. static void
  461. add_stream_log_impl(log_severity_list_t *severity,
  462. const char *name, FILE *stream)
  463. {
  464. logfile_t *lf;
  465. lf = tor_malloc_zero(sizeof(logfile_t));
  466. lf->filename = tor_strdup(name);
  467. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  468. lf->file = stream;
  469. lf->next = logfiles;
  470. logfiles = lf;
  471. _log_global_min_severity = get_min_log_level();
  472. }
  473. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  474. * to <b>stream</b>. Steals a reference to <b>severity</b>; the caller must
  475. * not use it after calling this function. */
  476. void
  477. add_stream_log(log_severity_list_t *severity,
  478. const char *name, FILE *stream)
  479. {
  480. LOCK_LOGS();
  481. add_stream_log_impl(severity, name, stream);
  482. UNLOCK_LOGS();
  483. }
  484. /** Initialize the global logging facility */
  485. void
  486. init_logging(void)
  487. {
  488. if (!log_mutex)
  489. log_mutex = tor_mutex_new();
  490. }
  491. /** Add a log handler to receive messages during startup (before the real
  492. * logs are initialized).
  493. */
  494. void
  495. add_temp_log(void)
  496. {
  497. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  498. set_log_severity_config(LOG_NOTICE, LOG_ERR, s);
  499. LOCK_LOGS();
  500. add_stream_log_impl(s, "<temp>", stdout);
  501. logfiles->is_temporary = 1;
  502. UNLOCK_LOGS();
  503. }
  504. /**
  505. * Add a log handler to send messages in <b>severity</b>
  506. * to the function <b>cb</b>.
  507. */
  508. int
  509. add_callback_log(log_severity_list_t *severity, log_callback cb)
  510. {
  511. logfile_t *lf;
  512. lf = tor_malloc_zero(sizeof(logfile_t));
  513. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  514. lf->filename = tor_strdup("<callback>");
  515. lf->callback = cb;
  516. lf->next = logfiles;
  517. LOCK_LOGS();
  518. logfiles = lf;
  519. _log_global_min_severity = get_min_log_level();
  520. UNLOCK_LOGS();
  521. return 0;
  522. }
  523. /** Adjust the configured severity of any logs whose callback function is
  524. * <b>cb</b>. */
  525. void
  526. change_callback_log_severity(int loglevelMin, int loglevelMax,
  527. log_callback cb)
  528. {
  529. logfile_t *lf;
  530. LOCK_LOGS();
  531. for (lf = logfiles; lf; lf = lf->next) {
  532. if (lf->callback == cb) {
  533. set_log_severity_config(loglevelMin, loglevelMax, lf->severities);
  534. }
  535. }
  536. _log_global_min_severity = get_min_log_level();
  537. UNLOCK_LOGS();
  538. }
  539. /** Close any log handlers added by add_temp_log or marked by mark_logs_temp */
  540. void
  541. close_temp_logs(void)
  542. {
  543. logfile_t *lf, **p;
  544. LOCK_LOGS();
  545. for (p = &logfiles; *p; ) {
  546. if ((*p)->is_temporary) {
  547. lf = *p;
  548. /* we use *p here to handle the edge case of the head of the list */
  549. *p = (*p)->next;
  550. close_log(lf);
  551. log_free(lf);
  552. } else {
  553. p = &((*p)->next);
  554. }
  555. }
  556. _log_global_min_severity = get_min_log_level();
  557. UNLOCK_LOGS();
  558. }
  559. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  560. * live again, and close all non-temporary logs. */
  561. void
  562. rollback_log_changes(void)
  563. {
  564. logfile_t *lf;
  565. LOCK_LOGS();
  566. for (lf = logfiles; lf; lf = lf->next)
  567. lf->is_temporary = ! lf->is_temporary;
  568. UNLOCK_LOGS();
  569. close_temp_logs();
  570. }
  571. /** Configure all log handles to be closed by close_temp_logs */
  572. void
  573. mark_logs_temp(void)
  574. {
  575. logfile_t *lf;
  576. LOCK_LOGS();
  577. for (lf = logfiles; lf; lf = lf->next)
  578. lf->is_temporary = 1;
  579. UNLOCK_LOGS();
  580. }
  581. /**
  582. * Add a log handler to send messages to <b>filename</b>. If opening
  583. * the logfile fails, -1 is returned and errno is set appropriately
  584. * (by fopen).
  585. */
  586. int
  587. add_file_log(log_severity_list_t *severity, const char *filename)
  588. {
  589. FILE *f;
  590. logfile_t *lf;
  591. f = fopen(filename, "a");
  592. if (!f) return -1;
  593. LOCK_LOGS();
  594. add_stream_log_impl(severity, filename, f);
  595. logfiles->needs_close = 1;
  596. lf = logfiles;
  597. _log_global_min_severity = get_min_log_level();
  598. UNLOCK_LOGS();
  599. if (log_tor_version(lf, 0) < 0) {
  600. LOCK_LOGS();
  601. delete_log(lf);
  602. UNLOCK_LOGS();
  603. }
  604. return 0;
  605. }
  606. #ifdef HAVE_SYSLOG_H
  607. /**
  608. * Add a log handler to send messages to they system log facility.
  609. */
  610. int
  611. add_syslog_log(log_severity_list_t *severity)
  612. {
  613. logfile_t *lf;
  614. if (syslog_count++ == 0)
  615. /* This is the first syslog. */
  616. openlog("Tor", LOG_PID | LOG_NDELAY, LOGFACILITY);
  617. lf = tor_malloc_zero(sizeof(logfile_t));
  618. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  619. lf->filename = tor_strdup("<syslog>");
  620. lf->is_syslog = 1;
  621. LOCK_LOGS();
  622. lf->next = logfiles;
  623. logfiles = lf;
  624. _log_global_min_severity = get_min_log_level();
  625. UNLOCK_LOGS();
  626. return 0;
  627. }
  628. #endif
  629. /** If <b>level</b> is a valid log severity, return the corresponding
  630. * numeric value. Otherwise, return -1. */
  631. int
  632. parse_log_level(const char *level)
  633. {
  634. if (!strcasecmp(level, "err"))
  635. return LOG_ERR;
  636. if (!strcasecmp(level, "warn"))
  637. return LOG_WARN;
  638. if (!strcasecmp(level, "notice"))
  639. return LOG_NOTICE;
  640. if (!strcasecmp(level, "info"))
  641. return LOG_INFO;
  642. if (!strcasecmp(level, "debug"))
  643. return LOG_DEBUG;
  644. return -1;
  645. }
  646. /** Return the string equivalent of a given log level. */
  647. const char *
  648. log_level_to_string(int level)
  649. {
  650. return sev_to_string(level);
  651. }
  652. /** DOCDOC */
  653. static const char *domain_list[] = {
  654. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  655. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  656. "OR", "EDGE", "ACCT", NULL
  657. };
  658. /** DOCDOC */
  659. static log_domain_mask_t
  660. parse_log_domain(const char *domain)
  661. {
  662. int i;
  663. for (i=0; domain_list[i]; ++i) {
  664. if (!strcasecmp(domain, domain_list[i]))
  665. return (1u<<i);
  666. }
  667. return 0;
  668. }
  669. #if 0
  670. /** DOCDOC */
  671. static const char *
  672. domain_to_string(log_domain_mask_t domain)
  673. {
  674. int bit = tor_log2(domain);
  675. if ((bit == 0 && domain == 0) || bit >= N_LOGGING_DOMAINS)
  676. return NULL;
  677. return domain_list[bit];
  678. }
  679. #endif
  680. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  681. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  682. * the parsed pattern. Return 0 on success, -1 on failure.
  683. *
  684. * The syntax for a SeverityPattern is:
  685. * <pre>
  686. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  687. * DomainSeverity = (DomainList SP)? SeverityRange
  688. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  689. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  690. * DomainSpec = "*" | Domain | "~" Domain
  691. * </pre>
  692. * A missing MaxSeverity defaults to ERR. Severities and domains are
  693. * case-insensitive. "~" indicates negation for a domain; negation happens
  694. * last inside a DomainList. Only one SeverityRange without a DomainList is
  695. * allowed per line.
  696. */
  697. int
  698. parse_log_severity_config(const char **cfg_ptr,
  699. log_severity_list_t *severity_out)
  700. {
  701. const char *cfg = *cfg_ptr;
  702. int got_anything = 0;
  703. int got_an_unqualified_range = 0;
  704. memset(severity_out, 0, sizeof(*severity_out));
  705. cfg = eat_whitespace(cfg);
  706. while (*cfg) {
  707. const char *dash, *space;
  708. char *sev_lo, *sev_hi;
  709. int low, high, i;
  710. log_domain_mask_t domains = ~0u;
  711. if (*cfg == '[') {
  712. int err = 0;
  713. char *domains_str;
  714. smartlist_t *domains_list;
  715. log_domain_mask_t neg_domains = 0;
  716. const char *closebracket = strchr(cfg, ']');
  717. if (!closebracket)
  718. return -1;
  719. domains = 0;
  720. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  721. domains_list = smartlist_create();
  722. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  723. -1);
  724. tor_free(domains_str);
  725. SMARTLIST_FOREACH(domains_list, const char *, domain,
  726. {
  727. if (!strcmp(domain, "*")) {
  728. domains = ~0u;
  729. } else {
  730. int d;
  731. int negate=0;
  732. if (*domain == '~') {
  733. negate = 1;
  734. ++domain;
  735. }
  736. d = parse_log_domain(domain);
  737. if (!d) {
  738. log_warn(LD_CONFIG, "No such loggging domain as %s", domain);
  739. err = 1;
  740. } else {
  741. if (negate)
  742. neg_domains |= d;
  743. else
  744. domains |= d;
  745. }
  746. }
  747. });
  748. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  749. smartlist_free(domains_list);
  750. if (err)
  751. return -1;
  752. domains &= ~neg_domains;
  753. cfg = eat_whitespace(closebracket+1);
  754. } else {
  755. ++got_an_unqualified_range;
  756. }
  757. if (!strcasecmpstart(cfg, "file") ||
  758. !strcasecmpstart(cfg, "stderr") ||
  759. !strcasecmpstart(cfg, "stdout") ||
  760. !strcasecmpstart(cfg, "syslog")) {
  761. goto done;
  762. }
  763. if (got_an_unqualified_range > 1)
  764. return -1;
  765. space = strchr(cfg, ' ');
  766. dash = strchr(cfg, '-');
  767. if (!space)
  768. space = strchr(cfg, '\0');
  769. if (dash && dash < space) {
  770. sev_lo = tor_strndup(cfg, dash-cfg);
  771. sev_hi = tor_strndup(dash+1, space-(dash+1));
  772. } else {
  773. sev_lo = tor_strndup(cfg, space-cfg);
  774. sev_hi = tor_strdup("ERR");
  775. }
  776. if ((low = parse_log_level(sev_lo)) == -1)
  777. return -1;
  778. if ((high = parse_log_level(sev_hi)) == -1)
  779. return -1;
  780. got_anything = 1;
  781. for (i=low; i >= high; --i)
  782. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  783. cfg = eat_whitespace(space);
  784. }
  785. done:
  786. *cfg_ptr = cfg;
  787. return got_anything ? 0 : -1;
  788. }
  789. /** Return the least severe log level that any current log is interested in. */
  790. int
  791. get_min_log_level(void)
  792. {
  793. logfile_t *lf;
  794. int i;
  795. int min = LOG_ERR;
  796. for (lf = logfiles; lf; lf = lf->next) {
  797. for (i = LOG_DEBUG; i > min; --i)
  798. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  799. min = i;
  800. }
  801. return min;
  802. }
  803. /** Switch all logs to output at most verbose level. */
  804. void
  805. switch_logs_debug(void)
  806. {
  807. logfile_t *lf;
  808. int i;
  809. LOCK_LOGS();
  810. for (lf = logfiles; lf; lf=lf->next) {
  811. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  812. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  813. }
  814. UNLOCK_LOGS();
  815. }
  816. #ifdef HAVE_EVENT_SET_LOG_CALLBACK
  817. /** A string which, if it appears in a libevent log, should be ignored. */
  818. static const char *suppress_msg = NULL;
  819. /** Callback function passed to event_set_log() so we can intercept
  820. * log messages from libevent. */
  821. static void
  822. libevent_logging_callback(int severity, const char *msg)
  823. {
  824. char buf[1024];
  825. size_t n;
  826. if (suppress_msg && strstr(msg, suppress_msg))
  827. return;
  828. n = strlcpy(buf, msg, sizeof(buf));
  829. if (n && n < sizeof(buf) && buf[n-1] == '\n') {
  830. buf[n-1] = '\0';
  831. }
  832. switch (severity) {
  833. case _EVENT_LOG_DEBUG:
  834. log(LOG_DEBUG, LD_NET, "Message from libevent: %s", buf);
  835. break;
  836. case _EVENT_LOG_MSG:
  837. log(LOG_INFO, LD_NET, "Message from libevent: %s", buf);
  838. break;
  839. case _EVENT_LOG_WARN:
  840. log(LOG_WARN, LD_GENERAL, "Warning from libevent: %s", buf);
  841. break;
  842. case _EVENT_LOG_ERR:
  843. log(LOG_ERR, LD_GENERAL, "Error from libevent: %s", buf);
  844. break;
  845. default:
  846. log(LOG_WARN, LD_GENERAL, "Message [%d] from libevent: %s",
  847. severity, buf);
  848. break;
  849. }
  850. }
  851. /** Set hook to intercept log messages from libevent. */
  852. void
  853. configure_libevent_logging(void)
  854. {
  855. event_set_log_callback(libevent_logging_callback);
  856. }
  857. /** Ignore any libevent log message that contains <b>msg</b>. */
  858. void
  859. suppress_libevent_log_msg(const char *msg)
  860. {
  861. suppress_msg = msg;
  862. }
  863. #else
  864. void
  865. configure_libevent_logging(void)
  866. {
  867. }
  868. void
  869. suppress_libevent_log_msg(const char *msg)
  870. {
  871. (void)msg;
  872. }
  873. #endif
  874. #if 0
  875. static void
  876. dump_log_info(logfile_t *lf)
  877. {
  878. const char *tp;
  879. if (lf->filename) {
  880. printf("=== log into \"%s\" (%s-%s) (%stemporary)\n", lf->filename,
  881. sev_to_string(lf->min_loglevel),
  882. sev_to_string(lf->max_loglevel),
  883. lf->is_temporary?"":"not ");
  884. } else if (lf->is_syslog) {
  885. printf("=== syslog (%s-%s) (%stemporary)\n",
  886. sev_to_string(lf->min_loglevel),
  887. sev_to_string(lf->max_loglevel),
  888. lf->is_temporary?"":"not ");
  889. } else {
  890. printf("=== log (%s-%s) (%stemporary)\n",
  891. sev_to_string(lf->min_loglevel),
  892. sev_to_string(lf->max_loglevel),
  893. lf->is_temporary?"":"not ");
  894. }
  895. }
  896. void
  897. describe_logs(void)
  898. {
  899. logfile_t *lf;
  900. printf("==== BEGIN LOGS ====\n");
  901. for (lf = logfiles; lf; lf = lf->next)
  902. dump_log_info(lf);
  903. printf("==== END LOGS ====\n");
  904. }
  905. #endif