log.c 45 KB

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