log.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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-2013, 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 specified
  332. * <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[10024];
  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. logfile_deliver(lf, msg->fullmsg, strlen(msg->fullmsg), msg->msg,
  968. msg->domain, msg->severity, &callbacks_deferred);
  969. }
  970. pending_log_message_free(msg);
  971. } SMARTLIST_FOREACH_END(msg);
  972. smartlist_free(pending_startup_messages);
  973. pending_startup_messages = NULL;
  974. out:
  975. UNLOCK_LOGS();
  976. }
  977. /** Close any log handlers added by add_temp_log() or marked by
  978. * mark_logs_temp(). */
  979. void
  980. close_temp_logs(void)
  981. {
  982. logfile_t *lf, **p;
  983. LOCK_LOGS();
  984. for (p = &logfiles; *p; ) {
  985. if ((*p)->is_temporary) {
  986. lf = *p;
  987. /* we use *p here to handle the edge case of the head of the list */
  988. *p = (*p)->next;
  989. close_log(lf);
  990. log_free(lf);
  991. } else {
  992. p = &((*p)->next);
  993. }
  994. }
  995. log_global_min_severity_ = get_min_log_level();
  996. UNLOCK_LOGS();
  997. }
  998. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  999. * live again, and close all non-temporary logs. */
  1000. void
  1001. rollback_log_changes(void)
  1002. {
  1003. logfile_t *lf;
  1004. LOCK_LOGS();
  1005. for (lf = logfiles; lf; lf = lf->next)
  1006. lf->is_temporary = ! lf->is_temporary;
  1007. UNLOCK_LOGS();
  1008. close_temp_logs();
  1009. }
  1010. /** Configure all log handles to be closed by close_temp_logs(). */
  1011. void
  1012. mark_logs_temp(void)
  1013. {
  1014. logfile_t *lf;
  1015. LOCK_LOGS();
  1016. for (lf = logfiles; lf; lf = lf->next)
  1017. lf->is_temporary = 1;
  1018. UNLOCK_LOGS();
  1019. }
  1020. /**
  1021. * Add a log handler to send messages to <b>filename</b>. If opening the
  1022. * logfile fails, -1 is returned and errno is set appropriately (by open(2)).
  1023. */
  1024. int
  1025. add_file_log(const log_severity_list_t *severity, const char *filename,
  1026. const int truncate)
  1027. {
  1028. int fd;
  1029. logfile_t *lf;
  1030. int open_flags = O_WRONLY|O_CREAT;
  1031. open_flags |= truncate ? O_TRUNC : O_APPEND;
  1032. fd = tor_open_cloexec(filename, open_flags, 0644);
  1033. if (fd<0)
  1034. return -1;
  1035. if (tor_fd_seekend(fd)<0) {
  1036. close(fd);
  1037. return -1;
  1038. }
  1039. LOCK_LOGS();
  1040. add_stream_log_impl(severity, filename, fd);
  1041. logfiles->needs_close = 1;
  1042. lf = logfiles;
  1043. log_global_min_severity_ = get_min_log_level();
  1044. if (log_tor_version(lf, 0) < 0) {
  1045. delete_log(lf);
  1046. }
  1047. UNLOCK_LOGS();
  1048. return 0;
  1049. }
  1050. #ifdef HAVE_SYSLOG_H
  1051. /**
  1052. * Add a log handler to send messages to they system log facility.
  1053. */
  1054. int
  1055. add_syslog_log(const log_severity_list_t *severity)
  1056. {
  1057. logfile_t *lf;
  1058. if (syslog_count++ == 0)
  1059. /* This is the first syslog. */
  1060. openlog("Tor", LOG_PID | LOG_NDELAY, LOGFACILITY);
  1061. lf = tor_malloc_zero(sizeof(logfile_t));
  1062. lf->fd = -1;
  1063. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  1064. lf->filename = tor_strdup("<syslog>");
  1065. lf->is_syslog = 1;
  1066. LOCK_LOGS();
  1067. lf->next = logfiles;
  1068. logfiles = lf;
  1069. log_global_min_severity_ = get_min_log_level();
  1070. UNLOCK_LOGS();
  1071. return 0;
  1072. }
  1073. #endif
  1074. /** If <b>level</b> is a valid log severity, return the corresponding
  1075. * numeric value. Otherwise, return -1. */
  1076. int
  1077. parse_log_level(const char *level)
  1078. {
  1079. if (!strcasecmp(level, "err"))
  1080. return LOG_ERR;
  1081. if (!strcasecmp(level, "warn"))
  1082. return LOG_WARN;
  1083. if (!strcasecmp(level, "notice"))
  1084. return LOG_NOTICE;
  1085. if (!strcasecmp(level, "info"))
  1086. return LOG_INFO;
  1087. if (!strcasecmp(level, "debug"))
  1088. return LOG_DEBUG;
  1089. return -1;
  1090. }
  1091. /** Return the string equivalent of a given log level. */
  1092. const char *
  1093. log_level_to_string(int level)
  1094. {
  1095. return sev_to_string(level);
  1096. }
  1097. /** NULL-terminated array of names for log domains such that domain_list[dom]
  1098. * is a description of <b>dom</b>. */
  1099. static const char *domain_list[] = {
  1100. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  1101. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  1102. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", "CHANNEL", NULL
  1103. };
  1104. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  1105. * or 0 if there is no such name. */
  1106. static log_domain_mask_t
  1107. parse_log_domain(const char *domain)
  1108. {
  1109. int i;
  1110. for (i=0; domain_list[i]; ++i) {
  1111. if (!strcasecmp(domain, domain_list[i]))
  1112. return (1u<<i);
  1113. }
  1114. return 0;
  1115. }
  1116. /** Translate a bitmask of log domains to a string. */
  1117. static char *
  1118. domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
  1119. {
  1120. char *cp = buf;
  1121. char *eos = buf+buflen;
  1122. buf[0] = '\0';
  1123. if (! domain)
  1124. return buf;
  1125. while (1) {
  1126. const char *d;
  1127. int bit = tor_log2(domain);
  1128. size_t n;
  1129. if (bit >= N_LOGGING_DOMAINS) {
  1130. tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
  1131. return buf+strlen(buf);
  1132. }
  1133. d = domain_list[bit];
  1134. n = strlcpy(cp, d, eos-cp);
  1135. if (n >= buflen) {
  1136. tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
  1137. return buf+strlen(buf);
  1138. }
  1139. cp += n;
  1140. domain &= ~(1<<bit);
  1141. if (domain == 0 || (eos-cp) < 2)
  1142. return cp;
  1143. memcpy(cp, ",", 2); /*Nul-terminated ,"*/
  1144. cp++;
  1145. }
  1146. }
  1147. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  1148. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  1149. * the parsed pattern. Return 0 on success, -1 on failure.
  1150. *
  1151. * The syntax for a SeverityPattern is:
  1152. * <pre>
  1153. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  1154. * DomainSeverity = (DomainList SP)? SeverityRange
  1155. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  1156. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  1157. * DomainSpec = "*" | Domain | "~" Domain
  1158. * </pre>
  1159. * A missing MaxSeverity defaults to ERR. Severities and domains are
  1160. * case-insensitive. "~" indicates negation for a domain; negation happens
  1161. * last inside a DomainList. Only one SeverityRange without a DomainList is
  1162. * allowed per line.
  1163. */
  1164. int
  1165. parse_log_severity_config(const char **cfg_ptr,
  1166. log_severity_list_t *severity_out)
  1167. {
  1168. const char *cfg = *cfg_ptr;
  1169. int got_anything = 0;
  1170. int got_an_unqualified_range = 0;
  1171. memset(severity_out, 0, sizeof(*severity_out));
  1172. cfg = eat_whitespace(cfg);
  1173. while (*cfg) {
  1174. const char *dash, *space;
  1175. char *sev_lo, *sev_hi;
  1176. int low, high, i;
  1177. log_domain_mask_t domains = ~0u;
  1178. if (*cfg == '[') {
  1179. int err = 0;
  1180. char *domains_str;
  1181. smartlist_t *domains_list;
  1182. log_domain_mask_t neg_domains = 0;
  1183. const char *closebracket = strchr(cfg, ']');
  1184. if (!closebracket)
  1185. return -1;
  1186. domains = 0;
  1187. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  1188. domains_list = smartlist_new();
  1189. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  1190. -1);
  1191. tor_free(domains_str);
  1192. SMARTLIST_FOREACH_BEGIN(domains_list, const char *, domain) {
  1193. if (!strcmp(domain, "*")) {
  1194. domains = ~0u;
  1195. } else {
  1196. int d;
  1197. int negate=0;
  1198. if (*domain == '~') {
  1199. negate = 1;
  1200. ++domain;
  1201. }
  1202. d = parse_log_domain(domain);
  1203. if (!d) {
  1204. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  1205. err = 1;
  1206. } else {
  1207. if (negate)
  1208. neg_domains |= d;
  1209. else
  1210. domains |= d;
  1211. }
  1212. }
  1213. } SMARTLIST_FOREACH_END(domain);
  1214. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  1215. smartlist_free(domains_list);
  1216. if (err)
  1217. return -1;
  1218. if (domains == 0 && neg_domains)
  1219. domains = ~neg_domains;
  1220. else
  1221. domains &= ~neg_domains;
  1222. cfg = eat_whitespace(closebracket+1);
  1223. } else {
  1224. ++got_an_unqualified_range;
  1225. }
  1226. if (!strcasecmpstart(cfg, "file") ||
  1227. !strcasecmpstart(cfg, "stderr") ||
  1228. !strcasecmpstart(cfg, "stdout") ||
  1229. !strcasecmpstart(cfg, "syslog")) {
  1230. goto done;
  1231. }
  1232. if (got_an_unqualified_range > 1)
  1233. return -1;
  1234. space = strchr(cfg, ' ');
  1235. dash = strchr(cfg, '-');
  1236. if (!space)
  1237. space = strchr(cfg, '\0');
  1238. if (dash && dash < space) {
  1239. sev_lo = tor_strndup(cfg, dash-cfg);
  1240. sev_hi = tor_strndup(dash+1, space-(dash+1));
  1241. } else {
  1242. sev_lo = tor_strndup(cfg, space-cfg);
  1243. sev_hi = tor_strdup("ERR");
  1244. }
  1245. low = parse_log_level(sev_lo);
  1246. high = parse_log_level(sev_hi);
  1247. tor_free(sev_lo);
  1248. tor_free(sev_hi);
  1249. if (low == -1)
  1250. return -1;
  1251. if (high == -1)
  1252. return -1;
  1253. got_anything = 1;
  1254. for (i=low; i >= high; --i)
  1255. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  1256. cfg = eat_whitespace(space);
  1257. }
  1258. done:
  1259. *cfg_ptr = cfg;
  1260. return got_anything ? 0 : -1;
  1261. }
  1262. /** Return the least severe log level that any current log is interested in. */
  1263. int
  1264. get_min_log_level(void)
  1265. {
  1266. logfile_t *lf;
  1267. int i;
  1268. int min = LOG_ERR;
  1269. for (lf = logfiles; lf; lf = lf->next) {
  1270. for (i = LOG_DEBUG; i > min; --i)
  1271. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  1272. min = i;
  1273. }
  1274. return min;
  1275. }
  1276. /** Switch all logs to output at most verbose level. */
  1277. void
  1278. switch_logs_debug(void)
  1279. {
  1280. logfile_t *lf;
  1281. int i;
  1282. LOCK_LOGS();
  1283. for (lf = logfiles; lf; lf=lf->next) {
  1284. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  1285. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  1286. }
  1287. log_global_min_severity_ = get_min_log_level();
  1288. UNLOCK_LOGS();
  1289. }
  1290. /** Truncate all the log files. */
  1291. void
  1292. truncate_logs(void)
  1293. {
  1294. logfile_t *lf;
  1295. for (lf = logfiles; lf; lf = lf->next) {
  1296. if (lf->fd >= 0) {
  1297. tor_ftruncate(lf->fd);
  1298. }
  1299. }
  1300. }