log.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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 && pending_cb_messages) {
  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. * is formatted printf-style based on <b>format</b> and extra arguments.
  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
  369. * <b>fn</b>, which 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. smartlist_t *messages;
  473. LOCK_LOGS();
  474. next = logfiles;
  475. logfiles = NULL;
  476. messages = pending_cb_messages;
  477. pending_cb_messages = NULL;
  478. UNLOCK_LOGS();
  479. while (next) {
  480. victim = next;
  481. next = next->next;
  482. close_log(victim);
  483. log_free(victim);
  484. }
  485. tor_free(appname);
  486. SMARTLIST_FOREACH(messages, pending_cb_message_t *, msg, {
  487. tor_free(msg->msg);
  488. tor_free(msg);
  489. });
  490. smartlist_free(messages);
  491. /* We _could_ destroy the log mutex here, but that would screw up any logs
  492. * that happened between here and the end of execution. */
  493. }
  494. /** Remove and free the log entry <b>victim</b> from the linked-list
  495. * logfiles (it is probably present, but it might not be due to thread
  496. * racing issues). After this function is called, the caller shouldn't
  497. * refer to <b>victim</b> anymore.
  498. *
  499. * Long-term, we need to do something about races in the log subsystem
  500. * in general. See bug 222 for more details.
  501. */
  502. static void
  503. delete_log(logfile_t *victim)
  504. {
  505. logfile_t *tmpl;
  506. if (victim == logfiles)
  507. logfiles = victim->next;
  508. else {
  509. for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
  510. // tor_assert(tmpl);
  511. // tor_assert(tmpl->next == victim);
  512. if (!tmpl)
  513. return;
  514. tmpl->next = victim->next;
  515. }
  516. log_free(victim);
  517. }
  518. /** Helper: release system resources (but not memory) held by a single
  519. * logfile_t. */
  520. static void
  521. close_log(logfile_t *victim)
  522. {
  523. if (victim->needs_close && victim->fd >= 0) {
  524. close(victim->fd);
  525. victim->fd = -1;
  526. } else if (victim->is_syslog) {
  527. #ifdef HAVE_SYSLOG_H
  528. if (--syslog_count == 0) {
  529. /* There are no other syslogs; close the logging facility. */
  530. closelog();
  531. }
  532. #endif
  533. }
  534. }
  535. /** Adjust a log severity configuration in <b>severity_out</b> to contain
  536. * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
  537. */
  538. void
  539. set_log_severity_config(int loglevelMin, int loglevelMax,
  540. log_severity_list_t *severity_out)
  541. {
  542. int i;
  543. tor_assert(loglevelMin >= loglevelMax);
  544. tor_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
  545. tor_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
  546. memset(severity_out, 0, sizeof(log_severity_list_t));
  547. for (i = loglevelMin; i >= loglevelMax; --i) {
  548. severity_out->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  549. }
  550. }
  551. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  552. * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
  553. static void
  554. add_stream_log_impl(const log_severity_list_t *severity,
  555. const char *name, int fd)
  556. {
  557. logfile_t *lf;
  558. lf = tor_malloc_zero(sizeof(logfile_t));
  559. lf->fd = fd;
  560. lf->filename = tor_strdup(name);
  561. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  562. lf->next = logfiles;
  563. logfiles = lf;
  564. _log_global_min_severity = get_min_log_level();
  565. }
  566. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  567. * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
  568. * not use it after calling this function. */
  569. void
  570. add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
  571. {
  572. LOCK_LOGS();
  573. add_stream_log_impl(severity, name, fd);
  574. UNLOCK_LOGS();
  575. }
  576. /** Initialize the global logging facility */
  577. void
  578. init_logging(void)
  579. {
  580. if (!log_mutex_initialized) {
  581. tor_mutex_init(&log_mutex);
  582. log_mutex_initialized = 1;
  583. }
  584. if (pending_cb_messages == NULL)
  585. pending_cb_messages = smartlist_create();
  586. }
  587. /** Set whether we report logging domains as a part of our log messages.
  588. */
  589. void
  590. logs_set_domain_logging(int enabled)
  591. {
  592. LOCK_LOGS();
  593. log_domains_are_logged = enabled;
  594. UNLOCK_LOGS();
  595. }
  596. /** Add a log handler to receive messages during startup (before the real
  597. * logs are initialized).
  598. */
  599. void
  600. add_temp_log(int min_severity)
  601. {
  602. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  603. set_log_severity_config(min_severity, LOG_ERR, s);
  604. LOCK_LOGS();
  605. add_stream_log_impl(s, "<temp>", fileno(stdout));
  606. tor_free(s);
  607. logfiles->is_temporary = 1;
  608. UNLOCK_LOGS();
  609. }
  610. /**
  611. * Add a log handler to send messages in <b>severity</b>
  612. * to the function <b>cb</b>.
  613. */
  614. int
  615. add_callback_log(const log_severity_list_t *severity, log_callback cb)
  616. {
  617. logfile_t *lf;
  618. lf = tor_malloc_zero(sizeof(logfile_t));
  619. lf->fd = -1;
  620. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  621. lf->filename = tor_strdup("<callback>");
  622. lf->callback = cb;
  623. lf->next = logfiles;
  624. LOCK_LOGS();
  625. logfiles = lf;
  626. _log_global_min_severity = get_min_log_level();
  627. UNLOCK_LOGS();
  628. return 0;
  629. }
  630. /** Adjust the configured severity of any logs whose callback function is
  631. * <b>cb</b>. */
  632. void
  633. change_callback_log_severity(int loglevelMin, int loglevelMax,
  634. log_callback cb)
  635. {
  636. logfile_t *lf;
  637. log_severity_list_t severities;
  638. set_log_severity_config(loglevelMin, loglevelMax, &severities);
  639. LOCK_LOGS();
  640. for (lf = logfiles; lf; lf = lf->next) {
  641. if (lf->callback == cb) {
  642. memcpy(lf->severities, &severities, sizeof(severities));
  643. }
  644. }
  645. _log_global_min_severity = get_min_log_level();
  646. UNLOCK_LOGS();
  647. }
  648. /** If there are any log messages that were genered with LD_NOCB waiting to
  649. * be sent to callback-based loggers, send them now. */
  650. void
  651. flush_pending_log_callbacks(void)
  652. {
  653. logfile_t *lf;
  654. smartlist_t *messages, *messages_tmp;
  655. LOCK_LOGS();
  656. if (0 == smartlist_len(pending_cb_messages)) {
  657. UNLOCK_LOGS();
  658. return;
  659. }
  660. messages = pending_cb_messages;
  661. pending_cb_messages = smartlist_create();
  662. do {
  663. SMARTLIST_FOREACH_BEGIN(messages, pending_cb_message_t *, msg) {
  664. const int severity = msg->severity;
  665. const int domain = msg->domain;
  666. for (lf = logfiles; lf; lf = lf->next) {
  667. if (! lf->callback || lf->seems_dead ||
  668. ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  669. continue;
  670. }
  671. lf->callback(severity, domain, msg->msg);
  672. }
  673. tor_free(msg->msg);
  674. tor_free(msg);
  675. } SMARTLIST_FOREACH_END(msg);
  676. smartlist_clear(messages);
  677. messages_tmp = pending_cb_messages;
  678. pending_cb_messages = messages;
  679. messages = messages_tmp;
  680. } while (smartlist_len(messages));
  681. smartlist_free(messages);
  682. UNLOCK_LOGS();
  683. }
  684. /** Close any log handlers added by add_temp_log() or marked by
  685. * mark_logs_temp(). */
  686. void
  687. close_temp_logs(void)
  688. {
  689. logfile_t *lf, **p;
  690. LOCK_LOGS();
  691. for (p = &logfiles; *p; ) {
  692. if ((*p)->is_temporary) {
  693. lf = *p;
  694. /* we use *p here to handle the edge case of the head of the list */
  695. *p = (*p)->next;
  696. close_log(lf);
  697. log_free(lf);
  698. } else {
  699. p = &((*p)->next);
  700. }
  701. }
  702. _log_global_min_severity = get_min_log_level();
  703. UNLOCK_LOGS();
  704. }
  705. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  706. * live again, and close all non-temporary logs. */
  707. void
  708. rollback_log_changes(void)
  709. {
  710. logfile_t *lf;
  711. LOCK_LOGS();
  712. for (lf = logfiles; lf; lf = lf->next)
  713. lf->is_temporary = ! lf->is_temporary;
  714. UNLOCK_LOGS();
  715. close_temp_logs();
  716. }
  717. /** Configure all log handles to be closed by close_temp_logs(). */
  718. void
  719. mark_logs_temp(void)
  720. {
  721. logfile_t *lf;
  722. LOCK_LOGS();
  723. for (lf = logfiles; lf; lf = lf->next)
  724. lf->is_temporary = 1;
  725. UNLOCK_LOGS();
  726. }
  727. /**
  728. * Add a log handler to send messages to <b>filename</b>. If opening the
  729. * logfile fails, -1 is returned and errno is set appropriately (by open(2)).
  730. */
  731. int
  732. add_file_log(const log_severity_list_t *severity, const char *filename)
  733. {
  734. int fd;
  735. logfile_t *lf;
  736. fd = open(filename, O_WRONLY|O_CREAT|O_APPEND, 0644);
  737. if (fd<0)
  738. return -1;
  739. if (tor_fd_seekend(fd)<0)
  740. return -1;
  741. LOCK_LOGS();
  742. add_stream_log_impl(severity, filename, fd);
  743. logfiles->needs_close = 1;
  744. lf = logfiles;
  745. _log_global_min_severity = get_min_log_level();
  746. if (log_tor_version(lf, 0) < 0) {
  747. delete_log(lf);
  748. }
  749. UNLOCK_LOGS();
  750. return 0;
  751. }
  752. #ifdef HAVE_SYSLOG_H
  753. /**
  754. * Add a log handler to send messages to they system log facility.
  755. */
  756. int
  757. add_syslog_log(const log_severity_list_t *severity)
  758. {
  759. logfile_t *lf;
  760. if (syslog_count++ == 0)
  761. /* This is the first syslog. */
  762. openlog("Tor", LOG_PID | LOG_NDELAY, LOGFACILITY);
  763. lf = tor_malloc_zero(sizeof(logfile_t));
  764. lf->fd = -1;
  765. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  766. lf->filename = tor_strdup("<syslog>");
  767. lf->is_syslog = 1;
  768. LOCK_LOGS();
  769. lf->next = logfiles;
  770. logfiles = lf;
  771. _log_global_min_severity = get_min_log_level();
  772. UNLOCK_LOGS();
  773. return 0;
  774. }
  775. #endif
  776. /** If <b>level</b> is a valid log severity, return the corresponding
  777. * numeric value. Otherwise, return -1. */
  778. int
  779. parse_log_level(const char *level)
  780. {
  781. if (!strcasecmp(level, "err"))
  782. return LOG_ERR;
  783. if (!strcasecmp(level, "warn"))
  784. return LOG_WARN;
  785. if (!strcasecmp(level, "notice"))
  786. return LOG_NOTICE;
  787. if (!strcasecmp(level, "info"))
  788. return LOG_INFO;
  789. if (!strcasecmp(level, "debug"))
  790. return LOG_DEBUG;
  791. return -1;
  792. }
  793. /** Return the string equivalent of a given log level. */
  794. const char *
  795. log_level_to_string(int level)
  796. {
  797. return sev_to_string(level);
  798. }
  799. /** NULL-terminated array of names for log domains such that domain_list[dom]
  800. * is a description of <b>dom</b>. */
  801. static const char *domain_list[] = {
  802. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  803. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  804. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", NULL
  805. };
  806. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  807. * or 0 if there is no such name. */
  808. static log_domain_mask_t
  809. parse_log_domain(const char *domain)
  810. {
  811. int i;
  812. for (i=0; domain_list[i]; ++i) {
  813. if (!strcasecmp(domain, domain_list[i]))
  814. return (1u<<i);
  815. }
  816. return 0;
  817. }
  818. /** Translate a bitmask of log domains to a string. */
  819. static char *
  820. domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
  821. {
  822. char *cp = buf;
  823. char *eos = buf+buflen;
  824. buf[0] = '\0';
  825. if (! domain)
  826. return buf;
  827. while (1) {
  828. const char *d;
  829. int bit = tor_log2(domain);
  830. size_t n;
  831. if (bit >= N_LOGGING_DOMAINS) {
  832. tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
  833. return buf+strlen(buf);
  834. }
  835. d = domain_list[bit];
  836. n = strlcpy(cp, d, eos-cp);
  837. if (n >= buflen) {
  838. tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
  839. return buf+strlen(buf);
  840. }
  841. cp += n;
  842. domain &= ~(1<<bit);
  843. if (domain == 0 || (eos-cp) < 2)
  844. return cp;
  845. memcpy(cp, ",", 2); /*Nul-terminated ,"*/
  846. cp++;
  847. }
  848. }
  849. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  850. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  851. * the parsed pattern. Return 0 on success, -1 on failure.
  852. *
  853. * The syntax for a SeverityPattern is:
  854. * <pre>
  855. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  856. * DomainSeverity = (DomainList SP)? SeverityRange
  857. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  858. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  859. * DomainSpec = "*" | Domain | "~" Domain
  860. * </pre>
  861. * A missing MaxSeverity defaults to ERR. Severities and domains are
  862. * case-insensitive. "~" indicates negation for a domain; negation happens
  863. * last inside a DomainList. Only one SeverityRange without a DomainList is
  864. * allowed per line.
  865. */
  866. int
  867. parse_log_severity_config(const char **cfg_ptr,
  868. log_severity_list_t *severity_out)
  869. {
  870. const char *cfg = *cfg_ptr;
  871. int got_anything = 0;
  872. int got_an_unqualified_range = 0;
  873. memset(severity_out, 0, sizeof(*severity_out));
  874. cfg = eat_whitespace(cfg);
  875. while (*cfg) {
  876. const char *dash, *space;
  877. char *sev_lo, *sev_hi;
  878. int low, high, i;
  879. log_domain_mask_t domains = ~0u;
  880. if (*cfg == '[') {
  881. int err = 0;
  882. char *domains_str;
  883. smartlist_t *domains_list;
  884. log_domain_mask_t neg_domains = 0;
  885. const char *closebracket = strchr(cfg, ']');
  886. if (!closebracket)
  887. return -1;
  888. domains = 0;
  889. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  890. domains_list = smartlist_create();
  891. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  892. -1);
  893. tor_free(domains_str);
  894. SMARTLIST_FOREACH(domains_list, const char *, domain,
  895. {
  896. if (!strcmp(domain, "*")) {
  897. domains = ~0u;
  898. } else {
  899. int d;
  900. int negate=0;
  901. if (*domain == '~') {
  902. negate = 1;
  903. ++domain;
  904. }
  905. d = parse_log_domain(domain);
  906. if (!d) {
  907. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  908. err = 1;
  909. } else {
  910. if (negate)
  911. neg_domains |= d;
  912. else
  913. domains |= d;
  914. }
  915. }
  916. });
  917. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  918. smartlist_free(domains_list);
  919. if (err)
  920. return -1;
  921. if (domains == 0 && neg_domains)
  922. domains = ~neg_domains;
  923. else
  924. domains &= ~neg_domains;
  925. cfg = eat_whitespace(closebracket+1);
  926. } else {
  927. ++got_an_unqualified_range;
  928. }
  929. if (!strcasecmpstart(cfg, "file") ||
  930. !strcasecmpstart(cfg, "stderr") ||
  931. !strcasecmpstart(cfg, "stdout") ||
  932. !strcasecmpstart(cfg, "syslog")) {
  933. goto done;
  934. }
  935. if (got_an_unqualified_range > 1)
  936. return -1;
  937. space = strchr(cfg, ' ');
  938. dash = strchr(cfg, '-');
  939. if (!space)
  940. space = strchr(cfg, '\0');
  941. if (dash && dash < space) {
  942. sev_lo = tor_strndup(cfg, dash-cfg);
  943. sev_hi = tor_strndup(dash+1, space-(dash+1));
  944. } else {
  945. sev_lo = tor_strndup(cfg, space-cfg);
  946. sev_hi = tor_strdup("ERR");
  947. }
  948. low = parse_log_level(sev_lo);
  949. high = parse_log_level(sev_hi);
  950. tor_free(sev_lo);
  951. tor_free(sev_hi);
  952. if (low == -1)
  953. return -1;
  954. if (high == -1)
  955. return -1;
  956. got_anything = 1;
  957. for (i=low; i >= high; --i)
  958. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  959. cfg = eat_whitespace(space);
  960. }
  961. done:
  962. *cfg_ptr = cfg;
  963. return got_anything ? 0 : -1;
  964. }
  965. /** Return the least severe log level that any current log is interested in. */
  966. int
  967. get_min_log_level(void)
  968. {
  969. logfile_t *lf;
  970. int i;
  971. int min = LOG_ERR;
  972. for (lf = logfiles; lf; lf = lf->next) {
  973. for (i = LOG_DEBUG; i > min; --i)
  974. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  975. min = i;
  976. }
  977. return min;
  978. }
  979. /** Switch all logs to output at most verbose level. */
  980. void
  981. switch_logs_debug(void)
  982. {
  983. logfile_t *lf;
  984. int i;
  985. LOCK_LOGS();
  986. for (lf = logfiles; lf; lf=lf->next) {
  987. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  988. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  989. }
  990. _log_global_min_severity = get_min_log_level();
  991. UNLOCK_LOGS();
  992. }
  993. #if 0
  994. static void
  995. dump_log_info(logfile_t *lf)
  996. {
  997. const char *tp;
  998. if (lf->filename) {
  999. printf("=== log into \"%s\" (%s-%s) (%stemporary)\n", lf->filename,
  1000. sev_to_string(lf->min_loglevel),
  1001. sev_to_string(lf->max_loglevel),
  1002. lf->is_temporary?"":"not ");
  1003. } else if (lf->is_syslog) {
  1004. printf("=== syslog (%s-%s) (%stemporary)\n",
  1005. sev_to_string(lf->min_loglevel),
  1006. sev_to_string(lf->max_loglevel),
  1007. lf->is_temporary?"":"not ");
  1008. } else {
  1009. printf("=== log (%s-%s) (%stemporary)\n",
  1010. sev_to_string(lf->min_loglevel),
  1011. sev_to_string(lf->max_loglevel),
  1012. lf->is_temporary?"":"not ");
  1013. }
  1014. }
  1015. void
  1016. describe_logs(void)
  1017. {
  1018. logfile_t *lf;
  1019. printf("==== BEGIN LOGS ====\n");
  1020. for (lf = logfiles; lf; lf = lf->next)
  1021. dump_log_info(lf);
  1022. printf("==== END LOGS ====\n");
  1023. }
  1024. #endif