rephist.c 67 KB

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