log.c 39 KB

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