hibernate.c 41 KB

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