rephist.c 67 KB

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