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