log.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  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. #include "lib/thread/threads.h"
  51. #ifdef HAVE_ANDROID_LOG_H
  52. #include <android/log.h>
  53. #endif // HAVE_ANDROID_LOG_H.
  54. /** @{ */
  55. /** The string we stick at the end of a log message when it is too long,
  56. * and its length. */
  57. #define TRUNCATED_STR "[...truncated]"
  58. #define TRUNCATED_STR_LEN 14
  59. /** @} */
  60. /** Defining compile-time constants for Tor log levels (used by the Rust
  61. * log wrapper at src/rust/tor_log) */
  62. const int LOG_WARN_ = LOG_WARN;
  63. const int LOG_NOTICE_ = LOG_NOTICE;
  64. const log_domain_mask_t LD_GENERAL_ = LD_GENERAL;
  65. const log_domain_mask_t LD_NET_ = LD_NET;
  66. /** Information for a single logfile; only used in log.c */
  67. typedef struct logfile_t {
  68. struct logfile_t *next; /**< Next logfile_t in the linked list. */
  69. char *filename; /**< Filename to open. */
  70. int fd; /**< fd to receive log messages, or -1 for none. */
  71. int seems_dead; /**< Boolean: true if the stream seems to be kaput. */
  72. int needs_close; /**< Boolean: true if the stream gets closed on shutdown. */
  73. int is_temporary; /**< Boolean: close after initializing logging subsystem.*/
  74. int is_syslog; /**< Boolean: send messages to syslog. */
  75. int is_android; /**< Boolean: send messages to Android's log subsystem. */
  76. char *android_tag; /**< Identity Tag used in Android's log subsystem. */
  77. log_callback callback; /**< If not NULL, send messages to this function. */
  78. log_severity_list_t *severities; /**< Which severity of messages should we
  79. * log for each log domain? */
  80. } logfile_t;
  81. static void log_free_(logfile_t *victim);
  82. #define log_free(lg) \
  83. FREE_AND_NULL(logfile_t, log_free_, (lg))
  84. /** Helper: map a log severity to descriptive string. */
  85. static inline const char *
  86. sev_to_string(int severity)
  87. {
  88. switch (severity) {
  89. case LOG_DEBUG: return "debug";
  90. case LOG_INFO: return "info";
  91. case LOG_NOTICE: return "notice";
  92. case LOG_WARN: return "warn";
  93. case LOG_ERR: return "err";
  94. default: /* Call raw_assert, not tor_assert, since tor_assert
  95. * calls log on failure. */
  96. raw_assert_unreached(); return "UNKNOWN"; // LCOV_EXCL_LINE
  97. }
  98. }
  99. /** Helper: decide whether to include the function name in the log message. */
  100. static inline int
  101. should_log_function_name(log_domain_mask_t domain, int severity)
  102. {
  103. switch (severity) {
  104. case LOG_DEBUG:
  105. case LOG_INFO:
  106. /* All debugging messages occur in interesting places. */
  107. return (domain & LD_NOFUNCNAME) == 0;
  108. case LOG_NOTICE:
  109. case LOG_WARN:
  110. case LOG_ERR:
  111. /* We care about places where bugs occur. */
  112. return (domain & (LD_BUG|LD_NOFUNCNAME)) == LD_BUG;
  113. default:
  114. /* Call raw_assert, not tor_assert, since tor_assert calls
  115. * log on failure. */
  116. raw_assert(0); return 0; // LCOV_EXCL_LINE
  117. }
  118. }
  119. #ifdef HAVE_ANDROID_LOG_H
  120. /** Helper function to convert Tor's log severity into the matching
  121. * Android log priority.
  122. */
  123. static int
  124. severity_to_android_log_priority(int severity)
  125. {
  126. switch (severity) {
  127. case LOG_DEBUG:
  128. return ANDROID_LOG_VERBOSE;
  129. case LOG_INFO:
  130. return ANDROID_LOG_DEBUG;
  131. case LOG_NOTICE:
  132. return ANDROID_LOG_INFO;
  133. case LOG_WARN:
  134. return ANDROID_LOG_WARN;
  135. case LOG_ERR:
  136. return ANDROID_LOG_ERROR;
  137. default:
  138. // LCOV_EXCL_START
  139. raw_assert(0);
  140. return 0;
  141. // LCOV_EXCL_STOP
  142. }
  143. }
  144. #endif /* defined(HAVE_ANDROID_LOG_H) */
  145. /** A mutex to guard changes to logfiles and logging. */
  146. static tor_mutex_t log_mutex;
  147. /** True iff we have initialized log_mutex */
  148. static int log_mutex_initialized = 0;
  149. /** Linked list of logfile_t. */
  150. static logfile_t *logfiles = NULL;
  151. /** Boolean: do we report logging domains? */
  152. static int log_domains_are_logged = 0;
  153. #ifdef HAVE_SYSLOG_H
  154. /** The number of open syslog log handlers that we have. When this reaches 0,
  155. * we can close our connection to the syslog facility. */
  156. static int syslog_count = 0;
  157. #endif
  158. /** Represents a log message that we are going to send to callback-driven
  159. * loggers once we can do so in a non-reentrant way. */
  160. typedef struct pending_log_message_t {
  161. int severity; /**< The severity of the message */
  162. log_domain_mask_t domain; /**< The domain of the message */
  163. char *fullmsg; /**< The message, with all decorations */
  164. char *msg; /**< The content of the message */
  165. } pending_log_message_t;
  166. /** Log messages waiting to be replayed onto callback-based logs */
  167. static smartlist_t *pending_cb_messages = NULL;
  168. /** Callback to invoke when pending_cb_messages becomes nonempty. */
  169. static pending_callback_callback pending_cb_cb = NULL;
  170. /** Log messages waiting to be replayed once the logging system is initialized.
  171. */
  172. static smartlist_t *pending_startup_messages = NULL;
  173. /** Number of bytes of messages queued in pending_startup_messages. (This is
  174. * the length of the messages, not the number of bytes used to store
  175. * them.) */
  176. static size_t pending_startup_messages_len;
  177. /** True iff we should store messages while waiting for the logs to get
  178. * configured. */
  179. static int queue_startup_messages = 1;
  180. /** True iff __PRETTY_FUNCTION__ includes parenthesized arguments. */
  181. static int pretty_fn_has_parens = 0;
  182. /** Don't store more than this many bytes of messages while waiting for the
  183. * logs to get configured. */
  184. #define MAX_STARTUP_MSG_LEN (1<<16)
  185. /** Lock the log_mutex to prevent others from changing the logfile_t list */
  186. #define LOCK_LOGS() STMT_BEGIN \
  187. raw_assert(log_mutex_initialized); \
  188. tor_mutex_acquire(&log_mutex); \
  189. STMT_END
  190. /** Unlock the log_mutex */
  191. #define UNLOCK_LOGS() STMT_BEGIN \
  192. raw_assert(log_mutex_initialized); \
  193. tor_mutex_release(&log_mutex); \
  194. STMT_END
  195. /** What's the lowest log level anybody cares about? Checking this lets us
  196. * bail out early from log_debug if we aren't debugging. */
  197. int log_global_min_severity_ = LOG_NOTICE;
  198. static void delete_log(logfile_t *victim);
  199. static void close_log(logfile_t *victim);
  200. static void close_log_sigsafe(logfile_t *victim);
  201. static char *domain_to_string(log_domain_mask_t domain,
  202. char *buf, size_t buflen);
  203. static inline char *format_msg(char *buf, size_t buf_len,
  204. log_domain_mask_t domain, int severity, const char *funcname,
  205. const char *suffix,
  206. const char *format, va_list ap, size_t *msg_len_out)
  207. CHECK_PRINTF(7,0);
  208. /** Name of the application: used to generate the message we write at the
  209. * start of each new log. */
  210. static char *appname = NULL;
  211. /** Set the "application name" for the logs to <b>name</b>: we'll use this
  212. * name in the message we write when starting up, and at the start of each new
  213. * log.
  214. *
  215. * Tor uses this string to write the version number to the log file. */
  216. void
  217. log_set_application_name(const char *name)
  218. {
  219. tor_free(appname);
  220. appname = name ? tor_strdup(name) : NULL;
  221. }
  222. /** Return true if some of the running logs might be interested in a log
  223. * message of the given severity in the given domains. If this function
  224. * returns true, the log message might be ignored anyway, but if it returns
  225. * false, it is definitely_ safe not to log the message. */
  226. int
  227. log_message_is_interesting(int severity, log_domain_mask_t domain)
  228. {
  229. (void) domain;
  230. return (severity <= log_global_min_severity_);
  231. }
  232. /**
  233. * As tor_log, but takes an optional function name, and does not treat its
  234. * <b>string</b> as a printf format.
  235. *
  236. * For use by Rust integration.
  237. */
  238. void
  239. tor_log_string(int severity, log_domain_mask_t domain,
  240. const char *function, const char *string)
  241. {
  242. log_fn_(severity, domain, function, "%s", string);
  243. }
  244. /** Log time granularity in milliseconds. */
  245. static int log_time_granularity = 1;
  246. /** Define log time granularity for all logs to be <b>granularity_msec</b>
  247. * milliseconds. */
  248. void
  249. set_log_time_granularity(int granularity_msec)
  250. {
  251. log_time_granularity = granularity_msec;
  252. tor_log_sigsafe_err_set_granularity(granularity_msec);
  253. }
  254. /** Helper: Write the standard prefix for log lines to a
  255. * <b>buf_len</b> character buffer in <b>buf</b>.
  256. */
  257. static inline size_t
  258. log_prefix_(char *buf, size_t buf_len, int severity)
  259. {
  260. time_t t;
  261. struct timeval now;
  262. struct tm tm;
  263. size_t n;
  264. int r, ms;
  265. tor_gettimeofday(&now);
  266. t = (time_t)now.tv_sec;
  267. ms = (int)now.tv_usec / 1000;
  268. if (log_time_granularity >= 1000) {
  269. t -= t % (log_time_granularity / 1000);
  270. ms = 0;
  271. } else {
  272. ms -= ((int)now.tv_usec / 1000) % log_time_granularity;
  273. }
  274. n = strftime(buf, buf_len, "%b %d %H:%M:%S",
  275. tor_localtime_r_msg(&t, &tm, NULL));
  276. r = tor_snprintf(buf+n, buf_len-n, ".%.3i [thrd=%05lx] [%s] ", ms,
  277. tor_get_thread_id() / 4096 % 1048576, /* Make it more readable */
  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. LOCK_LOGS();
  531. if ((! (domain & LD_NOCB)) && pending_cb_messages
  532. && smartlist_len(pending_cb_messages))
  533. flush_pending_log_callbacks();
  534. if (queue_startup_messages &&
  535. pending_startup_messages_len < MAX_STARTUP_MSG_LEN) {
  536. end_of_prefix =
  537. format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
  538. format, ap, &msg_len);
  539. formatted = 1;
  540. smartlist_add(pending_startup_messages,
  541. pending_log_message_new(severity,domain,buf,end_of_prefix));
  542. pending_startup_messages_len += msg_len;
  543. }
  544. for (lf = logfiles; lf; lf = lf->next) {
  545. if (! logfile_wants_message(lf, severity, domain))
  546. continue;
  547. if (!formatted) {
  548. end_of_prefix =
  549. format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
  550. format, ap, &msg_len);
  551. formatted = 1;
  552. }
  553. logfile_deliver(lf, buf, msg_len, end_of_prefix, domain, severity,
  554. &callbacks_deferred);
  555. }
  556. UNLOCK_LOGS();
  557. }
  558. /** Output a message to the log. It gets logged to all logfiles that
  559. * care about messages with <b>severity</b> in <b>domain</b>. The content
  560. * is formatted printf-style based on <b>format</b> and extra arguments.
  561. * */
  562. void
  563. tor_log(int severity, log_domain_mask_t domain, const char *format, ...)
  564. {
  565. va_list ap;
  566. /* check that domain is composed of known domains and flags */
  567. raw_assert((domain & (LD_ALL_DOMAINS|LD_ALL_FLAGS)) == domain);
  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. /* log_fds and err_fds contain matching entries: log_fds are the fds used by
  599. * the log module, and err_fds are the fds used by the err module.
  600. * For stdio logs, the log_fd and err_fd values are identical,
  601. * and the err module closes the fd on shutdown.
  602. * For file logs, the err_fd is a dup() of the log_fd,
  603. * and the log and err modules both close their respective fds on shutdown.
  604. * (Once all fds representing a file are closed, the underlying file is
  605. * closed.)
  606. */
  607. int log_fds[TOR_SIGSAFE_LOG_MAX_FDS];
  608. int err_fds[TOR_SIGSAFE_LOG_MAX_FDS];
  609. int n_fds;
  610. LOCK_LOGS();
  611. /* Reserve the first one for stderr. This is safe because when we daemonize,
  612. * we dup2 /dev/null to stderr.
  613. * For stderr, log_fds and err_fds are the same. */
  614. log_fds[0] = err_fds[0] = STDERR_FILENO;
  615. n_fds = 1;
  616. for (lf = logfiles; lf; lf = lf->next) {
  617. /* Don't try callback to the control port, syslogs, android logs, or any
  618. * other non-file descriptor log: We can't call arbitrary functions from a
  619. * signal handler.
  620. */
  621. if (lf->is_temporary || logfile_is_external(lf)
  622. || lf->seems_dead || lf->fd < 0)
  623. continue;
  624. if (lf->severities->masks[SEVERITY_MASK_IDX(LOG_ERR)] &
  625. (LD_BUG|LD_GENERAL)) {
  626. if (lf->fd == STDERR_FILENO)
  627. found_real_stderr = 1;
  628. /* Avoid duplicates by checking the log module fd against log_fds */
  629. if (int_array_contains(log_fds, n_fds, lf->fd))
  630. continue;
  631. /* Update log_fds using the log module's fd */
  632. log_fds[n_fds] = lf->fd;
  633. if (lf->needs_close) {
  634. /* File log fds are duplicated, because close_log() closes the log
  635. * module's fd, and tor_log_close_sigsafe_err_fds() closes the err
  636. * module's fd. Both refer to the same file. */
  637. err_fds[n_fds] = dup(lf->fd);
  638. } else {
  639. /* stdio log fds are not closed by the log module.
  640. * tor_log_close_sigsafe_err_fds() closes stdio logs. */
  641. err_fds[n_fds] = lf->fd;
  642. }
  643. n_fds++;
  644. if (n_fds == TOR_SIGSAFE_LOG_MAX_FDS)
  645. break;
  646. }
  647. }
  648. if (!found_real_stderr &&
  649. int_array_contains(log_fds, n_fds, STDOUT_FILENO)) {
  650. /* Don't use a virtual stderr when we're also logging to stdout.
  651. * If we reached max_fds logs, we'll now have (max_fds - 1) logs.
  652. * That's ok, max_fds is large enough that most tor instances don't exceed
  653. * it. */
  654. raw_assert(n_fds >= 2); /* Don't tor_assert inside log fns */
  655. --n_fds;
  656. log_fds[0] = log_fds[n_fds];
  657. err_fds[0] = err_fds[n_fds];
  658. }
  659. UNLOCK_LOGS();
  660. tor_log_set_sigsafe_err_fds(err_fds, n_fds);
  661. }
  662. /** Add to <b>out</b> a copy of every currently configured log file name. Used
  663. * to enable access to these filenames with the sandbox code. */
  664. void
  665. tor_log_get_logfile_names(smartlist_t *out)
  666. {
  667. logfile_t *lf;
  668. raw_assert(out);
  669. LOCK_LOGS();
  670. for (lf = logfiles; lf; lf = lf->next) {
  671. if (lf->is_temporary || logfile_is_external(lf))
  672. continue;
  673. if (lf->filename == NULL)
  674. continue;
  675. smartlist_add_strdup(out, lf->filename);
  676. }
  677. UNLOCK_LOGS();
  678. }
  679. /** Implementation of the log_fn backend, used when we have
  680. * variadic macros. All arguments are as for log_fn, except for
  681. * <b>fn</b>, which is the name of the calling function. */
  682. void
  683. log_fn_(int severity, log_domain_mask_t domain, const char *fn,
  684. const char *format, ...)
  685. {
  686. va_list ap;
  687. if (severity > log_global_min_severity_)
  688. return;
  689. va_start(ap,format);
  690. logv(severity, domain, fn, NULL, format, ap);
  691. va_end(ap);
  692. }
  693. void
  694. log_fn_ratelim_(ratelim_t *ratelim, int severity, log_domain_mask_t domain,
  695. const char *fn, const char *format, ...)
  696. {
  697. va_list ap;
  698. char *m;
  699. if (severity > log_global_min_severity_)
  700. return;
  701. m = rate_limit_log(ratelim, approx_time());
  702. if (m == NULL)
  703. return;
  704. va_start(ap, format);
  705. logv(severity, domain, fn, m, format, ap);
  706. va_end(ap);
  707. tor_free(m);
  708. }
  709. /** Free all storage held by <b>victim</b>. */
  710. static void
  711. log_free_(logfile_t *victim)
  712. {
  713. if (!victim)
  714. return;
  715. tor_free(victim->severities);
  716. tor_free(victim->filename);
  717. tor_free(victim->android_tag);
  718. tor_free(victim);
  719. }
  720. /** Close all open log files, and free other static memory. */
  721. void
  722. logs_free_all(void)
  723. {
  724. logfile_t *victim, *next;
  725. smartlist_t *messages, *messages2;
  726. LOCK_LOGS();
  727. next = logfiles;
  728. logfiles = NULL;
  729. messages = pending_cb_messages;
  730. pending_cb_messages = NULL;
  731. pending_cb_cb = NULL;
  732. messages2 = pending_startup_messages;
  733. pending_startup_messages = NULL;
  734. UNLOCK_LOGS();
  735. while (next) {
  736. victim = next;
  737. next = next->next;
  738. close_log(victim);
  739. log_free(victim);
  740. }
  741. tor_free(appname);
  742. SMARTLIST_FOREACH(messages, pending_log_message_t *, msg, {
  743. pending_log_message_free(msg);
  744. });
  745. smartlist_free(messages);
  746. if (messages2) {
  747. SMARTLIST_FOREACH(messages2, pending_log_message_t *, msg, {
  748. pending_log_message_free(msg);
  749. });
  750. smartlist_free(messages2);
  751. }
  752. /* We _could_ destroy the log mutex here, but that would screw up any logs
  753. * that happened between here and the end of execution.
  754. * If tor is re-initialized, log_mutex_initialized will still be 1. So we
  755. * won't trigger any undefined behaviour by trying to re-initialize the
  756. * log mutex. */
  757. }
  758. /** Close signal-safe log files.
  759. * Closing the log files makes the process and OS flush log buffers.
  760. *
  761. * This function is safe to call from a signal handler. It should only be
  762. * called when shutting down the log or err modules. It is currenly called
  763. * by the err module, when terminating the process on an abnormal condition.
  764. */
  765. void
  766. logs_close_sigsafe(void)
  767. {
  768. logfile_t *victim, *next;
  769. /* We can't LOCK_LOGS() in a signal handler, because it may call
  770. * signal-unsafe functions. And we can't deallocate memory, either. */
  771. next = logfiles;
  772. logfiles = NULL;
  773. while (next) {
  774. victim = next;
  775. next = next->next;
  776. if (victim->needs_close) {
  777. close_log_sigsafe(victim);
  778. }
  779. }
  780. }
  781. /** Remove and free the log entry <b>victim</b> from the linked-list
  782. * logfiles (it is probably present, but it might not be due to thread
  783. * racing issues). After this function is called, the caller shouldn't
  784. * refer to <b>victim</b> anymore.
  785. */
  786. static void
  787. delete_log(logfile_t *victim)
  788. {
  789. logfile_t *tmpl;
  790. if (victim == logfiles)
  791. logfiles = victim->next;
  792. else {
  793. for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
  794. // raw_assert(tmpl);
  795. // raw_assert(tmpl->next == victim);
  796. if (!tmpl)
  797. return;
  798. tmpl->next = victim->next;
  799. }
  800. log_free(victim);
  801. }
  802. /** Helper: release system resources (but not memory) held by a single
  803. * signal-safe logfile_t. If the log's resources can not be released in
  804. * a signal handler, does nothing. */
  805. static void
  806. close_log_sigsafe(logfile_t *victim)
  807. {
  808. if (victim->needs_close && victim->fd >= 0) {
  809. /* We can't do anything useful here if close() fails: we're shutting
  810. * down logging, and the err module only does fatal errors. */
  811. close(victim->fd);
  812. victim->fd = -1;
  813. }
  814. }
  815. /** Helper: release system resources (but not memory) held by a single
  816. * logfile_t. */
  817. static void
  818. close_log(logfile_t *victim)
  819. {
  820. if (victim->needs_close) {
  821. close_log_sigsafe(victim);
  822. } else if (victim->is_syslog) {
  823. #ifdef HAVE_SYSLOG_H
  824. if (--syslog_count == 0) {
  825. /* There are no other syslogs; close the logging facility. */
  826. closelog();
  827. }
  828. #endif /* defined(HAVE_SYSLOG_H) */
  829. }
  830. }
  831. /** Adjust a log severity configuration in <b>severity_out</b> to contain
  832. * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
  833. */
  834. void
  835. set_log_severity_config(int loglevelMin, int loglevelMax,
  836. log_severity_list_t *severity_out)
  837. {
  838. int i;
  839. raw_assert(loglevelMin >= loglevelMax);
  840. raw_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
  841. raw_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
  842. memset(severity_out, 0, sizeof(log_severity_list_t));
  843. for (i = loglevelMin; i >= loglevelMax; --i) {
  844. severity_out->masks[SEVERITY_MASK_IDX(i)] = LD_ALL_DOMAINS;
  845. }
  846. }
  847. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  848. * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
  849. static void
  850. add_stream_log_impl(const log_severity_list_t *severity,
  851. const char *name, int fd)
  852. {
  853. logfile_t *lf;
  854. lf = tor_malloc_zero(sizeof(logfile_t));
  855. lf->fd = fd;
  856. lf->filename = tor_strdup(name);
  857. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  858. lf->next = logfiles;
  859. logfiles = lf;
  860. log_global_min_severity_ = get_min_log_level();
  861. }
  862. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  863. * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
  864. * not use it after calling this function. */
  865. void
  866. add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
  867. {
  868. LOCK_LOGS();
  869. add_stream_log_impl(severity, name, fd);
  870. UNLOCK_LOGS();
  871. }
  872. /** Initialize the global logging facility */
  873. void
  874. init_logging(int disable_startup_queue)
  875. {
  876. if (!log_mutex_initialized) {
  877. tor_mutex_init(&log_mutex);
  878. log_mutex_initialized = 1;
  879. }
  880. #ifdef __GNUC__
  881. if (strchr(__PRETTY_FUNCTION__, '(')) {
  882. pretty_fn_has_parens = 1;
  883. }
  884. #endif
  885. if (pending_cb_messages == NULL)
  886. pending_cb_messages = smartlist_new();
  887. if (disable_startup_queue)
  888. queue_startup_messages = 0;
  889. if (pending_startup_messages == NULL && queue_startup_messages) {
  890. pending_startup_messages = smartlist_new();
  891. }
  892. }
  893. /** Set whether we report logging domains as a part of our log messages.
  894. */
  895. void
  896. logs_set_domain_logging(int enabled)
  897. {
  898. LOCK_LOGS();
  899. log_domains_are_logged = enabled;
  900. UNLOCK_LOGS();
  901. }
  902. /** Add a log handler to receive messages during startup (before the real
  903. * logs are initialized).
  904. */
  905. void
  906. add_temp_log(int min_severity)
  907. {
  908. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  909. set_log_severity_config(min_severity, LOG_ERR, s);
  910. LOCK_LOGS();
  911. add_stream_log_impl(s, "<temp>", fileno(stdout));
  912. tor_free(s);
  913. logfiles->is_temporary = 1;
  914. UNLOCK_LOGS();
  915. }
  916. /**
  917. * Register "cb" as the callback to call when there are new pending log
  918. * callbacks to be flushed with flush_pending_log_callbacks().
  919. *
  920. * Note that this callback, if present, can be invoked from any thread.
  921. *
  922. * This callback must not log.
  923. *
  924. * It is intentional that this function contains the name "callback" twice: it
  925. * sets a "callback" to be called on the condition that there is a "pending
  926. * callback".
  927. **/
  928. void
  929. logs_set_pending_callback_callback(pending_callback_callback cb)
  930. {
  931. pending_cb_cb = cb;
  932. }
  933. /**
  934. * Add a log handler to send messages in <b>severity</b>
  935. * to the function <b>cb</b>.
  936. */
  937. int
  938. add_callback_log(const log_severity_list_t *severity, log_callback cb)
  939. {
  940. logfile_t *lf;
  941. lf = tor_malloc_zero(sizeof(logfile_t));
  942. lf->fd = -1;
  943. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  944. lf->filename = tor_strdup("<callback>");
  945. lf->callback = cb;
  946. lf->next = logfiles;
  947. LOCK_LOGS();
  948. logfiles = lf;
  949. log_global_min_severity_ = get_min_log_level();
  950. UNLOCK_LOGS();
  951. return 0;
  952. }
  953. /** Adjust the configured severity of any logs whose callback function is
  954. * <b>cb</b>. */
  955. void
  956. change_callback_log_severity(int loglevelMin, int loglevelMax,
  957. log_callback cb)
  958. {
  959. logfile_t *lf;
  960. log_severity_list_t severities;
  961. set_log_severity_config(loglevelMin, loglevelMax, &severities);
  962. LOCK_LOGS();
  963. for (lf = logfiles; lf; lf = lf->next) {
  964. if (lf->callback == cb) {
  965. memcpy(lf->severities, &severities, sizeof(severities));
  966. }
  967. }
  968. log_global_min_severity_ = get_min_log_level();
  969. UNLOCK_LOGS();
  970. }
  971. /** If there are any log messages that were generated with LD_NOCB waiting to
  972. * be sent to callback-based loggers, send them now. */
  973. void
  974. flush_pending_log_callbacks(void)
  975. {
  976. logfile_t *lf;
  977. smartlist_t *messages, *messages_tmp;
  978. LOCK_LOGS();
  979. if (!pending_cb_messages || 0 == smartlist_len(pending_cb_messages)) {
  980. UNLOCK_LOGS();
  981. return;
  982. }
  983. messages = pending_cb_messages;
  984. pending_cb_messages = smartlist_new();
  985. do {
  986. SMARTLIST_FOREACH_BEGIN(messages, pending_log_message_t *, msg) {
  987. const int severity = msg->severity;
  988. const log_domain_mask_t domain = msg->domain;
  989. for (lf = logfiles; lf; lf = lf->next) {
  990. if (! lf->callback || lf->seems_dead ||
  991. ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  992. continue;
  993. }
  994. lf->callback(severity, domain, msg->msg);
  995. }
  996. pending_log_message_free(msg);
  997. } SMARTLIST_FOREACH_END(msg);
  998. smartlist_clear(messages);
  999. messages_tmp = pending_cb_messages;
  1000. pending_cb_messages = messages;
  1001. messages = messages_tmp;
  1002. } while (smartlist_len(messages));
  1003. smartlist_free(messages);
  1004. UNLOCK_LOGS();
  1005. }
  1006. /** Flush all the messages we stored from startup while waiting for log
  1007. * initialization.
  1008. */
  1009. void
  1010. flush_log_messages_from_startup(void)
  1011. {
  1012. logfile_t *lf;
  1013. LOCK_LOGS();
  1014. queue_startup_messages = 0;
  1015. pending_startup_messages_len = 0;
  1016. if (! pending_startup_messages)
  1017. goto out;
  1018. SMARTLIST_FOREACH_BEGIN(pending_startup_messages, pending_log_message_t *,
  1019. msg) {
  1020. int callbacks_deferred = 0;
  1021. for (lf = logfiles; lf; lf = lf->next) {
  1022. if (! logfile_wants_message(lf, msg->severity, msg->domain))
  1023. continue;
  1024. /* We configure a temporary startup log that goes to stdout, so we
  1025. * shouldn't replay to stdout/stderr*/
  1026. if (lf->fd == STDOUT_FILENO || lf->fd == STDERR_FILENO) {
  1027. continue;
  1028. }
  1029. logfile_deliver(lf, msg->fullmsg, strlen(msg->fullmsg), msg->msg,
  1030. msg->domain, msg->severity, &callbacks_deferred);
  1031. }
  1032. pending_log_message_free(msg);
  1033. } SMARTLIST_FOREACH_END(msg);
  1034. smartlist_free(pending_startup_messages);
  1035. pending_startup_messages = NULL;
  1036. out:
  1037. UNLOCK_LOGS();
  1038. }
  1039. /** Close any log handlers added by add_temp_log() or marked by
  1040. * mark_logs_temp(). */
  1041. void
  1042. close_temp_logs(void)
  1043. {
  1044. logfile_t *lf, **p;
  1045. LOCK_LOGS();
  1046. for (p = &logfiles; *p; ) {
  1047. if ((*p)->is_temporary) {
  1048. lf = *p;
  1049. /* we use *p here to handle the edge case of the head of the list */
  1050. *p = (*p)->next;
  1051. close_log(lf);
  1052. log_free(lf);
  1053. } else {
  1054. p = &((*p)->next);
  1055. }
  1056. }
  1057. log_global_min_severity_ = get_min_log_level();
  1058. UNLOCK_LOGS();
  1059. }
  1060. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  1061. * live again, and close all non-temporary logs. */
  1062. void
  1063. rollback_log_changes(void)
  1064. {
  1065. logfile_t *lf;
  1066. LOCK_LOGS();
  1067. for (lf = logfiles; lf; lf = lf->next)
  1068. lf->is_temporary = ! lf->is_temporary;
  1069. UNLOCK_LOGS();
  1070. close_temp_logs();
  1071. }
  1072. /** Configure all log handles to be closed by close_temp_logs(). */
  1073. void
  1074. mark_logs_temp(void)
  1075. {
  1076. logfile_t *lf;
  1077. LOCK_LOGS();
  1078. for (lf = logfiles; lf; lf = lf->next)
  1079. lf->is_temporary = 1;
  1080. UNLOCK_LOGS();
  1081. }
  1082. /**
  1083. * Add a log handler to send messages to <b>filename</b> via <b>fd</b>. If
  1084. * opening the logfile failed, -1 is returned and errno is set appropriately
  1085. * (by open(2)). Takes ownership of fd.
  1086. */
  1087. int
  1088. add_file_log(const log_severity_list_t *severity,
  1089. const char *filename,
  1090. int fd)
  1091. {
  1092. logfile_t *lf;
  1093. if (fd<0)
  1094. return -1;
  1095. if (tor_fd_seekend(fd)<0) {
  1096. close(fd);
  1097. return -1;
  1098. }
  1099. LOCK_LOGS();
  1100. add_stream_log_impl(severity, filename, fd);
  1101. logfiles->needs_close = 1;
  1102. lf = logfiles;
  1103. log_global_min_severity_ = get_min_log_level();
  1104. if (log_tor_version(lf, 0) < 0) {
  1105. delete_log(lf);
  1106. }
  1107. UNLOCK_LOGS();
  1108. return 0;
  1109. }
  1110. #ifdef HAVE_SYSLOG_H
  1111. /**
  1112. * Add a log handler to send messages to they system log facility.
  1113. *
  1114. * If this is the first log handler, opens syslog with ident Tor or
  1115. * Tor-<syslog_identity_tag> if that is not NULL.
  1116. */
  1117. int
  1118. add_syslog_log(const log_severity_list_t *severity,
  1119. const char* syslog_identity_tag)
  1120. {
  1121. logfile_t *lf;
  1122. if (syslog_count++ == 0) {
  1123. /* This is the first syslog. */
  1124. static char buf[256];
  1125. if (syslog_identity_tag) {
  1126. tor_snprintf(buf, sizeof(buf), "Tor-%s", syslog_identity_tag);
  1127. } else {
  1128. tor_snprintf(buf, sizeof(buf), "Tor");
  1129. }
  1130. openlog(buf, LOG_PID | LOG_NDELAY, LOGFACILITY);
  1131. }
  1132. lf = tor_malloc_zero(sizeof(logfile_t));
  1133. lf->fd = -1;
  1134. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  1135. lf->filename = tor_strdup("<syslog>");
  1136. lf->is_syslog = 1;
  1137. LOCK_LOGS();
  1138. lf->next = logfiles;
  1139. logfiles = lf;
  1140. log_global_min_severity_ = get_min_log_level();
  1141. UNLOCK_LOGS();
  1142. return 0;
  1143. }
  1144. #endif /* defined(HAVE_SYSLOG_H) */
  1145. #ifdef HAVE_ANDROID_LOG_H
  1146. /**
  1147. * Add a log handler to send messages to the Android platform log facility.
  1148. */
  1149. int
  1150. add_android_log(const log_severity_list_t *severity,
  1151. const char *android_tag)
  1152. {
  1153. logfile_t *lf = NULL;
  1154. lf = tor_malloc_zero(sizeof(logfile_t));
  1155. lf->fd = -1;
  1156. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  1157. lf->filename = tor_strdup("<android>");
  1158. lf->is_android = 1;
  1159. if (android_tag == NULL)
  1160. lf->android_tag = tor_strdup("Tor");
  1161. else {
  1162. char buf[256];
  1163. tor_snprintf(buf, sizeof(buf), "Tor-%s", android_tag);
  1164. lf->android_tag = tor_strdup(buf);
  1165. }
  1166. LOCK_LOGS();
  1167. lf->next = logfiles;
  1168. logfiles = lf;
  1169. log_global_min_severity_ = get_min_log_level();
  1170. UNLOCK_LOGS();
  1171. return 0;
  1172. }
  1173. #endif /* defined(HAVE_ANDROID_LOG_H) */
  1174. /** If <b>level</b> is a valid log severity, return the corresponding
  1175. * numeric value. Otherwise, return -1. */
  1176. int
  1177. parse_log_level(const char *level)
  1178. {
  1179. if (!strcasecmp(level, "err"))
  1180. return LOG_ERR;
  1181. if (!strcasecmp(level, "warn"))
  1182. return LOG_WARN;
  1183. if (!strcasecmp(level, "notice"))
  1184. return LOG_NOTICE;
  1185. if (!strcasecmp(level, "info"))
  1186. return LOG_INFO;
  1187. if (!strcasecmp(level, "debug"))
  1188. return LOG_DEBUG;
  1189. return -1;
  1190. }
  1191. /** Return the string equivalent of a given log level. */
  1192. const char *
  1193. log_level_to_string(int level)
  1194. {
  1195. return sev_to_string(level);
  1196. }
  1197. /** NULL-terminated array of names for log domains such that domain_list[dom]
  1198. * is a description of <b>dom</b>.
  1199. *
  1200. * Remember to update doc/tor.1.txt if you modify this list.
  1201. * */
  1202. static const char *domain_list[] = {
  1203. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  1204. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  1205. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", "CHANNEL",
  1206. "SCHED", "GUARD", "CONSDIFF", "DOS", "PROCESS", "PT", "BTRACK", "MESG",
  1207. NULL
  1208. };
  1209. CTASSERT(ARRAY_LENGTH(domain_list) == N_LOGGING_DOMAINS + 1);
  1210. CTASSERT(HIGHEST_RESERVED_LD_DOMAIN_ < LD_ALL_DOMAINS);
  1211. CTASSERT(LD_ALL_DOMAINS < LOWEST_RESERVED_LD_FLAG_);
  1212. CTASSERT(LOWEST_RESERVED_LD_FLAG_ < LD_ALL_FLAGS);
  1213. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  1214. * or 0 if there is no such name. */
  1215. static log_domain_mask_t
  1216. parse_log_domain(const char *domain)
  1217. {
  1218. int i;
  1219. for (i=0; domain_list[i]; ++i) {
  1220. if (!strcasecmp(domain, domain_list[i]))
  1221. return (UINT64_C(1)<<i);
  1222. }
  1223. return 0;
  1224. }
  1225. /** Translate a bitmask of log domains to a string. */
  1226. static char *
  1227. domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
  1228. {
  1229. char *cp = buf;
  1230. char *eos = buf+buflen;
  1231. buf[0] = '\0';
  1232. if (! domain)
  1233. return buf;
  1234. while (1) {
  1235. const char *d;
  1236. int bit = tor_log2(domain);
  1237. size_t n;
  1238. if ((unsigned)bit >= ARRAY_LENGTH(domain_list)-1 ||
  1239. bit >= N_LOGGING_DOMAINS) {
  1240. tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
  1241. return buf+strlen(buf);
  1242. }
  1243. d = domain_list[bit];
  1244. n = strlcpy(cp, d, eos-cp);
  1245. if (n >= buflen) {
  1246. tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
  1247. return buf+strlen(buf);
  1248. }
  1249. cp += n;
  1250. domain &= ~(1<<bit);
  1251. if (domain == 0 || (eos-cp) < 2)
  1252. return cp;
  1253. memcpy(cp, ",", 2); /*Nul-terminated ,"*/
  1254. cp++;
  1255. }
  1256. }
  1257. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  1258. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  1259. * the parsed pattern. Return 0 on success, -1 on failure.
  1260. *
  1261. * The syntax for a SeverityPattern is:
  1262. * <pre>
  1263. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  1264. * DomainSeverity = (DomainList SP)? SeverityRange
  1265. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  1266. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  1267. * DomainSpec = "*" | Domain | "~" Domain
  1268. * </pre>
  1269. * A missing MaxSeverity defaults to ERR. Severities and domains are
  1270. * case-insensitive. "~" indicates negation for a domain; negation happens
  1271. * last inside a DomainList. Only one SeverityRange without a DomainList is
  1272. * allowed per line.
  1273. */
  1274. int
  1275. parse_log_severity_config(const char **cfg_ptr,
  1276. log_severity_list_t *severity_out)
  1277. {
  1278. const char *cfg = *cfg_ptr;
  1279. int got_anything = 0;
  1280. int got_an_unqualified_range = 0;
  1281. memset(severity_out, 0, sizeof(*severity_out));
  1282. cfg = eat_whitespace(cfg);
  1283. while (*cfg) {
  1284. const char *dash, *space;
  1285. char *sev_lo, *sev_hi;
  1286. int low, high, i;
  1287. log_domain_mask_t domains = LD_ALL_DOMAINS;
  1288. if (*cfg == '[') {
  1289. int err = 0;
  1290. char *domains_str;
  1291. smartlist_t *domains_list;
  1292. log_domain_mask_t neg_domains = 0;
  1293. const char *closebracket = strchr(cfg, ']');
  1294. if (!closebracket)
  1295. return -1;
  1296. domains = 0;
  1297. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  1298. domains_list = smartlist_new();
  1299. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  1300. -1);
  1301. tor_free(domains_str);
  1302. SMARTLIST_FOREACH_BEGIN(domains_list, const char *, domain) {
  1303. if (!strcmp(domain, "*")) {
  1304. domains = LD_ALL_DOMAINS;
  1305. } else {
  1306. log_domain_mask_t d;
  1307. int negate=0;
  1308. if (*domain == '~') {
  1309. negate = 1;
  1310. ++domain;
  1311. }
  1312. d = parse_log_domain(domain);
  1313. if (!d) {
  1314. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  1315. err = 1;
  1316. } else {
  1317. if (negate)
  1318. neg_domains |= d;
  1319. else
  1320. domains |= d;
  1321. }
  1322. }
  1323. } SMARTLIST_FOREACH_END(domain);
  1324. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  1325. smartlist_free(domains_list);
  1326. if (err)
  1327. return -1;
  1328. if (domains == 0 && neg_domains)
  1329. domains = ~neg_domains;
  1330. else
  1331. domains &= ~neg_domains;
  1332. cfg = eat_whitespace(closebracket+1);
  1333. } else {
  1334. ++got_an_unqualified_range;
  1335. }
  1336. if (!strcasecmpstart(cfg, "file") ||
  1337. !strcasecmpstart(cfg, "stderr") ||
  1338. !strcasecmpstart(cfg, "stdout") ||
  1339. !strcasecmpstart(cfg, "syslog") ||
  1340. !strcasecmpstart(cfg, "android")) {
  1341. goto done;
  1342. }
  1343. if (got_an_unqualified_range > 1)
  1344. return -1;
  1345. space = find_whitespace(cfg);
  1346. dash = strchr(cfg, '-');
  1347. if (dash && dash < space) {
  1348. sev_lo = tor_strndup(cfg, dash-cfg);
  1349. sev_hi = tor_strndup(dash+1, space-(dash+1));
  1350. } else {
  1351. sev_lo = tor_strndup(cfg, space-cfg);
  1352. sev_hi = tor_strdup("ERR");
  1353. }
  1354. low = parse_log_level(sev_lo);
  1355. high = parse_log_level(sev_hi);
  1356. tor_free(sev_lo);
  1357. tor_free(sev_hi);
  1358. if (low == -1)
  1359. return -1;
  1360. if (high == -1)
  1361. return -1;
  1362. got_anything = 1;
  1363. for (i=low; i >= high; --i)
  1364. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  1365. cfg = eat_whitespace(space);
  1366. }
  1367. done:
  1368. *cfg_ptr = cfg;
  1369. return got_anything ? 0 : -1;
  1370. }
  1371. /** Return the least severe log level that any current log is interested in. */
  1372. int
  1373. get_min_log_level(void)
  1374. {
  1375. logfile_t *lf;
  1376. int i;
  1377. int min = LOG_ERR;
  1378. for (lf = logfiles; lf; lf = lf->next) {
  1379. for (i = LOG_DEBUG; i > min; --i)
  1380. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  1381. min = i;
  1382. }
  1383. return min;
  1384. }
  1385. /** Switch all logs to output at most verbose level. */
  1386. void
  1387. switch_logs_debug(void)
  1388. {
  1389. logfile_t *lf;
  1390. int i;
  1391. LOCK_LOGS();
  1392. for (lf = logfiles; lf; lf=lf->next) {
  1393. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  1394. lf->severities->masks[SEVERITY_MASK_IDX(i)] = LD_ALL_DOMAINS;
  1395. }
  1396. log_global_min_severity_ = get_min_log_level();
  1397. UNLOCK_LOGS();
  1398. }
  1399. /** Truncate all the log files. */
  1400. void
  1401. truncate_logs(void)
  1402. {
  1403. logfile_t *lf;
  1404. for (lf = logfiles; lf; lf = lf->next) {
  1405. if (lf->fd >= 0) {
  1406. tor_ftruncate(lf->fd);
  1407. }
  1408. }
  1409. }