log.c 28 KB

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