log.c 43 KB

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