hibernate.c 43 KB

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