log.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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-2016, 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. /** Given a severity, yields an index into log_severity_list_t.masks to use
  37. * for that severity. */
  38. #define SEVERITY_MASK_IDX(sev) ((sev) - LOG_ERR)
  39. /** @{ */
  40. /** The string we stick at the end of a log message when it is too long,
  41. * and its length. */
  42. #define TRUNCATED_STR "[...truncated]"
  43. #define TRUNCATED_STR_LEN 14
  44. /** @} */
  45. /** Information for a single logfile; only used in log.c */
  46. typedef struct logfile_t {
  47. struct logfile_t *next; /**< Next logfile_t in the linked list. */
  48. char *filename; /**< Filename to open. */
  49. int fd; /**< fd to receive log messages, or -1 for none. */
  50. int seems_dead; /**< Boolean: true if the stream seems to be kaput. */
  51. int needs_close; /**< Boolean: true if the stream gets closed on shutdown. */
  52. int is_temporary; /**< Boolean: close after initializing logging subsystem.*/
  53. int is_syslog; /**< Boolean: send messages to syslog. */
  54. log_callback callback; /**< If not NULL, send messages to this function. */
  55. log_severity_list_t *severities; /**< Which severity of messages should we
  56. * log for each log domain? */
  57. } logfile_t;
  58. static void log_free(logfile_t *victim);
  59. /** Helper: map a log severity to descriptive string. */
  60. static inline const char *
  61. sev_to_string(int severity)
  62. {
  63. switch (severity) {
  64. case LOG_DEBUG: return "debug";
  65. case LOG_INFO: return "info";
  66. case LOG_NOTICE: return "notice";
  67. case LOG_WARN: return "warn";
  68. case LOG_ERR: return "err";
  69. default: /* Call assert, not tor_assert, since tor_assert
  70. * calls log on failure. */
  71. assert(0); return "UNKNOWN"; // LCOV_EXCL_LINE
  72. }
  73. }
  74. /** Helper: decide whether to include the function name in the log message. */
  75. static inline int
  76. should_log_function_name(log_domain_mask_t domain, int severity)
  77. {
  78. switch (severity) {
  79. case LOG_DEBUG:
  80. case LOG_INFO:
  81. /* All debugging messages occur in interesting places. */
  82. return (domain & LD_NOFUNCNAME) == 0;
  83. case LOG_NOTICE:
  84. case LOG_WARN:
  85. case LOG_ERR:
  86. /* We care about places where bugs occur. */
  87. return (domain & (LD_BUG|LD_NOFUNCNAME)) == LD_BUG;
  88. default:
  89. /* Call assert, not tor_assert, since tor_assert calls log on failure. */
  90. assert(0); return 0; // LCOV_EXCL_LINE
  91. }
  92. }
  93. /** A mutex to guard changes to logfiles and logging. */
  94. static tor_mutex_t log_mutex;
  95. /** True iff we have initialized log_mutex */
  96. static int log_mutex_initialized = 0;
  97. /** Linked list of logfile_t. */
  98. static logfile_t *logfiles = NULL;
  99. /** Boolean: do we report logging domains? */
  100. static int log_domains_are_logged = 0;
  101. #ifdef HAVE_SYSLOG_H
  102. /** The number of open syslog log handlers that we have. When this reaches 0,
  103. * we can close our connection to the syslog facility. */
  104. static int syslog_count = 0;
  105. #endif
  106. /** Represents a log message that we are going to send to callback-driven
  107. * loggers once we can do so in a non-reentrant way. */
  108. typedef struct pending_log_message_t {
  109. int severity; /**< The severity of the message */
  110. log_domain_mask_t domain; /**< The domain of the message */
  111. char *fullmsg; /**< The message, with all decorations */
  112. char *msg; /**< The content of the message */
  113. } pending_log_message_t;
  114. /** Log messages waiting to be replayed onto callback-based logs */
  115. static smartlist_t *pending_cb_messages = NULL;
  116. /** Log messages waiting to be replayed once the logging system is initialized.
  117. */
  118. static smartlist_t *pending_startup_messages = NULL;
  119. /** Number of bytes of messages queued in pending_startup_messages. (This is
  120. * the length of the messages, not the number of bytes used to store
  121. * them.) */
  122. static size_t pending_startup_messages_len;
  123. /** True iff we should store messages while waiting for the logs to get
  124. * configured. */
  125. static int queue_startup_messages = 1;
  126. /** True iff __PRETTY_FUNCTION__ includes parenthesized arguments. */
  127. static int pretty_fn_has_parens = 0;
  128. /** Don't store more than this many bytes of messages while waiting for the
  129. * logs to get configured. */
  130. #define MAX_STARTUP_MSG_LEN (1<<16)
  131. /** Lock the log_mutex to prevent others from changing the logfile_t list */
  132. #define LOCK_LOGS() STMT_BEGIN \
  133. tor_assert(log_mutex_initialized); \
  134. tor_mutex_acquire(&log_mutex); \
  135. STMT_END
  136. /** Unlock the log_mutex */
  137. #define UNLOCK_LOGS() STMT_BEGIN \
  138. tor_assert(log_mutex_initialized); \
  139. tor_mutex_release(&log_mutex); \
  140. STMT_END
  141. /** What's the lowest log level anybody cares about? Checking this lets us
  142. * bail out early from log_debug if we aren't debugging. */
  143. int log_global_min_severity_ = LOG_NOTICE;
  144. static void delete_log(logfile_t *victim);
  145. static void close_log(logfile_t *victim);
  146. static char *domain_to_string(log_domain_mask_t domain,
  147. char *buf, size_t buflen);
  148. static inline char *format_msg(char *buf, size_t buf_len,
  149. log_domain_mask_t domain, int severity, const char *funcname,
  150. const char *suffix,
  151. const char *format, va_list ap, size_t *msg_len_out)
  152. CHECK_PRINTF(7,0);
  153. /** Name of the application: used to generate the message we write at the
  154. * start of each new log. */
  155. static char *appname = NULL;
  156. /** Set the "application name" for the logs to <b>name</b>: we'll use this
  157. * name in the message we write when starting up, and at the start of each new
  158. * log.
  159. *
  160. * Tor uses this string to write the version number to the log file. */
  161. void
  162. log_set_application_name(const char *name)
  163. {
  164. tor_free(appname);
  165. appname = name ? tor_strdup(name) : NULL;
  166. }
  167. /** Log time granularity in milliseconds. */
  168. static int log_time_granularity = 1;
  169. /** Define log time granularity for all logs to be <b>granularity_msec</b>
  170. * milliseconds. */
  171. void
  172. set_log_time_granularity(int granularity_msec)
  173. {
  174. log_time_granularity = granularity_msec;
  175. }
  176. /** Helper: Write the standard prefix for log lines to a
  177. * <b>buf_len</b> character buffer in <b>buf</b>.
  178. */
  179. static inline size_t
  180. log_prefix_(char *buf, size_t buf_len, int severity)
  181. {
  182. time_t t;
  183. struct timeval now;
  184. struct tm tm;
  185. size_t n;
  186. int r, ms;
  187. tor_gettimeofday(&now);
  188. t = (time_t)now.tv_sec;
  189. ms = (int)now.tv_usec / 1000;
  190. if (log_time_granularity >= 1000) {
  191. t -= t % (log_time_granularity / 1000);
  192. ms = 0;
  193. } else {
  194. ms -= ((int)now.tv_usec / 1000) % log_time_granularity;
  195. }
  196. n = strftime(buf, buf_len, "%b %d %H:%M:%S", tor_localtime_r(&t, &tm));
  197. r = tor_snprintf(buf+n, buf_len-n, ".%.3i [%s] ", ms,
  198. sev_to_string(severity));
  199. if (r<0)
  200. return buf_len-1;
  201. else
  202. return n+r;
  203. }
  204. /** If lf refers to an actual file that we have just opened, and the file
  205. * contains no data, log an "opening new logfile" message at the top.
  206. *
  207. * Return -1 if the log is broken and needs to be deleted, else return 0.
  208. */
  209. static int
  210. log_tor_version(logfile_t *lf, int reset)
  211. {
  212. char buf[256];
  213. size_t n;
  214. int is_new;
  215. if (!lf->needs_close)
  216. /* If it doesn't get closed, it isn't really a file. */
  217. return 0;
  218. if (lf->is_temporary)
  219. /* If it's temporary, it isn't really a file. */
  220. return 0;
  221. is_new = lf->fd >= 0 && tor_fd_getpos(lf->fd) == 0;
  222. if (reset && !is_new)
  223. /* We are resetting, but we aren't at the start of the file; no
  224. * need to log again. */
  225. return 0;
  226. n = log_prefix_(buf, sizeof(buf), LOG_NOTICE);
  227. if (appname) {
  228. tor_snprintf(buf+n, sizeof(buf)-n,
  229. "%s opening %slog file.\n", appname, is_new?"new ":"");
  230. } else {
  231. tor_snprintf(buf+n, sizeof(buf)-n,
  232. "Tor %s opening %slog file.\n", VERSION, is_new?"new ":"");
  233. }
  234. if (write_all(lf->fd, buf, strlen(buf), 0) < 0) /* error */
  235. return -1; /* failed */
  236. return 0;
  237. }
  238. static const char bug_suffix[] = " (on Tor " VERSION
  239. #ifndef _MSC_VER
  240. " "
  241. #include "micro-revision.i"
  242. #endif
  243. ")";
  244. /** Helper: Format a log message into a fixed-sized buffer. (This is
  245. * factored out of <b>logv</b> so that we never format a message more
  246. * than once.) Return a pointer to the first character of the message
  247. * portion of the formatted string.
  248. */
  249. static inline char *
  250. format_msg(char *buf, size_t buf_len,
  251. log_domain_mask_t domain, int severity, const char *funcname,
  252. const char *suffix,
  253. const char *format, va_list ap, size_t *msg_len_out)
  254. {
  255. size_t n;
  256. int r;
  257. char *end_of_prefix;
  258. char *buf_end;
  259. assert(buf_len >= 16); /* prevent integer underflow and general stupidity */
  260. buf_len -= 2; /* subtract 2 characters so we have room for \n\0 */
  261. buf_end = buf+buf_len; /* point *after* the last char we can write to */
  262. n = log_prefix_(buf, buf_len, severity);
  263. end_of_prefix = buf+n;
  264. if (log_domains_are_logged) {
  265. char *cp = buf+n;
  266. if (cp == buf_end) goto format_msg_no_room_for_domains;
  267. *cp++ = '{';
  268. if (cp == buf_end) goto format_msg_no_room_for_domains;
  269. cp = domain_to_string(domain, cp, (buf+buf_len-cp));
  270. if (cp == buf_end) goto format_msg_no_room_for_domains;
  271. *cp++ = '}';
  272. if (cp == buf_end) goto format_msg_no_room_for_domains;
  273. *cp++ = ' ';
  274. if (cp == buf_end) goto format_msg_no_room_for_domains;
  275. end_of_prefix = cp;
  276. n = cp-buf;
  277. format_msg_no_room_for_domains:
  278. /* This will leave end_of_prefix and n unchanged, and thus cause
  279. * whatever log domain string we had written to be clobbered. */
  280. ;
  281. }
  282. if (funcname && should_log_function_name(domain, severity)) {
  283. r = tor_snprintf(buf+n, buf_len-n,
  284. pretty_fn_has_parens ? "%s: " : "%s(): ",
  285. funcname);
  286. if (r<0)
  287. n = strlen(buf);
  288. else
  289. n += r;
  290. }
  291. if (domain == LD_BUG && buf_len-n > 6) {
  292. memcpy(buf+n, "Bug: ", 6);
  293. n += 5;
  294. }
  295. r = tor_vsnprintf(buf+n,buf_len-n,format,ap);
  296. if (r < 0) {
  297. /* The message was too long; overwrite the end of the buffer with
  298. * "[...truncated]" */
  299. if (buf_len >= TRUNCATED_STR_LEN) {
  300. size_t offset = buf_len-TRUNCATED_STR_LEN;
  301. /* We have an extra 2 characters after buf_len to hold the \n\0,
  302. * so it's safe to add 1 to the size here. */
  303. strlcpy(buf+offset, TRUNCATED_STR, buf_len-offset+1);
  304. }
  305. /* Set 'n' to the end of the buffer, where we'll be writing \n\0.
  306. * Since we already subtracted 2 from buf_len, this is safe.*/
  307. n = buf_len;
  308. } else {
  309. n += r;
  310. if (suffix) {
  311. size_t suffix_len = strlen(suffix);
  312. if (buf_len-n >= suffix_len) {
  313. memcpy(buf+n, suffix, suffix_len);
  314. n += suffix_len;
  315. }
  316. }
  317. }
  318. if (domain == LD_BUG &&
  319. buf_len - n > strlen(bug_suffix)+1) {
  320. memcpy(buf+n, bug_suffix, strlen(bug_suffix));
  321. n += strlen(bug_suffix);
  322. }
  323. buf[n]='\n';
  324. buf[n+1]='\0';
  325. *msg_len_out = n+1;
  326. return end_of_prefix;
  327. }
  328. /* Create a new pending_log_message_t with appropriate values */
  329. static pending_log_message_t *
  330. pending_log_message_new(int severity, log_domain_mask_t domain,
  331. const char *fullmsg, const char *shortmsg)
  332. {
  333. pending_log_message_t *m = tor_malloc(sizeof(pending_log_message_t));
  334. m->severity = severity;
  335. m->domain = domain;
  336. m->fullmsg = fullmsg ? tor_strdup(fullmsg) : NULL;
  337. m->msg = tor_strdup(shortmsg);
  338. return m;
  339. }
  340. /** Release all storage held by <b>msg</b>. */
  341. static void
  342. pending_log_message_free(pending_log_message_t *msg)
  343. {
  344. if (!msg)
  345. return;
  346. tor_free(msg->msg);
  347. tor_free(msg->fullmsg);
  348. tor_free(msg);
  349. }
  350. /** Return true iff <b>lf</b> would like to receive a message with the
  351. * specified <b>severity</b> in the specified <b>domain</b>.
  352. */
  353. static inline int
  354. logfile_wants_message(const logfile_t *lf, int severity,
  355. log_domain_mask_t domain)
  356. {
  357. if (! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  358. return 0;
  359. }
  360. if (! (lf->fd >= 0 || lf->is_syslog || lf->callback)) {
  361. return 0;
  362. }
  363. if (lf->seems_dead) {
  364. return 0;
  365. }
  366. return 1;
  367. }
  368. /** Send a message to <b>lf</b>. The full message, with time prefix and
  369. * severity, is in <b>buf</b>. The message itself is in
  370. * <b>msg_after_prefix</b>. If <b>callbacks_deferred</b> points to true, then
  371. * we already deferred this message for pending callbacks and don't need to do
  372. * it again. Otherwise, if we need to do it, do it, and set
  373. * <b>callbacks_deferred</b> to 1. */
  374. static inline void
  375. logfile_deliver(logfile_t *lf, const char *buf, size_t msg_len,
  376. const char *msg_after_prefix, log_domain_mask_t domain,
  377. int severity, int *callbacks_deferred)
  378. {
  379. if (lf->is_syslog) {
  380. #ifdef HAVE_SYSLOG_H
  381. #ifdef MAXLINE
  382. /* Some syslog implementations have limits on the length of what you can
  383. * pass them, and some very old ones do not detect overflow so well.
  384. * Regrettably, they call their maximum line length MAXLINE. */
  385. #if MAXLINE < 64
  386. #warn "MAXLINE is a very low number; it might not be from syslog.h after all"
  387. #endif
  388. char *m = msg_after_prefix;
  389. if (msg_len >= MAXLINE)
  390. m = tor_strndup(msg_after_prefix, MAXLINE-1);
  391. syslog(severity, "%s", m);
  392. if (m != msg_after_prefix) {
  393. tor_free(m);
  394. }
  395. #else
  396. /* We have syslog but not MAXLINE. That's promising! */
  397. syslog(severity, "%s", msg_after_prefix);
  398. #endif
  399. #endif
  400. } else if (lf->callback) {
  401. if (domain & LD_NOCB) {
  402. if (!*callbacks_deferred && pending_cb_messages) {
  403. smartlist_add(pending_cb_messages,
  404. pending_log_message_new(severity,domain,NULL,msg_after_prefix));
  405. *callbacks_deferred = 1;
  406. }
  407. } else {
  408. lf->callback(severity, domain, msg_after_prefix);
  409. }
  410. } else {
  411. if (write_all(lf->fd, buf, msg_len, 0) < 0) { /* error */
  412. /* don't log the error! mark this log entry to be blown away, and
  413. * continue. */
  414. lf->seems_dead = 1;
  415. }
  416. }
  417. }
  418. /** Helper: sends a message to the appropriate logfiles, at loglevel
  419. * <b>severity</b>. If provided, <b>funcname</b> is prepended to the
  420. * message. The actual message is derived as from tor_snprintf(format,ap).
  421. */
  422. MOCK_IMPL(STATIC void,
  423. logv,(int severity, log_domain_mask_t domain, const char *funcname,
  424. const char *suffix, const char *format, va_list ap))
  425. {
  426. char buf[10240];
  427. size_t msg_len = 0;
  428. int formatted = 0;
  429. logfile_t *lf;
  430. char *end_of_prefix=NULL;
  431. int callbacks_deferred = 0;
  432. /* Call assert, not tor_assert, since tor_assert calls log on failure. */
  433. assert(format);
  434. /* check that severity is sane. Overrunning the masks array leads to
  435. * interesting and hard to diagnose effects */
  436. assert(severity >= LOG_ERR && severity <= LOG_DEBUG);
  437. /* check that we've initialised the log mutex before we try to lock it */
  438. assert(log_mutex_initialized);
  439. LOCK_LOGS();
  440. if ((! (domain & LD_NOCB)) && pending_cb_messages
  441. && smartlist_len(pending_cb_messages))
  442. flush_pending_log_callbacks();
  443. if (queue_startup_messages &&
  444. pending_startup_messages_len < MAX_STARTUP_MSG_LEN) {
  445. end_of_prefix =
  446. format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
  447. format, ap, &msg_len);
  448. formatted = 1;
  449. smartlist_add(pending_startup_messages,
  450. pending_log_message_new(severity,domain,buf,end_of_prefix));
  451. pending_startup_messages_len += msg_len;
  452. }
  453. for (lf = logfiles; lf; lf = lf->next) {
  454. if (! logfile_wants_message(lf, severity, domain))
  455. continue;
  456. if (!formatted) {
  457. end_of_prefix =
  458. format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
  459. format, ap, &msg_len);
  460. formatted = 1;
  461. }
  462. logfile_deliver(lf, buf, msg_len, end_of_prefix, domain, severity,
  463. &callbacks_deferred);
  464. }
  465. UNLOCK_LOGS();
  466. }
  467. /** Output a message to the log. It gets logged to all logfiles that
  468. * care about messages with <b>severity</b> in <b>domain</b>. The content
  469. * is formatted printf-style based on <b>format</b> and extra arguments.
  470. * */
  471. void
  472. tor_log(int severity, log_domain_mask_t domain, const char *format, ...)
  473. {
  474. va_list ap;
  475. if (severity > log_global_min_severity_)
  476. return;
  477. va_start(ap,format);
  478. #ifdef TOR_UNIT_TESTS
  479. if (domain & LD_NO_MOCK)
  480. logv__real(severity, domain, NULL, NULL, format, ap);
  481. else
  482. #endif
  483. logv(severity, domain, NULL, NULL, format, ap);
  484. va_end(ap);
  485. }
  486. /** Maximum number of fds that will get notifications if we crash */
  487. #define MAX_SIGSAFE_FDS 8
  488. /** Array of fds to log crash-style warnings to. */
  489. static int sigsafe_log_fds[MAX_SIGSAFE_FDS] = { STDERR_FILENO };
  490. /** The number of elements used in sigsafe_log_fds */
  491. static int n_sigsafe_log_fds = 1;
  492. /** Write <b>s</b> to each element of sigsafe_log_fds. Return 0 on success, -1
  493. * on failure. */
  494. static int
  495. tor_log_err_sigsafe_write(const char *s)
  496. {
  497. int i;
  498. ssize_t r;
  499. size_t len = strlen(s);
  500. int err = 0;
  501. for (i=0; i < n_sigsafe_log_fds; ++i) {
  502. r = write(sigsafe_log_fds[i], s, len);
  503. err += (r != (ssize_t)len);
  504. }
  505. return err ? -1 : 0;
  506. }
  507. /** Given a list of string arguments ending with a NULL, writes them
  508. * to our logs and to stderr (if possible). This function is safe to call
  509. * from within a signal handler. */
  510. void
  511. tor_log_err_sigsafe(const char *m, ...)
  512. {
  513. va_list ap;
  514. const char *x;
  515. char timebuf[33];
  516. time_t now = time(NULL);
  517. if (!m)
  518. return;
  519. if (log_time_granularity >= 2000) {
  520. int g = log_time_granularity / 1000;
  521. now -= now % g;
  522. }
  523. timebuf[0] = now < 0 ? '-' : ' ';
  524. if (now < 0) now = -now;
  525. timebuf[1] = '\0';
  526. format_dec_number_sigsafe(now, timebuf+1, sizeof(timebuf)-1);
  527. tor_log_err_sigsafe_write("\n=========================================="
  528. "================== T=");
  529. tor_log_err_sigsafe_write(timebuf);
  530. tor_log_err_sigsafe_write("\n");
  531. tor_log_err_sigsafe_write(m);
  532. va_start(ap, m);
  533. while ((x = va_arg(ap, const char*))) {
  534. tor_log_err_sigsafe_write(x);
  535. }
  536. va_end(ap);
  537. }
  538. /** Set *<b>out</b> to a pointer to an array of the fds to log errors to from
  539. * inside a signal handler. Return the number of elements in the array. */
  540. int
  541. tor_log_get_sigsafe_err_fds(const int **out)
  542. {
  543. *out = sigsafe_log_fds;
  544. return n_sigsafe_log_fds;
  545. }
  546. /** Helper function; return true iff the <b>n</b>-element array <b>array</b>
  547. * contains <b>item</b>. */
  548. static int
  549. int_array_contains(const int *array, int n, int item)
  550. {
  551. int j;
  552. for (j = 0; j < n; ++j) {
  553. if (array[j] == item)
  554. return 1;
  555. }
  556. return 0;
  557. }
  558. /** Function to call whenever the list of logs changes to get ready to log
  559. * from signal handlers. */
  560. void
  561. tor_log_update_sigsafe_err_fds(void)
  562. {
  563. const logfile_t *lf;
  564. int found_real_stderr = 0;
  565. LOCK_LOGS();
  566. /* Reserve the first one for stderr. This is safe because when we daemonize,
  567. * we dup2 /dev/null to stderr, */
  568. sigsafe_log_fds[0] = STDERR_FILENO;
  569. n_sigsafe_log_fds = 1;
  570. for (lf = logfiles; lf; lf = lf->next) {
  571. /* Don't try callback to the control port, or syslogs: We can't
  572. * do them from a signal handler. Don't try stdout: we always do stderr.
  573. */
  574. if (lf->is_temporary || lf->is_syslog ||
  575. lf->callback || lf->seems_dead || lf->fd < 0)
  576. continue;
  577. if (lf->severities->masks[SEVERITY_MASK_IDX(LOG_ERR)] &
  578. (LD_BUG|LD_GENERAL)) {
  579. if (lf->fd == STDERR_FILENO)
  580. found_real_stderr = 1;
  581. /* Avoid duplicates */
  582. if (int_array_contains(sigsafe_log_fds, n_sigsafe_log_fds, lf->fd))
  583. continue;
  584. sigsafe_log_fds[n_sigsafe_log_fds++] = lf->fd;
  585. if (n_sigsafe_log_fds == MAX_SIGSAFE_FDS)
  586. break;
  587. }
  588. }
  589. if (!found_real_stderr &&
  590. int_array_contains(sigsafe_log_fds, n_sigsafe_log_fds, STDOUT_FILENO)) {
  591. /* Don't use a virtual stderr when we're also logging to stdout. */
  592. assert(n_sigsafe_log_fds >= 2); /* Don't use assert inside log functions*/
  593. sigsafe_log_fds[0] = sigsafe_log_fds[--n_sigsafe_log_fds];
  594. }
  595. UNLOCK_LOGS();
  596. }
  597. /** Add to <b>out</b> a copy of every currently configured log file name. Used
  598. * to enable access to these filenames with the sandbox code. */
  599. void
  600. tor_log_get_logfile_names(smartlist_t *out)
  601. {
  602. logfile_t *lf;
  603. tor_assert(out);
  604. LOCK_LOGS();
  605. for (lf = logfiles; lf; lf = lf->next) {
  606. if (lf->is_temporary || lf->is_syslog || lf->callback)
  607. continue;
  608. if (lf->filename == NULL)
  609. continue;
  610. smartlist_add(out, tor_strdup(lf->filename));
  611. }
  612. UNLOCK_LOGS();
  613. }
  614. /** Implementation of the log_fn backend, used when we have
  615. * variadic macros. All arguments are as for log_fn, except for
  616. * <b>fn</b>, which is the name of the calling functions. */
  617. void
  618. log_fn_(int severity, log_domain_mask_t domain, const char *fn,
  619. const char *format, ...)
  620. {
  621. va_list ap;
  622. if (severity > log_global_min_severity_)
  623. return;
  624. va_start(ap,format);
  625. logv(severity, domain, fn, NULL, format, ap);
  626. va_end(ap);
  627. }
  628. void
  629. log_fn_ratelim_(ratelim_t *ratelim, int severity, log_domain_mask_t domain,
  630. const char *fn, const char *format, ...)
  631. {
  632. va_list ap;
  633. char *m;
  634. if (severity > log_global_min_severity_)
  635. return;
  636. m = rate_limit_log(ratelim, approx_time());
  637. if (m == NULL)
  638. return;
  639. va_start(ap, format);
  640. logv(severity, domain, fn, m, format, ap);
  641. va_end(ap);
  642. tor_free(m);
  643. }
  644. /** Free all storage held by <b>victim</b>. */
  645. static void
  646. log_free(logfile_t *victim)
  647. {
  648. if (!victim)
  649. return;
  650. tor_free(victim->severities);
  651. tor_free(victim->filename);
  652. tor_free(victim);
  653. }
  654. /** Close all open log files, and free other static memory. */
  655. void
  656. logs_free_all(void)
  657. {
  658. logfile_t *victim, *next;
  659. smartlist_t *messages, *messages2;
  660. LOCK_LOGS();
  661. next = logfiles;
  662. logfiles = NULL;
  663. messages = pending_cb_messages;
  664. pending_cb_messages = NULL;
  665. messages2 = pending_startup_messages;
  666. pending_startup_messages = NULL;
  667. UNLOCK_LOGS();
  668. while (next) {
  669. victim = next;
  670. next = next->next;
  671. close_log(victim);
  672. log_free(victim);
  673. }
  674. tor_free(appname);
  675. SMARTLIST_FOREACH(messages, pending_log_message_t *, msg, {
  676. pending_log_message_free(msg);
  677. });
  678. smartlist_free(messages);
  679. if (messages2) {
  680. SMARTLIST_FOREACH(messages2, pending_log_message_t *, msg, {
  681. pending_log_message_free(msg);
  682. });
  683. smartlist_free(messages2);
  684. }
  685. /* We _could_ destroy the log mutex here, but that would screw up any logs
  686. * that happened between here and the end of execution. */
  687. }
  688. /** Remove and free the log entry <b>victim</b> from the linked-list
  689. * logfiles (it is probably present, but it might not be due to thread
  690. * racing issues). After this function is called, the caller shouldn't
  691. * refer to <b>victim</b> anymore.
  692. *
  693. * Long-term, we need to do something about races in the log subsystem
  694. * in general. See bug 222 for more details.
  695. */
  696. static void
  697. delete_log(logfile_t *victim)
  698. {
  699. logfile_t *tmpl;
  700. if (victim == logfiles)
  701. logfiles = victim->next;
  702. else {
  703. for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
  704. // tor_assert(tmpl);
  705. // tor_assert(tmpl->next == victim);
  706. if (!tmpl)
  707. return;
  708. tmpl->next = victim->next;
  709. }
  710. log_free(victim);
  711. }
  712. /** Helper: release system resources (but not memory) held by a single
  713. * logfile_t. */
  714. static void
  715. close_log(logfile_t *victim)
  716. {
  717. if (victim->needs_close && victim->fd >= 0) {
  718. close(victim->fd);
  719. victim->fd = -1;
  720. } else if (victim->is_syslog) {
  721. #ifdef HAVE_SYSLOG_H
  722. if (--syslog_count == 0) {
  723. /* There are no other syslogs; close the logging facility. */
  724. closelog();
  725. }
  726. #endif
  727. }
  728. }
  729. /** Adjust a log severity configuration in <b>severity_out</b> to contain
  730. * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
  731. */
  732. void
  733. set_log_severity_config(int loglevelMin, int loglevelMax,
  734. log_severity_list_t *severity_out)
  735. {
  736. int i;
  737. tor_assert(loglevelMin >= loglevelMax);
  738. tor_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
  739. tor_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
  740. memset(severity_out, 0, sizeof(log_severity_list_t));
  741. for (i = loglevelMin; i >= loglevelMax; --i) {
  742. severity_out->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  743. }
  744. }
  745. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  746. * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
  747. static void
  748. add_stream_log_impl(const log_severity_list_t *severity,
  749. const char *name, int fd)
  750. {
  751. logfile_t *lf;
  752. lf = tor_malloc_zero(sizeof(logfile_t));
  753. lf->fd = fd;
  754. lf->filename = tor_strdup(name);
  755. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  756. lf->next = logfiles;
  757. logfiles = lf;
  758. log_global_min_severity_ = get_min_log_level();
  759. }
  760. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  761. * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
  762. * not use it after calling this function. */
  763. void
  764. add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
  765. {
  766. LOCK_LOGS();
  767. add_stream_log_impl(severity, name, fd);
  768. UNLOCK_LOGS();
  769. }
  770. /** Initialize the global logging facility */
  771. void
  772. init_logging(int disable_startup_queue)
  773. {
  774. if (!log_mutex_initialized) {
  775. tor_mutex_init(&log_mutex);
  776. log_mutex_initialized = 1;
  777. }
  778. #ifdef __GNUC__
  779. if (strchr(__PRETTY_FUNCTION__, '(')) {
  780. pretty_fn_has_parens = 1;
  781. }
  782. #endif
  783. if (pending_cb_messages == NULL)
  784. pending_cb_messages = smartlist_new();
  785. if (disable_startup_queue)
  786. queue_startup_messages = 0;
  787. if (pending_startup_messages == NULL && queue_startup_messages) {
  788. pending_startup_messages = smartlist_new();
  789. }
  790. }
  791. /** Set whether we report logging domains as a part of our log messages.
  792. */
  793. void
  794. logs_set_domain_logging(int enabled)
  795. {
  796. LOCK_LOGS();
  797. log_domains_are_logged = enabled;
  798. UNLOCK_LOGS();
  799. }
  800. /** Add a log handler to receive messages during startup (before the real
  801. * logs are initialized).
  802. */
  803. void
  804. add_temp_log(int min_severity)
  805. {
  806. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  807. set_log_severity_config(min_severity, LOG_ERR, s);
  808. LOCK_LOGS();
  809. add_stream_log_impl(s, "<temp>", fileno(stdout));
  810. tor_free(s);
  811. logfiles->is_temporary = 1;
  812. UNLOCK_LOGS();
  813. }
  814. /**
  815. * Add a log handler to send messages in <b>severity</b>
  816. * to the function <b>cb</b>.
  817. */
  818. int
  819. add_callback_log(const log_severity_list_t *severity, log_callback cb)
  820. {
  821. logfile_t *lf;
  822. lf = tor_malloc_zero(sizeof(logfile_t));
  823. lf->fd = -1;
  824. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  825. lf->filename = tor_strdup("<callback>");
  826. lf->callback = cb;
  827. lf->next = logfiles;
  828. LOCK_LOGS();
  829. logfiles = lf;
  830. log_global_min_severity_ = get_min_log_level();
  831. UNLOCK_LOGS();
  832. return 0;
  833. }
  834. /** Adjust the configured severity of any logs whose callback function is
  835. * <b>cb</b>. */
  836. void
  837. change_callback_log_severity(int loglevelMin, int loglevelMax,
  838. log_callback cb)
  839. {
  840. logfile_t *lf;
  841. log_severity_list_t severities;
  842. set_log_severity_config(loglevelMin, loglevelMax, &severities);
  843. LOCK_LOGS();
  844. for (lf = logfiles; lf; lf = lf->next) {
  845. if (lf->callback == cb) {
  846. memcpy(lf->severities, &severities, sizeof(severities));
  847. }
  848. }
  849. log_global_min_severity_ = get_min_log_level();
  850. UNLOCK_LOGS();
  851. }
  852. /** If there are any log messages that were generated with LD_NOCB waiting to
  853. * be sent to callback-based loggers, send them now. */
  854. void
  855. flush_pending_log_callbacks(void)
  856. {
  857. logfile_t *lf;
  858. smartlist_t *messages, *messages_tmp;
  859. LOCK_LOGS();
  860. if (!pending_cb_messages || 0 == smartlist_len(pending_cb_messages)) {
  861. UNLOCK_LOGS();
  862. return;
  863. }
  864. messages = pending_cb_messages;
  865. pending_cb_messages = smartlist_new();
  866. do {
  867. SMARTLIST_FOREACH_BEGIN(messages, pending_log_message_t *, msg) {
  868. const int severity = msg->severity;
  869. const int domain = msg->domain;
  870. for (lf = logfiles; lf; lf = lf->next) {
  871. if (! lf->callback || lf->seems_dead ||
  872. ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  873. continue;
  874. }
  875. lf->callback(severity, domain, msg->msg);
  876. }
  877. pending_log_message_free(msg);
  878. } SMARTLIST_FOREACH_END(msg);
  879. smartlist_clear(messages);
  880. messages_tmp = pending_cb_messages;
  881. pending_cb_messages = messages;
  882. messages = messages_tmp;
  883. } while (smartlist_len(messages));
  884. smartlist_free(messages);
  885. UNLOCK_LOGS();
  886. }
  887. /** Flush all the messages we stored from startup while waiting for log
  888. * initialization.
  889. */
  890. void
  891. flush_log_messages_from_startup(void)
  892. {
  893. logfile_t *lf;
  894. LOCK_LOGS();
  895. queue_startup_messages = 0;
  896. pending_startup_messages_len = 0;
  897. if (! pending_startup_messages)
  898. goto out;
  899. SMARTLIST_FOREACH_BEGIN(pending_startup_messages, pending_log_message_t *,
  900. msg) {
  901. int callbacks_deferred = 0;
  902. for (lf = logfiles; lf; lf = lf->next) {
  903. if (! logfile_wants_message(lf, msg->severity, msg->domain))
  904. continue;
  905. /* We configure a temporary startup log that goes to stdout, so we
  906. * shouldn't replay to stdout/stderr*/
  907. if (lf->fd == STDOUT_FILENO || lf->fd == STDERR_FILENO) {
  908. continue;
  909. }
  910. logfile_deliver(lf, msg->fullmsg, strlen(msg->fullmsg), msg->msg,
  911. msg->domain, msg->severity, &callbacks_deferred);
  912. }
  913. pending_log_message_free(msg);
  914. } SMARTLIST_FOREACH_END(msg);
  915. smartlist_free(pending_startup_messages);
  916. pending_startup_messages = NULL;
  917. out:
  918. UNLOCK_LOGS();
  919. }
  920. /** Close any log handlers added by add_temp_log() or marked by
  921. * mark_logs_temp(). */
  922. void
  923. close_temp_logs(void)
  924. {
  925. logfile_t *lf, **p;
  926. LOCK_LOGS();
  927. for (p = &logfiles; *p; ) {
  928. if ((*p)->is_temporary) {
  929. lf = *p;
  930. /* we use *p here to handle the edge case of the head of the list */
  931. *p = (*p)->next;
  932. close_log(lf);
  933. log_free(lf);
  934. } else {
  935. p = &((*p)->next);
  936. }
  937. }
  938. log_global_min_severity_ = get_min_log_level();
  939. UNLOCK_LOGS();
  940. }
  941. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  942. * live again, and close all non-temporary logs. */
  943. void
  944. rollback_log_changes(void)
  945. {
  946. logfile_t *lf;
  947. LOCK_LOGS();
  948. for (lf = logfiles; lf; lf = lf->next)
  949. lf->is_temporary = ! lf->is_temporary;
  950. UNLOCK_LOGS();
  951. close_temp_logs();
  952. }
  953. /** Configure all log handles to be closed by close_temp_logs(). */
  954. void
  955. mark_logs_temp(void)
  956. {
  957. logfile_t *lf;
  958. LOCK_LOGS();
  959. for (lf = logfiles; lf; lf = lf->next)
  960. lf->is_temporary = 1;
  961. UNLOCK_LOGS();
  962. }
  963. /**
  964. * Add a log handler to send messages to <b>filename</b>. If opening the
  965. * logfile fails, -1 is returned and errno is set appropriately (by open(2)).
  966. */
  967. int
  968. add_file_log(const log_severity_list_t *severity, const char *filename,
  969. const int truncate_log)
  970. {
  971. int fd;
  972. logfile_t *lf;
  973. int open_flags = O_WRONLY|O_CREAT;
  974. open_flags |= truncate_log ? O_TRUNC : O_APPEND;
  975. fd = tor_open_cloexec(filename, open_flags, 0644);
  976. if (fd<0)
  977. return -1;
  978. if (tor_fd_seekend(fd)<0) {
  979. close(fd);
  980. return -1;
  981. }
  982. LOCK_LOGS();
  983. add_stream_log_impl(severity, filename, fd);
  984. logfiles->needs_close = 1;
  985. lf = logfiles;
  986. log_global_min_severity_ = get_min_log_level();
  987. if (log_tor_version(lf, 0) < 0) {
  988. delete_log(lf);
  989. }
  990. UNLOCK_LOGS();
  991. return 0;
  992. }
  993. #ifdef HAVE_SYSLOG_H
  994. /**
  995. * Add a log handler to send messages to they system log facility.
  996. *
  997. * If this is the first log handler, opens syslog with ident Tor or
  998. * Tor-<syslog_identity_tag> if that is not NULL.
  999. */
  1000. int
  1001. add_syslog_log(const log_severity_list_t *severity,
  1002. const char* syslog_identity_tag)
  1003. {
  1004. logfile_t *lf;
  1005. if (syslog_count++ == 0) {
  1006. /* This is the first syslog. */
  1007. static char buf[256];
  1008. if (syslog_identity_tag) {
  1009. tor_snprintf(buf, sizeof(buf), "Tor-%s", syslog_identity_tag);
  1010. } else {
  1011. tor_snprintf(buf, sizeof(buf), "Tor");
  1012. }
  1013. openlog(buf, LOG_PID | LOG_NDELAY, LOGFACILITY);
  1014. }
  1015. lf = tor_malloc_zero(sizeof(logfile_t));
  1016. lf->fd = -1;
  1017. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  1018. lf->filename = tor_strdup("<syslog>");
  1019. lf->is_syslog = 1;
  1020. LOCK_LOGS();
  1021. lf->next = logfiles;
  1022. logfiles = lf;
  1023. log_global_min_severity_ = get_min_log_level();
  1024. UNLOCK_LOGS();
  1025. return 0;
  1026. }
  1027. #endif
  1028. /** If <b>level</b> is a valid log severity, return the corresponding
  1029. * numeric value. Otherwise, return -1. */
  1030. int
  1031. parse_log_level(const char *level)
  1032. {
  1033. if (!strcasecmp(level, "err"))
  1034. return LOG_ERR;
  1035. if (!strcasecmp(level, "warn"))
  1036. return LOG_WARN;
  1037. if (!strcasecmp(level, "notice"))
  1038. return LOG_NOTICE;
  1039. if (!strcasecmp(level, "info"))
  1040. return LOG_INFO;
  1041. if (!strcasecmp(level, "debug"))
  1042. return LOG_DEBUG;
  1043. return -1;
  1044. }
  1045. /** Return the string equivalent of a given log level. */
  1046. const char *
  1047. log_level_to_string(int level)
  1048. {
  1049. return sev_to_string(level);
  1050. }
  1051. /** NULL-terminated array of names for log domains such that domain_list[dom]
  1052. * is a description of <b>dom</b>. */
  1053. static const char *domain_list[] = {
  1054. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  1055. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  1056. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", "CHANNEL",
  1057. "SCHED", NULL
  1058. };
  1059. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  1060. * or 0 if there is no such name. */
  1061. static log_domain_mask_t
  1062. parse_log_domain(const char *domain)
  1063. {
  1064. int i;
  1065. for (i=0; domain_list[i]; ++i) {
  1066. if (!strcasecmp(domain, domain_list[i]))
  1067. return (1u<<i);
  1068. }
  1069. return 0;
  1070. }
  1071. /** Translate a bitmask of log domains to a string. */
  1072. static char *
  1073. domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
  1074. {
  1075. char *cp = buf;
  1076. char *eos = buf+buflen;
  1077. buf[0] = '\0';
  1078. if (! domain)
  1079. return buf;
  1080. while (1) {
  1081. const char *d;
  1082. int bit = tor_log2(domain);
  1083. size_t n;
  1084. if ((unsigned)bit >= ARRAY_LENGTH(domain_list)-1 ||
  1085. bit >= N_LOGGING_DOMAINS) {
  1086. tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
  1087. return buf+strlen(buf);
  1088. }
  1089. d = domain_list[bit];
  1090. n = strlcpy(cp, d, eos-cp);
  1091. if (n >= buflen) {
  1092. tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
  1093. return buf+strlen(buf);
  1094. }
  1095. cp += n;
  1096. domain &= ~(1<<bit);
  1097. if (domain == 0 || (eos-cp) < 2)
  1098. return cp;
  1099. memcpy(cp, ",", 2); /*Nul-terminated ,"*/
  1100. cp++;
  1101. }
  1102. }
  1103. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  1104. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  1105. * the parsed pattern. Return 0 on success, -1 on failure.
  1106. *
  1107. * The syntax for a SeverityPattern is:
  1108. * <pre>
  1109. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  1110. * DomainSeverity = (DomainList SP)? SeverityRange
  1111. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  1112. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  1113. * DomainSpec = "*" | Domain | "~" Domain
  1114. * </pre>
  1115. * A missing MaxSeverity defaults to ERR. Severities and domains are
  1116. * case-insensitive. "~" indicates negation for a domain; negation happens
  1117. * last inside a DomainList. Only one SeverityRange without a DomainList is
  1118. * allowed per line.
  1119. */
  1120. int
  1121. parse_log_severity_config(const char **cfg_ptr,
  1122. log_severity_list_t *severity_out)
  1123. {
  1124. const char *cfg = *cfg_ptr;
  1125. int got_anything = 0;
  1126. int got_an_unqualified_range = 0;
  1127. memset(severity_out, 0, sizeof(*severity_out));
  1128. cfg = eat_whitespace(cfg);
  1129. while (*cfg) {
  1130. const char *dash, *space;
  1131. char *sev_lo, *sev_hi;
  1132. int low, high, i;
  1133. log_domain_mask_t domains = ~0u;
  1134. if (*cfg == '[') {
  1135. int err = 0;
  1136. char *domains_str;
  1137. smartlist_t *domains_list;
  1138. log_domain_mask_t neg_domains = 0;
  1139. const char *closebracket = strchr(cfg, ']');
  1140. if (!closebracket)
  1141. return -1;
  1142. domains = 0;
  1143. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  1144. domains_list = smartlist_new();
  1145. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  1146. -1);
  1147. tor_free(domains_str);
  1148. SMARTLIST_FOREACH_BEGIN(domains_list, const char *, domain) {
  1149. if (!strcmp(domain, "*")) {
  1150. domains = ~0u;
  1151. } else {
  1152. int d;
  1153. int negate=0;
  1154. if (*domain == '~') {
  1155. negate = 1;
  1156. ++domain;
  1157. }
  1158. d = parse_log_domain(domain);
  1159. if (!d) {
  1160. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  1161. err = 1;
  1162. } else {
  1163. if (negate)
  1164. neg_domains |= d;
  1165. else
  1166. domains |= d;
  1167. }
  1168. }
  1169. } SMARTLIST_FOREACH_END(domain);
  1170. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  1171. smartlist_free(domains_list);
  1172. if (err)
  1173. return -1;
  1174. if (domains == 0 && neg_domains)
  1175. domains = ~neg_domains;
  1176. else
  1177. domains &= ~neg_domains;
  1178. cfg = eat_whitespace(closebracket+1);
  1179. } else {
  1180. ++got_an_unqualified_range;
  1181. }
  1182. if (!strcasecmpstart(cfg, "file") ||
  1183. !strcasecmpstart(cfg, "stderr") ||
  1184. !strcasecmpstart(cfg, "stdout") ||
  1185. !strcasecmpstart(cfg, "syslog")) {
  1186. goto done;
  1187. }
  1188. if (got_an_unqualified_range > 1)
  1189. return -1;
  1190. space = strchr(cfg, ' ');
  1191. dash = strchr(cfg, '-');
  1192. if (!space)
  1193. space = strchr(cfg, '\0');
  1194. if (dash && dash < space) {
  1195. sev_lo = tor_strndup(cfg, dash-cfg);
  1196. sev_hi = tor_strndup(dash+1, space-(dash+1));
  1197. } else {
  1198. sev_lo = tor_strndup(cfg, space-cfg);
  1199. sev_hi = tor_strdup("ERR");
  1200. }
  1201. low = parse_log_level(sev_lo);
  1202. high = parse_log_level(sev_hi);
  1203. tor_free(sev_lo);
  1204. tor_free(sev_hi);
  1205. if (low == -1)
  1206. return -1;
  1207. if (high == -1)
  1208. return -1;
  1209. got_anything = 1;
  1210. for (i=low; i >= high; --i)
  1211. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  1212. cfg = eat_whitespace(space);
  1213. }
  1214. done:
  1215. *cfg_ptr = cfg;
  1216. return got_anything ? 0 : -1;
  1217. }
  1218. /** Return the least severe log level that any current log is interested in. */
  1219. int
  1220. get_min_log_level(void)
  1221. {
  1222. logfile_t *lf;
  1223. int i;
  1224. int min = LOG_ERR;
  1225. for (lf = logfiles; lf; lf = lf->next) {
  1226. for (i = LOG_DEBUG; i > min; --i)
  1227. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  1228. min = i;
  1229. }
  1230. return min;
  1231. }
  1232. /** Switch all logs to output at most verbose level. */
  1233. void
  1234. switch_logs_debug(void)
  1235. {
  1236. logfile_t *lf;
  1237. int i;
  1238. LOCK_LOGS();
  1239. for (lf = logfiles; lf; lf=lf->next) {
  1240. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  1241. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  1242. }
  1243. log_global_min_severity_ = get_min_log_level();
  1244. UNLOCK_LOGS();
  1245. }
  1246. /** Truncate all the log files. */
  1247. void
  1248. truncate_logs(void)
  1249. {
  1250. logfile_t *lf;
  1251. for (lf = logfiles; lf; lf = lf->next) {
  1252. if (lf->fd >= 0) {
  1253. tor_ftruncate(lf->fd);
  1254. }
  1255. }
  1256. }