hibernate.c 37 KB

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