hibernate.c 41 KB

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