log.c 30 KB

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