log.c 40 KB

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