log.c 42 KB

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