log.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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. /* check that we've initialised the log mutex before we try to lock it */
  529. raw_assert(log_mutex_initialized);
  530. LOCK_LOGS();
  531. if ((! (domain & LD_NOCB)) && pending_cb_messages
  532. && smartlist_len(pending_cb_messages))
  533. flush_pending_log_callbacks();
  534. if (queue_startup_messages &&
  535. pending_startup_messages_len < MAX_STARTUP_MSG_LEN) {
  536. end_of_prefix =
  537. format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
  538. format, ap, &msg_len);
  539. formatted = 1;
  540. smartlist_add(pending_startup_messages,
  541. pending_log_message_new(severity,domain,buf,end_of_prefix));
  542. pending_startup_messages_len += msg_len;
  543. }
  544. for (lf = logfiles; lf; lf = lf->next) {
  545. if (! logfile_wants_message(lf, severity, domain))
  546. continue;
  547. if (!formatted) {
  548. end_of_prefix =
  549. format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
  550. format, ap, &msg_len);
  551. formatted = 1;
  552. }
  553. logfile_deliver(lf, buf, msg_len, end_of_prefix, domain, severity,
  554. &callbacks_deferred);
  555. }
  556. UNLOCK_LOGS();
  557. }
  558. /** Output a message to the log. It gets logged to all logfiles that
  559. * care about messages with <b>severity</b> in <b>domain</b>. The content
  560. * is formatted printf-style based on <b>format</b> and extra arguments.
  561. * */
  562. void
  563. tor_log(int severity, log_domain_mask_t domain, const char *format, ...)
  564. {
  565. va_list ap;
  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 functions. */
  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. * Long-term, we need to do something about races in the log subsystem
  785. * in general. See bug 222 for more details.
  786. */
  787. static void
  788. delete_log(logfile_t *victim)
  789. {
  790. logfile_t *tmpl;
  791. if (victim == logfiles)
  792. logfiles = victim->next;
  793. else {
  794. for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
  795. // raw_assert(tmpl);
  796. // raw_assert(tmpl->next == victim);
  797. if (!tmpl)
  798. return;
  799. tmpl->next = victim->next;
  800. }
  801. log_free(victim);
  802. }
  803. /** Helper: release system resources (but not memory) held by a single
  804. * signal-safe logfile_t. If the log's resources can not be released in
  805. * a signal handler, does nothing. */
  806. static void
  807. close_log_sigsafe(logfile_t *victim)
  808. {
  809. if (victim->needs_close && victim->fd >= 0) {
  810. /* We can't do anything useful here if close() fails: we're shutting
  811. * down logging, and the err module only does fatal errors. */
  812. close(victim->fd);
  813. victim->fd = -1;
  814. }
  815. }
  816. /** Helper: release system resources (but not memory) held by a single
  817. * logfile_t. */
  818. static void
  819. close_log(logfile_t *victim)
  820. {
  821. if (victim->needs_close) {
  822. close_log_sigsafe(victim);
  823. } else if (victim->is_syslog) {
  824. #ifdef HAVE_SYSLOG_H
  825. if (--syslog_count == 0) {
  826. /* There are no other syslogs; close the logging facility. */
  827. closelog();
  828. }
  829. #endif /* defined(HAVE_SYSLOG_H) */
  830. }
  831. }
  832. /** Adjust a log severity configuration in <b>severity_out</b> to contain
  833. * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
  834. */
  835. void
  836. set_log_severity_config(int loglevelMin, int loglevelMax,
  837. log_severity_list_t *severity_out)
  838. {
  839. int i;
  840. raw_assert(loglevelMin >= loglevelMax);
  841. raw_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
  842. raw_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
  843. memset(severity_out, 0, sizeof(log_severity_list_t));
  844. for (i = loglevelMin; i >= loglevelMax; --i) {
  845. severity_out->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  846. }
  847. }
  848. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  849. * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
  850. static void
  851. add_stream_log_impl(const log_severity_list_t *severity,
  852. const char *name, int fd)
  853. {
  854. logfile_t *lf;
  855. lf = tor_malloc_zero(sizeof(logfile_t));
  856. lf->fd = fd;
  857. lf->filename = tor_strdup(name);
  858. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  859. lf->next = logfiles;
  860. logfiles = lf;
  861. log_global_min_severity_ = get_min_log_level();
  862. }
  863. /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
  864. * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
  865. * not use it after calling this function. */
  866. void
  867. add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
  868. {
  869. LOCK_LOGS();
  870. add_stream_log_impl(severity, name, fd);
  871. UNLOCK_LOGS();
  872. }
  873. /** Initialize the global logging facility */
  874. void
  875. init_logging(int disable_startup_queue)
  876. {
  877. if (!log_mutex_initialized) {
  878. tor_mutex_init(&log_mutex);
  879. log_mutex_initialized = 1;
  880. }
  881. #ifdef __GNUC__
  882. if (strchr(__PRETTY_FUNCTION__, '(')) {
  883. pretty_fn_has_parens = 1;
  884. }
  885. #endif
  886. if (pending_cb_messages == NULL)
  887. pending_cb_messages = smartlist_new();
  888. if (disable_startup_queue)
  889. queue_startup_messages = 0;
  890. if (pending_startup_messages == NULL && queue_startup_messages) {
  891. pending_startup_messages = smartlist_new();
  892. }
  893. }
  894. /** Set whether we report logging domains as a part of our log messages.
  895. */
  896. void
  897. logs_set_domain_logging(int enabled)
  898. {
  899. LOCK_LOGS();
  900. log_domains_are_logged = enabled;
  901. UNLOCK_LOGS();
  902. }
  903. /** Add a log handler to receive messages during startup (before the real
  904. * logs are initialized).
  905. */
  906. void
  907. add_temp_log(int min_severity)
  908. {
  909. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  910. set_log_severity_config(min_severity, LOG_ERR, s);
  911. LOCK_LOGS();
  912. add_stream_log_impl(s, "<temp>", fileno(stdout));
  913. tor_free(s);
  914. logfiles->is_temporary = 1;
  915. UNLOCK_LOGS();
  916. }
  917. /**
  918. * Register "cb" as the callback to call when there are new pending log
  919. * callbacks to be flushed with flush_pending_log_callbacks().
  920. *
  921. * Note that this callback, if present, can be invoked from any thread.
  922. *
  923. * This callback must not log.
  924. *
  925. * It is intentional that this function contains the name "callback" twice: it
  926. * sets a "callback" to be called on the condition that there is a "pending
  927. * callback".
  928. **/
  929. void
  930. logs_set_pending_callback_callback(pending_callback_callback cb)
  931. {
  932. pending_cb_cb = cb;
  933. }
  934. /**
  935. * Add a log handler to send messages in <b>severity</b>
  936. * to the function <b>cb</b>.
  937. */
  938. int
  939. add_callback_log(const log_severity_list_t *severity, log_callback cb)
  940. {
  941. logfile_t *lf;
  942. lf = tor_malloc_zero(sizeof(logfile_t));
  943. lf->fd = -1;
  944. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  945. lf->filename = tor_strdup("<callback>");
  946. lf->callback = cb;
  947. lf->next = logfiles;
  948. LOCK_LOGS();
  949. logfiles = lf;
  950. log_global_min_severity_ = get_min_log_level();
  951. UNLOCK_LOGS();
  952. return 0;
  953. }
  954. /** Adjust the configured severity of any logs whose callback function is
  955. * <b>cb</b>. */
  956. void
  957. change_callback_log_severity(int loglevelMin, int loglevelMax,
  958. log_callback cb)
  959. {
  960. logfile_t *lf;
  961. log_severity_list_t severities;
  962. set_log_severity_config(loglevelMin, loglevelMax, &severities);
  963. LOCK_LOGS();
  964. for (lf = logfiles; lf; lf = lf->next) {
  965. if (lf->callback == cb) {
  966. memcpy(lf->severities, &severities, sizeof(severities));
  967. }
  968. }
  969. log_global_min_severity_ = get_min_log_level();
  970. UNLOCK_LOGS();
  971. }
  972. /** If there are any log messages that were generated with LD_NOCB waiting to
  973. * be sent to callback-based loggers, send them now. */
  974. void
  975. flush_pending_log_callbacks(void)
  976. {
  977. logfile_t *lf;
  978. smartlist_t *messages, *messages_tmp;
  979. LOCK_LOGS();
  980. if (!pending_cb_messages || 0 == smartlist_len(pending_cb_messages)) {
  981. UNLOCK_LOGS();
  982. return;
  983. }
  984. messages = pending_cb_messages;
  985. pending_cb_messages = smartlist_new();
  986. do {
  987. SMARTLIST_FOREACH_BEGIN(messages, pending_log_message_t *, msg) {
  988. const int severity = msg->severity;
  989. const log_domain_mask_t domain = msg->domain;
  990. for (lf = logfiles; lf; lf = lf->next) {
  991. if (! lf->callback || lf->seems_dead ||
  992. ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
  993. continue;
  994. }
  995. lf->callback(severity, domain, msg->msg);
  996. }
  997. pending_log_message_free(msg);
  998. } SMARTLIST_FOREACH_END(msg);
  999. smartlist_clear(messages);
  1000. messages_tmp = pending_cb_messages;
  1001. pending_cb_messages = messages;
  1002. messages = messages_tmp;
  1003. } while (smartlist_len(messages));
  1004. smartlist_free(messages);
  1005. UNLOCK_LOGS();
  1006. }
  1007. /** Flush all the messages we stored from startup while waiting for log
  1008. * initialization.
  1009. */
  1010. void
  1011. flush_log_messages_from_startup(void)
  1012. {
  1013. logfile_t *lf;
  1014. LOCK_LOGS();
  1015. queue_startup_messages = 0;
  1016. pending_startup_messages_len = 0;
  1017. if (! pending_startup_messages)
  1018. goto out;
  1019. SMARTLIST_FOREACH_BEGIN(pending_startup_messages, pending_log_message_t *,
  1020. msg) {
  1021. int callbacks_deferred = 0;
  1022. for (lf = logfiles; lf; lf = lf->next) {
  1023. if (! logfile_wants_message(lf, msg->severity, msg->domain))
  1024. continue;
  1025. /* We configure a temporary startup log that goes to stdout, so we
  1026. * shouldn't replay to stdout/stderr*/
  1027. if (lf->fd == STDOUT_FILENO || lf->fd == STDERR_FILENO) {
  1028. continue;
  1029. }
  1030. logfile_deliver(lf, msg->fullmsg, strlen(msg->fullmsg), msg->msg,
  1031. msg->domain, msg->severity, &callbacks_deferred);
  1032. }
  1033. pending_log_message_free(msg);
  1034. } SMARTLIST_FOREACH_END(msg);
  1035. smartlist_free(pending_startup_messages);
  1036. pending_startup_messages = NULL;
  1037. out:
  1038. UNLOCK_LOGS();
  1039. }
  1040. /** Close any log handlers added by add_temp_log() or marked by
  1041. * mark_logs_temp(). */
  1042. void
  1043. close_temp_logs(void)
  1044. {
  1045. logfile_t *lf, **p;
  1046. LOCK_LOGS();
  1047. for (p = &logfiles; *p; ) {
  1048. if ((*p)->is_temporary) {
  1049. lf = *p;
  1050. /* we use *p here to handle the edge case of the head of the list */
  1051. *p = (*p)->next;
  1052. close_log(lf);
  1053. log_free(lf);
  1054. } else {
  1055. p = &((*p)->next);
  1056. }
  1057. }
  1058. log_global_min_severity_ = get_min_log_level();
  1059. UNLOCK_LOGS();
  1060. }
  1061. /** Make all currently temporary logs (set to be closed by close_temp_logs)
  1062. * live again, and close all non-temporary logs. */
  1063. void
  1064. rollback_log_changes(void)
  1065. {
  1066. logfile_t *lf;
  1067. LOCK_LOGS();
  1068. for (lf = logfiles; lf; lf = lf->next)
  1069. lf->is_temporary = ! lf->is_temporary;
  1070. UNLOCK_LOGS();
  1071. close_temp_logs();
  1072. }
  1073. /** Configure all log handles to be closed by close_temp_logs(). */
  1074. void
  1075. mark_logs_temp(void)
  1076. {
  1077. logfile_t *lf;
  1078. LOCK_LOGS();
  1079. for (lf = logfiles; lf; lf = lf->next)
  1080. lf->is_temporary = 1;
  1081. UNLOCK_LOGS();
  1082. }
  1083. /**
  1084. * Add a log handler to send messages to <b>filename</b> via <b>fd</b>. If
  1085. * opening the logfile failed, -1 is returned and errno is set appropriately
  1086. * (by open(2)). Takes ownership of fd.
  1087. */
  1088. int
  1089. add_file_log(const log_severity_list_t *severity,
  1090. const char *filename,
  1091. int fd)
  1092. {
  1093. logfile_t *lf;
  1094. if (fd<0)
  1095. return -1;
  1096. if (tor_fd_seekend(fd)<0) {
  1097. close(fd);
  1098. return -1;
  1099. }
  1100. LOCK_LOGS();
  1101. add_stream_log_impl(severity, filename, fd);
  1102. logfiles->needs_close = 1;
  1103. lf = logfiles;
  1104. log_global_min_severity_ = get_min_log_level();
  1105. if (log_tor_version(lf, 0) < 0) {
  1106. delete_log(lf);
  1107. }
  1108. UNLOCK_LOGS();
  1109. return 0;
  1110. }
  1111. #ifdef HAVE_SYSLOG_H
  1112. /**
  1113. * Add a log handler to send messages to they system log facility.
  1114. *
  1115. * If this is the first log handler, opens syslog with ident Tor or
  1116. * Tor-<syslog_identity_tag> if that is not NULL.
  1117. */
  1118. int
  1119. add_syslog_log(const log_severity_list_t *severity,
  1120. const char* syslog_identity_tag)
  1121. {
  1122. logfile_t *lf;
  1123. if (syslog_count++ == 0) {
  1124. /* This is the first syslog. */
  1125. static char buf[256];
  1126. if (syslog_identity_tag) {
  1127. tor_snprintf(buf, sizeof(buf), "Tor-%s", syslog_identity_tag);
  1128. } else {
  1129. tor_snprintf(buf, sizeof(buf), "Tor");
  1130. }
  1131. openlog(buf, LOG_PID | LOG_NDELAY, LOGFACILITY);
  1132. }
  1133. lf = tor_malloc_zero(sizeof(logfile_t));
  1134. lf->fd = -1;
  1135. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  1136. lf->filename = tor_strdup("<syslog>");
  1137. lf->is_syslog = 1;
  1138. LOCK_LOGS();
  1139. lf->next = logfiles;
  1140. logfiles = lf;
  1141. log_global_min_severity_ = get_min_log_level();
  1142. UNLOCK_LOGS();
  1143. return 0;
  1144. }
  1145. #endif /* defined(HAVE_SYSLOG_H) */
  1146. #ifdef HAVE_ANDROID_LOG_H
  1147. /**
  1148. * Add a log handler to send messages to the Android platform log facility.
  1149. */
  1150. int
  1151. add_android_log(const log_severity_list_t *severity,
  1152. const char *android_tag)
  1153. {
  1154. logfile_t *lf = NULL;
  1155. lf = tor_malloc_zero(sizeof(logfile_t));
  1156. lf->fd = -1;
  1157. lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
  1158. lf->filename = tor_strdup("<android>");
  1159. lf->is_android = 1;
  1160. if (android_tag == NULL)
  1161. lf->android_tag = tor_strdup("Tor");
  1162. else {
  1163. char buf[256];
  1164. tor_snprintf(buf, sizeof(buf), "Tor-%s", android_tag);
  1165. lf->android_tag = tor_strdup(buf);
  1166. }
  1167. LOCK_LOGS();
  1168. lf->next = logfiles;
  1169. logfiles = lf;
  1170. log_global_min_severity_ = get_min_log_level();
  1171. UNLOCK_LOGS();
  1172. return 0;
  1173. }
  1174. #endif /* defined(HAVE_ANDROID_LOG_H) */
  1175. /** If <b>level</b> is a valid log severity, return the corresponding
  1176. * numeric value. Otherwise, return -1. */
  1177. int
  1178. parse_log_level(const char *level)
  1179. {
  1180. if (!strcasecmp(level, "err"))
  1181. return LOG_ERR;
  1182. if (!strcasecmp(level, "warn"))
  1183. return LOG_WARN;
  1184. if (!strcasecmp(level, "notice"))
  1185. return LOG_NOTICE;
  1186. if (!strcasecmp(level, "info"))
  1187. return LOG_INFO;
  1188. if (!strcasecmp(level, "debug"))
  1189. return LOG_DEBUG;
  1190. return -1;
  1191. }
  1192. /** Return the string equivalent of a given log level. */
  1193. const char *
  1194. log_level_to_string(int level)
  1195. {
  1196. return sev_to_string(level);
  1197. }
  1198. /** NULL-terminated array of names for log domains such that domain_list[dom]
  1199. * is a description of <b>dom</b>.
  1200. *
  1201. * Remember to update doc/tor.1.txt if you modify this list.
  1202. * */
  1203. static const char *domain_list[] = {
  1204. "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
  1205. "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
  1206. "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", "CHANNEL",
  1207. "SCHED", "GUARD", "CONSDIFF", "DOS", "PROCESS", "PT", "BTRACK", "MESG",
  1208. NULL
  1209. };
  1210. CTASSERT(ARRAY_LENGTH(domain_list) == N_LOGGING_DOMAINS + 1);
  1211. CTASSERT((UINT64_C(1)<<(N_LOGGING_DOMAINS-1)) < LOWEST_RESERVED_LD_FLAG_);
  1212. /** Return a bitmask for the log domain for which <b>domain</b> is the name,
  1213. * or 0 if there is no such name. */
  1214. static log_domain_mask_t
  1215. parse_log_domain(const char *domain)
  1216. {
  1217. int i;
  1218. for (i=0; domain_list[i]; ++i) {
  1219. if (!strcasecmp(domain, domain_list[i]))
  1220. return (UINT64_C(1)<<i);
  1221. }
  1222. return 0;
  1223. }
  1224. /** Translate a bitmask of log domains to a string. */
  1225. static char *
  1226. domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
  1227. {
  1228. char *cp = buf;
  1229. char *eos = buf+buflen;
  1230. buf[0] = '\0';
  1231. if (! domain)
  1232. return buf;
  1233. while (1) {
  1234. const char *d;
  1235. int bit = tor_log2(domain);
  1236. size_t n;
  1237. if ((unsigned)bit >= ARRAY_LENGTH(domain_list)-1 ||
  1238. bit >= N_LOGGING_DOMAINS) {
  1239. tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
  1240. return buf+strlen(buf);
  1241. }
  1242. d = domain_list[bit];
  1243. n = strlcpy(cp, d, eos-cp);
  1244. if (n >= buflen) {
  1245. tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
  1246. return buf+strlen(buf);
  1247. }
  1248. cp += n;
  1249. domain &= ~(1<<bit);
  1250. if (domain == 0 || (eos-cp) < 2)
  1251. return cp;
  1252. memcpy(cp, ",", 2); /*Nul-terminated ,"*/
  1253. cp++;
  1254. }
  1255. }
  1256. /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
  1257. * the end of the severityPattern. Set the value of <b>severity_out</b> to
  1258. * the parsed pattern. Return 0 on success, -1 on failure.
  1259. *
  1260. * The syntax for a SeverityPattern is:
  1261. * <pre>
  1262. * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
  1263. * DomainSeverity = (DomainList SP)? SeverityRange
  1264. * SeverityRange = MinSeverity ("-" MaxSeverity )?
  1265. * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
  1266. * DomainSpec = "*" | Domain | "~" Domain
  1267. * </pre>
  1268. * A missing MaxSeverity defaults to ERR. Severities and domains are
  1269. * case-insensitive. "~" indicates negation for a domain; negation happens
  1270. * last inside a DomainList. Only one SeverityRange without a DomainList is
  1271. * allowed per line.
  1272. */
  1273. int
  1274. parse_log_severity_config(const char **cfg_ptr,
  1275. log_severity_list_t *severity_out)
  1276. {
  1277. const char *cfg = *cfg_ptr;
  1278. int got_anything = 0;
  1279. int got_an_unqualified_range = 0;
  1280. memset(severity_out, 0, sizeof(*severity_out));
  1281. cfg = eat_whitespace(cfg);
  1282. while (*cfg) {
  1283. const char *dash, *space;
  1284. char *sev_lo, *sev_hi;
  1285. int low, high, i;
  1286. log_domain_mask_t domains = ~0u;
  1287. if (*cfg == '[') {
  1288. int err = 0;
  1289. char *domains_str;
  1290. smartlist_t *domains_list;
  1291. log_domain_mask_t neg_domains = 0;
  1292. const char *closebracket = strchr(cfg, ']');
  1293. if (!closebracket)
  1294. return -1;
  1295. domains = 0;
  1296. domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
  1297. domains_list = smartlist_new();
  1298. smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
  1299. -1);
  1300. tor_free(domains_str);
  1301. SMARTLIST_FOREACH_BEGIN(domains_list, const char *, domain) {
  1302. if (!strcmp(domain, "*")) {
  1303. domains = ~0u;
  1304. } else {
  1305. log_domain_mask_t d;
  1306. int negate=0;
  1307. if (*domain == '~') {
  1308. negate = 1;
  1309. ++domain;
  1310. }
  1311. d = parse_log_domain(domain);
  1312. if (!d) {
  1313. log_warn(LD_CONFIG, "No such logging domain as %s", domain);
  1314. err = 1;
  1315. } else {
  1316. if (negate)
  1317. neg_domains |= d;
  1318. else
  1319. domains |= d;
  1320. }
  1321. }
  1322. } SMARTLIST_FOREACH_END(domain);
  1323. SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
  1324. smartlist_free(domains_list);
  1325. if (err)
  1326. return -1;
  1327. if (domains == 0 && neg_domains)
  1328. domains = ~neg_domains;
  1329. else
  1330. domains &= ~neg_domains;
  1331. cfg = eat_whitespace(closebracket+1);
  1332. } else {
  1333. ++got_an_unqualified_range;
  1334. }
  1335. if (!strcasecmpstart(cfg, "file") ||
  1336. !strcasecmpstart(cfg, "stderr") ||
  1337. !strcasecmpstart(cfg, "stdout") ||
  1338. !strcasecmpstart(cfg, "syslog") ||
  1339. !strcasecmpstart(cfg, "android")) {
  1340. goto done;
  1341. }
  1342. if (got_an_unqualified_range > 1)
  1343. return -1;
  1344. space = find_whitespace(cfg);
  1345. dash = strchr(cfg, '-');
  1346. if (dash && dash < space) {
  1347. sev_lo = tor_strndup(cfg, dash-cfg);
  1348. sev_hi = tor_strndup(dash+1, space-(dash+1));
  1349. } else {
  1350. sev_lo = tor_strndup(cfg, space-cfg);
  1351. sev_hi = tor_strdup("ERR");
  1352. }
  1353. low = parse_log_level(sev_lo);
  1354. high = parse_log_level(sev_hi);
  1355. tor_free(sev_lo);
  1356. tor_free(sev_hi);
  1357. if (low == -1)
  1358. return -1;
  1359. if (high == -1)
  1360. return -1;
  1361. got_anything = 1;
  1362. for (i=low; i >= high; --i)
  1363. severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
  1364. cfg = eat_whitespace(space);
  1365. }
  1366. done:
  1367. *cfg_ptr = cfg;
  1368. return got_anything ? 0 : -1;
  1369. }
  1370. /** Return the least severe log level that any current log is interested in. */
  1371. int
  1372. get_min_log_level(void)
  1373. {
  1374. logfile_t *lf;
  1375. int i;
  1376. int min = LOG_ERR;
  1377. for (lf = logfiles; lf; lf = lf->next) {
  1378. for (i = LOG_DEBUG; i > min; --i)
  1379. if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
  1380. min = i;
  1381. }
  1382. return min;
  1383. }
  1384. /** Switch all logs to output at most verbose level. */
  1385. void
  1386. switch_logs_debug(void)
  1387. {
  1388. logfile_t *lf;
  1389. int i;
  1390. LOCK_LOGS();
  1391. for (lf = logfiles; lf; lf=lf->next) {
  1392. for (i = LOG_DEBUG; i >= LOG_ERR; --i)
  1393. lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
  1394. }
  1395. log_global_min_severity_ = get_min_log_level();
  1396. UNLOCK_LOGS();
  1397. }
  1398. /** Truncate all the log files. */
  1399. void
  1400. truncate_logs(void)
  1401. {
  1402. logfile_t *lf;
  1403. for (lf = logfiles; lf; lf = lf->next) {
  1404. if (lf->fd >= 0) {
  1405. tor_ftruncate(lf->fd);
  1406. }
  1407. }
  1408. }