log.c 42 KB

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