log.c 40 KB

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