log.c 26 KB

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