log.c 43 KB

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