log.c 27 KB

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