log.c 25 KB

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