torlog.c 42 KB

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