log.c 42 KB

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