log.c 31 KB

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