log.c 42 KB

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