log.c 39 KB

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