log.c 39 KB

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