rephist.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. 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. while (i >= NUM_TOTALS) i -= NUM_TOTALS;
  548. if (n==(b->num_maxes_set-1))
  549. tor_snprintf(cp, len-(cp-buf), U64_FORMAT,
  550. U64_PRINTF_ARG(b->totals[i]));
  551. else
  552. tor_snprintf(cp, len-(cp-buf), U64_FORMAT",",
  553. U64_PRINTF_ARG(b->totals[i]));
  554. cp += strlen(cp);
  555. }
  556. return cp-buf;
  557. }
  558. /** Allocate and return lines for representing this server's bandwidth
  559. * history in its descriptor.
  560. */
  561. char *
  562. rep_hist_get_bandwidth_lines(void)
  563. {
  564. char *buf, *cp;
  565. char t[ISO_TIME_LEN+1];
  566. int r;
  567. bw_array_t *b;
  568. size_t len;
  569. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  570. len = (60+20*NUM_TOTALS)*2;
  571. buf = tor_malloc_zero(len);
  572. cp = buf;
  573. for (r=0;r<2;++r) {
  574. b = r?read_array:write_array;
  575. tor_assert(b);
  576. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  577. tor_snprintf(cp, len-(cp-buf), "opt %s %s (%d s) ",
  578. r ? "read-history" : "write-history", t,
  579. NUM_SECS_BW_SUM_INTERVAL);
  580. cp += strlen(cp);
  581. cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
  582. strlcat(cp, "\n", len-(cp-buf));
  583. ++cp;
  584. }
  585. return buf;
  586. }
  587. /** Update <b>state</b> with the newest bandwidth history. */
  588. void
  589. rep_hist_update_state(or_state_t *state)
  590. {
  591. int len, r;
  592. char *buf, *cp;
  593. smartlist_t **s_values;
  594. time_t *s_begins;
  595. int *s_interval;
  596. bw_array_t *b;
  597. len = 20*NUM_TOTALS+1;
  598. buf = tor_malloc_zero(len);
  599. for (r=0;r<2;++r) {
  600. b = r?read_array:write_array;
  601. s_begins = r?&state->BWHistoryReadEnds :&state->BWHistoryWriteEnds;
  602. s_interval= r?&state->BWHistoryReadInterval:&state->BWHistoryWriteInterval;
  603. s_values = r?&state->BWHistoryReadValues :&state->BWHistoryWriteValues;
  604. if (*s_values) {
  605. SMARTLIST_FOREACH(*s_values, char *, cp, tor_free(cp));
  606. smartlist_free(*s_values);
  607. }
  608. if (! server_mode(get_options())) {
  609. /* Clients don't need to store bandwidth history persistently;
  610. * force these values to the defaults. */
  611. if (*s_begins != 0 || *s_interval != 900)
  612. or_state_mark_dirty(get_or_state(), time(NULL)+600);
  613. *s_begins = 0;
  614. *s_interval = 900;
  615. *s_values = smartlist_create();
  616. continue;
  617. }
  618. *s_begins = b->next_period;
  619. *s_interval = NUM_SECS_BW_SUM_INTERVAL;
  620. cp = buf;
  621. cp += rep_hist_fill_bandwidth_history(cp, len, b);
  622. tor_snprintf(cp, len-(cp-buf), cp == buf ? U64_FORMAT : ","U64_FORMAT,
  623. U64_PRINTF_ARG(b->total_in_period));
  624. *s_values = smartlist_create();
  625. if (server_mode(get_options()))
  626. smartlist_split_string(*s_values, buf, ",", SPLIT_SKIP_SPACE, 0);
  627. }
  628. tor_free(buf);
  629. if (server_mode(get_options()))
  630. or_state_mark_dirty(get_or_state(), time(NULL)+(2*3600));
  631. }
  632. /** Set bandwidth history from our saved state. */
  633. int
  634. rep_hist_load_state(or_state_t *state, char **err)
  635. {
  636. time_t s_begins, start;
  637. time_t now = time(NULL);
  638. uint64_t v;
  639. int r,i,ok;
  640. int all_ok = 1;
  641. int s_interval;
  642. smartlist_t *s_values;
  643. bw_array_t *b;
  644. /* Assert they already have been malloced */
  645. tor_assert(read_array && write_array);
  646. for (r=0;r<2;++r) {
  647. b = r?read_array:write_array;
  648. s_begins = r?state->BWHistoryReadEnds:state->BWHistoryWriteEnds;
  649. s_interval = r?state->BWHistoryReadInterval:state->BWHistoryWriteInterval;
  650. s_values = r?state->BWHistoryReadValues:state->BWHistoryWriteValues;
  651. if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
  652. start = s_begins - s_interval*(smartlist_len(s_values));
  653. b->cur_obs_time = start;
  654. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  655. SMARTLIST_FOREACH(s_values, char *, cp, {
  656. v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
  657. if (!ok) {
  658. all_ok=0;
  659. log_notice(LD_GENERAL, "Could not parse '%s' into a number.'", cp);
  660. }
  661. add_obs(b, start, v);
  662. start += NUM_SECS_BW_SUM_INTERVAL;
  663. });
  664. }
  665. /* Clean up maxima and observed */
  666. /* Do we really want to zero this for the purpose of max capacity? */
  667. for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
  668. b->obs[i] = 0;
  669. }
  670. b->total_obs = 0;
  671. for (i=0; i<NUM_TOTALS; ++i) {
  672. b->maxima[i] = 0;
  673. }
  674. b->max_total = 0;
  675. }
  676. if (!all_ok) {
  677. *err = tor_strdup("Parsing of bandwidth history values failed");
  678. /* and create fresh arrays */
  679. tor_free(read_array);
  680. tor_free(write_array);
  681. read_array = bw_array_new();
  682. write_array = bw_array_new();
  683. return -1;
  684. }
  685. return 0;
  686. }
  687. /*********************************************************************/
  688. /** A list of port numbers that have been used recently. */
  689. static smartlist_t *predicted_ports_list=NULL;
  690. /** The corresponding most recently used time for each port. */
  691. static smartlist_t *predicted_ports_times=NULL;
  692. /** We just got an application request for a connection with
  693. * port <b>port</b>. Remember it for the future, so we can keep
  694. * some circuits open that will exit to this port.
  695. */
  696. static void
  697. add_predicted_port(uint16_t port, time_t now)
  698. {
  699. /* XXXX we could just use uintptr_t here, I think. */
  700. uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
  701. time_t *tmp_time = tor_malloc(sizeof(time_t));
  702. *tmp_port = port;
  703. *tmp_time = now;
  704. rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
  705. smartlist_add(predicted_ports_list, tmp_port);
  706. smartlist_add(predicted_ports_times, tmp_time);
  707. }
  708. /** Initialize whatever memory and structs are needed for predicting
  709. * which ports will be used. Also seed it with port 80, so we'll build
  710. * circuits on start-up.
  711. */
  712. static void
  713. predicted_ports_init(void)
  714. {
  715. predicted_ports_list = smartlist_create();
  716. predicted_ports_times = smartlist_create();
  717. add_predicted_port(80, time(NULL)); /* add one to kickstart us */
  718. }
  719. /** Free whatever memory is needed for predicting which ports will
  720. * be used.
  721. */
  722. static void
  723. predicted_ports_free(void)
  724. {
  725. rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
  726. SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
  727. smartlist_free(predicted_ports_list);
  728. rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
  729. SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
  730. smartlist_free(predicted_ports_times);
  731. }
  732. /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
  733. * This is used for predicting what sorts of streams we'll make in the
  734. * future and making exit circuits to anticipate that.
  735. */
  736. void
  737. rep_hist_note_used_port(uint16_t port, time_t now)
  738. {
  739. int i;
  740. uint16_t *tmp_port;
  741. time_t *tmp_time;
  742. tor_assert(predicted_ports_list);
  743. tor_assert(predicted_ports_times);
  744. if (!port) /* record nothing */
  745. return;
  746. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  747. tmp_port = smartlist_get(predicted_ports_list, i);
  748. tmp_time = smartlist_get(predicted_ports_times, i);
  749. if (*tmp_port == port) {
  750. *tmp_time = now;
  751. return;
  752. }
  753. }
  754. /* it's not there yet; we need to add it */
  755. add_predicted_port(port, now);
  756. }
  757. /** For this long after we've seen a request for a given port, assume that
  758. * we'll want to make connections to the same port in the future. */
  759. #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
  760. /** Return a pointer to the list of port numbers that
  761. * are likely to be asked for in the near future.
  762. *
  763. * The caller promises not to mess with it.
  764. */
  765. smartlist_t *
  766. rep_hist_get_predicted_ports(time_t now)
  767. {
  768. int i;
  769. uint16_t *tmp_port;
  770. time_t *tmp_time;
  771. tor_assert(predicted_ports_list);
  772. tor_assert(predicted_ports_times);
  773. /* clean out obsolete entries */
  774. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  775. tmp_time = smartlist_get(predicted_ports_times, i);
  776. if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
  777. tmp_port = smartlist_get(predicted_ports_list, i);
  778. log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
  779. smartlist_del(predicted_ports_list, i);
  780. smartlist_del(predicted_ports_times, i);
  781. rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
  782. tor_free(tmp_port);
  783. tor_free(tmp_time);
  784. i--;
  785. }
  786. }
  787. return predicted_ports_list;
  788. }
  789. /** The user asked us to do a resolve. Rather than keeping track of
  790. * timings and such of resolves, we fake it for now by making treating
  791. * it the same way as a connection to port 80. This way we will continue
  792. * to have circuits lying around if the user only uses Tor for resolves.
  793. */
  794. void
  795. rep_hist_note_used_resolve(time_t now)
  796. {
  797. rep_hist_note_used_port(80, now);
  798. }
  799. #if 0
  800. int
  801. rep_hist_get_predicted_resolve(time_t now)
  802. {
  803. return 0;
  804. }
  805. #endif
  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. void
  873. note_crypto_pk_op(pk_op_t operation)
  874. {
  875. switch (operation)
  876. {
  877. case SIGN_DIR:
  878. n_signed_dir_objs++;
  879. break;
  880. case SIGN_RTR:
  881. n_signed_routerdescs++;
  882. break;
  883. case VERIFY_DIR:
  884. n_verified_dir_objs++;
  885. break;
  886. case VERIFY_RTR:
  887. n_verified_routerdescs++;
  888. break;
  889. case ENC_ONIONSKIN:
  890. n_onionskins_encrypted++;
  891. break;
  892. case DEC_ONIONSKIN:
  893. n_onionskins_decrypted++;
  894. break;
  895. case TLS_HANDSHAKE_C:
  896. n_tls_client_handshakes++;
  897. break;
  898. case TLS_HANDSHAKE_S:
  899. n_tls_server_handshakes++;
  900. break;
  901. case REND_CLIENT:
  902. n_rend_client_ops++;
  903. break;
  904. case REND_MID:
  905. n_rend_mid_ops++;
  906. break;
  907. case REND_SERVER:
  908. n_rend_server_ops++;
  909. break;
  910. default:
  911. log_warn(LD_BUG, "Unknown pk operation %d", operation);
  912. }
  913. }
  914. void
  915. dump_pk_ops(int severity)
  916. {
  917. log(severity, LD_GENERAL,
  918. "PK operations: %lu directory objects signed, "
  919. "%lu directory objects verified, "
  920. "%lu routerdescs signed, "
  921. "%lu routerdescs verified, "
  922. "%lu onionskins encrypted, "
  923. "%lu onionskins decrypted, "
  924. "%lu client-side TLS handshakes, "
  925. "%lu server-side TLS handshakes, "
  926. "%lu rendezvous client operations, "
  927. "%lu rendezvous middle operations, "
  928. "%lu rendezvous server operations.",
  929. (unsigned long) n_signed_dir_objs,
  930. (unsigned long) n_verified_dir_objs,
  931. (unsigned long) n_signed_routerdescs,
  932. (unsigned long) n_verified_routerdescs,
  933. (unsigned long) n_onionskins_encrypted,
  934. (unsigned long) n_onionskins_decrypted,
  935. (unsigned long) n_tls_client_handshakes,
  936. (unsigned long) n_tls_server_handshakes,
  937. (unsigned long) n_rend_client_ops,
  938. (unsigned long) n_rend_mid_ops,
  939. (unsigned long) n_rend_server_ops);
  940. }
  941. /** Free all storage held by the OR/link history caches, by the
  942. * bandwidth history arrays, or by the port history. */
  943. void
  944. rep_hist_free_all(void)
  945. {
  946. digestmap_free(history_map, free_or_history);
  947. tor_free(read_array);
  948. tor_free(write_array);
  949. predicted_ports_free();
  950. }