rephist.c 66 KB

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