rephist.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /* Copyright 2004 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char rephist_c_id[] = "$Id$";
  5. /**
  6. * \file rephist.c
  7. * \brief Basic history functionality for reputation module.
  8. **/
  9. #include "or.h"
  10. static void bw_arrays_init(void);
  11. static void predicted_ports_init(void);
  12. /** History of an OR-\>OR link. */
  13. typedef struct link_history_t {
  14. /** When did we start tracking this list? */
  15. time_t since;
  16. /** When did we most recently note a change to this link */
  17. time_t changed;
  18. /** How many times did extending from OR1 to OR2 succeed? */
  19. unsigned long n_extend_ok;
  20. /** How many times did extending from OR1 to OR2 fail? */
  21. unsigned long n_extend_fail;
  22. } link_history_t;
  23. /** History of an OR. */
  24. typedef struct or_history_t {
  25. /** When did we start tracking this OR? */
  26. time_t since;
  27. /** When did we most recently note a change to this OR? */
  28. time_t changed;
  29. /** How many times did we successfully connect? */
  30. unsigned long n_conn_ok;
  31. /** How many times did we try to connect and fail?*/
  32. unsigned long n_conn_fail;
  33. /** How many seconds have we been connected to this OR before
  34. * 'up_since'? */
  35. unsigned long uptime;
  36. /** How many seconds have we been unable to connect to this OR before
  37. * 'down_since'? */
  38. unsigned long downtime;
  39. /** If nonzero, we have been connected since this time. */
  40. time_t up_since;
  41. /** If nonzero, we have been unable to connect since this time. */
  42. time_t down_since;
  43. /** Map from hex OR2 identity digest to a link_history_t for the link
  44. * from this OR to OR2. */
  45. strmap_t *link_history_map;
  46. } or_history_t;
  47. /** Map from hex OR identity digest to or_history_t. */
  48. static strmap_t *history_map = NULL;
  49. /** Return the or_history_t for the named OR, creating it if necessary.
  50. */
  51. static or_history_t *get_or_history(const char* id)
  52. {
  53. or_history_t *hist;
  54. char hexid[HEX_DIGEST_LEN+1];
  55. base16_encode(hexid, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  56. if (!strcmp(hexid, "0000000000000000000000000000000000000000"))
  57. return NULL;
  58. hist = (or_history_t*) strmap_get(history_map, hexid);
  59. if (!hist) {
  60. hist = tor_malloc_zero(sizeof(or_history_t));
  61. hist->link_history_map = strmap_new();
  62. hist->since = hist->changed = time(NULL);
  63. strmap_set(history_map, hexid, hist);
  64. }
  65. return hist;
  66. }
  67. /** Return the link_history_t for the link from the first named OR to
  68. * the second, creating it if necessary. (ORs are identified by
  69. * identity digest)
  70. */
  71. static link_history_t *get_link_history(const char *from_id,
  72. const char *to_id)
  73. {
  74. or_history_t *orhist;
  75. link_history_t *lhist;
  76. char to_hexid[HEX_DIGEST_LEN+1];
  77. orhist = get_or_history(from_id);
  78. if (!orhist)
  79. return NULL;
  80. base16_encode(to_hexid, HEX_DIGEST_LEN+1, to_id, DIGEST_LEN);
  81. if (!strcmp(to_hexid, "0000000000000000000000000000000000000000"))
  82. return NULL;
  83. lhist = (link_history_t*) strmap_get(orhist->link_history_map, to_hexid);
  84. if (!lhist) {
  85. lhist = tor_malloc_zero(sizeof(link_history_t));
  86. lhist->since = lhist->changed = time(NULL);
  87. strmap_set(orhist->link_history_map, to_hexid, lhist);
  88. }
  89. return lhist;
  90. }
  91. static void
  92. _free_link_history(void *val)
  93. {
  94. tor_free(val);
  95. }
  96. static void
  97. free_or_history(or_history_t *hist)
  98. {
  99. strmap_free(hist->link_history_map, _free_link_history);
  100. tor_free(hist);
  101. }
  102. /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
  103. * count is up-to-date as of <b>when</b>.
  104. */
  105. static void update_or_history(or_history_t *hist, time_t when)
  106. {
  107. tor_assert(hist);
  108. if (hist->up_since) {
  109. tor_assert(!hist->down_since);
  110. hist->uptime += (when - hist->up_since);
  111. hist->up_since = when;
  112. } else if (hist->down_since) {
  113. hist->downtime += (when - hist->down_since);
  114. hist->down_since = when;
  115. }
  116. }
  117. /** Initialize the static data structures for tracking history.
  118. */
  119. void rep_hist_init(void)
  120. {
  121. history_map = strmap_new();
  122. bw_arrays_init();
  123. predicted_ports_init();
  124. }
  125. /** Remember that an attempt to connect to the OR with identity digest
  126. * <b>id</b> failed at <b>when</b>.
  127. */
  128. void rep_hist_note_connect_failed(const char* id, time_t when)
  129. {
  130. or_history_t *hist;
  131. hist = get_or_history(id);
  132. if (!hist)
  133. return;
  134. ++hist->n_conn_fail;
  135. if (hist->up_since) {
  136. hist->uptime += (when - hist->up_since);
  137. hist->up_since = 0;
  138. }
  139. if (!hist->down_since)
  140. hist->down_since = when;
  141. hist->changed = when;
  142. }
  143. /** Remember that an attempt to connect to the OR with identity digest
  144. * <b>id</b> succeeded at <b>when</b>.
  145. */
  146. void rep_hist_note_connect_succeeded(const char* id, time_t when)
  147. {
  148. or_history_t *hist;
  149. hist = get_or_history(id);
  150. if (!hist)
  151. return;
  152. ++hist->n_conn_ok;
  153. if (hist->down_since) {
  154. hist->downtime += (when - hist->down_since);
  155. hist->down_since = 0;
  156. }
  157. if (!hist->up_since)
  158. hist->up_since = when;
  159. hist->changed = when;
  160. }
  161. /** Remember that we intentionally closed our connection to the OR
  162. * with identity digest <b>id</b> at <b>when</b>.
  163. */
  164. void rep_hist_note_disconnect(const char* id, time_t when)
  165. {
  166. or_history_t *hist;
  167. hist = get_or_history(id);
  168. if (!hist)
  169. return;
  170. ++hist->n_conn_ok;
  171. if (hist->up_since) {
  172. hist->uptime += (when - hist->up_since);
  173. hist->up_since = 0;
  174. }
  175. hist->changed = when;
  176. }
  177. /** Remember that our connection to the OR with identity digest
  178. * <b>id</b> had an error and stopped working at <b>when</b>.
  179. */
  180. void rep_hist_note_connection_died(const char* id, time_t when)
  181. {
  182. or_history_t *hist;
  183. if (!id) {
  184. /* XXXX009 Well, everybody has an ID now. Hm. */
  185. /* If conn has no nickname, it's either an OP, or it is an OR
  186. * which didn't complete its handshake (or did and was unapproved).
  187. * Ignore it.
  188. */
  189. return;
  190. }
  191. hist = get_or_history(id);
  192. if (!hist)
  193. return;
  194. if (hist->up_since) {
  195. hist->uptime += (when - hist->up_since);
  196. hist->up_since = 0;
  197. }
  198. if (!hist->down_since)
  199. hist->down_since = when;
  200. hist->changed = when;
  201. }
  202. /** Remember that we successfully extended from the OR with identity
  203. * digest <b>from_id</b> to the OR with identity digest
  204. * <b>to_name</b>.
  205. */
  206. void rep_hist_note_extend_succeeded(const char *from_id,
  207. const char *to_id)
  208. {
  209. link_history_t *hist;
  210. /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
  211. hist = get_link_history(from_id, to_id);
  212. if (!hist)
  213. return;
  214. ++hist->n_extend_ok;
  215. hist->changed = time(NULL);
  216. }
  217. /** Remember that we tried to extend from the OR with identity digest
  218. * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
  219. * failed.
  220. */
  221. void rep_hist_note_extend_failed(const char *from_id, const char *to_id)
  222. {
  223. link_history_t *hist;
  224. /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
  225. hist = get_link_history(from_id, to_id);
  226. if (!hist)
  227. return;
  228. ++hist->n_extend_fail;
  229. hist->changed = time(NULL);
  230. }
  231. /** Log all the reliability data we have remembered, with the chosen
  232. * severity.
  233. */
  234. void rep_hist_dump_stats(time_t now, int severity)
  235. {
  236. strmap_iter_t *lhist_it;
  237. strmap_iter_t *orhist_it;
  238. const char *name1, *name2, *hexdigest1, *hexdigest2;
  239. or_history_t *or_history;
  240. link_history_t *link_history;
  241. void *or_history_p, *link_history_p;
  242. double uptime;
  243. char buffer[2048];
  244. size_t len;
  245. int ret;
  246. unsigned long upt, downt;
  247. routerinfo_t *r;
  248. rep_history_clean(now-24*60*60);
  249. log(severity, "--------------- Dumping history information:");
  250. for (orhist_it = strmap_iter_init(history_map); !strmap_iter_done(orhist_it);
  251. orhist_it = strmap_iter_next(history_map,orhist_it)) {
  252. strmap_iter_get(orhist_it, &hexdigest1, &or_history_p);
  253. or_history = (or_history_t*) or_history_p;
  254. if ((r = router_get_by_hexdigest(hexdigest1)))
  255. name1 = r->nickname;
  256. else
  257. name1 = "(unknown)";
  258. update_or_history(or_history, now);
  259. upt = or_history->uptime;
  260. downt = or_history->downtime;
  261. if (upt+downt) {
  262. uptime = ((double)upt) / (upt+downt);
  263. } else {
  264. uptime=1.0;
  265. }
  266. log(severity,
  267. "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%)",
  268. name1, hexdigest1,
  269. or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
  270. upt, upt+downt, uptime*100.0);
  271. if (!strmap_isempty(or_history->link_history_map)) {
  272. strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
  273. len = strlen(buffer);
  274. for (lhist_it = strmap_iter_init(or_history->link_history_map);
  275. !strmap_iter_done(lhist_it);
  276. lhist_it = strmap_iter_next(or_history->link_history_map, lhist_it)) {
  277. strmap_iter_get(lhist_it, &hexdigest2, &link_history_p);
  278. if ((r = router_get_by_hexdigest(hexdigest2)))
  279. name2 = r->nickname;
  280. else
  281. name2 = "(unknown)";
  282. link_history = (link_history_t*) link_history_p;
  283. ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
  284. link_history->n_extend_ok,
  285. link_history->n_extend_ok+link_history->n_extend_fail);
  286. if (ret<0)
  287. break;
  288. else
  289. len += ret;
  290. }
  291. log(severity, "%s", buffer);
  292. }
  293. }
  294. }
  295. /** Remove history info for routers/links that haven't changed since
  296. * <b>before</b> */
  297. void rep_history_clean(time_t before)
  298. {
  299. or_history_t *or_history;
  300. link_history_t *link_history;
  301. void *or_history_p, *link_history_p;
  302. strmap_iter_t *orhist_it, *lhist_it;
  303. const char *hd1, *hd2;
  304. orhist_it = strmap_iter_init(history_map);
  305. while (!strmap_iter_done(orhist_it)) {
  306. strmap_iter_get(orhist_it, &hd1, &or_history_p);
  307. or_history = or_history_p;
  308. if (or_history->changed < before) {
  309. free_or_history(or_history);
  310. orhist_it = strmap_iter_next_rmv(history_map, orhist_it);
  311. continue;
  312. }
  313. for (lhist_it = strmap_iter_init(or_history->link_history_map);
  314. !strmap_iter_done(lhist_it); ) {
  315. strmap_iter_get(lhist_it, &hd2, &link_history_p);
  316. link_history = link_history_p;
  317. if (link_history->changed < before) {
  318. tor_free(link_history);
  319. lhist_it = strmap_iter_next_rmv(or_history->link_history_map,lhist_it);
  320. continue;
  321. }
  322. lhist_it = strmap_iter_next(or_history->link_history_map,lhist_it);
  323. }
  324. orhist_it = strmap_iter_next(history_map, orhist_it);
  325. }
  326. }
  327. #if 0
  328. void write_rep_history(const char *filename)
  329. {
  330. FILE *f = NULL;
  331. char *tmpfile;
  332. int completed = 0;
  333. or_history_t *or_history;
  334. link_history_t *link_history;
  335. strmap_iter_t *lhist_it;
  336. strmap_iter_t *orhist_it;
  337. void *or_history_p, *link_history_p;
  338. const char *name1;
  339. tmpfile = tor_malloc(strlen(filename)+5);
  340. tor_snprintf(tmpfile, strlen(filename)+5, "%s_tmp", filename);
  341. f = fopen(tmpfile, "w");
  342. if (!f) goto done;
  343. for (orhist_it = strmap_iter_init(history_map); !strmap_iter_done(orhist_it);
  344. orhist_it = strmap_iter_next(history_map,orhist_it)) {
  345. strmap_iter_get(orhist_it, &name1, &or_history_p);
  346. or_history = (or_history_t*) or_history_p;
  347. fprintf(f, "link %s connected:u%ld failed:%uld uptime:%uld",
  348. name1, or_history->since1,
  349. }
  350. done:
  351. if (f)
  352. fclose(f);
  353. if (completed)
  354. replace_file(filename, tmpfile);
  355. else
  356. unlink(tmpfile);
  357. tor_free(tmpfile);
  358. }
  359. #endif
  360. #define NUM_SECS_ROLLING_MEASURE 10
  361. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60) /* one day */
  362. #define NUM_SECS_BW_SUM_INTERVAL (15*60)
  363. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  364. /**
  365. * Structure to track bandwidth use, and remember the maxima for a given
  366. * time period.
  367. */
  368. typedef struct bw_array_t {
  369. /** Observation array: Total number of bytes transferred in each of the last
  370. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  371. int obs[NUM_SECS_ROLLING_MEASURE];
  372. int cur_obs_idx; /**< Current position in obs. */
  373. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  374. int total_obs; /**< Total for all members of obs except obs[cur_obs_idx] */
  375. int max_total; /**< Largest value that total_obs has taken on in the current
  376. * period. */
  377. int total_in_period; /**< Total bytes transferred in the current period. */
  378. /** When does the next period begin? */
  379. time_t next_period;
  380. /** Where in 'maxima' should the maximum bandwidth usage for the current
  381. * period be stored? */
  382. int next_max_idx;
  383. /** How many values in maxima/totals have been set ever? */
  384. int num_maxes_set;
  385. /** Circular array of the maximum
  386. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  387. * NUM_TOTALS periods */
  388. int maxima[NUM_TOTALS];
  389. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  390. * periods */
  391. int totals[NUM_TOTALS];
  392. } bw_array_t;
  393. /** Shift the current period of b forward by one.
  394. */
  395. static void commit_max(bw_array_t *b) {
  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 advance_obs(bw_array_t *b) {
  414. int nextidx;
  415. int total;
  416. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  417. * seconds; adjust max_total as needed.*/
  418. total = b->total_obs + b->obs[b->cur_obs_idx];
  419. if (total > b->max_total)
  420. b->max_total = total;
  421. nextidx = b->cur_obs_idx+1;
  422. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  423. nextidx = 0;
  424. b->total_obs = total - b->obs[nextidx];
  425. b->obs[nextidx]=0;
  426. b->cur_obs_idx = nextidx;
  427. if (++b->cur_obs_time >= b->next_period)
  428. commit_max(b);
  429. }
  430. /** Add 'n' bytes to the number of bytes in b for second 'when'.
  431. */
  432. static INLINE void add_obs(bw_array_t *b, time_t when, int n) {
  433. /* Don't record data in the past. */
  434. if (when<b->cur_obs_time)
  435. return;
  436. /* If we're currently adding observations for an earlier second than
  437. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  438. * appropriate number of seconds, and do all the other housekeeping */
  439. while (when>b->cur_obs_time)
  440. advance_obs(b);
  441. b->obs[b->cur_obs_idx] += n;
  442. b->total_in_period += n;
  443. }
  444. /** Allocate, initialize, and return a new bw_array.
  445. */
  446. static bw_array_t *bw_array_new(void) {
  447. bw_array_t *b;
  448. time_t start;
  449. b = tor_malloc_zero(sizeof(bw_array_t));
  450. start = time(NULL);
  451. b->cur_obs_time = start;
  452. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  453. return b;
  454. }
  455. static bw_array_t *read_array = NULL;
  456. static bw_array_t *write_array = NULL;
  457. /** Set up read_array and write_array
  458. */
  459. static void bw_arrays_init(void)
  460. {
  461. read_array = bw_array_new();
  462. write_array = bw_array_new();
  463. }
  464. /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
  465. *
  466. * Add num_bytes to the current running total for <b>when</b>.
  467. *
  468. * <b>when</b> can go back to time, but it's safe to ignore calls
  469. * earlier than the latest <b>when</b> you've heard of.
  470. */
  471. void rep_hist_note_bytes_written(int num_bytes, time_t when) {
  472. /* Maybe a circular array for recent seconds, and step to a new point
  473. * every time a new second shows up. Or simpler is to just to have
  474. * a normal array and push down each item every second; it's short.
  475. */
  476. /* When a new second has rolled over, compute the sum of the bytes we've
  477. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  478. * somewhere. See rep_hist_bandwidth_assess() below.
  479. */
  480. add_obs(write_array, when, num_bytes);
  481. }
  482. /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
  483. * (like rep_hist_note_bytes_written() above)
  484. */
  485. void rep_hist_note_bytes_read(int num_bytes, time_t when) {
  486. /* if we're smart, we can make this func and the one above share code */
  487. add_obs(read_array, when, num_bytes);
  488. }
  489. /** Helper: Return the largest value in b->maxima. (This is equal to the
  490. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  491. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  492. */
  493. static int find_largest_max(bw_array_t *b)
  494. {
  495. int i,max;
  496. max=0;
  497. for (i=0; i<NUM_TOTALS; ++i) {
  498. if (b->maxima[i]>max)
  499. max = b->maxima[i];
  500. }
  501. return max;
  502. }
  503. /**
  504. * Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  505. * seconds. Find one sum for reading and one for writing. They don't have
  506. * to be at the same time).
  507. *
  508. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  509. */
  510. int rep_hist_bandwidth_assess(void) {
  511. int w,r;
  512. r = find_largest_max(read_array);
  513. w = find_largest_max(write_array);
  514. if (r>w)
  515. return (int)(w/(double)NUM_SECS_ROLLING_MEASURE);
  516. else
  517. return (int)(r/(double)NUM_SECS_ROLLING_MEASURE);
  518. return 0;
  519. }
  520. /**
  521. * Allocate and return lines for representing this server's bandwidth
  522. * history in its descriptor.
  523. */
  524. char *
  525. rep_hist_get_bandwidth_lines(void)
  526. {
  527. char *buf, *cp;
  528. char t[ISO_TIME_LEN+1];
  529. int r, i, n;
  530. bw_array_t *b;
  531. size_t len;
  532. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  533. len = (60+12*NUM_TOTALS)*2;
  534. buf = tor_malloc_zero(len);
  535. cp = buf;
  536. for (r=0;r<2;++r) {
  537. b = r?read_array:write_array;
  538. tor_assert(b);
  539. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  540. tor_snprintf(cp, len-(cp-buf), "opt %s %s (%d s) ", r?"read-history ":"write-history", t,
  541. NUM_SECS_BW_SUM_INTERVAL);
  542. cp += strlen(cp);
  543. if (b->num_maxes_set <= b->next_max_idx)
  544. /* We haven't been through the circular array yet; time starts at i=0.*/
  545. i = 0;
  546. else
  547. /* We've been around the array at least once. The next i to be
  548. overwritten is the oldest. */
  549. i = b->next_max_idx;
  550. for (n=0; n<b->num_maxes_set; ++n,++i) {
  551. while (i >= NUM_TOTALS) i -= NUM_TOTALS;
  552. if (n==(b->num_maxes_set-1))
  553. tor_snprintf(cp, len-(cp-buf), "%d", b->totals[i]);
  554. else
  555. tor_snprintf(cp, len-(cp-buf), "%d,", b->totals[i]);
  556. cp += strlen(cp);
  557. }
  558. strlcat(cp, "\n", len-(cp-buf));
  559. ++cp;
  560. }
  561. return buf;
  562. }
  563. /** A list of port numbers that have been used recently. */
  564. static smartlist_t *predicted_ports_list=NULL;
  565. /** The corresponding most recently used time for each port. */
  566. static smartlist_t *predicted_ports_times=NULL;
  567. static void add_predicted_port(uint16_t port, time_t now) {
  568. uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
  569. time_t *tmp_time = tor_malloc(sizeof(time_t));
  570. *tmp_port = port;
  571. *tmp_time = now;
  572. smartlist_add(predicted_ports_list, tmp_port);
  573. smartlist_add(predicted_ports_times, tmp_time);
  574. }
  575. static void predicted_ports_init(void) {
  576. predicted_ports_list = smartlist_create();
  577. predicted_ports_times = smartlist_create();
  578. add_predicted_port(80, time(NULL)); /* add one to kickstart us */
  579. }
  580. /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
  581. * This is used for predicting what sorts of streams we'll make in the
  582. * future and making circuits to anticipate that.
  583. */
  584. void rep_hist_note_used_port(uint16_t port, time_t now) {
  585. int i;
  586. uint16_t *tmp_port;
  587. time_t *tmp_time;
  588. tor_assert(predicted_ports_list);
  589. tor_assert(predicted_ports_times);
  590. if (!port) /* record nothing */
  591. return;
  592. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  593. tmp_port = smartlist_get(predicted_ports_list, i);
  594. tmp_time = smartlist_get(predicted_ports_times, i);
  595. if (*tmp_port == port) {
  596. *tmp_time = now;
  597. return;
  598. }
  599. }
  600. /* it's not there yet; we need to add it */
  601. add_predicted_port(port, now);
  602. }
  603. #define PREDICTED_PORTS_RELEVANCE_TIME (6*3600) /* 6 hours */
  604. /** Return a pointer to the list of port numbers that
  605. * are likely to be asked for in the near future.
  606. *
  607. * The caller promises not to mess with it.
  608. */
  609. smartlist_t *rep_hist_get_predicted_ports(time_t now) {
  610. int i;
  611. uint16_t *tmp_port;
  612. time_t *tmp_time;
  613. tor_assert(predicted_ports_list);
  614. tor_assert(predicted_ports_times);
  615. /* clean out obsolete entries */
  616. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  617. tmp_time = smartlist_get(predicted_ports_times, i);
  618. if (*tmp_time + PREDICTED_PORTS_RELEVANCE_TIME < now) {
  619. tmp_port = smartlist_get(predicted_ports_list, i);
  620. log_fn(LOG_DEBUG, "Expiring predicted port %d", *tmp_port);
  621. smartlist_del(predicted_ports_list, i);
  622. smartlist_del(predicted_ports_times, i);
  623. tor_free(tmp_port);
  624. tor_free(tmp_time);
  625. i--;
  626. }
  627. }
  628. return predicted_ports_list;
  629. }