torlog.c 42 KB

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