log.c 45 KB

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