log.c 42 KB

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