log.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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-2010, 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 "torlog.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. tor_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. if (log_tor_version(lf, 0) < 0) {
  628. delete_log(lf);
  629. }
  630. UNLOCK_LOGS();
  631. return 0;
  632. }
  633. #ifdef HAVE_SYSLOG_H
  634. /**
  635. * Add a log handler to send messages to they system log facility.
  636. */
  637. int
  638. add_syslog_log(const log_severity_list_t *severity)
  639. {
  640. logfile_t *lf;
  641. if (syslog_count++ == 0)
  642. /* This is the first syslog. */
  643. openlog("Tor", LOG_PID | LOG_NDELAY, LOGFACILITY);
  644. lf = tor_malloc_zero(sizeof(logfile_t));
  645. lf->fd = -1;
  646. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  647. lf->filename = tor_strdup("<syslog>");
  648. lf->is_syslog = 1;
  649. LOCK_LOGS();
  650. lf->next = logfiles;
  651. logfiles = lf;
  652. _log_global_min_severity = get_min_log_level();
  653. UNLOCK_LOGS();
  654. return 0;
  655. }
  656. #endif
  657. /** If <b>level</b> is a valid log severity, return the corresponding
  658. * numeric value. Otherwise, return -1. */
  659. int
  660. parse_log_level(const char *level)
  661. {
  662. if (!strcasecmp(level, "err"))
  663. return LOG_ERR;
  664. if (!strcasecmp(level, "warn"))
  665. return LOG_WARN;
  666. if (!strcasecmp(level, "notice"))
  667. return LOG_NOTICE;
  668. if (!strcasecmp(level, "info"))
  669. return LOG_INFO;
  670. if (!strcasecmp(level, "debug"))
  671. return LOG_DEBUG;
  672. return -1;
  673. }
  674. /** Return the string equivalent of a given log level. */
  675. const char *
  676. log_level_to_string(int level)
  677. {
  678. return sev_to_string(level);
  679. }
  680. /** NULL-terminated array of names for log domains such that domain_list[dom]
  681. * is a description of <b>dom</b>. */
  682. static const char *domain_list[] = {
  683. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  684. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  685. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", NULL
  686. };
  687. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  688. * or 0 if there is no such name. */
  689. static log_domain_mask_t
  690. parse_log_domain(const char *domain)
  691. {
  692. int i;
  693. for (i=0; domain_list[i]; ++i) {
  694. if (!strcasecmp(domain, domain_list[i]))
  695. return (1u<<i);
  696. }
  697. return 0;
  698. }
  699. #if 0
  700. /** Translate a bitmask of log domains to a string, or NULL if the bitmask
  701. * is undecodable. */
  702. static const char *
  703. domain_to_string(log_domain_mask_t domain)
  704. {
  705. int bit = tor_log2(domain);
  706. if ((bit == 0 && domain == 0) || bit >= N_LOGGING_DOMAINS)
  707. return NULL;
  708. return domain_list[bit];
  709. }
  710. #endif
  711. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  712. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  713. * the parsed pattern. Return 0 on success, -1 on failure.
  714. *
  715. * The syntax for a SeverityPattern is:
  716. * <pre>
  717. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  718. * DomainSeverity = (DomainList SP)? SeverityRange
  719. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  720. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  721. * DomainSpec = "*" | Domain | "~" Domain
  722. * </pre>
  723. * A missing MaxSeverity defaults to ERR. Severities and domains are
  724. * case-insensitive. "~" indicates negation for a domain; negation happens
  725. * last inside a DomainList. Only one SeverityRange without a DomainList is
  726. * allowed per line.
  727. */
  728. int
  729. parse_log_severity_config(const char **cfg_ptr,
  730. log_severity_list_t *severity_out)
  731. {
  732. const char *cfg = *cfg_ptr;
  733. int got_anything = 0;
  734. int got_an_unqualified_range = 0;
  735. memset(severity_out, 0, sizeof(*severity_out));
  736. cfg = eat_whitespace(cfg);
  737. while (*cfg) {
  738. const char *dash, *space;
  739. char *sev_lo, *sev_hi;
  740. int low, high, i;
  741. log_domain_mask_t domains = ~0u;
  742. if (*cfg == '[') {
  743. int err = 0;
  744. char *domains_str;
  745. smartlist_t *domains_list;
  746. log_domain_mask_t neg_domains = 0;
  747. const char *closebracket = strchr(cfg, ']');
  748. if (!closebracket)
  749. return -1;
  750. domains = 0;
  751. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  752. domains_list = smartlist_create();
  753. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  754. -1);
  755. tor_free(domains_str);
  756. SMARTLIST_FOREACH(domains_list, const char *, domain,
  757. {
  758. if (!strcmp(domain, "*")) {
  759. domains = ~0u;
  760. } else {
  761. int d;
  762. int negate=0;
  763. if (*domain == '~') {
  764. negate = 1;
  765. ++domain;
  766. }
  767. d = parse_log_domain(domain);
  768. if (!d) {
  769. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  770. err = 1;
  771. } else {
  772. if (negate)
  773. neg_domains |= d;
  774. else
  775. domains |= d;
  776. }
  777. }
  778. });
  779. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  780. smartlist_free(domains_list);
  781. if (err)
  782. return -1;
  783. domains &= ~neg_domains;
  784. cfg = eat_whitespace(closebracket+1);
  785. } else {
  786. ++got_an_unqualified_range;
  787. }
  788. if (!strcasecmpstart(cfg, "file") ||
  789. !strcasecmpstart(cfg, "stderr") ||
  790. !strcasecmpstart(cfg, "stdout") ||
  791. !strcasecmpstart(cfg, "syslog")) {
  792. goto done;
  793. }
  794. if (got_an_unqualified_range > 1)
  795. return -1;
  796. space = strchr(cfg, ' ');
  797. dash = strchr(cfg, '-');
  798. if (!space)
  799. space = strchr(cfg, '\0');
  800. if (dash && dash < space) {
  801. sev_lo = tor_strndup(cfg, dash-cfg);
  802. sev_hi = tor_strndup(dash+1, space-(dash+1));
  803. } else {
  804. sev_lo = tor_strndup(cfg, space-cfg);
  805. sev_hi = tor_strdup("ERR");
  806. }
  807. low = parse_log_level(sev_lo);
  808. high = parse_log_level(sev_hi);
  809. tor_free(sev_lo);
  810. tor_free(sev_hi);
  811. if (low == -1)
  812. return -1;
  813. if (high == -1)
  814. return -1;
  815. got_anything = 1;
  816. for (i=low; i >= high; --i)
  817. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  818. cfg = eat_whitespace(space);
  819. }
  820. done:
  821. *cfg_ptr = cfg;
  822. return got_anything ? 0 : -1;
  823. }
  824. /** Return the least severe log level that any current log is interested in. */
  825. int
  826. get_min_log_level(void)
  827. {
  828. logfile_t *lf;
  829. int i;
  830. int min = LOG_ERR;
  831. for (lf = logfiles; lf; lf = lf->next) {
  832. for (i = LOG_DEBUG; i > min; --i)
  833. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  834. min = i;
  835. }
  836. return min;
  837. }
  838. /** Switch all logs to output at most verbose level. */
  839. void
  840. switch_logs_debug(void)
  841. {
  842. logfile_t *lf;
  843. int i;
  844. LOCK_LOGS();
  845. for (lf = logfiles; lf; lf=lf->next) {
  846. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  847. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  848. }
  849. _log_global_min_severity = get_min_log_level();
  850. UNLOCK_LOGS();
  851. }
  852. #if 0
  853. static void
  854. dump_log_info(logfile_t *lf)
  855. {
  856. const char *tp;
  857. if (lf->filename) {
  858. printf("=== log into \"%s\" (%s-%s) (%stemporary)\n", lf->filename,
  859. sev_to_string(lf->min_loglevel),
  860. sev_to_string(lf->max_loglevel),
  861. lf->is_temporary?"":"not ");
  862. } else if (lf->is_syslog) {
  863. printf("=== syslog (%s-%s) (%stemporary)\n",
  864. sev_to_string(lf->min_loglevel),
  865. sev_to_string(lf->max_loglevel),
  866. lf->is_temporary?"":"not ");
  867. } else {
  868. printf("=== log (%s-%s) (%stemporary)\n",
  869. sev_to_string(lf->min_loglevel),
  870. sev_to_string(lf->max_loglevel),
  871. lf->is_temporary?"":"not ");
  872. }
  873. }
  874. void
  875. describe_logs(void)
  876. {
  877. logfile_t *lf;
  878. printf("==== BEGIN LOGS ====\n");
  879. for (lf = logfiles; lf; lf = lf->next)
  880. dump_log_info(lf);
  881. printf("==== END LOGS ====\n");
  882. }
  883. #endif