log.c 42 KB

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