rephist.c 77 KB

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