log.c 43 KB

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