torlog.c 42 KB

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