log.c 41 KB

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