torlog.c 42 KB

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