log.c 26 KB

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