rephist.c 72 KB

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