log.c 42 KB

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