rephist.c 87 KB

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