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