log.c 45 KB

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