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