rephist.c 69 KB

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