rephist.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  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. static void hs_usage_init(void);
  16. uint64_t rephist_total_alloc=0;
  17. uint32_t rephist_total_num=0;
  18. /** If the total weighted run count of all runs for a router ever falls
  19. * below this amount, the router can be treated as having 0 MTBF. */
  20. #define STABILITY_EPSILON 0.0001
  21. /** Value by which to discount all old intervals for MTBF purposses. This
  22. * is compounded every STABILITY_INTERVAL. */
  23. #define STABILITY_ALPHA 0.95
  24. /** Interval at which to discount all old intervals for MTBF purposes. */
  25. #define STABILITY_INTERVAL (12*60*60)
  26. /* (This combination of ALPHA, INTERVAL, and EPSILON makes it so that an
  27. * interval that just ended counts twice as much as one that ended a week ago,
  28. * 20X as much as one that ended a month ago, and routers that have had no
  29. * uptime data for about half a year will get forgotten.) */
  30. /** History of an OR-\>OR link. */
  31. typedef struct link_history_t {
  32. /** When did we start tracking this list? */
  33. time_t since;
  34. /** When did we most recently note a change to this link */
  35. time_t changed;
  36. /** How many times did extending from OR1 to OR2 succeed? */
  37. unsigned long n_extend_ok;
  38. /** How many times did extending from OR1 to OR2 fail? */
  39. unsigned long n_extend_fail;
  40. } link_history_t;
  41. /** History of an OR. */
  42. typedef struct or_history_t {
  43. /** When did we start tracking this OR? */
  44. time_t since;
  45. /** When did we most recently note a change to this OR? */
  46. time_t changed;
  47. /** How many times did we successfully connect? */
  48. unsigned long n_conn_ok;
  49. /** How many times did we try to connect and fail?*/
  50. unsigned long n_conn_fail;
  51. /** How many seconds have we been connected to this OR before
  52. * 'up_since'? */
  53. unsigned long uptime;
  54. /** How many seconds have we been unable to connect to this OR before
  55. * 'down_since'? */
  56. unsigned long downtime;
  57. /** If nonzero, we have been connected since this time. */
  58. time_t up_since;
  59. /** If nonzero, we have been unable to connect since this time. */
  60. time_t down_since;
  61. /* === For MTBF tracking: */
  62. /** Weighted sum total of all times that this router has been online.
  63. */
  64. unsigned long weighted_run_length;
  65. /** If the router is now online (according to stability-checking rules),
  66. * when did it come online? */
  67. time_t start_of_run;
  68. /** Sum of weights for runs in weighted_run_length. */
  69. double total_run_weights;
  70. /* === For fractional uptime tracking: */
  71. time_t start_of_downtime;
  72. unsigned long weighted_uptime;
  73. unsigned long total_weighted_time;
  74. /** Map from hex OR2 identity digest to a link_history_t for the link
  75. * from this OR to OR2. */
  76. digestmap_t *link_history_map;
  77. } or_history_t;
  78. /** When did we last multiply all routers' weighted_run_length and
  79. * total_run_weights by STABILITY_ALPHA? */
  80. static time_t stability_last_downrated = 0;
  81. /** */
  82. static time_t started_tracking_stability = 0;
  83. /** Map from hex OR identity digest to or_history_t. */
  84. static digestmap_t *history_map = NULL;
  85. /** Return the or_history_t for the OR with identity digest <b>id</b>,
  86. * creating it if necessary. */
  87. static or_history_t *
  88. get_or_history(const char* id)
  89. {
  90. or_history_t *hist;
  91. if (tor_mem_is_zero(id, DIGEST_LEN))
  92. return NULL;
  93. hist = digestmap_get(history_map, id);
  94. if (!hist) {
  95. hist = tor_malloc_zero(sizeof(or_history_t));
  96. rephist_total_alloc += sizeof(or_history_t);
  97. rephist_total_num++;
  98. hist->link_history_map = digestmap_new();
  99. hist->since = hist->changed = time(NULL);
  100. digestmap_set(history_map, id, hist);
  101. }
  102. return hist;
  103. }
  104. /** Return the link_history_t for the link from the first named OR to
  105. * the second, creating it if necessary. (ORs are identified by
  106. * identity digest.)
  107. */
  108. static link_history_t *
  109. get_link_history(const char *from_id, const char *to_id)
  110. {
  111. or_history_t *orhist;
  112. link_history_t *lhist;
  113. orhist = get_or_history(from_id);
  114. if (!orhist)
  115. return NULL;
  116. if (tor_mem_is_zero(to_id, DIGEST_LEN))
  117. return NULL;
  118. lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
  119. if (!lhist) {
  120. lhist = tor_malloc_zero(sizeof(link_history_t));
  121. rephist_total_alloc += sizeof(link_history_t);
  122. lhist->since = lhist->changed = time(NULL);
  123. digestmap_set(orhist->link_history_map, to_id, lhist);
  124. }
  125. return lhist;
  126. }
  127. /** Helper: free storage held by a single link history entry. */
  128. static void
  129. _free_link_history(void *val)
  130. {
  131. rephist_total_alloc -= sizeof(link_history_t);
  132. tor_free(val);
  133. }
  134. /** Helper: free storage held by a single OR history entry. */
  135. static void
  136. free_or_history(void *_hist)
  137. {
  138. or_history_t *hist = _hist;
  139. digestmap_free(hist->link_history_map, _free_link_history);
  140. rephist_total_alloc -= sizeof(or_history_t);
  141. rephist_total_num--;
  142. tor_free(hist);
  143. }
  144. /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
  145. * count is up-to-date as of <b>when</b>.
  146. */
  147. static void
  148. update_or_history(or_history_t *hist, time_t when)
  149. {
  150. tor_assert(hist);
  151. if (hist->up_since) {
  152. tor_assert(!hist->down_since);
  153. hist->uptime += (when - hist->up_since);
  154. hist->up_since = when;
  155. } else if (hist->down_since) {
  156. hist->downtime += (when - hist->down_since);
  157. hist->down_since = when;
  158. }
  159. }
  160. /** Initialize the static data structures for tracking history. */
  161. void
  162. rep_hist_init(void)
  163. {
  164. history_map = digestmap_new();
  165. bw_arrays_init();
  166. predicted_ports_init();
  167. hs_usage_init();
  168. }
  169. /** Helper: note that we are no longer connected to the router with history
  170. * <b>hist</b>. If <b>failed</b>, the connection failed; otherwise, it was
  171. * closed correctly. */
  172. static void
  173. mark_or_down(or_history_t *hist, time_t when, int failed)
  174. {
  175. if (hist->up_since) {
  176. hist->uptime += (when - hist->up_since);
  177. hist->up_since = 0;
  178. }
  179. if (failed && !hist->down_since) {
  180. hist->down_since = when;
  181. }
  182. }
  183. /** Helper: note that we are connected to the router with history
  184. * <b>hist</b>. */
  185. static void
  186. mark_or_up(or_history_t *hist, time_t when)
  187. {
  188. if (hist->down_since) {
  189. hist->downtime += (when - hist->down_since);
  190. hist->down_since = 0;
  191. }
  192. if (!hist->up_since) {
  193. hist->up_since = when;
  194. }
  195. }
  196. /** Remember that an attempt to connect to the OR with identity digest
  197. * <b>id</b> failed at <b>when</b>.
  198. */
  199. void
  200. rep_hist_note_connect_failed(const char* id, time_t when)
  201. {
  202. or_history_t *hist;
  203. hist = get_or_history(id);
  204. if (!hist)
  205. return;
  206. ++hist->n_conn_fail;
  207. mark_or_down(hist, when, 1);
  208. hist->changed = when;
  209. }
  210. /** Remember that an attempt to connect to the OR with identity digest
  211. * <b>id</b> succeeded at <b>when</b>.
  212. */
  213. void
  214. rep_hist_note_connect_succeeded(const char* id, time_t when)
  215. {
  216. or_history_t *hist;
  217. hist = get_or_history(id);
  218. if (!hist)
  219. return;
  220. ++hist->n_conn_ok;
  221. mark_or_up(hist, when);
  222. hist->changed = when;
  223. }
  224. /** Remember that we intentionally closed our connection to the OR
  225. * with identity digest <b>id</b> at <b>when</b>.
  226. */
  227. void
  228. rep_hist_note_disconnect(const char* id, time_t when)
  229. {
  230. or_history_t *hist;
  231. hist = get_or_history(id);
  232. if (!hist)
  233. return;
  234. mark_or_down(hist, when, 0);
  235. hist->changed = when;
  236. }
  237. /** Remember that our connection to the OR with identity digest
  238. * <b>id</b> had an error and stopped working at <b>when</b>.
  239. */
  240. void
  241. rep_hist_note_connection_died(const char* id, time_t when)
  242. {
  243. or_history_t *hist;
  244. if (!id) {
  245. /* If conn has no identity, it didn't complete its handshake, or something
  246. * went wrong. Ignore it.
  247. */
  248. return;
  249. }
  250. hist = get_or_history(id);
  251. if (!hist)
  252. return;
  253. mark_or_down(hist, when, 1);
  254. hist->changed = when;
  255. }
  256. /** We have just decided that this router is reachable, meaning
  257. * we will give it a "Running" flag for the next while. */
  258. void
  259. rep_hist_note_router_reachable(const char *id, time_t when)
  260. {
  261. or_history_t *hist = get_or_history(id);
  262. if (!started_tracking_stability)
  263. started_tracking_stability = time(NULL);
  264. if (hist && !hist->start_of_run) {
  265. hist->start_of_run = when;
  266. }
  267. if (hist && hist->start_of_downtime) {
  268. long down_length = when - hist->start_of_downtime;
  269. hist->total_weighted_time += down_length;
  270. hist->start_of_downtime = 0;
  271. }
  272. }
  273. /** We have just decided that this router is unreachable, meaning
  274. * we are taking away its "Running" flag. */
  275. void
  276. rep_hist_note_router_unreachable(const char *id, time_t when)
  277. {
  278. or_history_t *hist = get_or_history(id);
  279. if (!started_tracking_stability)
  280. started_tracking_stability = time(NULL);
  281. if (hist && hist->start_of_run) {
  282. /*XXXX020 treat failure specially? */
  283. long run_length = when - hist->start_of_run;
  284. hist->weighted_run_length += run_length;
  285. hist->total_run_weights += 1.0;
  286. hist->start_of_run = 0;
  287. hist->weighted_uptime += run_length;
  288. hist->total_weighted_time += run_length;
  289. }
  290. if (hist && !hist->start_of_downtime) {
  291. hist->start_of_downtime = when;
  292. }
  293. }
  294. /** Helper: Discount all old MTBF data, if it is time to do so. Return
  295. * the time at which we should next discount MTBF data. */
  296. time_t
  297. rep_hist_downrate_old_runs(time_t now)
  298. {
  299. digestmap_iter_t *orhist_it;
  300. const char *digest1;
  301. or_history_t *hist;
  302. void *hist_p;
  303. double alpha = 1.0;
  304. if (!history_map)
  305. history_map = digestmap_new();
  306. if (!stability_last_downrated)
  307. stability_last_downrated = now;
  308. if (stability_last_downrated + STABILITY_INTERVAL > now)
  309. return stability_last_downrated + STABILITY_INTERVAL;
  310. /* Okay, we should downrate the data. By how much? */
  311. while (stability_last_downrated + STABILITY_INTERVAL < now) {
  312. stability_last_downrated += STABILITY_INTERVAL;
  313. alpha *= STABILITY_ALPHA;
  314. }
  315. /* Multiply every w_r_l, t_r_w pair by alpha. */
  316. for (orhist_it = digestmap_iter_init(history_map);
  317. !digestmap_iter_done(orhist_it);
  318. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  319. digestmap_iter_get(orhist_it, &digest1, &hist_p);
  320. hist = hist_p;
  321. hist->weighted_run_length =
  322. (unsigned long)(hist->weighted_run_length * alpha);
  323. hist->total_run_weights *= alpha;
  324. hist->weighted_uptime *= alpha;
  325. hist->total_weighted_time *= alpha;
  326. }
  327. return stability_last_downrated + STABILITY_INTERVAL;
  328. }
  329. /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
  330. static double
  331. get_stability(or_history_t *hist, time_t when)
  332. {
  333. unsigned long total = hist->weighted_run_length;
  334. double total_weights = hist->total_run_weights;
  335. if (hist->start_of_run) {
  336. /* We're currently in a run. Let total and total_weights hold the values
  337. * they would hold if the current run were to end now. */
  338. total += (when-hist->start_of_run);
  339. total_weights += 1.0;
  340. }
  341. if (total_weights < STABILITY_EPSILON) {
  342. /* Round down to zero, and avoid divide-by-zero. */
  343. return 0.0;
  344. }
  345. return total / total_weights;
  346. }
  347. /** Helper: Return the weighted percent-of-time-online of the router with
  348. * history <b>hist</b>. */
  349. static double
  350. get_weighted_fractional_uptime(or_history_t *hist, time_t when)
  351. {
  352. unsigned long total = hist->total_weighted_time;
  353. unsigned long up = hist->weighted_uptime;
  354. if (hist->start_of_run) {
  355. long run_length = (when - hist->start_of_run);
  356. up += run_length;
  357. total += run_length;
  358. } else if (hist->start_of_downtime) {
  359. total += (when - hist->start_of_downtime);
  360. }
  361. return ((double) up) / total;
  362. }
  363. /** Return an estimated MTBF for the router whose identity digest is
  364. * <b>id</b>. Return 0 if the router is unknown. */
  365. double
  366. rep_hist_get_stability(const char *id, time_t when)
  367. {
  368. or_history_t *hist = get_or_history(id);
  369. if (!hist)
  370. return 0.0;
  371. return get_stability(hist, when);
  372. }
  373. /** Return an estimated percent-of-time-online for the router whose identity
  374. * digest is <b>id</b>. Return 0 if the router is unknown. */
  375. double
  376. rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
  377. {
  378. or_history_t *hist = get_or_history(id);
  379. if (!hist)
  380. return 0.0;
  381. return get_weighted_fractional_uptime(hist, when);
  382. }
  383. /** Return true if we've been measuring MTBFs for long enough to
  384. * prounounce on Stability. */
  385. int
  386. rep_hist_have_measured_enough_stability(void)
  387. {
  388. /* XXXX020 This doesn't do so well when we change our opinion
  389. * as to whether we're tracking router stability. */
  390. return started_tracking_stability < time(NULL) - 4*60*60;
  391. }
  392. /** Remember that we successfully extended from the OR with identity
  393. * digest <b>from_id</b> to the OR with identity digest
  394. * <b>to_name</b>.
  395. */
  396. void
  397. rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
  398. {
  399. link_history_t *hist;
  400. /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
  401. hist = get_link_history(from_id, to_id);
  402. if (!hist)
  403. return;
  404. ++hist->n_extend_ok;
  405. hist->changed = time(NULL);
  406. }
  407. /** Remember that we tried to extend from the OR with identity digest
  408. * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
  409. * failed.
  410. */
  411. void
  412. rep_hist_note_extend_failed(const char *from_id, const char *to_id)
  413. {
  414. link_history_t *hist;
  415. /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
  416. hist = get_link_history(from_id, to_id);
  417. if (!hist)
  418. return;
  419. ++hist->n_extend_fail;
  420. hist->changed = time(NULL);
  421. }
  422. /** Log all the reliability data we have remembered, with the chosen
  423. * severity.
  424. */
  425. void
  426. rep_hist_dump_stats(time_t now, int severity)
  427. {
  428. digestmap_iter_t *lhist_it;
  429. digestmap_iter_t *orhist_it;
  430. const char *name1, *name2, *digest1, *digest2;
  431. char hexdigest1[HEX_DIGEST_LEN+1];
  432. or_history_t *or_history;
  433. link_history_t *link_history;
  434. void *or_history_p, *link_history_p;
  435. double uptime;
  436. char buffer[2048];
  437. size_t len;
  438. int ret;
  439. unsigned long upt, downt;
  440. routerinfo_t *r;
  441. rep_history_clean(now - get_options()->RephistTrackTime);
  442. log(severity, LD_GENERAL, "--------------- Dumping history information:");
  443. for (orhist_it = digestmap_iter_init(history_map);
  444. !digestmap_iter_done(orhist_it);
  445. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  446. double s;
  447. long stability;
  448. digestmap_iter_get(orhist_it, &digest1, &or_history_p);
  449. or_history = (or_history_t*) or_history_p;
  450. if ((r = router_get_by_digest(digest1)))
  451. name1 = r->nickname;
  452. else
  453. name1 = "(unknown)";
  454. base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
  455. update_or_history(or_history, now);
  456. upt = or_history->uptime;
  457. downt = or_history->downtime;
  458. s = get_stability(or_history, now);
  459. stability = (long)s;
  460. if (upt+downt) {
  461. uptime = ((double)upt) / (upt+downt);
  462. } else {
  463. uptime=1.0;
  464. }
  465. log(severity, LD_GENERAL,
  466. "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
  467. "wmtbf %lu:%02lu:%02lu",
  468. name1, hexdigest1,
  469. or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
  470. upt, upt+downt, uptime*100.0,
  471. stability/3600, (stability/60)%60, stability%60);
  472. if (!digestmap_isempty(or_history->link_history_map)) {
  473. strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
  474. len = strlen(buffer);
  475. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  476. !digestmap_iter_done(lhist_it);
  477. lhist_it = digestmap_iter_next(or_history->link_history_map,
  478. lhist_it)) {
  479. digestmap_iter_get(lhist_it, &digest2, &link_history_p);
  480. if ((r = router_get_by_digest(digest2)))
  481. name2 = r->nickname;
  482. else
  483. name2 = "(unknown)";
  484. link_history = (link_history_t*) link_history_p;
  485. ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
  486. link_history->n_extend_ok,
  487. link_history->n_extend_ok+link_history->n_extend_fail);
  488. if (ret<0)
  489. break;
  490. else
  491. len += ret;
  492. }
  493. log(severity, LD_GENERAL, "%s", buffer);
  494. }
  495. }
  496. }
  497. /** Remove history info for routers/links that haven't changed since
  498. * <b>before</b>.
  499. */
  500. void
  501. rep_history_clean(time_t before)
  502. {
  503. int authority = authdir_mode(get_options());
  504. or_history_t *or_history;
  505. link_history_t *link_history;
  506. void *or_history_p, *link_history_p;
  507. digestmap_iter_t *orhist_it, *lhist_it;
  508. const char *d1, *d2;
  509. orhist_it = digestmap_iter_init(history_map);
  510. while (!digestmap_iter_done(orhist_it)) {
  511. int remove;
  512. digestmap_iter_get(orhist_it, &d1, &or_history_p);
  513. or_history = or_history_p;
  514. remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
  515. !or_history->start_of_run)
  516. : (or_history->changed < before);
  517. if (remove) {
  518. orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
  519. free_or_history(or_history);
  520. continue;
  521. }
  522. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  523. !digestmap_iter_done(lhist_it); ) {
  524. digestmap_iter_get(lhist_it, &d2, &link_history_p);
  525. link_history = link_history_p;
  526. if (link_history->changed < before) {
  527. lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
  528. lhist_it);
  529. rephist_total_alloc -= sizeof(link_history_t);
  530. tor_free(link_history);
  531. continue;
  532. }
  533. lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
  534. }
  535. orhist_it = digestmap_iter_next(history_map, orhist_it);
  536. }
  537. }
  538. /** Return a newly allocated string holding the filename in which we store
  539. * MTBF information. */
  540. static char *
  541. get_mtbf_filename(void)
  542. {
  543. const char *datadir = get_options()->DataDirectory;
  544. size_t len = strlen(datadir)+32;
  545. char *fn = tor_malloc(len);
  546. tor_snprintf(fn, len, "%s"PATH_SEPARATOR"router-stability", datadir);
  547. return fn;
  548. }
  549. /** Write MTBF data to disk. Returns 0 on success, negative on failure. */
  550. int
  551. rep_hist_record_mtbf_data(void)
  552. {
  553. char time_buf[ISO_TIME_LEN+1];
  554. digestmap_iter_t *orhist_it;
  555. const char *digest;
  556. void *or_history_p;
  557. or_history_t *hist;
  558. open_file_t *open_file = NULL;
  559. FILE *f;
  560. {
  561. char *filename = get_mtbf_filename();
  562. f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
  563. &open_file);
  564. tor_free(filename);
  565. if (!f)
  566. return -1;
  567. }
  568. /* File format is:
  569. * FormatLine *KeywordLine Data
  570. *
  571. * FormatLine = "format 1" NL
  572. * KeywordLine = Keyword SP Arguments NL
  573. * Data = "data" NL *RouterMTBFLine "." NL
  574. * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
  575. * TotalRunWeights [SP S=StartRunTime] NL
  576. */
  577. #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
  578. #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
  579. PUT("format 1\n");
  580. format_iso_time(time_buf, time(NULL));
  581. PRINTF((f, "stored-at %s\n", time_buf));
  582. if (started_tracking_stability) {
  583. format_iso_time(time_buf, started_tracking_stability);
  584. PRINTF((f, "tracked-since %s\n", time_buf));
  585. }
  586. if (stability_last_downrated) {
  587. format_iso_time(time_buf, stability_last_downrated);
  588. PRINTF((f, "last-downrated %s\n", time_buf));
  589. }
  590. PUT("data\n");
  591. for (orhist_it = digestmap_iter_init(history_map);
  592. !digestmap_iter_done(orhist_it);
  593. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  594. char dbuf[HEX_DIGEST_LEN+1];
  595. const char *t = NULL;
  596. digestmap_iter_get(orhist_it, &digest, &or_history_p);
  597. hist = (or_history_t*) or_history_p;
  598. base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
  599. if (hist->start_of_run) {
  600. format_iso_time(time_buf, hist->start_of_run);
  601. t = time_buf;
  602. }
  603. PRINTF((f, "%s %lu %.5lf%s%s\n",
  604. dbuf, hist->weighted_run_length, hist->total_run_weights,
  605. t ? " S=" : "", t ? t : ""));
  606. }
  607. PUT(".\n");
  608. #undef PUT
  609. #undef PRINTF
  610. return finish_writing_to_file(open_file);
  611. err:
  612. abort_writing_to_file(open_file);
  613. return -1;
  614. }
  615. /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
  616. * on failure. */
  617. int
  618. rep_hist_load_mtbf_data(time_t now)
  619. {
  620. /* XXXX won't handle being called while history is already populated. */
  621. smartlist_t *lines;
  622. const char *line = NULL;
  623. int r=0, i;
  624. time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
  625. time_t latest_possible_start = now;
  626. {
  627. char *filename = get_mtbf_filename();
  628. char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  629. tor_free(filename);
  630. if (!d)
  631. return -1;
  632. lines = smartlist_create();
  633. smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
  634. tor_free(d);
  635. }
  636. if (smartlist_len(lines)<4 || strcmp(smartlist_get(lines, 0), "format 1")) {
  637. log_warn(LD_GENERAL,"Unrecognized format in mtbf history file. Skipping.");
  638. goto err;
  639. }
  640. for (i = 1; i < smartlist_len(lines); ++i) {
  641. line = smartlist_get(lines, i);
  642. if (!strcmp(line, "data"))
  643. break;
  644. if (!strcmpstart(line, "last-downrated ")) {
  645. if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
  646. log_warn(LD_GENERAL,"Couldn't parse downrate time in mtbf "
  647. "history file.");
  648. }
  649. if (!strcmpstart(line, "stored-at ")) {
  650. if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
  651. log_warn(LD_GENERAL,"Couldn't parse stored time in mtbf "
  652. "history file.");
  653. }
  654. if (!strcmpstart(line, "tracked-since ")) {
  655. if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
  656. log_warn(LD_GENERAL,"Couldn't parse started-tracking time in mtbf "
  657. "history file.");
  658. }
  659. }
  660. if (last_downrated > now)
  661. last_downrated = now;
  662. if (tracked_since > now)
  663. tracked_since = now;
  664. if (!stored_at) {
  665. log_warn(LD_GENERAL, "No stored time recorded.");
  666. goto err;
  667. }
  668. if (line && !strcmp(line, "data"))
  669. ++i;
  670. for (; i < smartlist_len(lines); ++i) {
  671. char digest[DIGEST_LEN];
  672. char hexbuf[HEX_DIGEST_LEN+1];
  673. char timebuf[ISO_TIME_LEN+1];
  674. time_t start_of_run = 0;
  675. long wrl;
  676. double trw;
  677. int n;
  678. or_history_t *hist;
  679. line = smartlist_get(lines, i);
  680. if (!strcmp(line, "."))
  681. break;
  682. /* XXXX020 audit the heck out of my scanf usage. */
  683. n = sscanf(line, "%40s %ld %lf S=%10s %8s",
  684. hexbuf, &wrl, &trw, timebuf, timebuf+11);
  685. if (n != 3 && n != 5) {
  686. log_warn(LD_GENERAL, "Couldn't scan line %s", escaped(line));
  687. continue;
  688. }
  689. if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
  690. log_warn(LD_GENERAL, "Couldn't hex string %s", escaped(hexbuf));
  691. continue;
  692. }
  693. if (n == 5) {
  694. timebuf[10] = ' ';
  695. if (parse_iso_time(timebuf, &start_of_run)<0)
  696. log_warn(LD_GENERAL, "Couldn't parse time %s", escaped(timebuf));
  697. }
  698. hist = get_or_history(digest);
  699. if (!hist)
  700. continue;
  701. if (!start_of_run || start_of_run > stored_at) {
  702. hist->start_of_run = 0;
  703. } else {
  704. long run_length = stored_at - start_of_run;
  705. hist->start_of_run = now - run_length;
  706. }
  707. if (hist->start_of_run < latest_possible_start + wrl)
  708. latest_possible_start = hist->start_of_run - wrl;
  709. hist->weighted_run_length = wrl;
  710. hist->total_run_weights = trw;
  711. }
  712. if (strcmp(line, "."))
  713. log_warn(LD_GENERAL, "Truncated MTBF file.");
  714. if (!tracked_since)
  715. tracked_since = latest_possible_start;
  716. stability_last_downrated = last_downrated;
  717. started_tracking_stability = tracked_since;
  718. goto done;
  719. err:
  720. r = -1;
  721. done:
  722. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  723. smartlist_free(lines);
  724. return r;
  725. }
  726. /** For how many seconds do we keep track of individual per-second bandwidth
  727. * totals? */
  728. #define NUM_SECS_ROLLING_MEASURE 10
  729. /** How large are the intervals for which we track and report bandwidth use? */
  730. #define NUM_SECS_BW_SUM_INTERVAL (15*60)
  731. /** How far in the past do we remember and publish bandwidth use? */
  732. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
  733. /** How many bandwidth usage intervals do we remember? (derived) */
  734. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  735. /** Structure to track bandwidth use, and remember the maxima for a given
  736. * time period.
  737. */
  738. typedef struct bw_array_t {
  739. /** Observation array: Total number of bytes transferred in each of the last
  740. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  741. uint64_t obs[NUM_SECS_ROLLING_MEASURE];
  742. int cur_obs_idx; /**< Current position in obs. */
  743. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  744. uint64_t total_obs; /**< Total for all members of obs except
  745. * obs[cur_obs_idx] */
  746. uint64_t max_total; /**< Largest value that total_obs has taken on in the
  747. * current period. */
  748. uint64_t total_in_period; /**< Total bytes transferred in the current
  749. * period. */
  750. /** When does the next period begin? */
  751. time_t next_period;
  752. /** Where in 'maxima' should the maximum bandwidth usage for the current
  753. * period be stored? */
  754. int next_max_idx;
  755. /** How many values in maxima/totals have been set ever? */
  756. int num_maxes_set;
  757. /** Circular array of the maximum
  758. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  759. * NUM_TOTALS periods */
  760. uint64_t maxima[NUM_TOTALS];
  761. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  762. * periods */
  763. uint64_t totals[NUM_TOTALS];
  764. } bw_array_t;
  765. /** Shift the current period of b forward by one. */
  766. static void
  767. commit_max(bw_array_t *b)
  768. {
  769. /* Store total from current period. */
  770. b->totals[b->next_max_idx] = b->total_in_period;
  771. /* Store maximum from current period. */
  772. b->maxima[b->next_max_idx++] = b->max_total;
  773. /* Advance next_period and next_max_idx */
  774. b->next_period += NUM_SECS_BW_SUM_INTERVAL;
  775. if (b->next_max_idx == NUM_TOTALS)
  776. b->next_max_idx = 0;
  777. if (b->num_maxes_set < NUM_TOTALS)
  778. ++b->num_maxes_set;
  779. /* Reset max_total. */
  780. b->max_total = 0;
  781. /* Reset total_in_period. */
  782. b->total_in_period = 0;
  783. }
  784. /** Shift the current observation time of 'b' forward by one second. */
  785. static INLINE void
  786. advance_obs(bw_array_t *b)
  787. {
  788. int nextidx;
  789. uint64_t total;
  790. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  791. * seconds; adjust max_total as needed.*/
  792. total = b->total_obs + b->obs[b->cur_obs_idx];
  793. if (total > b->max_total)
  794. b->max_total = total;
  795. nextidx = b->cur_obs_idx+1;
  796. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  797. nextidx = 0;
  798. b->total_obs = total - b->obs[nextidx];
  799. b->obs[nextidx]=0;
  800. b->cur_obs_idx = nextidx;
  801. if (++b->cur_obs_time >= b->next_period)
  802. commit_max(b);
  803. }
  804. /** Add 'n' bytes to the number of bytes in b for second 'when'. */
  805. static INLINE void
  806. add_obs(bw_array_t *b, time_t when, uint64_t n)
  807. {
  808. /* Don't record data in the past. */
  809. if (when<b->cur_obs_time)
  810. return;
  811. /* If we're currently adding observations for an earlier second than
  812. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  813. * appropriate number of seconds, and do all the other housekeeping */
  814. while (when>b->cur_obs_time)
  815. advance_obs(b);
  816. b->obs[b->cur_obs_idx] += n;
  817. b->total_in_period += n;
  818. }
  819. /** Allocate, initialize, and return a new bw_array. */
  820. static bw_array_t *
  821. bw_array_new(void)
  822. {
  823. bw_array_t *b;
  824. time_t start;
  825. b = tor_malloc_zero(sizeof(bw_array_t));
  826. rephist_total_alloc += sizeof(bw_array_t);
  827. start = time(NULL);
  828. b->cur_obs_time = start;
  829. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  830. return b;
  831. }
  832. static bw_array_t *read_array = NULL;
  833. static bw_array_t *write_array = NULL;
  834. /** Set up read_array and write_array. */
  835. static void
  836. bw_arrays_init(void)
  837. {
  838. read_array = bw_array_new();
  839. write_array = bw_array_new();
  840. }
  841. /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
  842. *
  843. * Add num_bytes to the current running total for <b>when</b>.
  844. *
  845. * <b>when</b> can go back to time, but it's safe to ignore calls
  846. * earlier than the latest <b>when</b> you've heard of.
  847. */
  848. void
  849. rep_hist_note_bytes_written(int num_bytes, time_t when)
  850. {
  851. /* Maybe a circular array for recent seconds, and step to a new point
  852. * every time a new second shows up. Or simpler is to just to have
  853. * a normal array and push down each item every second; it's short.
  854. */
  855. /* When a new second has rolled over, compute the sum of the bytes we've
  856. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  857. * somewhere. See rep_hist_bandwidth_assess() below.
  858. */
  859. add_obs(write_array, when, num_bytes);
  860. }
  861. /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
  862. * (like rep_hist_note_bytes_written() above)
  863. */
  864. void
  865. rep_hist_note_bytes_read(int num_bytes, time_t when)
  866. {
  867. /* if we're smart, we can make this func and the one above share code */
  868. add_obs(read_array, when, num_bytes);
  869. }
  870. /** Helper: Return the largest value in b->maxima. (This is equal to the
  871. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  872. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  873. */
  874. static uint64_t
  875. find_largest_max(bw_array_t *b)
  876. {
  877. int i;
  878. uint64_t max;
  879. max=0;
  880. for (i=0; i<NUM_TOTALS; ++i) {
  881. if (b->maxima[i]>max)
  882. max = b->maxima[i];
  883. }
  884. return max;
  885. }
  886. /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  887. * seconds. Find one sum for reading and one for writing. They don't have
  888. * to be at the same time).
  889. *
  890. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  891. */
  892. int
  893. rep_hist_bandwidth_assess(void)
  894. {
  895. uint64_t w,r;
  896. r = find_largest_max(read_array);
  897. w = find_largest_max(write_array);
  898. if (r>w)
  899. return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
  900. else
  901. return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
  902. }
  903. /** Print the bandwidth history of b (either read_array or write_array)
  904. * into the buffer pointed to by buf. The format is simply comma
  905. * separated numbers, from oldest to newest.
  906. *
  907. * It returns the number of bytes written.
  908. */
  909. static size_t
  910. rep_hist_fill_bandwidth_history(char *buf, size_t len, bw_array_t *b)
  911. {
  912. char *cp = buf;
  913. int i, n;
  914. if (b->num_maxes_set <= b->next_max_idx) {
  915. /* We haven't been through the circular array yet; time starts at i=0.*/
  916. i = 0;
  917. } else {
  918. /* We've been around the array at least once. The next i to be
  919. overwritten is the oldest. */
  920. i = b->next_max_idx;
  921. }
  922. for (n=0; n<b->num_maxes_set; ++n,++i) {
  923. uint64_t total;
  924. if (i >= NUM_TOTALS)
  925. i -= NUM_TOTALS;
  926. tor_assert(i < NUM_TOTALS);
  927. /* Round the bandwidth used down to the nearest 1k. */
  928. total = b->totals[i] & ~0x3ff;
  929. if (n==(b->num_maxes_set-1))
  930. tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
  931. else
  932. tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
  933. cp += strlen(cp);
  934. }
  935. return cp-buf;
  936. }
  937. /** Allocate and return lines for representing this server's bandwidth
  938. * history in its descriptor.
  939. */
  940. char *
  941. rep_hist_get_bandwidth_lines(int for_extrainfo)
  942. {
  943. char *buf, *cp;
  944. char t[ISO_TIME_LEN+1];
  945. int r;
  946. bw_array_t *b;
  947. size_t len;
  948. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  949. len = (60+20*NUM_TOTALS)*2;
  950. buf = tor_malloc_zero(len);
  951. cp = buf;
  952. for (r=0;r<2;++r) {
  953. b = r?read_array:write_array;
  954. tor_assert(b);
  955. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  956. tor_snprintf(cp, len-(cp-buf), "%s%s %s (%d s) ",
  957. for_extrainfo ? "" : "opt ",
  958. r ? "read-history" : "write-history", t,
  959. NUM_SECS_BW_SUM_INTERVAL);
  960. cp += strlen(cp);
  961. cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
  962. strlcat(cp, "\n", len-(cp-buf));
  963. ++cp;
  964. }
  965. return buf;
  966. }
  967. /** Update <b>state</b> with the newest bandwidth history. */
  968. void
  969. rep_hist_update_state(or_state_t *state)
  970. {
  971. int len, r;
  972. char *buf, *cp;
  973. smartlist_t **s_values;
  974. time_t *s_begins;
  975. int *s_interval;
  976. bw_array_t *b;
  977. len = 20*NUM_TOTALS+1;
  978. buf = tor_malloc_zero(len);
  979. for (r=0;r<2;++r) {
  980. b = r?read_array:write_array;
  981. s_begins = r?&state->BWHistoryReadEnds :&state->BWHistoryWriteEnds;
  982. s_interval= r?&state->BWHistoryReadInterval:&state->BWHistoryWriteInterval;
  983. s_values = r?&state->BWHistoryReadValues :&state->BWHistoryWriteValues;
  984. if (*s_values) {
  985. SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
  986. smartlist_free(*s_values);
  987. }
  988. if (! server_mode(get_options())) {
  989. /* Clients don't need to store bandwidth history persistently;
  990. * force these values to the defaults. */
  991. /* FFFF we should pull the default out of config.c's state table,
  992. * so we don't have two defaults. */
  993. if (*s_begins != 0 || *s_interval != 900) {
  994. time_t now = time(NULL);
  995. time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
  996. or_state_mark_dirty(state, save_at);
  997. }
  998. *s_begins = 0;
  999. *s_interval = 900;
  1000. *s_values = smartlist_create();
  1001. continue;
  1002. }
  1003. *s_begins = b->next_period;
  1004. *s_interval = NUM_SECS_BW_SUM_INTERVAL;
  1005. cp = buf;
  1006. cp += rep_hist_fill_bandwidth_history(cp, len, b);
  1007. tor_snprintf(cp, len-(cp-buf), cp == buf ? U64_FORMAT : ","U64_FORMAT,
  1008. U64_PRINTF_ARG(b->total_in_period));
  1009. *s_values = smartlist_create();
  1010. if (server_mode(get_options()))
  1011. smartlist_split_string(*s_values, buf, ",", SPLIT_SKIP_SPACE, 0);
  1012. }
  1013. tor_free(buf);
  1014. if (server_mode(get_options())) {
  1015. or_state_mark_dirty(get_or_state(), time(NULL)+(2*3600));
  1016. }
  1017. }
  1018. /** Set bandwidth history from our saved state. */
  1019. int
  1020. rep_hist_load_state(or_state_t *state, char **err)
  1021. {
  1022. time_t s_begins, start;
  1023. time_t now = time(NULL);
  1024. uint64_t v;
  1025. int r,i,ok;
  1026. int all_ok = 1;
  1027. int s_interval;
  1028. smartlist_t *s_values;
  1029. bw_array_t *b;
  1030. /* Assert they already have been malloced */
  1031. tor_assert(read_array && write_array);
  1032. for (r=0;r<2;++r) {
  1033. b = r?read_array:write_array;
  1034. s_begins = r?state->BWHistoryReadEnds:state->BWHistoryWriteEnds;
  1035. s_interval = r?state->BWHistoryReadInterval:state->BWHistoryWriteInterval;
  1036. s_values = r?state->BWHistoryReadValues:state->BWHistoryWriteValues;
  1037. if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
  1038. start = s_begins - s_interval*(smartlist_len(s_values));
  1039. if (start > now)
  1040. continue;
  1041. b->cur_obs_time = start;
  1042. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  1043. SMARTLIST_FOREACH(s_values, char *, cp, {
  1044. v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
  1045. if (!ok) {
  1046. all_ok=0;
  1047. log_notice(LD_GENERAL, "Could not parse '%s' into a number.'", cp);
  1048. }
  1049. if (start < now) {
  1050. add_obs(b, start, v);
  1051. start += NUM_SECS_BW_SUM_INTERVAL;
  1052. }
  1053. });
  1054. }
  1055. /* Clean up maxima and observed */
  1056. /* Do we really want to zero this for the purpose of max capacity? */
  1057. for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
  1058. b->obs[i] = 0;
  1059. }
  1060. b->total_obs = 0;
  1061. for (i=0; i<NUM_TOTALS; ++i) {
  1062. b->maxima[i] = 0;
  1063. }
  1064. b->max_total = 0;
  1065. }
  1066. if (!all_ok) {
  1067. *err = tor_strdup("Parsing of bandwidth history values failed");
  1068. /* and create fresh arrays */
  1069. tor_free(read_array);
  1070. tor_free(write_array);
  1071. read_array = bw_array_new();
  1072. write_array = bw_array_new();
  1073. return -1;
  1074. }
  1075. return 0;
  1076. }
  1077. /*********************************************************************/
  1078. /** A list of port numbers that have been used recently. */
  1079. static smartlist_t *predicted_ports_list=NULL;
  1080. /** The corresponding most recently used time for each port. */
  1081. static smartlist_t *predicted_ports_times=NULL;
  1082. /** We just got an application request for a connection with
  1083. * port <b>port</b>. Remember it for the future, so we can keep
  1084. * some circuits open that will exit to this port.
  1085. */
  1086. static void
  1087. add_predicted_port(uint16_t port, time_t now)
  1088. {
  1089. /* XXXX we could just use uintptr_t here, I think. */
  1090. uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
  1091. time_t *tmp_time = tor_malloc(sizeof(time_t));
  1092. *tmp_port = port;
  1093. *tmp_time = now;
  1094. rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
  1095. smartlist_add(predicted_ports_list, tmp_port);
  1096. smartlist_add(predicted_ports_times, tmp_time);
  1097. }
  1098. /** Initialize whatever memory and structs are needed for predicting
  1099. * which ports will be used. Also seed it with port 80, so we'll build
  1100. * circuits on start-up.
  1101. */
  1102. static void
  1103. predicted_ports_init(void)
  1104. {
  1105. predicted_ports_list = smartlist_create();
  1106. predicted_ports_times = smartlist_create();
  1107. add_predicted_port(80, time(NULL)); /* add one to kickstart us */
  1108. }
  1109. /** Free whatever memory is needed for predicting which ports will
  1110. * be used.
  1111. */
  1112. static void
  1113. predicted_ports_free(void)
  1114. {
  1115. rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
  1116. SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
  1117. smartlist_free(predicted_ports_list);
  1118. rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
  1119. SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
  1120. smartlist_free(predicted_ports_times);
  1121. }
  1122. /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
  1123. * This is used for predicting what sorts of streams we'll make in the
  1124. * future and making exit circuits to anticipate that.
  1125. */
  1126. void
  1127. rep_hist_note_used_port(uint16_t port, time_t now)
  1128. {
  1129. int i;
  1130. uint16_t *tmp_port;
  1131. time_t *tmp_time;
  1132. tor_assert(predicted_ports_list);
  1133. tor_assert(predicted_ports_times);
  1134. if (!port) /* record nothing */
  1135. return;
  1136. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  1137. tmp_port = smartlist_get(predicted_ports_list, i);
  1138. tmp_time = smartlist_get(predicted_ports_times, i);
  1139. if (*tmp_port == port) {
  1140. *tmp_time = now;
  1141. return;
  1142. }
  1143. }
  1144. /* it's not there yet; we need to add it */
  1145. add_predicted_port(port, now);
  1146. }
  1147. /** For this long after we've seen a request for a given port, assume that
  1148. * we'll want to make connections to the same port in the future. */
  1149. #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
  1150. /** Return a pointer to the list of port numbers that
  1151. * are likely to be asked for in the near future.
  1152. *
  1153. * The caller promises not to mess with it.
  1154. */
  1155. smartlist_t *
  1156. rep_hist_get_predicted_ports(time_t now)
  1157. {
  1158. int i;
  1159. uint16_t *tmp_port;
  1160. time_t *tmp_time;
  1161. tor_assert(predicted_ports_list);
  1162. tor_assert(predicted_ports_times);
  1163. /* clean out obsolete entries */
  1164. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  1165. tmp_time = smartlist_get(predicted_ports_times, i);
  1166. if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
  1167. tmp_port = smartlist_get(predicted_ports_list, i);
  1168. log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
  1169. smartlist_del(predicted_ports_list, i);
  1170. smartlist_del(predicted_ports_times, i);
  1171. rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
  1172. tor_free(tmp_port);
  1173. tor_free(tmp_time);
  1174. i--;
  1175. }
  1176. }
  1177. return predicted_ports_list;
  1178. }
  1179. /** The user asked us to do a resolve. Rather than keeping track of
  1180. * timings and such of resolves, we fake it for now by making treating
  1181. * it the same way as a connection to port 80. This way we will continue
  1182. * to have circuits lying around if the user only uses Tor for resolves.
  1183. */
  1184. void
  1185. rep_hist_note_used_resolve(time_t now)
  1186. {
  1187. rep_hist_note_used_port(80, now);
  1188. }
  1189. /** The last time at which we needed an internal circ. */
  1190. static time_t predicted_internal_time = 0;
  1191. /** The last time we needed an internal circ with good uptime. */
  1192. static time_t predicted_internal_uptime_time = 0;
  1193. /** The last time we needed an internal circ with good capacity. */
  1194. static time_t predicted_internal_capacity_time = 0;
  1195. /** Remember that we used an internal circ at time <b>now</b>. */
  1196. void
  1197. rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
  1198. {
  1199. predicted_internal_time = now;
  1200. if (need_uptime)
  1201. predicted_internal_uptime_time = now;
  1202. if (need_capacity)
  1203. predicted_internal_capacity_time = now;
  1204. }
  1205. /** Return 1 if we've used an internal circ recently; else return 0. */
  1206. int
  1207. rep_hist_get_predicted_internal(time_t now, int *need_uptime,
  1208. int *need_capacity)
  1209. {
  1210. if (!predicted_internal_time) { /* initialize it */
  1211. predicted_internal_time = now;
  1212. predicted_internal_uptime_time = now;
  1213. predicted_internal_capacity_time = now;
  1214. }
  1215. if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
  1216. return 0; /* too long ago */
  1217. if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
  1218. *need_uptime = 1;
  1219. if (predicted_internal_capacity_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
  1220. *need_capacity = 1;
  1221. return 1;
  1222. }
  1223. /** Any ports used lately? These are pre-seeded if we just started
  1224. * up or if we're running a hidden service. */
  1225. int
  1226. any_predicted_circuits(time_t now)
  1227. {
  1228. return smartlist_len(predicted_ports_list) ||
  1229. predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now;
  1230. }
  1231. /** Return 1 if we have no need for circuits currently, else return 0. */
  1232. int
  1233. rep_hist_circbuilding_dormant(time_t now)
  1234. {
  1235. if (any_predicted_circuits(now))
  1236. return 0;
  1237. /* see if we'll still need to build testing circuits */
  1238. if (server_mode(get_options()) && !check_whether_orport_reachable())
  1239. return 0;
  1240. if (!check_whether_dirport_reachable())
  1241. return 0;
  1242. return 1;
  1243. }
  1244. static uint32_t n_signed_dir_objs = 0;
  1245. static uint32_t n_signed_routerdescs = 0;
  1246. static uint32_t n_verified_dir_objs = 0;
  1247. static uint32_t n_verified_routerdescs = 0;
  1248. static uint32_t n_onionskins_encrypted = 0;
  1249. static uint32_t n_onionskins_decrypted = 0;
  1250. static uint32_t n_tls_client_handshakes = 0;
  1251. static uint32_t n_tls_server_handshakes = 0;
  1252. static uint32_t n_rend_client_ops = 0;
  1253. static uint32_t n_rend_mid_ops = 0;
  1254. static uint32_t n_rend_server_ops = 0;
  1255. /** Increment the count of the number of times we've done <b>operation</b>. */
  1256. void
  1257. note_crypto_pk_op(pk_op_t operation)
  1258. {
  1259. switch (operation)
  1260. {
  1261. case SIGN_DIR:
  1262. n_signed_dir_objs++;
  1263. break;
  1264. case SIGN_RTR:
  1265. n_signed_routerdescs++;
  1266. break;
  1267. case VERIFY_DIR:
  1268. n_verified_dir_objs++;
  1269. break;
  1270. case VERIFY_RTR:
  1271. n_verified_routerdescs++;
  1272. break;
  1273. case ENC_ONIONSKIN:
  1274. n_onionskins_encrypted++;
  1275. break;
  1276. case DEC_ONIONSKIN:
  1277. n_onionskins_decrypted++;
  1278. break;
  1279. case TLS_HANDSHAKE_C:
  1280. n_tls_client_handshakes++;
  1281. break;
  1282. case TLS_HANDSHAKE_S:
  1283. n_tls_server_handshakes++;
  1284. break;
  1285. case REND_CLIENT:
  1286. n_rend_client_ops++;
  1287. break;
  1288. case REND_MID:
  1289. n_rend_mid_ops++;
  1290. break;
  1291. case REND_SERVER:
  1292. n_rend_server_ops++;
  1293. break;
  1294. default:
  1295. log_warn(LD_BUG, "Unknown pk operation %d", operation);
  1296. }
  1297. }
  1298. /** Log the number of times we've done each public/private-key operation. */
  1299. void
  1300. dump_pk_ops(int severity)
  1301. {
  1302. log(severity, LD_GENERAL,
  1303. "PK operations: %lu directory objects signed, "
  1304. "%lu directory objects verified, "
  1305. "%lu routerdescs signed, "
  1306. "%lu routerdescs verified, "
  1307. "%lu onionskins encrypted, "
  1308. "%lu onionskins decrypted, "
  1309. "%lu client-side TLS handshakes, "
  1310. "%lu server-side TLS handshakes, "
  1311. "%lu rendezvous client operations, "
  1312. "%lu rendezvous middle operations, "
  1313. "%lu rendezvous server operations.",
  1314. (unsigned long) n_signed_dir_objs,
  1315. (unsigned long) n_verified_dir_objs,
  1316. (unsigned long) n_signed_routerdescs,
  1317. (unsigned long) n_verified_routerdescs,
  1318. (unsigned long) n_onionskins_encrypted,
  1319. (unsigned long) n_onionskins_decrypted,
  1320. (unsigned long) n_tls_client_handshakes,
  1321. (unsigned long) n_tls_server_handshakes,
  1322. (unsigned long) n_rend_client_ops,
  1323. (unsigned long) n_rend_mid_ops,
  1324. (unsigned long) n_rend_server_ops);
  1325. }
  1326. /** Free all storage held by the OR/link history caches, by the
  1327. * bandwidth history arrays, or by the port history. */
  1328. void
  1329. rep_hist_free_all(void)
  1330. {
  1331. digestmap_free(history_map, free_or_history);
  1332. tor_free(read_array);
  1333. tor_free(write_array);
  1334. predicted_ports_free();
  1335. }
  1336. /****************** hidden service usage statistics ******************/
  1337. /** How large are the intervals for which we track and report hidden service
  1338. * use? */
  1339. #define NUM_SECS_HS_USAGE_SUM_INTERVAL (15*60)
  1340. /** How far in the past do we remember and publish hidden service use? */
  1341. #define NUM_SECS_HS_USAGE_SUM_IS_VALID (24*60*60)
  1342. /** How many hidden service usage intervals do we remember? (derived) */
  1343. #define NUM_TOTALS_HS_USAGE (NUM_SECS_HS_USAGE_SUM_IS_VALID/ \
  1344. NUM_SECS_HS_USAGE_SUM_INTERVAL)
  1345. /** List element containing a service id and the count. */
  1346. typedef struct hs_usage_list_elem_t {
  1347. /** Service id of this elem. */
  1348. char service_id[REND_SERVICE_ID_LEN+1];
  1349. /** Number of occurrences for the given service id. */
  1350. uint32_t count;
  1351. /* Pointer to next list elem */
  1352. struct hs_usage_list_elem_t *next;
  1353. } hs_usage_list_elem_t;
  1354. /* Ordered list that stores service ids and the number of observations. It is
  1355. * ordered by the number of occurrences in descending order. Its purpose is to
  1356. * calculate the frequency distribution when the period is over. */
  1357. typedef struct hs_usage_list_t {
  1358. /* Pointer to the first element in the list. */
  1359. hs_usage_list_elem_t *start;
  1360. /* Number of total occurrences for all list elements. */
  1361. uint32_t total_count;
  1362. /* Number of service ids, i.e. number of list elements. */
  1363. uint32_t total_service_ids;
  1364. } hs_usage_list_t;
  1365. /** Tracks service-related observations in the current period and their
  1366. * history. */
  1367. typedef struct hs_usage_service_related_observation_t {
  1368. /** Ordered list that stores service ids and the number of observations in
  1369. * the current period. It is ordered by the number of occurrences in
  1370. * descending order. Its purpose is to calculate the frequency distribution
  1371. * when the period is over. */
  1372. hs_usage_list_t *list;
  1373. /** Circular arrays that store the history of observations. totals stores all
  1374. * observations, twenty (ten, five) the number of observations related to a
  1375. * service id being accounted for the top 20 (10, 5) percent of all
  1376. * observations. */
  1377. uint32_t totals[NUM_TOTALS_HS_USAGE];
  1378. uint32_t five[NUM_TOTALS_HS_USAGE];
  1379. uint32_t ten[NUM_TOTALS_HS_USAGE];
  1380. uint32_t twenty[NUM_TOTALS_HS_USAGE];
  1381. } hs_usage_service_related_observation_t;
  1382. /** Tracks the history of general period-related observations, i.e. those that
  1383. * cannot be related to a specific service id. */
  1384. typedef struct hs_usage_general_period_related_observations_t {
  1385. /** Circular array that stores the history of observations. */
  1386. uint32_t totals[NUM_TOTALS_HS_USAGE];
  1387. } hs_usage_general_period_related_observations_t;
  1388. /** Keeps information about the current observation period and its relation to
  1389. * the histories of observations. */
  1390. typedef struct hs_usage_current_observation_period_t {
  1391. /** Where do we write the next history entry? */
  1392. int next_idx;
  1393. /** How many values in history have been set ever? (upper bound!) */
  1394. int num_set;
  1395. /** When did this period begin? */
  1396. time_t start_of_current_period;
  1397. /** When does the next period begin? */
  1398. time_t start_of_next_period;
  1399. } hs_usage_current_observation_period_t;
  1400. static hs_usage_current_observation_period_t *current_period = NULL;
  1401. static hs_usage_service_related_observation_t *publish_total = NULL;
  1402. static hs_usage_service_related_observation_t *publish_novel = NULL;
  1403. static hs_usage_service_related_observation_t *fetch_total = NULL;
  1404. static hs_usage_service_related_observation_t *fetch_successful = NULL;
  1405. static hs_usage_general_period_related_observations_t *descs = NULL;
  1406. /** Creates an empty ordered list element. */
  1407. static hs_usage_list_elem_t *
  1408. hs_usage_list_elem_new(void)
  1409. {
  1410. hs_usage_list_elem_t *e;
  1411. e = tor_malloc_zero(sizeof(hs_usage_list_elem_t));
  1412. rephist_total_alloc += sizeof(hs_usage_list_elem_t);
  1413. e->count = 1;
  1414. e->next = NULL;
  1415. return e;
  1416. }
  1417. /** Creates an empty ordered list. */
  1418. static hs_usage_list_t *
  1419. hs_usage_list_new(void)
  1420. {
  1421. hs_usage_list_t *l;
  1422. l = tor_malloc_zero(sizeof(hs_usage_list_t));
  1423. rephist_total_alloc += sizeof(hs_usage_list_t);
  1424. l->start = NULL;
  1425. l->total_count = 0;
  1426. l->total_service_ids = 0;
  1427. return l;
  1428. }
  1429. /** Creates an empty structure for storing service-related observations. */
  1430. static hs_usage_service_related_observation_t *
  1431. hs_usage_service_related_observation_new(void)
  1432. {
  1433. hs_usage_service_related_observation_t *h;
  1434. h = tor_malloc_zero(sizeof(hs_usage_service_related_observation_t));
  1435. rephist_total_alloc += sizeof(hs_usage_service_related_observation_t);
  1436. h->list = hs_usage_list_new();
  1437. return h;
  1438. }
  1439. /** Creates an empty structure for storing general period-related
  1440. * observations. */
  1441. static hs_usage_general_period_related_observations_t *
  1442. hs_usage_general_period_related_observations_new(void)
  1443. {
  1444. hs_usage_general_period_related_observations_t *p;
  1445. p = tor_malloc_zero(sizeof(hs_usage_general_period_related_observations_t));
  1446. rephist_total_alloc+= sizeof(hs_usage_general_period_related_observations_t);
  1447. return p;
  1448. }
  1449. /** Creates an empty structure for storing period-specific information. */
  1450. static hs_usage_current_observation_period_t *
  1451. hs_usage_current_observation_period_new(void)
  1452. {
  1453. hs_usage_current_observation_period_t *c;
  1454. time_t now;
  1455. c = tor_malloc_zero(sizeof(hs_usage_current_observation_period_t));
  1456. rephist_total_alloc += sizeof(hs_usage_current_observation_period_t);
  1457. now = time(NULL);
  1458. c->start_of_current_period = now;
  1459. c->start_of_next_period = now + NUM_SECS_HS_USAGE_SUM_INTERVAL;
  1460. return c;
  1461. }
  1462. /** Initializes the structures for collecting hidden service usage data. */
  1463. static void
  1464. hs_usage_init(void)
  1465. {
  1466. current_period = hs_usage_current_observation_period_new();
  1467. publish_total = hs_usage_service_related_observation_new();
  1468. publish_novel = hs_usage_service_related_observation_new();
  1469. fetch_total = hs_usage_service_related_observation_new();
  1470. fetch_successful = hs_usage_service_related_observation_new();
  1471. descs = hs_usage_general_period_related_observations_new();
  1472. }
  1473. /** Clears the given ordered list by resetting its attributes and releasing
  1474. * the memory allocated by its elements. */
  1475. static void
  1476. hs_usage_list_clear(hs_usage_list_t *lst)
  1477. {
  1478. /* walk through elements and free memory */
  1479. hs_usage_list_elem_t *current = lst->start;
  1480. hs_usage_list_elem_t *tmp;
  1481. while (current != NULL) {
  1482. tmp = current->next;
  1483. rephist_total_alloc -= sizeof(hs_usage_list_elem_t);
  1484. tor_free(current);
  1485. current = tmp;
  1486. }
  1487. /* reset attributes */
  1488. lst->start = NULL;
  1489. lst->total_count = 0;
  1490. lst->total_service_ids = 0;
  1491. return;
  1492. }
  1493. /** Frees the memory used by the given list. */
  1494. static void
  1495. hs_usage_list_free(hs_usage_list_t *lst)
  1496. {
  1497. if (!lst)
  1498. return;
  1499. hs_usage_list_clear(lst);
  1500. rephist_total_alloc -= sizeof(hs_usage_list_t);
  1501. tor_free(lst);
  1502. }
  1503. /** Frees the memory used by the given service-related observations. */
  1504. static void
  1505. hs_usage_service_related_observation_free(
  1506. hs_usage_service_related_observation_t *s)
  1507. {
  1508. if (!s)
  1509. return;
  1510. hs_usage_list_free(s->list);
  1511. rephist_total_alloc -= sizeof(hs_usage_service_related_observation_t);
  1512. tor_free(s);
  1513. }
  1514. /** Frees the memory used by the given period-specific observations. */
  1515. static void
  1516. hs_usage_general_period_related_observations_free(
  1517. hs_usage_general_period_related_observations_t *s)
  1518. {
  1519. rephist_total_alloc-=sizeof(hs_usage_general_period_related_observations_t);
  1520. tor_free(s);
  1521. }
  1522. /** Frees the memory used by period-specific information. */
  1523. static void
  1524. hs_usage_current_observation_period_free(
  1525. hs_usage_current_observation_period_t *s)
  1526. {
  1527. rephist_total_alloc -= sizeof(hs_usage_current_observation_period_t);
  1528. tor_free(s);
  1529. }
  1530. /** Frees all memory that was used for collecting hidden service usage data. */
  1531. void
  1532. hs_usage_free_all(void)
  1533. {
  1534. hs_usage_general_period_related_observations_free(descs);
  1535. descs = NULL;
  1536. hs_usage_service_related_observation_free(fetch_successful);
  1537. hs_usage_service_related_observation_free(fetch_total);
  1538. hs_usage_service_related_observation_free(publish_novel);
  1539. hs_usage_service_related_observation_free(publish_total);
  1540. fetch_successful = fetch_total = publish_novel = publish_total = NULL;
  1541. hs_usage_current_observation_period_free(current_period);
  1542. current_period = NULL;
  1543. }
  1544. /** Inserts a new occurrence for the given service id to the given ordered
  1545. * list. */
  1546. static void
  1547. hs_usage_insert_value(hs_usage_list_t *lst, const char *service_id)
  1548. {
  1549. /* search if there is already an elem with same service_id in list */
  1550. hs_usage_list_elem_t *current = lst->start;
  1551. hs_usage_list_elem_t *previous = NULL;
  1552. while (current != NULL && strcasecmp(current->service_id,service_id)) {
  1553. previous = current;
  1554. current = current->next;
  1555. }
  1556. /* found an element with same service_id? */
  1557. if (current == NULL) {
  1558. /* not found! append to end (which could also be the end of a zero-length
  1559. * list), don't need to sort (1 is smallest value). */
  1560. /* create elem */
  1561. hs_usage_list_elem_t *e = hs_usage_list_elem_new();
  1562. /* update list attributes (one new elem, one new occurrence) */
  1563. lst->total_count++;
  1564. lst->total_service_ids++;
  1565. /* copy service id to elem */
  1566. strlcpy(e->service_id,service_id,sizeof(e->service_id));
  1567. /* let either l->start or previously last elem point to new elem */
  1568. if (lst->start == NULL) {
  1569. /* this is the first elem */
  1570. lst->start = e;
  1571. } else {
  1572. /* there were elems in the list before */
  1573. previous->next = e;
  1574. }
  1575. } else {
  1576. /* found! add occurrence to elem and consider resorting */
  1577. /* update list attributes (no new elem, but one new occurrence) */
  1578. lst->total_count++;
  1579. /* add occurrence to elem */
  1580. current->count++;
  1581. /* is it another than the first list elem? and has previous elem fewer
  1582. * count than current? then we need to resort */
  1583. if (previous != NULL && previous->count < current->count) {
  1584. /* yes! we need to resort */
  1585. /* remove current elem first */
  1586. previous->next = current->next;
  1587. /* can we prepend elem to all other elements? */
  1588. if (lst->start->count <= current->count) {
  1589. /* yes! prepend elem */
  1590. current->next = lst->start;
  1591. lst->start = current;
  1592. } else {
  1593. /* no! walk through list a second time and insert at correct place */
  1594. hs_usage_list_elem_t *insert_current = lst->start->next;
  1595. hs_usage_list_elem_t *insert_previous = lst->start;
  1596. while (insert_current != NULL &&
  1597. insert_current->count > current->count) {
  1598. insert_previous = insert_current;
  1599. insert_current = insert_current->next;
  1600. }
  1601. /* insert here */
  1602. current->next = insert_current;
  1603. insert_previous->next = current;
  1604. }
  1605. }
  1606. }
  1607. }
  1608. /** Writes the current service-related observations to the history array and
  1609. * clears the observations of the current period. */
  1610. static void
  1611. hs_usage_write_service_related_observations_to_history(
  1612. hs_usage_current_observation_period_t *p,
  1613. hs_usage_service_related_observation_t *h)
  1614. {
  1615. /* walk through the first 20 % of list elements and calculate frequency
  1616. * distributions */
  1617. /* maximum indices for the three frequencies */
  1618. int five_percent_idx = h->list->total_service_ids/20;
  1619. int ten_percent_idx = h->list->total_service_ids/10;
  1620. int twenty_percent_idx = h->list->total_service_ids/5;
  1621. /* temp values */
  1622. uint32_t five_percent = 0;
  1623. uint32_t ten_percent = 0;
  1624. uint32_t twenty_percent = 0;
  1625. /* walk through list */
  1626. hs_usage_list_elem_t *current = h->list->start;
  1627. int i=0;
  1628. while (current != NULL && i <= twenty_percent_idx) {
  1629. twenty_percent += current->count;
  1630. if (i <= ten_percent_idx)
  1631. ten_percent += current->count;
  1632. if (i <= five_percent_idx)
  1633. five_percent += current->count;
  1634. current = current->next;
  1635. i++;
  1636. }
  1637. /* copy frequencies */
  1638. h->twenty[p->next_idx] = twenty_percent;
  1639. h->ten[p->next_idx] = ten_percent;
  1640. h->five[p->next_idx] = five_percent;
  1641. /* copy total number of observations */
  1642. h->totals[p->next_idx] = h->list->total_count;
  1643. /* free memory of old list */
  1644. hs_usage_list_clear(h->list);
  1645. }
  1646. /** Advances to next observation period. */
  1647. static void
  1648. hs_usage_advance_current_observation_period(void)
  1649. {
  1650. /* aggregate observations to history, including frequency distribution
  1651. * arrays */
  1652. hs_usage_write_service_related_observations_to_history(
  1653. current_period, publish_total);
  1654. hs_usage_write_service_related_observations_to_history(
  1655. current_period, publish_novel);
  1656. hs_usage_write_service_related_observations_to_history(
  1657. current_period, fetch_total);
  1658. hs_usage_write_service_related_observations_to_history(
  1659. current_period, fetch_successful);
  1660. /* write current number of descriptors to descs history */
  1661. descs->totals[current_period->next_idx] = rend_cache_size();
  1662. /* advance to next period */
  1663. current_period->next_idx++;
  1664. if (current_period->next_idx == NUM_TOTALS_HS_USAGE)
  1665. current_period->next_idx = 0;
  1666. if (current_period->num_set < NUM_TOTALS_HS_USAGE)
  1667. ++current_period->num_set;
  1668. current_period->start_of_current_period=current_period->start_of_next_period;
  1669. current_period->start_of_next_period += NUM_SECS_HS_USAGE_SUM_INTERVAL;
  1670. }
  1671. /** Checks if the current period is up to date, and if not, advances it. */
  1672. static void
  1673. hs_usage_check_if_current_period_is_up_to_date(time_t now)
  1674. {
  1675. while (now > current_period->start_of_next_period) {
  1676. hs_usage_advance_current_observation_period();
  1677. }
  1678. }
  1679. /** Adds a service-related observation, maybe after advancing to next
  1680. * observation period. */
  1681. static void
  1682. hs_usage_add_service_related_observation(
  1683. hs_usage_service_related_observation_t *h,
  1684. time_t now,
  1685. const char *service_id)
  1686. {
  1687. if (now < current_period->start_of_current_period) {
  1688. /* don't record old data */
  1689. return;
  1690. }
  1691. /* check if we are up-to-date */
  1692. hs_usage_check_if_current_period_is_up_to_date(now);
  1693. /* add observation */
  1694. hs_usage_insert_value(h->list, service_id);
  1695. }
  1696. /** Adds the observation of storing a rendezvous service descriptor to our
  1697. * cache in our role as HS authoritative directory. */
  1698. void
  1699. hs_usage_note_publish_total(const char *service_id, time_t now)
  1700. {
  1701. hs_usage_add_service_related_observation(publish_total, now, service_id);
  1702. }
  1703. /** Adds the observation of storing a novel rendezvous service descriptor to
  1704. * our cache in our role as HS authoritative directory. */
  1705. void
  1706. hs_usage_note_publish_novel(const char *service_id, time_t now)
  1707. {
  1708. hs_usage_add_service_related_observation(publish_novel, now, service_id);
  1709. }
  1710. /** Adds the observation of being requested for a rendezvous service descriptor
  1711. * in our role as HS authoritative directory. */
  1712. void
  1713. hs_usage_note_fetch_total(const char *service_id, time_t now)
  1714. {
  1715. hs_usage_add_service_related_observation(fetch_total, now, service_id);
  1716. }
  1717. /** Adds the observation of being requested for a rendezvous service descriptor
  1718. * in our role as HS authoritative directory and being able to answer that
  1719. * request successfully. */
  1720. void
  1721. hs_usage_note_fetch_successful(const char *service_id, time_t now)
  1722. {
  1723. hs_usage_add_service_related_observation(fetch_successful, now, service_id);
  1724. }
  1725. /** Writes the given circular array to a string. */
  1726. static size_t
  1727. hs_usage_format_history(char *buf, size_t len, uint32_t *data)
  1728. {
  1729. char *cp = buf; /* pointer where we are in the buffer */
  1730. int i, n;
  1731. if (current_period->num_set <= current_period->next_idx) {
  1732. i = 0; /* not been through circular array */
  1733. } else {
  1734. i = current_period->next_idx;
  1735. }
  1736. for (n = 0; n < current_period->num_set; ++n,++i) {
  1737. if (i >= NUM_TOTALS_HS_USAGE)
  1738. i -= NUM_TOTALS_HS_USAGE;
  1739. tor_assert(i < NUM_TOTALS_HS_USAGE);
  1740. if (n == (current_period->num_set-1))
  1741. tor_snprintf(cp, len-(cp-buf), "%d", data[i]);
  1742. else
  1743. tor_snprintf(cp, len-(cp-buf), "%d,", data[i]);
  1744. cp += strlen(cp);
  1745. }
  1746. return cp-buf;
  1747. }
  1748. /** Writes the complete usage history as hidden service authoritative directory
  1749. * to a string. */
  1750. static char *
  1751. hs_usage_format_statistics(void)
  1752. {
  1753. char *buf, *cp, *s = NULL;
  1754. char t[ISO_TIME_LEN+1];
  1755. int r;
  1756. uint32_t *data = NULL;
  1757. size_t len;
  1758. len = (70+20*NUM_TOTALS_HS_USAGE)*11;
  1759. buf = tor_malloc_zero(len);
  1760. cp = buf;
  1761. for (r = 0; r < 11; ++r) {
  1762. switch (r) {
  1763. case 0:
  1764. s = (char*) "publish-total-history";
  1765. data = publish_total->totals;
  1766. break;
  1767. case 1:
  1768. s = (char*) "publish-novel-history";
  1769. data = publish_novel->totals;
  1770. break;
  1771. case 2:
  1772. s = (char*) "publish-top-5-percent-history";
  1773. data = publish_total->five;
  1774. break;
  1775. case 3:
  1776. s = (char*) "publish-top-10-percent-history";
  1777. data = publish_total->ten;
  1778. break;
  1779. case 4:
  1780. s = (char*) "publish-top-20-percent-history";
  1781. data = publish_total->twenty;
  1782. break;
  1783. case 5:
  1784. s = (char*) "fetch-total-history";
  1785. data = fetch_total->totals;
  1786. break;
  1787. case 6:
  1788. s = (char*) "fetch-successful-history";
  1789. data = fetch_successful->totals;
  1790. break;
  1791. case 7:
  1792. s = (char*) "fetch-top-5-percent-history";
  1793. data = fetch_total->five;
  1794. break;
  1795. case 8:
  1796. s = (char*) "fetch-top-10-percent-history";
  1797. data = fetch_total->ten;
  1798. break;
  1799. case 9:
  1800. s = (char*) "fetch-top-20-percent-history";
  1801. data = fetch_total->twenty;
  1802. break;
  1803. case 10:
  1804. s = (char*) "desc-total-history";
  1805. data = descs->totals;
  1806. break;
  1807. }
  1808. format_iso_time(t, current_period->start_of_current_period);
  1809. tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ", s, t,
  1810. NUM_SECS_HS_USAGE_SUM_INTERVAL);
  1811. cp += strlen(cp);
  1812. cp += hs_usage_format_history(cp, len-(cp-buf), data);
  1813. strlcat(cp, "\n", len-(cp-buf));
  1814. ++cp;
  1815. }
  1816. return buf;
  1817. }
  1818. /** Writes current statistics to file. */
  1819. void
  1820. hs_usage_write_statistics_to_file(time_t now)
  1821. {
  1822. char *buf;
  1823. size_t len;
  1824. char *fname;
  1825. or_options_t *options;
  1826. /* check if we are up-to-date */
  1827. hs_usage_check_if_current_period_is_up_to_date(now);
  1828. buf = hs_usage_format_statistics();
  1829. options = get_options();
  1830. len = strlen(options->DataDirectory) + 16;
  1831. fname = tor_malloc(len);
  1832. tor_snprintf(fname,len, "%s"PATH_SEPARATOR"hsusage", options->DataDirectory);
  1833. write_str_to_file(fname,buf,0);
  1834. tor_free(buf);
  1835. tor_free(fname);
  1836. }