log.c 38 KB

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