hibernate.c 39 KB

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