rephist.c 30 KB

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