log.c 29 KB

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