hibernate.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file hibernate.c
  6. * \brief Functions to close listeners, stop allowing new circuits,
  7. * etc in preparation for closing down or going dormant; and to track
  8. * bandwidth and time intervals to know when to hibernate and when to
  9. * stop hibernating.
  10. *
  11. * Ordinarily a Tor relay is "Live".
  12. *
  13. * A live relay can stop accepting connections for one of two reasons: either
  14. * it is trying to conserve bandwidth because of bandwidth accounting rules
  15. * ("soft hibernation"), or it is about to shut down ("exiting").
  16. **/
  17. /*
  18. hibernating, phase 1:
  19. - send destroy in response to create cells
  20. - send end (policy failed) in response to begin cells
  21. - close an OR conn when it has no circuits
  22. hibernating, phase 2:
  23. (entered when bandwidth hard limit reached)
  24. - close all OR/AP/exit conns)
  25. */
  26. #define HIBERNATE_PRIVATE
  27. #include "or/or.h"
  28. #include "or/channel.h"
  29. #include "or/channeltls.h"
  30. #include "or/config.h"
  31. #include "or/connection.h"
  32. #include "or/connection_edge.h"
  33. #include "or/connection_or.h"
  34. #include "or/control.h"
  35. #include "lib/crypt_ops/crypto_rand.h"
  36. #include "or/hibernate.h"
  37. #include "or/main.h"
  38. #include "or/router.h"
  39. #include "or/statefile.h"
  40. #include "common/compat_libevent.h"
  41. #include "or/or_connection_st.h"
  42. #include "or/or_state_st.h"
  43. #ifdef HAVE_UNISTD_H
  44. #include <unistd.h>
  45. #endif
  46. /** Are we currently awake, asleep, running out of bandwidth, or shutting
  47. * down? */
  48. static hibernate_state_t hibernate_state = HIBERNATE_STATE_INITIAL;
  49. /** If are hibernating, when do we plan to wake up? Set to 0 if we
  50. * aren't hibernating. */
  51. static time_t hibernate_end_time = 0;
  52. /** If we are shutting down, when do we plan finally exit? Set to 0 if
  53. * we aren't shutting down. */
  54. static time_t shutdown_time = 0;
  55. /** A timed event that we'll use when it's time to wake up from
  56. * hibernation. */
  57. static mainloop_event_t *wakeup_event = NULL;
  58. /** Possible accounting periods. */
  59. typedef enum {
  60. UNIT_MONTH=1, UNIT_WEEK=2, UNIT_DAY=3,
  61. } time_unit_t;
  62. /*
  63. * @file hibernate.c
  64. *
  65. * <h4>Accounting</h4>
  66. * Accounting is designed to ensure that no more than N bytes are sent in
  67. * either direction over a given interval (currently, one month, one week, or
  68. * one day) We could
  69. * try to do this by choking our bandwidth to a trickle, but that
  70. * would make our streams useless. Instead, we estimate what our
  71. * bandwidth usage will be, and guess how long we'll be able to
  72. * provide that much bandwidth before hitting our limit. We then
  73. * choose a random time within the accounting interval to come up (so
  74. * that we don't get 50 Tors running on the 1st of the month and none
  75. * on the 30th).
  76. *
  77. * Each interval runs as follows:
  78. *
  79. * <ol>
  80. * <li>We guess our bandwidth usage, based on how much we used
  81. * last time. We choose a "wakeup time" within the interval to come up.
  82. * <li>Until the chosen wakeup time, we hibernate.
  83. * <li> We come up at the wakeup time, and provide bandwidth until we are
  84. * "very close" to running out.
  85. * <li> Then we go into low-bandwidth mode, and stop accepting new
  86. * connections, but provide bandwidth until we run out.
  87. * <li> Then we hibernate until the end of the interval.
  88. *
  89. * If the interval ends before we run out of bandwidth, we go back to
  90. * step one.
  91. *
  92. * Accounting is controlled by the AccountingMax, AccountingRule, and
  93. * AccountingStart options.
  94. */
  95. /** How many bytes have we read in this accounting interval? */
  96. static uint64_t n_bytes_read_in_interval = 0;
  97. /** How many bytes have we written in this accounting interval? */
  98. static uint64_t n_bytes_written_in_interval = 0;
  99. /** How many seconds have we been running this interval? */
  100. static uint32_t n_seconds_active_in_interval = 0;
  101. /** How many seconds were we active in this interval before we hit our soft
  102. * limit? */
  103. static int n_seconds_to_hit_soft_limit = 0;
  104. /** When in this interval was the soft limit hit. */
  105. static time_t soft_limit_hit_at = 0;
  106. /** How many bytes had we read/written when we hit the soft limit? */
  107. static uint64_t n_bytes_at_soft_limit = 0;
  108. /** When did this accounting interval start? */
  109. static time_t interval_start_time = 0;
  110. /** When will this accounting interval end? */
  111. static time_t interval_end_time = 0;
  112. /** How far into the accounting interval should we hibernate? */
  113. static time_t interval_wakeup_time = 0;
  114. /** How much bandwidth do we 'expect' to use per minute? (0 if we have no
  115. * info from the last period.) */
  116. static uint64_t expected_bandwidth_usage = 0;
  117. /** What unit are we using for our accounting? */
  118. static time_unit_t cfg_unit = UNIT_MONTH;
  119. /** How many days,hours,minutes into each unit does our accounting interval
  120. * start? */
  121. /** @{ */
  122. static int cfg_start_day = 0,
  123. cfg_start_hour = 0,
  124. cfg_start_min = 0;
  125. /** @} */
  126. static const char *hibernate_state_to_string(hibernate_state_t state);
  127. static void reset_accounting(time_t now);
  128. static int read_bandwidth_usage(void);
  129. static time_t start_of_accounting_period_after(time_t now);
  130. static time_t start_of_accounting_period_containing(time_t now);
  131. static void accounting_set_wakeup_time(void);
  132. static void on_hibernate_state_change(hibernate_state_t prev_state);
  133. static void hibernate_schedule_wakeup_event(time_t now, time_t end_time);
  134. static void wakeup_event_callback(mainloop_event_t *ev, void *data);
  135. /**
  136. * Return the human-readable name for the hibernation state <b>state</b>
  137. */
  138. static const char *
  139. hibernate_state_to_string(hibernate_state_t state)
  140. {
  141. static char buf[64];
  142. switch (state) {
  143. case HIBERNATE_STATE_EXITING: return "EXITING";
  144. case HIBERNATE_STATE_LOWBANDWIDTH: return "SOFT";
  145. case HIBERNATE_STATE_DORMANT: return "HARD";
  146. case HIBERNATE_STATE_INITIAL:
  147. case HIBERNATE_STATE_LIVE:
  148. return "AWAKE";
  149. default:
  150. log_warn(LD_BUG, "unknown hibernate state %d", state);
  151. tor_snprintf(buf, sizeof(buf), "unknown [%d]", state);
  152. return buf;
  153. }
  154. }
  155. /* ************
  156. * Functions for bandwidth accounting.
  157. * ************/
  158. /** Configure accounting start/end time settings based on
  159. * options->AccountingStart. Return 0 on success, -1 on failure. If
  160. * <b>validate_only</b> is true, do not change the current settings. */
  161. int
  162. accounting_parse_options(const or_options_t *options, int validate_only)
  163. {
  164. time_unit_t unit;
  165. int ok, idx;
  166. long d,h,m;
  167. smartlist_t *items;
  168. const char *v = options->AccountingStart;
  169. const char *s;
  170. char *cp;
  171. if (!v) {
  172. if (!validate_only) {
  173. cfg_unit = UNIT_MONTH;
  174. cfg_start_day = 1;
  175. cfg_start_hour = 0;
  176. cfg_start_min = 0;
  177. }
  178. return 0;
  179. }
  180. items = smartlist_new();
  181. smartlist_split_string(items, v, NULL,
  182. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
  183. if (smartlist_len(items)<2) {
  184. log_warn(LD_CONFIG, "Too few arguments to AccountingStart");
  185. goto err;
  186. }
  187. s = smartlist_get(items,0);
  188. if (0==strcasecmp(s, "month")) {
  189. unit = UNIT_MONTH;
  190. } else if (0==strcasecmp(s, "week")) {
  191. unit = UNIT_WEEK;
  192. } else if (0==strcasecmp(s, "day")) {
  193. unit = UNIT_DAY;
  194. } else {
  195. log_warn(LD_CONFIG,
  196. "Unrecognized accounting unit '%s': only 'month', 'week',"
  197. " and 'day' are supported.", s);
  198. goto err;
  199. }
  200. switch (unit) {
  201. case UNIT_WEEK:
  202. d = tor_parse_long(smartlist_get(items,1), 10, 1, 7, &ok, NULL);
  203. if (!ok) {
  204. log_warn(LD_CONFIG, "Weekly accounting must begin on a day between "
  205. "1 (Monday) and 7 (Sunday)");
  206. goto err;
  207. }
  208. break;
  209. case UNIT_MONTH:
  210. d = tor_parse_long(smartlist_get(items,1), 10, 1, 28, &ok, NULL);
  211. if (!ok) {
  212. log_warn(LD_CONFIG, "Monthly accounting must begin on a day between "
  213. "1 and 28");
  214. goto err;
  215. }
  216. break;
  217. case UNIT_DAY:
  218. d = 0;
  219. break;
  220. /* Coverity dislikes unreachable default cases; some compilers warn on
  221. * switch statements missing a case. Tell Coverity not to worry. */
  222. /* coverity[dead_error_begin] */
  223. default:
  224. tor_assert(0);
  225. }
  226. idx = unit==UNIT_DAY?1:2;
  227. if (smartlist_len(items) != (idx+1)) {
  228. log_warn(LD_CONFIG,"Accounting unit '%s' requires %d argument%s.",
  229. s, idx, (idx>1)?"s":"");
  230. goto err;
  231. }
  232. s = smartlist_get(items, idx);
  233. h = tor_parse_long(s, 10, 0, 23, &ok, &cp);
  234. if (!ok) {
  235. log_warn(LD_CONFIG,"Accounting start time not parseable: bad hour.");
  236. goto err;
  237. }
  238. if (!cp || *cp!=':') {
  239. log_warn(LD_CONFIG,
  240. "Accounting start time not parseable: not in HH:MM format");
  241. goto err;
  242. }
  243. m = tor_parse_long(cp+1, 10, 0, 59, &ok, &cp);
  244. if (!ok) {
  245. log_warn(LD_CONFIG, "Accounting start time not parseable: bad minute");
  246. goto err;
  247. }
  248. if (!cp || *cp!='\0') {
  249. log_warn(LD_CONFIG,
  250. "Accounting start time not parseable: not in HH:MM format");
  251. goto err;
  252. }
  253. if (!validate_only) {
  254. cfg_unit = unit;
  255. cfg_start_day = (int)d;
  256. cfg_start_hour = (int)h;
  257. cfg_start_min = (int)m;
  258. }
  259. SMARTLIST_FOREACH(items, char *, item, tor_free(item));
  260. smartlist_free(items);
  261. return 0;
  262. err:
  263. SMARTLIST_FOREACH(items, char *, item, tor_free(item));
  264. smartlist_free(items);
  265. return -1;
  266. }
  267. /** If we want to manage the accounting system and potentially
  268. * hibernate, return 1, else return 0.
  269. */
  270. MOCK_IMPL(int,
  271. accounting_is_enabled,(const or_options_t *options))
  272. {
  273. if (options->AccountingMax)
  274. return 1;
  275. return 0;
  276. }
  277. /** If accounting is enabled, return how long (in seconds) this
  278. * interval lasts. */
  279. int
  280. accounting_get_interval_length(void)
  281. {
  282. return (int)(interval_end_time - interval_start_time);
  283. }
  284. /** Return the time at which the current accounting interval will end. */
  285. MOCK_IMPL(time_t,
  286. accounting_get_end_time,(void))
  287. {
  288. return interval_end_time;
  289. }
  290. /** Called from connection.c to tell us that <b>seconds</b> seconds have
  291. * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
  292. * bytes have been written. */
  293. void
  294. accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
  295. {
  296. n_bytes_read_in_interval += n_read;
  297. n_bytes_written_in_interval += n_written;
  298. /* If we haven't been called in 10 seconds, we're probably jumping
  299. * around in time. */
  300. n_seconds_active_in_interval += (seconds < 10) ? seconds : 0;
  301. }
  302. /** If get_end, return the end of the accounting period that contains
  303. * the time <b>now</b>. Else, return the start of the accounting
  304. * period that contains the time <b>now</b> */
  305. static time_t
  306. edge_of_accounting_period_containing(time_t now, int get_end)
  307. {
  308. int before;
  309. struct tm tm;
  310. tor_localtime_r(&now, &tm);
  311. /* Set 'before' to true iff the current time is before the hh:mm
  312. * changeover time for today. */
  313. before = tm.tm_hour < cfg_start_hour ||
  314. (tm.tm_hour == cfg_start_hour && tm.tm_min < cfg_start_min);
  315. /* Dispatch by unit. First, find the start day of the given period;
  316. * then, if get_end is true, increment to the end day. */
  317. switch (cfg_unit)
  318. {
  319. case UNIT_MONTH: {
  320. /* If this is before the Nth, we want the Nth of last month. */
  321. if (tm.tm_mday < cfg_start_day ||
  322. (tm.tm_mday == cfg_start_day && before)) {
  323. --tm.tm_mon;
  324. }
  325. /* Otherwise, the month is correct. */
  326. tm.tm_mday = cfg_start_day;
  327. if (get_end)
  328. ++tm.tm_mon;
  329. break;
  330. }
  331. case UNIT_WEEK: {
  332. /* What is the 'target' day of the week in struct tm format? (We
  333. say Sunday==7; struct tm says Sunday==0.) */
  334. int wday = cfg_start_day % 7;
  335. /* How many days do we subtract from today to get to the right day? */
  336. int delta = (7+tm.tm_wday-wday)%7;
  337. /* If we are on the right day, but the changeover hasn't happened yet,
  338. * then subtract a whole week. */
  339. if (delta == 0 && before)
  340. delta = 7;
  341. tm.tm_mday -= delta;
  342. if (get_end)
  343. tm.tm_mday += 7;
  344. break;
  345. }
  346. case UNIT_DAY:
  347. if (before)
  348. --tm.tm_mday;
  349. if (get_end)
  350. ++tm.tm_mday;
  351. break;
  352. default:
  353. tor_assert(0);
  354. }
  355. tm.tm_hour = cfg_start_hour;
  356. tm.tm_min = cfg_start_min;
  357. tm.tm_sec = 0;
  358. tm.tm_isdst = -1; /* Autodetect DST */
  359. return mktime(&tm);
  360. }
  361. /** Return the start of the accounting period containing the time
  362. * <b>now</b>. */
  363. static time_t
  364. start_of_accounting_period_containing(time_t now)
  365. {
  366. return edge_of_accounting_period_containing(now, 0);
  367. }
  368. /** Return the start of the accounting period that comes after the one
  369. * containing the time <b>now</b>. */
  370. static time_t
  371. start_of_accounting_period_after(time_t now)
  372. {
  373. return edge_of_accounting_period_containing(now, 1);
  374. }
  375. /** Return the length of the accounting period containing the time
  376. * <b>now</b>. */
  377. static long
  378. length_of_accounting_period_containing(time_t now)
  379. {
  380. return edge_of_accounting_period_containing(now, 1) -
  381. edge_of_accounting_period_containing(now, 0);
  382. }
  383. /** Initialize the accounting subsystem. */
  384. void
  385. configure_accounting(time_t now)
  386. {
  387. time_t s_now;
  388. /* Try to remember our recorded usage. */
  389. if (!interval_start_time)
  390. read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
  391. * reset below.*/
  392. s_now = start_of_accounting_period_containing(now);
  393. if (!interval_start_time) {
  394. /* We didn't have recorded usage; Start a new interval. */
  395. log_info(LD_ACCT, "Starting new accounting interval.");
  396. reset_accounting(now);
  397. } else if (s_now == interval_start_time) {
  398. log_info(LD_ACCT, "Continuing accounting interval.");
  399. /* We are in the interval we thought we were in. Do nothing.*/
  400. interval_end_time = start_of_accounting_period_after(interval_start_time);
  401. } else {
  402. long duration =
  403. length_of_accounting_period_containing(interval_start_time);
  404. double delta = ((double)(s_now - interval_start_time)) / duration;
  405. if (-0.50 <= delta && delta <= 0.50) {
  406. /* The start of the period is now a little later or earlier than we
  407. * remembered. That's fine; we might lose some bytes we could otherwise
  408. * have written, but better to err on the side of obeying accounting
  409. * settings. */
  410. log_info(LD_ACCT, "Accounting interval moved by %.02f%%; "
  411. "that's fine.", delta*100);
  412. interval_end_time = start_of_accounting_period_after(now);
  413. } else if (delta >= 0.99) {
  414. /* This is the regular time-moved-forward case; don't be too noisy
  415. * about it or people will complain */
  416. log_info(LD_ACCT, "Accounting interval elapsed; starting a new one");
  417. reset_accounting(now);
  418. } else {
  419. log_warn(LD_ACCT,
  420. "Mismatched accounting interval: moved by %.02f%%. "
  421. "Starting a fresh one.", delta*100);
  422. reset_accounting(now);
  423. }
  424. }
  425. accounting_set_wakeup_time();
  426. }
  427. /** Return the relevant number of bytes sent/received this interval
  428. * based on the set AccountingRule */
  429. uint64_t
  430. get_accounting_bytes(void)
  431. {
  432. if (get_options()->AccountingRule == ACCT_SUM)
  433. return n_bytes_read_in_interval+n_bytes_written_in_interval;
  434. else if (get_options()->AccountingRule == ACCT_IN)
  435. return n_bytes_read_in_interval;
  436. else if (get_options()->AccountingRule == ACCT_OUT)
  437. return n_bytes_written_in_interval;
  438. else
  439. return MAX(n_bytes_read_in_interval, n_bytes_written_in_interval);
  440. }
  441. /** Set expected_bandwidth_usage based on how much we sent/received
  442. * per minute last interval (if we were up for at least 30 minutes),
  443. * or based on our declared bandwidth otherwise. */
  444. static void
  445. update_expected_bandwidth(void)
  446. {
  447. uint64_t expected;
  448. const or_options_t *options= get_options();
  449. uint64_t max_configured = (options->RelayBandwidthRate > 0 ?
  450. options->RelayBandwidthRate :
  451. options->BandwidthRate) * 60;
  452. /* max_configured is the larger of bytes read and bytes written
  453. * If we are accounting based on sum, worst case is both are
  454. * at max, doubling the expected sum of bandwidth */
  455. if (get_options()->AccountingRule == ACCT_SUM)
  456. max_configured *= 2;
  457. #define MIN_TIME_FOR_MEASUREMENT (1800)
  458. if (soft_limit_hit_at > interval_start_time && n_bytes_at_soft_limit &&
  459. (soft_limit_hit_at - interval_start_time) > MIN_TIME_FOR_MEASUREMENT) {
  460. /* If we hit our soft limit last time, only count the bytes up to that
  461. * time. This is a better predictor of our actual bandwidth than
  462. * considering the entirety of the last interval, since we likely started
  463. * using bytes very slowly once we hit our soft limit. */
  464. expected = n_bytes_at_soft_limit /
  465. (soft_limit_hit_at - interval_start_time);
  466. expected /= 60;
  467. } else if (n_seconds_active_in_interval >= MIN_TIME_FOR_MEASUREMENT) {
  468. /* Otherwise, we either measured enough time in the last interval but
  469. * never hit our soft limit, or we're using a state file from a Tor that
  470. * doesn't know to store soft-limit info. Just take rate at which
  471. * we were reading/writing in the last interval as our expected rate.
  472. */
  473. uint64_t used = get_accounting_bytes();
  474. expected = used / (n_seconds_active_in_interval / 60);
  475. } else {
  476. /* If we haven't gotten enough data last interval, set 'expected'
  477. * to 0. This will set our wakeup to the start of the interval.
  478. * Next interval, we'll choose our starting time based on how much
  479. * we sent this interval.
  480. */
  481. expected = 0;
  482. }
  483. if (expected > max_configured)
  484. expected = max_configured;
  485. expected_bandwidth_usage = expected;
  486. }
  487. /** Called at the start of a new accounting interval: reset our
  488. * expected bandwidth usage based on what happened last time, set up
  489. * the start and end of the interval, and clear byte/time totals.
  490. */
  491. static void
  492. reset_accounting(time_t now)
  493. {
  494. log_info(LD_ACCT, "Starting new accounting interval.");
  495. update_expected_bandwidth();
  496. interval_start_time = start_of_accounting_period_containing(now);
  497. interval_end_time = start_of_accounting_period_after(interval_start_time);
  498. n_bytes_read_in_interval = 0;
  499. n_bytes_written_in_interval = 0;
  500. n_seconds_active_in_interval = 0;
  501. n_bytes_at_soft_limit = 0;
  502. soft_limit_hit_at = 0;
  503. n_seconds_to_hit_soft_limit = 0;
  504. }
  505. /** Return true iff we should save our bandwidth usage to disk. */
  506. static inline int
  507. time_to_record_bandwidth_usage(time_t now)
  508. {
  509. /* Note every 600 sec */
  510. #define NOTE_INTERVAL (600)
  511. /* Or every 20 megabytes */
  512. #define NOTE_BYTES 20*(1024*1024)
  513. static uint64_t last_read_bytes_noted = 0;
  514. static uint64_t last_written_bytes_noted = 0;
  515. static time_t last_time_noted = 0;
  516. if (last_time_noted + NOTE_INTERVAL <= now ||
  517. last_read_bytes_noted + NOTE_BYTES <= n_bytes_read_in_interval ||
  518. last_written_bytes_noted + NOTE_BYTES <= n_bytes_written_in_interval ||
  519. (interval_end_time && interval_end_time <= now)) {
  520. last_time_noted = now;
  521. last_read_bytes_noted = n_bytes_read_in_interval;
  522. last_written_bytes_noted = n_bytes_written_in_interval;
  523. return 1;
  524. }
  525. return 0;
  526. }
  527. /** Invoked once per second. Checks whether it is time to hibernate,
  528. * record bandwidth used, etc. */
  529. void
  530. accounting_run_housekeeping(time_t now)
  531. {
  532. if (now >= interval_end_time) {
  533. configure_accounting(now);
  534. }
  535. if (time_to_record_bandwidth_usage(now)) {
  536. if (accounting_record_bandwidth_usage(now, get_or_state())) {
  537. log_warn(LD_FS, "Couldn't record bandwidth usage to disk.");
  538. }
  539. }
  540. }
  541. /** Based on our interval and our estimated bandwidth, choose a
  542. * deterministic (but random-ish) time to wake up. */
  543. static void
  544. accounting_set_wakeup_time(void)
  545. {
  546. char digest[DIGEST_LEN];
  547. crypto_digest_t *d_env;
  548. uint64_t time_to_exhaust_bw;
  549. int time_to_consider;
  550. if (! server_identity_key_is_set()) {
  551. if (init_keys() < 0) {
  552. log_err(LD_BUG, "Error initializing keys");
  553. tor_assert(0);
  554. }
  555. }
  556. if (server_identity_key_is_set()) {
  557. char buf[ISO_TIME_LEN+1];
  558. format_iso_time(buf, interval_start_time);
  559. if (crypto_pk_get_digest(get_server_identity_key(), digest) < 0) {
  560. log_err(LD_BUG, "Error getting our key's digest.");
  561. tor_assert(0);
  562. }
  563. d_env = crypto_digest_new();
  564. crypto_digest_add_bytes(d_env, buf, ISO_TIME_LEN);
  565. crypto_digest_add_bytes(d_env, digest, DIGEST_LEN);
  566. crypto_digest_get_digest(d_env, digest, DIGEST_LEN);
  567. crypto_digest_free(d_env);
  568. } else {
  569. crypto_rand(digest, DIGEST_LEN);
  570. }
  571. if (!expected_bandwidth_usage) {
  572. char buf1[ISO_TIME_LEN+1];
  573. char buf2[ISO_TIME_LEN+1];
  574. format_local_iso_time(buf1, interval_start_time);
  575. format_local_iso_time(buf2, interval_end_time);
  576. interval_wakeup_time = interval_start_time;
  577. log_notice(LD_ACCT,
  578. "Configured hibernation. This interval begins at %s "
  579. "and ends at %s. We have no prior estimate for bandwidth, so "
  580. "we will start out awake and hibernate when we exhaust our quota.",
  581. buf1, buf2);
  582. return;
  583. }
  584. time_to_exhaust_bw =
  585. (get_options()->AccountingMax/expected_bandwidth_usage)*60;
  586. if (time_to_exhaust_bw > INT_MAX) {
  587. time_to_exhaust_bw = INT_MAX;
  588. time_to_consider = 0;
  589. } else {
  590. time_to_consider = accounting_get_interval_length() -
  591. (int)time_to_exhaust_bw;
  592. }
  593. if (time_to_consider<=0) {
  594. interval_wakeup_time = interval_start_time;
  595. } else {
  596. /* XXX can we simplify this just by picking a random (non-deterministic)
  597. * time to be up? If we go down and come up, then we pick a new one. Is
  598. * that good enough? -RD */
  599. /* This is not a perfectly unbiased conversion, but it is good enough:
  600. * in the worst case, the first half of the day is 0.06 percent likelier
  601. * to be chosen than the last half. */
  602. interval_wakeup_time = interval_start_time +
  603. (get_uint32(digest) % time_to_consider);
  604. }
  605. {
  606. char buf1[ISO_TIME_LEN+1];
  607. char buf2[ISO_TIME_LEN+1];
  608. char buf3[ISO_TIME_LEN+1];
  609. char buf4[ISO_TIME_LEN+1];
  610. time_t down_time;
  611. if (interval_wakeup_time+time_to_exhaust_bw > TIME_MAX)
  612. down_time = TIME_MAX;
  613. else
  614. down_time = (time_t)(interval_wakeup_time+time_to_exhaust_bw);
  615. if (down_time>interval_end_time)
  616. down_time = interval_end_time;
  617. format_local_iso_time(buf1, interval_start_time);
  618. format_local_iso_time(buf2, interval_wakeup_time);
  619. format_local_iso_time(buf3, down_time);
  620. format_local_iso_time(buf4, interval_end_time);
  621. log_notice(LD_ACCT,
  622. "Configured hibernation. This interval began at %s; "
  623. "the scheduled wake-up time %s %s; "
  624. "we expect%s to exhaust our quota for this interval around %s; "
  625. "the next interval begins at %s (all times local)",
  626. buf1,
  627. time(NULL)<interval_wakeup_time?"is":"was", buf2,
  628. time(NULL)<down_time?"":"ed", buf3,
  629. buf4);
  630. }
  631. }
  632. /* This rounds 0 up to 1000, but that's actually a feature. */
  633. #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
  634. /** Save all our bandwidth tracking information to disk. Return 0 on
  635. * success, -1 on failure. */
  636. int
  637. accounting_record_bandwidth_usage(time_t now, or_state_t *state)
  638. {
  639. /* Just update the state */
  640. state->AccountingIntervalStart = interval_start_time;
  641. state->AccountingBytesReadInInterval = ROUND_UP(n_bytes_read_in_interval);
  642. state->AccountingBytesWrittenInInterval =
  643. ROUND_UP(n_bytes_written_in_interval);
  644. state->AccountingSecondsActive = n_seconds_active_in_interval;
  645. state->AccountingExpectedUsage = expected_bandwidth_usage;
  646. state->AccountingSecondsToReachSoftLimit = n_seconds_to_hit_soft_limit;
  647. state->AccountingSoftLimitHitAt = soft_limit_hit_at;
  648. state->AccountingBytesAtSoftLimit = n_bytes_at_soft_limit;
  649. or_state_mark_dirty(state,
  650. now+(get_options()->AvoidDiskWrites ? 7200 : 60));
  651. return 0;
  652. }
  653. #undef ROUND_UP
  654. /** Read stored accounting information from disk. Return 0 on success;
  655. * return -1 and change nothing on failure. */
  656. static int
  657. read_bandwidth_usage(void)
  658. {
  659. or_state_t *state = get_or_state();
  660. {
  661. char *fname = get_datadir_fname("bw_accounting");
  662. int res;
  663. res = unlink(fname);
  664. if (res != 0 && errno != ENOENT) {
  665. log_warn(LD_FS,
  666. "Failed to unlink %s: %s",
  667. fname, strerror(errno));
  668. }
  669. tor_free(fname);
  670. }
  671. if (!state)
  672. return -1;
  673. log_info(LD_ACCT, "Reading bandwidth accounting data from state file");
  674. n_bytes_read_in_interval = state->AccountingBytesReadInInterval;
  675. n_bytes_written_in_interval = state->AccountingBytesWrittenInInterval;
  676. n_seconds_active_in_interval = state->AccountingSecondsActive;
  677. interval_start_time = state->AccountingIntervalStart;
  678. expected_bandwidth_usage = state->AccountingExpectedUsage;
  679. /* Older versions of Tor (before 0.2.2.17-alpha or so) didn't generate these
  680. * fields. If you switch back and forth, you might get an
  681. * AccountingSoftLimitHitAt value from long before the most recent
  682. * interval_start_time. If that's so, then ignore the softlimit-related
  683. * values. */
  684. if (state->AccountingSoftLimitHitAt > interval_start_time) {
  685. soft_limit_hit_at = state->AccountingSoftLimitHitAt;
  686. n_bytes_at_soft_limit = state->AccountingBytesAtSoftLimit;
  687. n_seconds_to_hit_soft_limit = state->AccountingSecondsToReachSoftLimit;
  688. } else {
  689. soft_limit_hit_at = 0;
  690. n_bytes_at_soft_limit = 0;
  691. n_seconds_to_hit_soft_limit = 0;
  692. }
  693. {
  694. char tbuf1[ISO_TIME_LEN+1];
  695. char tbuf2[ISO_TIME_LEN+1];
  696. format_iso_time(tbuf1, state->LastWritten);
  697. format_iso_time(tbuf2, state->AccountingIntervalStart);
  698. log_info(LD_ACCT,
  699. "Successfully read bandwidth accounting info from state written at %s "
  700. "for interval starting at %s. We have been active for %lu seconds in "
  701. "this interval. At the start of the interval, we expected to use "
  702. "about %lu KB per second. (%"PRIu64" bytes read so far, "
  703. "%"PRIu64" bytes written so far)",
  704. tbuf1, tbuf2,
  705. (unsigned long)n_seconds_active_in_interval,
  706. (unsigned long)(expected_bandwidth_usage*1024/60),
  707. (n_bytes_read_in_interval),
  708. (n_bytes_written_in_interval));
  709. }
  710. return 0;
  711. }
  712. /** Return true iff we have sent/received all the bytes we are willing
  713. * to send/receive this interval. */
  714. static int
  715. hibernate_hard_limit_reached(void)
  716. {
  717. uint64_t hard_limit = get_options()->AccountingMax;
  718. if (!hard_limit)
  719. return 0;
  720. return get_accounting_bytes() >= hard_limit;
  721. }
  722. /** Return true iff we have sent/received almost all the bytes we are willing
  723. * to send/receive this interval. */
  724. static int
  725. hibernate_soft_limit_reached(void)
  726. {
  727. const uint64_t acct_max = get_options()->AccountingMax;
  728. #define SOFT_LIM_PCT (.95)
  729. #define SOFT_LIM_BYTES (500*1024*1024)
  730. #define SOFT_LIM_MINUTES (3*60)
  731. /* The 'soft limit' is a fair bit more complicated now than once it was.
  732. * We want to stop accepting connections when ALL of the following are true:
  733. * - We expect to use up the remaining bytes in under 3 hours
  734. * - We have used up 95% of our bytes.
  735. * - We have less than 500MB of bytes left.
  736. */
  737. uint64_t soft_limit = (uint64_t) (acct_max * SOFT_LIM_PCT);
  738. if (acct_max > SOFT_LIM_BYTES && acct_max - SOFT_LIM_BYTES > soft_limit) {
  739. soft_limit = acct_max - SOFT_LIM_BYTES;
  740. }
  741. if (expected_bandwidth_usage) {
  742. const uint64_t expected_usage =
  743. expected_bandwidth_usage * SOFT_LIM_MINUTES;
  744. if (acct_max > expected_usage && acct_max - expected_usage > soft_limit)
  745. soft_limit = acct_max - expected_usage;
  746. }
  747. if (!soft_limit)
  748. return 0;
  749. return get_accounting_bytes() >= soft_limit;
  750. }
  751. /** Called when we get a SIGINT, or when bandwidth soft limit is
  752. * reached. Puts us into "loose hibernation": we don't accept new
  753. * connections, but we continue handling old ones. */
  754. static void
  755. hibernate_begin(hibernate_state_t new_state, time_t now)
  756. {
  757. const or_options_t *options = get_options();
  758. if (new_state == HIBERNATE_STATE_EXITING &&
  759. hibernate_state != HIBERNATE_STATE_LIVE) {
  760. log_notice(LD_GENERAL,"SIGINT received %s; exiting now.",
  761. hibernate_state == HIBERNATE_STATE_EXITING ?
  762. "a second time" : "while hibernating");
  763. tor_shutdown_event_loop_and_exit(0);
  764. return;
  765. }
  766. if (new_state == HIBERNATE_STATE_LOWBANDWIDTH &&
  767. hibernate_state == HIBERNATE_STATE_LIVE) {
  768. soft_limit_hit_at = now;
  769. n_seconds_to_hit_soft_limit = n_seconds_active_in_interval;
  770. n_bytes_at_soft_limit = get_accounting_bytes();
  771. }
  772. /* close listeners. leave control listener(s). */
  773. connection_mark_all_noncontrol_listeners();
  774. /* XXX kill intro point circs */
  775. /* XXX upload rendezvous service descriptors with no intro points */
  776. if (new_state == HIBERNATE_STATE_EXITING) {
  777. log_notice(LD_GENERAL,"Interrupt: we have stopped accepting new "
  778. "connections, and will shut down in %d seconds. Interrupt "
  779. "again to exit now.", options->ShutdownWaitLength);
  780. shutdown_time = time(NULL) + options->ShutdownWaitLength;
  781. } else { /* soft limit reached */
  782. hibernate_end_time = interval_end_time;
  783. }
  784. hibernate_state = new_state;
  785. accounting_record_bandwidth_usage(now, get_or_state());
  786. or_state_mark_dirty(get_or_state(),
  787. get_options()->AvoidDiskWrites ? now+600 : 0);
  788. }
  789. /** Called when we've been hibernating and our timeout is reached. */
  790. static void
  791. hibernate_end(hibernate_state_t new_state)
  792. {
  793. tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
  794. hibernate_state == HIBERNATE_STATE_DORMANT ||
  795. hibernate_state == HIBERNATE_STATE_INITIAL);
  796. /* listeners will be relaunched in run_scheduled_events() in main.c */
  797. if (hibernate_state != HIBERNATE_STATE_INITIAL)
  798. log_notice(LD_ACCT,"Hibernation period ended. Resuming normal activity.");
  799. hibernate_state = new_state;
  800. hibernate_end_time = 0; /* no longer hibernating */
  801. reset_uptime(); /* reset published uptime */
  802. }
  803. /** A wrapper around hibernate_begin, for when we get SIGINT. */
  804. void
  805. hibernate_begin_shutdown(void)
  806. {
  807. hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
  808. }
  809. /**
  810. * Return true iff we are currently hibernating -- that is, if we are in
  811. * any non-live state.
  812. */
  813. MOCK_IMPL(int,
  814. we_are_hibernating,(void))
  815. {
  816. return hibernate_state != HIBERNATE_STATE_LIVE;
  817. }
  818. /**
  819. * Return true iff we are currently _fully_ hibernating -- that is, if we are
  820. * in a state where we expect to handle no network activity at all.
  821. */
  822. MOCK_IMPL(int,
  823. we_are_fully_hibernating,(void))
  824. {
  825. return hibernate_state == HIBERNATE_STATE_DORMANT;
  826. }
  827. /** If we aren't currently dormant, close all connections and become
  828. * dormant. */
  829. static void
  830. hibernate_go_dormant(time_t now)
  831. {
  832. connection_t *conn;
  833. if (hibernate_state == HIBERNATE_STATE_DORMANT)
  834. return;
  835. else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
  836. hibernate_state = HIBERNATE_STATE_DORMANT;
  837. else
  838. hibernate_begin(HIBERNATE_STATE_DORMANT, now);
  839. log_notice(LD_ACCT,"Going dormant. Blowing away remaining connections.");
  840. /* Close all OR/AP/exit conns. Leave dir conns because we still want
  841. * to be able to upload server descriptors so clients know we're still
  842. * running, and download directories so we can detect if we're obsolete.
  843. * Leave control conns because we still want to be controllable.
  844. */
  845. while ((conn = connection_get_by_type(CONN_TYPE_OR)) ||
  846. (conn = connection_get_by_type(CONN_TYPE_AP)) ||
  847. (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
  848. if (CONN_IS_EDGE(conn)) {
  849. connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_HIBERNATING);
  850. }
  851. log_info(LD_NET,"Closing conn type %d", conn->type);
  852. if (conn->type == CONN_TYPE_AP) {
  853. /* send socks failure if needed */
  854. connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
  855. END_STREAM_REASON_HIBERNATING);
  856. } else if (conn->type == CONN_TYPE_OR) {
  857. if (TO_OR_CONN(conn)->chan) {
  858. connection_or_close_normally(TO_OR_CONN(conn), 0);
  859. } else {
  860. connection_mark_for_close(conn);
  861. }
  862. } else {
  863. connection_mark_for_close(conn);
  864. }
  865. }
  866. if (now < interval_wakeup_time)
  867. hibernate_end_time = interval_wakeup_time;
  868. else
  869. hibernate_end_time = interval_end_time;
  870. accounting_record_bandwidth_usage(now, get_or_state());
  871. or_state_mark_dirty(get_or_state(),
  872. get_options()->AvoidDiskWrites ? now+600 : 0);
  873. hibernate_schedule_wakeup_event(now, hibernate_end_time);
  874. }
  875. /**
  876. * Schedule a mainloop event at <b>end_time</b> to wake up from a dormant
  877. * state. We can't rely on this happening from second_elapsed_callback,
  878. * since second_elapsed_callback will be shut down when we're dormant.
  879. *
  880. * (Note that We might immediately go back to sleep after we set the next
  881. * wakeup time.)
  882. */
  883. static void
  884. hibernate_schedule_wakeup_event(time_t now, time_t end_time)
  885. {
  886. struct timeval delay = { 0, 0 };
  887. if (now >= end_time) {
  888. // In these cases we always wait at least a second, to avoid running
  889. // the callback in a tight loop.
  890. delay.tv_sec = 1;
  891. } else {
  892. delay.tv_sec = (end_time - now);
  893. }
  894. if (!wakeup_event) {
  895. wakeup_event = mainloop_event_postloop_new(wakeup_event_callback, NULL);
  896. }
  897. mainloop_event_schedule(wakeup_event, &delay);
  898. }
  899. /**
  900. * Called at the end of the interval, or at the wakeup time of the current
  901. * interval, to exit the dormant state.
  902. **/
  903. static void
  904. wakeup_event_callback(mainloop_event_t *ev, void *data)
  905. {
  906. (void) ev;
  907. (void) data;
  908. const time_t now = time(NULL);
  909. accounting_run_housekeeping(now);
  910. consider_hibernation(now);
  911. if (hibernate_state != HIBERNATE_STATE_DORMANT) {
  912. /* We woke up, so everything's great here */
  913. return;
  914. }
  915. /* We're still dormant. */
  916. if (now < interval_wakeup_time)
  917. hibernate_end_time = interval_wakeup_time;
  918. else
  919. hibernate_end_time = interval_end_time;
  920. hibernate_schedule_wakeup_event(now, hibernate_end_time);
  921. }
  922. /** Called when hibernate_end_time has arrived. */
  923. static void
  924. hibernate_end_time_elapsed(time_t now)
  925. {
  926. char buf[ISO_TIME_LEN+1];
  927. /* The interval has ended, or it is wakeup time. Find out which. */
  928. accounting_run_housekeeping(now);
  929. if (interval_wakeup_time <= now) {
  930. /* The interval hasn't changed, but interval_wakeup_time has passed.
  931. * It's time to wake up and start being a server. */
  932. hibernate_end(HIBERNATE_STATE_LIVE);
  933. return;
  934. } else {
  935. /* The interval has changed, and it isn't time to wake up yet. */
  936. hibernate_end_time = interval_wakeup_time;
  937. format_iso_time(buf,interval_wakeup_time);
  938. if (hibernate_state != HIBERNATE_STATE_DORMANT) {
  939. /* We weren't sleeping before; we should sleep now. */
  940. log_notice(LD_ACCT,
  941. "Accounting period ended. Commencing hibernation until "
  942. "%s UTC", buf);
  943. hibernate_go_dormant(now);
  944. } else {
  945. log_notice(LD_ACCT,
  946. "Accounting period ended. This period, we will hibernate"
  947. " until %s UTC",buf);
  948. }
  949. }
  950. }
  951. /** Consider our environment and decide if it's time
  952. * to start/stop hibernating.
  953. */
  954. void
  955. consider_hibernation(time_t now)
  956. {
  957. int accounting_enabled = get_options()->AccountingMax != 0;
  958. char buf[ISO_TIME_LEN+1];
  959. hibernate_state_t prev_state = hibernate_state;
  960. /* If we're in 'exiting' mode, then we just shut down after the interval
  961. * elapses. */
  962. if (hibernate_state == HIBERNATE_STATE_EXITING) {
  963. tor_assert(shutdown_time);
  964. if (shutdown_time <= now) {
  965. log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
  966. tor_shutdown_event_loop_and_exit(0);
  967. }
  968. return; /* if exiting soon, don't worry about bandwidth limits */
  969. }
  970. if (hibernate_state == HIBERNATE_STATE_DORMANT) {
  971. /* We've been hibernating because of bandwidth accounting. */
  972. tor_assert(hibernate_end_time);
  973. if (hibernate_end_time > now && accounting_enabled) {
  974. /* If we're hibernating, don't wake up until it's time, regardless of
  975. * whether we're in a new interval. */
  976. return ;
  977. } else {
  978. hibernate_end_time_elapsed(now);
  979. }
  980. }
  981. /* Else, we aren't hibernating. See if it's time to start hibernating, or to
  982. * go dormant. */
  983. if (hibernate_state == HIBERNATE_STATE_LIVE ||
  984. hibernate_state == HIBERNATE_STATE_INITIAL) {
  985. if (hibernate_soft_limit_reached()) {
  986. log_notice(LD_ACCT,
  987. "Bandwidth soft limit reached; commencing hibernation. "
  988. "No new connections will be accepted");
  989. hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
  990. } else if (accounting_enabled && now < interval_wakeup_time) {
  991. format_local_iso_time(buf,interval_wakeup_time);
  992. log_notice(LD_ACCT,
  993. "Commencing hibernation. We will wake up at %s local time.",
  994. buf);
  995. hibernate_go_dormant(now);
  996. } else if (hibernate_state == HIBERNATE_STATE_INITIAL) {
  997. hibernate_end(HIBERNATE_STATE_LIVE);
  998. }
  999. }
  1000. if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
  1001. if (!accounting_enabled) {
  1002. hibernate_end_time_elapsed(now);
  1003. } else if (hibernate_hard_limit_reached()) {
  1004. hibernate_go_dormant(now);
  1005. } else if (hibernate_end_time <= now) {
  1006. /* The hibernation period ended while we were still in lowbandwidth.*/
  1007. hibernate_end_time_elapsed(now);
  1008. }
  1009. }
  1010. /* Dispatch a controller event if the hibernation state changed. */
  1011. if (hibernate_state != prev_state)
  1012. on_hibernate_state_change(prev_state);
  1013. }
  1014. /** Helper function: called when we get a GETINFO request for an
  1015. * accounting-related key on the control connection <b>conn</b>. If we can
  1016. * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
  1017. * allocated string holding the result. Otherwise, set *<b>answer</b> to
  1018. * NULL. */
  1019. int
  1020. getinfo_helper_accounting(control_connection_t *conn,
  1021. const char *question, char **answer,
  1022. const char **errmsg)
  1023. {
  1024. (void) conn;
  1025. (void) errmsg;
  1026. if (!strcmp(question, "accounting/enabled")) {
  1027. *answer = tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
  1028. } else if (!strcmp(question, "accounting/hibernating")) {
  1029. *answer = tor_strdup(hibernate_state_to_string(hibernate_state));
  1030. tor_strlower(*answer);
  1031. } else if (!strcmp(question, "accounting/bytes")) {
  1032. tor_asprintf(answer, "%"PRIu64" %"PRIu64,
  1033. (n_bytes_read_in_interval),
  1034. (n_bytes_written_in_interval));
  1035. } else if (!strcmp(question, "accounting/bytes-left")) {
  1036. uint64_t limit = get_options()->AccountingMax;
  1037. if (get_options()->AccountingRule == ACCT_SUM) {
  1038. uint64_t total_left = 0;
  1039. uint64_t total_bytes = get_accounting_bytes();
  1040. if (total_bytes < limit)
  1041. total_left = limit - total_bytes;
  1042. tor_asprintf(answer, "%"PRIu64" %"PRIu64,
  1043. (total_left), (total_left));
  1044. } else if (get_options()->AccountingRule == ACCT_IN) {
  1045. uint64_t read_left = 0;
  1046. if (n_bytes_read_in_interval < limit)
  1047. read_left = limit - n_bytes_read_in_interval;
  1048. tor_asprintf(answer, "%"PRIu64" %"PRIu64,
  1049. (read_left), (limit));
  1050. } else if (get_options()->AccountingRule == ACCT_OUT) {
  1051. uint64_t write_left = 0;
  1052. if (n_bytes_written_in_interval < limit)
  1053. write_left = limit - n_bytes_written_in_interval;
  1054. tor_asprintf(answer, "%"PRIu64" %"PRIu64,
  1055. (limit), (write_left));
  1056. } else {
  1057. uint64_t read_left = 0, write_left = 0;
  1058. if (n_bytes_read_in_interval < limit)
  1059. read_left = limit - n_bytes_read_in_interval;
  1060. if (n_bytes_written_in_interval < limit)
  1061. write_left = limit - n_bytes_written_in_interval;
  1062. tor_asprintf(answer, "%"PRIu64" %"PRIu64,
  1063. (read_left), (write_left));
  1064. }
  1065. } else if (!strcmp(question, "accounting/interval-start")) {
  1066. *answer = tor_malloc(ISO_TIME_LEN+1);
  1067. format_iso_time(*answer, interval_start_time);
  1068. } else if (!strcmp(question, "accounting/interval-wake")) {
  1069. *answer = tor_malloc(ISO_TIME_LEN+1);
  1070. format_iso_time(*answer, interval_wakeup_time);
  1071. } else if (!strcmp(question, "accounting/interval-end")) {
  1072. *answer = tor_malloc(ISO_TIME_LEN+1);
  1073. format_iso_time(*answer, interval_end_time);
  1074. } else {
  1075. *answer = NULL;
  1076. }
  1077. return 0;
  1078. }
  1079. /**
  1080. * Helper function: called when the hibernation state changes, and sends a
  1081. * SERVER_STATUS event to notify interested controllers of the accounting
  1082. * state change.
  1083. */
  1084. static void
  1085. on_hibernate_state_change(hibernate_state_t prev_state)
  1086. {
  1087. control_event_server_status(LOG_NOTICE,
  1088. "HIBERNATION_STATUS STATUS=%s",
  1089. hibernate_state_to_string(hibernate_state));
  1090. /* We are changing hibernation state, this can affect the main loop event
  1091. * list. Rescan it to update the events state. We do this whatever the new
  1092. * hibernation state because they can each possibly affect an event. The
  1093. * initial state means we are booting up so we shouldn't scan here because
  1094. * at this point the events in the list haven't been initialized. */
  1095. if (prev_state != HIBERNATE_STATE_INITIAL) {
  1096. rescan_periodic_events(get_options());
  1097. }
  1098. reschedule_per_second_timer();
  1099. }
  1100. /** Free all resources held by the accounting module */
  1101. void
  1102. accounting_free_all(void)
  1103. {
  1104. mainloop_event_free(wakeup_event);
  1105. hibernate_state = HIBERNATE_STATE_INITIAL;
  1106. hibernate_end_time = 0;
  1107. shutdown_time = 0;
  1108. }
  1109. #ifdef TOR_UNIT_TESTS
  1110. /**
  1111. * Manually change the hibernation state. Private; used only by the unit
  1112. * tests.
  1113. */
  1114. void
  1115. hibernate_set_state_for_testing_(hibernate_state_t newstate)
  1116. {
  1117. hibernate_state = newstate;
  1118. }
  1119. #endif /* defined(TOR_UNIT_TESTS) */