hibernate.c 41 KB

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