rephist.c 69 KB

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