log.c 28 KB

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