log.c 41 KB

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