log.c 31 KB

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