rephist.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. /* Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char rephist_c_id[] =
  5. "$Id$";
  6. /**
  7. * \file rephist.c
  8. * \brief Basic history and "reputation" functionality to remember
  9. * which servers have worked in the past, how much bandwidth we've
  10. * been using, which ports we tend to want, and so on.
  11. **/
  12. #include "or.h"
  13. static void bw_arrays_init(void);
  14. static void predicted_ports_init(void);
  15. uint64_t rephist_total_alloc=0;
  16. uint32_t rephist_total_num=0;
  17. /** History of an OR-\>OR link. */
  18. typedef struct link_history_t {
  19. /** When did we start tracking this list? */
  20. time_t since;
  21. /** When did we most recently note a change to this link */
  22. time_t changed;
  23. /** How many times did extending from OR1 to OR2 succeed? */
  24. unsigned long n_extend_ok;
  25. /** How many times did extending from OR1 to OR2 fail? */
  26. unsigned long n_extend_fail;
  27. } link_history_t;
  28. /** History of an OR. */
  29. typedef struct or_history_t {
  30. /** When did we start tracking this OR? */
  31. time_t since;
  32. /** When did we most recently note a change to this OR? */
  33. time_t changed;
  34. /** How many times did we successfully connect? */
  35. unsigned long n_conn_ok;
  36. /** How many times did we try to connect and fail?*/
  37. unsigned long n_conn_fail;
  38. /** How many seconds have we been connected to this OR before
  39. * 'up_since'? */
  40. unsigned long uptime;
  41. /** How many seconds have we been unable to connect to this OR before
  42. * 'down_since'? */
  43. unsigned long downtime;
  44. /** If nonzero, we have been connected since this time. */
  45. time_t up_since;
  46. /** If nonzero, we have been unable to connect since this time. */
  47. time_t down_since;
  48. /** Map from hex OR2 identity digest to a link_history_t for the link
  49. * from this OR to OR2. */
  50. digestmap_t *link_history_map;
  51. } or_history_t;
  52. /** Map from hex OR identity digest to or_history_t. */
  53. static digestmap_t *history_map = NULL;
  54. /** Return the or_history_t for the named OR, creating it if necessary.
  55. */
  56. static or_history_t *
  57. get_or_history(const char* id)
  58. {
  59. or_history_t *hist;
  60. if (!memcmp(id, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", DIGEST_LEN))
  61. return NULL;
  62. hist = digestmap_get(history_map, id);
  63. if (!hist) {
  64. hist = tor_malloc_zero(sizeof(or_history_t));
  65. rephist_total_alloc += sizeof(or_history_t);
  66. rephist_total_num++;
  67. hist->link_history_map = digestmap_new();
  68. hist->since = hist->changed = time(NULL);
  69. digestmap_set(history_map, id, hist);
  70. }
  71. return hist;
  72. }
  73. /** Return the link_history_t for the link from the first named OR to
  74. * the second, creating it if necessary. (ORs are identified by
  75. * identity digest)
  76. */
  77. static link_history_t *
  78. get_link_history(const char *from_id, const char *to_id)
  79. {
  80. or_history_t *orhist;
  81. link_history_t *lhist;
  82. orhist = get_or_history(from_id);
  83. if (!orhist)
  84. return NULL;
  85. if (!memcmp(to_id, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", DIGEST_LEN))
  86. return NULL;
  87. lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
  88. if (!lhist) {
  89. lhist = tor_malloc_zero(sizeof(link_history_t));
  90. rephist_total_alloc += sizeof(link_history_t);
  91. lhist->since = lhist->changed = time(NULL);
  92. digestmap_set(orhist->link_history_map, to_id, lhist);
  93. }
  94. return lhist;
  95. }
  96. /** Helper: free storage held by a single link history entry */
  97. static void
  98. _free_link_history(void *val)
  99. {
  100. rephist_total_alloc -= sizeof(link_history_t);
  101. tor_free(val);
  102. }
  103. /** Helper: free storage held by a single OR history entry */
  104. static void
  105. free_or_history(void *_hist)
  106. {
  107. or_history_t *hist = _hist;
  108. digestmap_free(hist->link_history_map, _free_link_history);
  109. rephist_total_alloc -= sizeof(or_history_t);
  110. rephist_total_num--;
  111. tor_free(hist);
  112. }
  113. /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
  114. * count is up-to-date as of <b>when</b>.
  115. */
  116. static void
  117. update_or_history(or_history_t *hist, time_t when)
  118. {
  119. tor_assert(hist);
  120. if (hist->up_since) {
  121. tor_assert(!hist->down_since);
  122. hist->uptime += (when - hist->up_since);
  123. hist->up_since = when;
  124. } else if (hist->down_since) {
  125. hist->downtime += (when - hist->down_since);
  126. hist->down_since = when;
  127. }
  128. }
  129. /** Initialize the static data structures for tracking history.
  130. */
  131. void
  132. rep_hist_init(void)
  133. {
  134. history_map = digestmap_new();
  135. bw_arrays_init();
  136. predicted_ports_init();
  137. }
  138. /** Remember that an attempt to connect to the OR with identity digest
  139. * <b>id</b> failed at <b>when</b>.
  140. */
  141. void
  142. rep_hist_note_connect_failed(const char* id, time_t when)
  143. {
  144. or_history_t *hist;
  145. hist = get_or_history(id);
  146. if (!hist)
  147. return;
  148. ++hist->n_conn_fail;
  149. if (hist->up_since) {
  150. hist->uptime += (when - hist->up_since);
  151. hist->up_since = 0;
  152. }
  153. if (!hist->down_since)
  154. hist->down_since = when;
  155. hist->changed = when;
  156. }
  157. /** Remember that an attempt to connect to the OR with identity digest
  158. * <b>id</b> succeeded at <b>when</b>.
  159. */
  160. void
  161. rep_hist_note_connect_succeeded(const char* id, time_t when)
  162. {
  163. or_history_t *hist;
  164. hist = get_or_history(id);
  165. if (!hist)
  166. return;
  167. ++hist->n_conn_ok;
  168. if (hist->down_since) {
  169. hist->downtime += (when - hist->down_since);
  170. hist->down_since = 0;
  171. }
  172. if (!hist->up_since)
  173. hist->up_since = when;
  174. hist->changed = when;
  175. }
  176. /** Remember that we intentionally closed our connection to the OR
  177. * with identity digest <b>id</b> at <b>when</b>.
  178. */
  179. void
  180. rep_hist_note_disconnect(const char* id, time_t when)
  181. {
  182. or_history_t *hist;
  183. hist = get_or_history(id);
  184. if (!hist)
  185. return;
  186. ++hist->n_conn_ok;
  187. if (hist->up_since) {
  188. hist->uptime += (when - hist->up_since);
  189. hist->up_since = 0;
  190. }
  191. hist->changed = when;
  192. }
  193. /** Remember that our connection to the OR with identity digest
  194. * <b>id</b> had an error and stopped working at <b>when</b>.
  195. */
  196. void
  197. rep_hist_note_connection_died(const char* id, time_t when)
  198. {
  199. or_history_t *hist;
  200. if (!id) {
  201. /* If conn has no nickname, it didn't complete its handshake, or something
  202. * went wrong. Ignore it.
  203. */
  204. return;
  205. }
  206. hist = get_or_history(id);
  207. if (!hist)
  208. return;
  209. if (hist->up_since) {
  210. hist->uptime += (when - hist->up_since);
  211. hist->up_since = 0;
  212. }
  213. if (!hist->down_since)
  214. hist->down_since = when;
  215. hist->changed = when;
  216. }
  217. /** Remember that we successfully extended from the OR with identity
  218. * digest <b>from_id</b> to the OR with identity digest
  219. * <b>to_name</b>.
  220. */
  221. void
  222. rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
  223. {
  224. link_history_t *hist;
  225. /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
  226. hist = get_link_history(from_id, to_id);
  227. if (!hist)
  228. return;
  229. ++hist->n_extend_ok;
  230. hist->changed = time(NULL);
  231. }
  232. /** Remember that we tried to extend from the OR with identity digest
  233. * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
  234. * failed.
  235. */
  236. void
  237. rep_hist_note_extend_failed(const char *from_id, const char *to_id)
  238. {
  239. link_history_t *hist;
  240. /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
  241. hist = get_link_history(from_id, to_id);
  242. if (!hist)
  243. return;
  244. ++hist->n_extend_fail;
  245. hist->changed = time(NULL);
  246. }
  247. /** Log all the reliability data we have remembered, with the chosen
  248. * severity.
  249. */
  250. void
  251. rep_hist_dump_stats(time_t now, int severity)
  252. {
  253. digestmap_iter_t *lhist_it;
  254. digestmap_iter_t *orhist_it;
  255. const char *name1, *name2, *digest1, *digest2;
  256. char hexdigest1[HEX_DIGEST_LEN+1];
  257. or_history_t *or_history;
  258. link_history_t *link_history;
  259. void *or_history_p, *link_history_p;
  260. double uptime;
  261. char buffer[2048];
  262. size_t len;
  263. int ret;
  264. unsigned long upt, downt;
  265. routerinfo_t *r;
  266. rep_history_clean(now - get_options()->RephistTrackTime);
  267. log(severity, LD_GENERAL, "--------------- Dumping history information:");
  268. for (orhist_it = digestmap_iter_init(history_map);
  269. !digestmap_iter_done(orhist_it);
  270. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  271. digestmap_iter_get(orhist_it, &digest1, &or_history_p);
  272. or_history = (or_history_t*) or_history_p;
  273. if ((r = router_get_by_digest(digest1)))
  274. name1 = r->nickname;
  275. else
  276. name1 = "(unknown)";
  277. base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
  278. update_or_history(or_history, now);
  279. upt = or_history->uptime;
  280. downt = or_history->downtime;
  281. if (upt+downt) {
  282. uptime = ((double)upt) / (upt+downt);
  283. } else {
  284. uptime=1.0;
  285. }
  286. log(severity, LD_GENERAL,
  287. "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%)",
  288. name1, hexdigest1,
  289. or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
  290. upt, upt+downt, uptime*100.0);
  291. if (!digestmap_isempty(or_history->link_history_map)) {
  292. strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
  293. len = strlen(buffer);
  294. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  295. !digestmap_iter_done(lhist_it);
  296. lhist_it = digestmap_iter_next(or_history->link_history_map,
  297. lhist_it)) {
  298. digestmap_iter_get(lhist_it, &digest2, &link_history_p);
  299. if ((r = router_get_by_digest(digest2)))
  300. name2 = r->nickname;
  301. else
  302. name2 = "(unknown)";
  303. link_history = (link_history_t*) link_history_p;
  304. ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
  305. link_history->n_extend_ok,
  306. link_history->n_extend_ok+link_history->n_extend_fail);
  307. if (ret<0)
  308. break;
  309. else
  310. len += ret;
  311. }
  312. log(severity, LD_GENERAL, "%s", buffer);
  313. }
  314. }
  315. }
  316. /** Remove history info for routers/links that haven't changed since
  317. * <b>before</b> */
  318. void
  319. rep_history_clean(time_t before)
  320. {
  321. or_history_t *or_history;
  322. link_history_t *link_history;
  323. void *or_history_p, *link_history_p;
  324. digestmap_iter_t *orhist_it, *lhist_it;
  325. const char *d1, *d2;
  326. orhist_it = digestmap_iter_init(history_map);
  327. while (!digestmap_iter_done(orhist_it)) {
  328. digestmap_iter_get(orhist_it, &d1, &or_history_p);
  329. or_history = or_history_p;
  330. if (or_history->changed < before) {
  331. orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
  332. free_or_history(or_history);
  333. continue;
  334. }
  335. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  336. !digestmap_iter_done(lhist_it); ) {
  337. digestmap_iter_get(lhist_it, &d2, &link_history_p);
  338. link_history = link_history_p;
  339. if (link_history->changed < before) {
  340. lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
  341. lhist_it);
  342. rephist_total_alloc -= sizeof(link_history_t);
  343. tor_free(link_history);
  344. continue;
  345. }
  346. lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
  347. }
  348. orhist_it = digestmap_iter_next(history_map, orhist_it);
  349. }
  350. }
  351. /** For how many seconds do we keep track of individual per-second bandwidth
  352. * totals? */
  353. #define NUM_SECS_ROLLING_MEASURE 10
  354. /** How large are the intervals for with we track and report bandwidth use? */
  355. #define NUM_SECS_BW_SUM_INTERVAL (15*60)
  356. /** How far in the past do we remember and publish bandwidth use? */
  357. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
  358. /** How many bandwidth usage intervals do we remember? (derived.) */
  359. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  360. /**
  361. * Structure to track bandwidth use, and remember the maxima for a given
  362. * time period.
  363. */
  364. typedef struct bw_array_t {
  365. /** Observation array: Total number of bytes transferred in each of the last
  366. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  367. uint64_t obs[NUM_SECS_ROLLING_MEASURE];
  368. int cur_obs_idx; /**< Current position in obs. */
  369. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  370. uint64_t total_obs; /**< Total for all members of obs except
  371. * obs[cur_obs_idx] */
  372. uint64_t max_total; /**< Largest value that total_obs has taken on in the
  373. * current period. */
  374. uint64_t total_in_period; /**< Total bytes transferred in the current
  375. * period. */
  376. /** When does the next period begin? */
  377. time_t next_period;
  378. /** Where in 'maxima' should the maximum bandwidth usage for the current
  379. * period be stored? */
  380. int next_max_idx;
  381. /** How many values in maxima/totals have been set ever? */
  382. int num_maxes_set;
  383. /** Circular array of the maximum
  384. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  385. * NUM_TOTALS periods */
  386. uint64_t maxima[NUM_TOTALS];
  387. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  388. * periods */
  389. uint64_t totals[NUM_TOTALS];
  390. } bw_array_t;
  391. /** Shift the current period of b forward by one.
  392. */
  393. static void
  394. commit_max(bw_array_t *b)
  395. {
  396. /* Store total from current period. */
  397. b->totals[b->next_max_idx] = b->total_in_period;
  398. /* Store maximum from current period. */
  399. b->maxima[b->next_max_idx++] = b->max_total;
  400. /* Advance next_period and next_max_idx */
  401. b->next_period += NUM_SECS_BW_SUM_INTERVAL;
  402. if (b->next_max_idx == NUM_TOTALS)
  403. b->next_max_idx = 0;
  404. if (b->num_maxes_set < NUM_TOTALS)
  405. ++b->num_maxes_set;
  406. /* Reset max_total. */
  407. b->max_total = 0;
  408. /* Reset total_in_period. */
  409. b->total_in_period = 0;
  410. }
  411. /** Shift the current observation time of 'b' forward by one second.
  412. */
  413. static INLINE void
  414. advance_obs(bw_array_t *b)
  415. {
  416. int nextidx;
  417. uint64_t total;
  418. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  419. * seconds; adjust max_total as needed.*/
  420. total = b->total_obs + b->obs[b->cur_obs_idx];
  421. if (total > b->max_total)
  422. b->max_total = total;
  423. nextidx = b->cur_obs_idx+1;
  424. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  425. nextidx = 0;
  426. b->total_obs = total - b->obs[nextidx];
  427. b->obs[nextidx]=0;
  428. b->cur_obs_idx = nextidx;
  429. if (++b->cur_obs_time >= b->next_period)
  430. commit_max(b);
  431. }
  432. /** Add 'n' bytes to the number of bytes in b for second 'when'.
  433. */
  434. static INLINE void
  435. add_obs(bw_array_t *b, time_t when, uint64_t n)
  436. {
  437. /* Don't record data in the past. */
  438. if (when<b->cur_obs_time)
  439. return;
  440. /* If we're currently adding observations for an earlier second than
  441. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  442. * appropriate number of seconds, and do all the other housekeeping */
  443. while (when>b->cur_obs_time)
  444. advance_obs(b);
  445. b->obs[b->cur_obs_idx] += n;
  446. b->total_in_period += n;
  447. }
  448. /** Allocate, initialize, and return a new bw_array.
  449. */
  450. static bw_array_t *
  451. bw_array_new(void)
  452. {
  453. bw_array_t *b;
  454. time_t start;
  455. b = tor_malloc_zero(sizeof(bw_array_t));
  456. rephist_total_alloc += sizeof(bw_array_t);
  457. start = time(NULL);
  458. b->cur_obs_time = start;
  459. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  460. return b;
  461. }
  462. static bw_array_t *read_array = NULL;
  463. static bw_array_t *write_array = NULL;
  464. /** Set up read_array and write_array
  465. */
  466. static void
  467. bw_arrays_init(void)
  468. {
  469. read_array = bw_array_new();
  470. write_array = bw_array_new();
  471. }
  472. /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
  473. *
  474. * Add num_bytes to the current running total for <b>when</b>.
  475. *
  476. * <b>when</b> can go back to time, but it's safe to ignore calls
  477. * earlier than the latest <b>when</b> you've heard of.
  478. */
  479. void
  480. rep_hist_note_bytes_written(int num_bytes, time_t when)
  481. {
  482. /* Maybe a circular array for recent seconds, and step to a new point
  483. * every time a new second shows up. Or simpler is to just to have
  484. * a normal array and push down each item every second; it's short.
  485. */
  486. /* When a new second has rolled over, compute the sum of the bytes we've
  487. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  488. * somewhere. See rep_hist_bandwidth_assess() below.
  489. */
  490. add_obs(write_array, when, num_bytes);
  491. }
  492. /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
  493. * (like rep_hist_note_bytes_written() above)
  494. */
  495. void
  496. rep_hist_note_bytes_read(int num_bytes, time_t when)
  497. {
  498. /* if we're smart, we can make this func and the one above share code */
  499. add_obs(read_array, when, num_bytes);
  500. }
  501. /** Helper: Return the largest value in b->maxima. (This is equal to the
  502. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  503. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  504. */
  505. static uint64_t
  506. find_largest_max(bw_array_t *b)
  507. {
  508. int i;
  509. uint64_t max;
  510. max=0;
  511. for (i=0; i<NUM_TOTALS; ++i) {
  512. if (b->maxima[i]>max)
  513. max = b->maxima[i];
  514. }
  515. return max;
  516. }
  517. /**
  518. * Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  519. * seconds. Find one sum for reading and one for writing. They don't have
  520. * to be at the same time).
  521. *
  522. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  523. */
  524. int
  525. rep_hist_bandwidth_assess(void)
  526. {
  527. uint64_t w,r;
  528. r = find_largest_max(read_array);
  529. w = find_largest_max(write_array);
  530. if (r>w)
  531. return (int)(w/(double)NUM_SECS_ROLLING_MEASURE);
  532. else
  533. return (int)(r/(double)NUM_SECS_ROLLING_MEASURE);
  534. return 0;
  535. }
  536. /**
  537. * Print the bandwidth history of b (either read_array or write_array)
  538. * into the buffer pointed to by buf. The format is simply comma
  539. * separated numbers, from oldest to newest.
  540. *
  541. * It returns the number of bytes written.
  542. */
  543. static size_t
  544. rep_hist_fill_bandwidth_history(char *buf, size_t len, bw_array_t *b)
  545. {
  546. char *cp = buf;
  547. int i, n;
  548. if (b->num_maxes_set <= b->next_max_idx) {
  549. /* We haven't been through the circular array yet; time starts at i=0.*/
  550. i = 0;
  551. } else {
  552. /* We've been around the array at least once. The next i to be
  553. overwritten is the oldest. */
  554. i = b->next_max_idx;
  555. }
  556. for (n=0; n<b->num_maxes_set; ++n,++i) {
  557. while (i >= NUM_TOTALS) i -= NUM_TOTALS;
  558. if (n==(b->num_maxes_set-1))
  559. tor_snprintf(cp, len-(cp-buf), U64_FORMAT,
  560. U64_PRINTF_ARG(b->totals[i]));
  561. else
  562. tor_snprintf(cp, len-(cp-buf), U64_FORMAT",",
  563. U64_PRINTF_ARG(b->totals[i]));
  564. cp += strlen(cp);
  565. }
  566. return cp-buf;
  567. }
  568. /**
  569. * Allocate and return lines for representing this server's bandwidth
  570. * history in its descriptor.
  571. */
  572. char *
  573. rep_hist_get_bandwidth_lines(void)
  574. {
  575. char *buf, *cp;
  576. char t[ISO_TIME_LEN+1];
  577. int r;
  578. bw_array_t *b;
  579. size_t len;
  580. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  581. len = (60+20*NUM_TOTALS)*2;
  582. buf = tor_malloc_zero(len);
  583. cp = buf;
  584. for (r=0;r<2;++r) {
  585. b = r?read_array:write_array;
  586. tor_assert(b);
  587. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  588. tor_snprintf(cp, len-(cp-buf), "opt %s %s (%d s) ",
  589. r ? "read-history" : "write-history", t,
  590. NUM_SECS_BW_SUM_INTERVAL);
  591. cp += strlen(cp);
  592. cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
  593. strlcat(cp, "\n", len-(cp-buf));
  594. ++cp;
  595. }
  596. return buf;
  597. }
  598. /** Update <b>state</b> with the newest bandwidth history. */
  599. void
  600. rep_hist_update_state(or_state_t *state)
  601. {
  602. int len, r;
  603. char *buf, *cp;
  604. smartlist_t **s_values;
  605. time_t *s_begins;
  606. int *s_interval;
  607. bw_array_t *b;
  608. len = 20*NUM_TOTALS+1;
  609. buf = tor_malloc_zero(len);
  610. for (r=0;r<2;++r) {
  611. b = r?read_array:write_array;
  612. s_begins = r?&state->BWHistoryReadEnds :&state->BWHistoryWriteEnds;
  613. s_interval= r?&state->BWHistoryReadInterval:&state->BWHistoryWriteInterval;
  614. s_values = r?&state->BWHistoryReadValues :&state->BWHistoryWriteValues;
  615. *s_begins = b->next_period;
  616. *s_interval = NUM_SECS_BW_SUM_INTERVAL;
  617. if (*s_values) {
  618. SMARTLIST_FOREACH(*s_values, char *, cp, tor_free(cp));
  619. smartlist_free(*s_values);
  620. }
  621. cp = buf;
  622. cp += rep_hist_fill_bandwidth_history(cp, len, b);
  623. tor_snprintf(cp, len-(cp-buf), cp == buf ? U64_FORMAT : ","U64_FORMAT,
  624. U64_PRINTF_ARG(b->total_in_period));
  625. *s_values = smartlist_create();
  626. if (server_mode(get_options()))
  627. smartlist_split_string(*s_values, buf, ",", SPLIT_SKIP_SPACE, 0);
  628. }
  629. tor_free(buf);
  630. state->dirty = 1;
  631. }
  632. /** Set bandwidth history from our saved state.
  633. */
  634. int
  635. rep_hist_load_state(or_state_t *state, char **err)
  636. {
  637. time_t s_begins, start;
  638. time_t now = time(NULL);
  639. uint64_t v;
  640. int r,i,ok;
  641. int all_ok = 1;
  642. int s_interval;
  643. smartlist_t *s_values;
  644. bw_array_t *b;
  645. /* Assert they already have been malloced */
  646. tor_assert(read_array && write_array);
  647. for (r=0;r<2;++r) {
  648. b = r?read_array:write_array;
  649. s_begins = r?state->BWHistoryReadEnds:state->BWHistoryWriteEnds;
  650. s_interval = r?state->BWHistoryReadInterval:state->BWHistoryWriteInterval;
  651. s_values = r?state->BWHistoryReadValues:state->BWHistoryWriteValues;
  652. if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
  653. start = s_begins - s_interval*(smartlist_len(s_values));
  654. b->cur_obs_time = start;
  655. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  656. SMARTLIST_FOREACH(s_values, char *, cp, {
  657. v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
  658. if (!ok) {
  659. all_ok=0;
  660. log_notice(LD_GENERAL, "Could not parse '%s' into a number.'", cp);
  661. }
  662. add_obs(b, start, v);
  663. start += NUM_SECS_BW_SUM_INTERVAL;
  664. });
  665. }
  666. /* Clean up maxima and observed */
  667. /* Do we really want to zero this for the purpose of max capacity? */
  668. for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
  669. b->obs[i] = 0;
  670. }
  671. b->total_obs = 0;
  672. for (i=0; i<NUM_TOTALS; ++i) {
  673. b->maxima[i] = 0;
  674. }
  675. b->max_total = 0;
  676. }
  677. if (!all_ok) {
  678. *err = tor_strdup("Parsing of bandwidth history values failed");
  679. /* and create fresh arrays */
  680. tor_free(read_array);
  681. tor_free(write_array);
  682. read_array = bw_array_new();
  683. write_array = bw_array_new();
  684. return -1;
  685. }
  686. return 0;
  687. }
  688. /*********************************************************************/
  689. /** A list of port numbers that have been used recently. */
  690. static smartlist_t *predicted_ports_list=NULL;
  691. /** The corresponding most recently used time for each port. */
  692. static smartlist_t *predicted_ports_times=NULL;
  693. /** DOCDOC */
  694. static void
  695. add_predicted_port(uint16_t port, time_t now)
  696. {
  697. /* XXXX we could just use uintptr_t here, I think. */
  698. uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
  699. time_t *tmp_time = tor_malloc(sizeof(time_t));
  700. *tmp_port = port;
  701. *tmp_time = now;
  702. rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
  703. smartlist_add(predicted_ports_list, tmp_port);
  704. smartlist_add(predicted_ports_times, tmp_time);
  705. }
  706. /** DOCDOC */
  707. static void
  708. predicted_ports_init(void)
  709. {
  710. predicted_ports_list = smartlist_create();
  711. predicted_ports_times = smartlist_create();
  712. add_predicted_port(80, time(NULL)); /* add one to kickstart us */
  713. }
  714. /** DOCDOC */
  715. static void
  716. predicted_ports_free(void)
  717. {
  718. rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
  719. SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
  720. smartlist_free(predicted_ports_list);
  721. rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
  722. SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
  723. smartlist_free(predicted_ports_times);
  724. }
  725. /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
  726. * This is used for predicting what sorts of streams we'll make in the
  727. * future and making exit circuits to anticipate that.
  728. */
  729. void
  730. rep_hist_note_used_port(uint16_t port, time_t now)
  731. {
  732. int i;
  733. uint16_t *tmp_port;
  734. time_t *tmp_time;
  735. tor_assert(predicted_ports_list);
  736. tor_assert(predicted_ports_times);
  737. if (!port) /* record nothing */
  738. return;
  739. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  740. tmp_port = smartlist_get(predicted_ports_list, i);
  741. tmp_time = smartlist_get(predicted_ports_times, i);
  742. if (*tmp_port == port) {
  743. *tmp_time = now;
  744. return;
  745. }
  746. }
  747. /* it's not there yet; we need to add it */
  748. add_predicted_port(port, now);
  749. }
  750. /** For this long after we've seen a request for a given port, assume that
  751. * we'll want to make connections to the same port in the future. */
  752. #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
  753. /** Return a pointer to the list of port numbers that
  754. * are likely to be asked for in the near future.
  755. *
  756. * The caller promises not to mess with it.
  757. */
  758. smartlist_t *
  759. rep_hist_get_predicted_ports(time_t now)
  760. {
  761. int i;
  762. uint16_t *tmp_port;
  763. time_t *tmp_time;
  764. tor_assert(predicted_ports_list);
  765. tor_assert(predicted_ports_times);
  766. /* clean out obsolete entries */
  767. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  768. tmp_time = smartlist_get(predicted_ports_times, i);
  769. if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
  770. tmp_port = smartlist_get(predicted_ports_list, i);
  771. log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
  772. smartlist_del(predicted_ports_list, i);
  773. smartlist_del(predicted_ports_times, i);
  774. rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
  775. tor_free(tmp_port);
  776. tor_free(tmp_time);
  777. i--;
  778. }
  779. }
  780. return predicted_ports_list;
  781. }
  782. /** The user asked us to do a resolve. Rather than keeping track of
  783. * timings and such of resolves, we fake it for now by making treating
  784. * it the same way as a connection to port 80. This way we will continue
  785. * to have circuits lying around if the user only uses Tor for resolves.
  786. */
  787. void
  788. rep_hist_note_used_resolve(time_t now)
  789. {
  790. rep_hist_note_used_port(80, now);
  791. }
  792. #if 0
  793. int
  794. rep_hist_get_predicted_resolve(time_t now)
  795. {
  796. return 0;
  797. }
  798. #endif
  799. /** The last time at which we needed an internal circ. */
  800. static time_t predicted_internal_time = 0;
  801. /** The last time we needed an internal circ with good uptime. */
  802. static time_t predicted_internal_uptime_time = 0;
  803. /** The last time we needed an internal circ with good capacity. */
  804. static time_t predicted_internal_capacity_time = 0;
  805. /** Remember that we used an internal circ at time <b>now</b>. */
  806. void
  807. rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
  808. {
  809. predicted_internal_time = now;
  810. if (need_uptime)
  811. predicted_internal_uptime_time = now;
  812. if (need_capacity)
  813. predicted_internal_capacity_time = now;
  814. }
  815. /** Return 1 if we've used an internal circ recently; else return 0. */
  816. int
  817. rep_hist_get_predicted_internal(time_t now, int *need_uptime,
  818. int *need_capacity)
  819. {
  820. if (!predicted_internal_time) { /* initialize it */
  821. predicted_internal_time = now;
  822. predicted_internal_uptime_time = now;
  823. predicted_internal_capacity_time = now;
  824. }
  825. if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
  826. return 0; /* too long ago */
  827. if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
  828. *need_uptime = 1;
  829. if (predicted_internal_capacity_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
  830. *need_capacity = 1;
  831. return 1;
  832. }
  833. /** Return 1 if we have no need for circuits currently, else return 0. */
  834. int
  835. rep_hist_circbuilding_dormant(time_t now)
  836. {
  837. /* Any ports used lately? These are pre-seeded if we just started
  838. * up or if we're running a hidden service. */
  839. if (smartlist_len(predicted_ports_list) ||
  840. predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
  841. return 0;
  842. /* see if we'll still need to build testing circuits */
  843. if (server_mode(get_options()) && !check_whether_orport_reachable())
  844. return 0;
  845. if (!check_whether_dirport_reachable())
  846. return 0;
  847. return 1;
  848. }
  849. /** Free all storage held by the OR/link history caches, by the
  850. * bandwidth history arrays, or by the port history. */
  851. void
  852. rep_hist_free_all(void)
  853. {
  854. digestmap_free(history_map, free_or_history);
  855. tor_free(read_array);
  856. tor_free(write_array);
  857. predicted_ports_free();
  858. }