log.c 29 KB

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