rephist.c 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2016, 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_digest_is_zero(id))
  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_digest_is_zero(to_id))
  132. return NULL;
  133. lhist = 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 && !tor_addr_is_null(&hist->last_reached_addr) &&
  283. tor_addr_compare(at_addr, &hist->last_reached_addr, CMP_EXACT) != 0;
  284. port_changed = at_port && hist->last_reached_port &&
  285. at_port != hist->last_reached_port;
  286. if (!started_tracking_stability)
  287. started_tracking_stability = time(NULL);
  288. if (!hist->start_of_run) {
  289. hist->start_of_run = when;
  290. was_in_run = 0;
  291. }
  292. if (hist->start_of_downtime) {
  293. long down_length;
  294. format_local_iso_time(tbuf, hist->start_of_downtime);
  295. log_info(LD_HIST, "Router %s is now Running; it had been down since %s.",
  296. hex_str(id, DIGEST_LEN), tbuf);
  297. if (was_in_run)
  298. log_info(LD_HIST, " (Paradoxically, it was already Running too.)");
  299. down_length = when - hist->start_of_downtime;
  300. hist->total_weighted_time += down_length;
  301. hist->start_of_downtime = 0;
  302. } else if (addr_changed || port_changed) {
  303. /* If we're reachable, but the address changed, treat this as some
  304. * downtime. */
  305. int penalty = get_options()->TestingTorNetwork ? 240 : 3600;
  306. networkstatus_t *ns;
  307. if ((ns = networkstatus_get_latest_consensus())) {
  308. int fresh_interval = (int)(ns->fresh_until - ns->valid_after);
  309. int live_interval = (int)(ns->valid_until - ns->valid_after);
  310. /* on average, a descriptor addr change takes .5 intervals to make it
  311. * into a consensus, and half a liveness period to make it to
  312. * clients. */
  313. penalty = (int)(fresh_interval + live_interval) / 2;
  314. }
  315. format_local_iso_time(tbuf, hist->start_of_run);
  316. log_info(LD_HIST,"Router %s still seems Running, but its address appears "
  317. "to have changed since the last time it was reachable. I'm "
  318. "going to treat it as having been down for %d seconds",
  319. hex_str(id, DIGEST_LEN), penalty);
  320. rep_hist_note_router_unreachable(id, when-penalty);
  321. rep_hist_note_router_reachable(id, NULL, 0, when);
  322. } else {
  323. format_local_iso_time(tbuf, hist->start_of_run);
  324. if (was_in_run)
  325. log_debug(LD_HIST, "Router %s is still Running; it has been Running "
  326. "since %s", hex_str(id, DIGEST_LEN), tbuf);
  327. else
  328. log_info(LD_HIST,"Router %s is now Running; it was previously untracked",
  329. hex_str(id, DIGEST_LEN));
  330. }
  331. if (at_addr)
  332. tor_addr_copy(&hist->last_reached_addr, at_addr);
  333. if (at_port)
  334. hist->last_reached_port = at_port;
  335. }
  336. /** We have just decided that this router is unreachable, meaning
  337. * we are taking away its "Running" flag. */
  338. void
  339. rep_hist_note_router_unreachable(const char *id, time_t when)
  340. {
  341. or_history_t *hist = get_or_history(id);
  342. char tbuf[ISO_TIME_LEN+1];
  343. int was_running = 0;
  344. if (!started_tracking_stability)
  345. started_tracking_stability = time(NULL);
  346. tor_assert(hist);
  347. if (hist->start_of_run) {
  348. /*XXXX We could treat failed connections differently from failed
  349. * connect attempts. */
  350. long run_length = when - hist->start_of_run;
  351. format_local_iso_time(tbuf, hist->start_of_run);
  352. hist->total_run_weights += 1.0;
  353. hist->start_of_run = 0;
  354. if (run_length < 0) {
  355. unsigned long penalty = -run_length;
  356. #define SUBTRACT_CLAMPED(var, penalty) \
  357. do { (var) = (var) < (penalty) ? 0 : (var) - (penalty); } while (0)
  358. SUBTRACT_CLAMPED(hist->weighted_run_length, penalty);
  359. SUBTRACT_CLAMPED(hist->weighted_uptime, penalty);
  360. } else {
  361. hist->weighted_run_length += run_length;
  362. hist->weighted_uptime += run_length;
  363. hist->total_weighted_time += run_length;
  364. }
  365. was_running = 1;
  366. log_info(LD_HIST, "Router %s is now non-Running: it had previously been "
  367. "Running since %s. Its total weighted uptime is %lu/%lu.",
  368. hex_str(id, DIGEST_LEN), tbuf, hist->weighted_uptime,
  369. hist->total_weighted_time);
  370. }
  371. if (!hist->start_of_downtime) {
  372. hist->start_of_downtime = when;
  373. if (!was_running)
  374. log_info(LD_HIST, "Router %s is now non-Running; it was previously "
  375. "untracked.", hex_str(id, DIGEST_LEN));
  376. } else {
  377. if (!was_running) {
  378. format_local_iso_time(tbuf, hist->start_of_downtime);
  379. log_info(LD_HIST, "Router %s is still non-Running; it has been "
  380. "non-Running since %s.", hex_str(id, DIGEST_LEN), tbuf);
  381. }
  382. }
  383. }
  384. /** Mark a router with ID <b>id</b> as non-Running, and retroactively declare
  385. * that it has never been running: give it no stability and no WFU. */
  386. void
  387. rep_hist_make_router_pessimal(const char *id, time_t when)
  388. {
  389. or_history_t *hist = get_or_history(id);
  390. tor_assert(hist);
  391. rep_hist_note_router_unreachable(id, when);
  392. mark_or_down(hist, when, 1);
  393. hist->weighted_run_length = 0;
  394. hist->weighted_uptime = 0;
  395. }
  396. /** Helper: Discount all old MTBF data, if it is time to do so. Return
  397. * the time at which we should next discount MTBF data. */
  398. time_t
  399. rep_hist_downrate_old_runs(time_t now)
  400. {
  401. digestmap_iter_t *orhist_it;
  402. const char *digest1;
  403. or_history_t *hist;
  404. void *hist_p;
  405. double alpha = 1.0;
  406. if (!history_map)
  407. history_map = digestmap_new();
  408. if (!stability_last_downrated)
  409. stability_last_downrated = now;
  410. if (stability_last_downrated + STABILITY_INTERVAL > now)
  411. return stability_last_downrated + STABILITY_INTERVAL;
  412. /* Okay, we should downrate the data. By how much? */
  413. while (stability_last_downrated + STABILITY_INTERVAL < now) {
  414. stability_last_downrated += STABILITY_INTERVAL;
  415. alpha *= STABILITY_ALPHA;
  416. }
  417. log_info(LD_HIST, "Discounting all old stability info by a factor of %f",
  418. alpha);
  419. /* Multiply every w_r_l, t_r_w pair by alpha. */
  420. for (orhist_it = digestmap_iter_init(history_map);
  421. !digestmap_iter_done(orhist_it);
  422. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  423. digestmap_iter_get(orhist_it, &digest1, &hist_p);
  424. hist = hist_p;
  425. hist->weighted_run_length =
  426. (unsigned long)(hist->weighted_run_length * alpha);
  427. hist->total_run_weights *= alpha;
  428. hist->weighted_uptime = (unsigned long)(hist->weighted_uptime * alpha);
  429. hist->total_weighted_time = (unsigned long)
  430. (hist->total_weighted_time * alpha);
  431. }
  432. return stability_last_downrated + STABILITY_INTERVAL;
  433. }
  434. /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
  435. static double
  436. get_stability(or_history_t *hist, time_t when)
  437. {
  438. long total = hist->weighted_run_length;
  439. double total_weights = hist->total_run_weights;
  440. if (hist->start_of_run) {
  441. /* We're currently in a run. Let total and total_weights hold the values
  442. * they would hold if the current run were to end now. */
  443. total += (when-hist->start_of_run);
  444. total_weights += 1.0;
  445. }
  446. if (total_weights < STABILITY_EPSILON) {
  447. /* Round down to zero, and avoid divide-by-zero. */
  448. return 0.0;
  449. }
  450. return total / total_weights;
  451. }
  452. /** Return the total amount of time we've been observing, with each run of
  453. * time downrated by the appropriate factor. */
  454. static long
  455. get_total_weighted_time(or_history_t *hist, time_t when)
  456. {
  457. long total = hist->total_weighted_time;
  458. if (hist->start_of_run) {
  459. total += (when - hist->start_of_run);
  460. } else if (hist->start_of_downtime) {
  461. total += (when - hist->start_of_downtime);
  462. }
  463. return total;
  464. }
  465. /** Helper: Return the weighted percent-of-time-online of the router with
  466. * history <b>hist</b>. */
  467. static double
  468. get_weighted_fractional_uptime(or_history_t *hist, time_t when)
  469. {
  470. long total = hist->total_weighted_time;
  471. long up = hist->weighted_uptime;
  472. if (hist->start_of_run) {
  473. long run_length = (when - hist->start_of_run);
  474. up += run_length;
  475. total += run_length;
  476. } else if (hist->start_of_downtime) {
  477. total += (when - hist->start_of_downtime);
  478. }
  479. if (!total) {
  480. /* Avoid calling anybody's uptime infinity (which should be impossible if
  481. * the code is working), or NaN (which can happen for any router we haven't
  482. * observed up or down yet). */
  483. return 0.0;
  484. }
  485. return ((double) up) / total;
  486. }
  487. /** Return how long the router whose identity digest is <b>id</b> has
  488. * been reachable. Return 0 if the router is unknown or currently deemed
  489. * unreachable. */
  490. long
  491. rep_hist_get_uptime(const char *id, time_t when)
  492. {
  493. or_history_t *hist = get_or_history(id);
  494. if (!hist)
  495. return 0;
  496. if (!hist->start_of_run || when < hist->start_of_run)
  497. return 0;
  498. return when - hist->start_of_run;
  499. }
  500. /** Return an estimated MTBF for the router whose identity digest is
  501. * <b>id</b>. Return 0 if the router is unknown. */
  502. double
  503. rep_hist_get_stability(const char *id, time_t when)
  504. {
  505. or_history_t *hist = get_or_history(id);
  506. if (!hist)
  507. return 0.0;
  508. return get_stability(hist, when);
  509. }
  510. /** Return an estimated percent-of-time-online for the router whose identity
  511. * digest is <b>id</b>. Return 0 if the router is unknown. */
  512. double
  513. rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
  514. {
  515. or_history_t *hist = get_or_history(id);
  516. if (!hist)
  517. return 0.0;
  518. return get_weighted_fractional_uptime(hist, when);
  519. }
  520. /** Return a number representing how long we've known about the router whose
  521. * digest is <b>id</b>. Return 0 if the router is unknown.
  522. *
  523. * Be careful: this measure increases monotonically as we know the router for
  524. * longer and longer, but it doesn't increase linearly.
  525. */
  526. long
  527. rep_hist_get_weighted_time_known(const char *id, time_t when)
  528. {
  529. or_history_t *hist = get_or_history(id);
  530. if (!hist)
  531. return 0;
  532. return get_total_weighted_time(hist, when);
  533. }
  534. /** Return true if we've been measuring MTBFs for long enough to
  535. * pronounce on Stability. */
  536. int
  537. rep_hist_have_measured_enough_stability(void)
  538. {
  539. /* XXXX++ This doesn't do so well when we change our opinion
  540. * as to whether we're tracking router stability. */
  541. return started_tracking_stability < time(NULL) - 4*60*60;
  542. }
  543. /** Remember that we successfully extended from the OR with identity
  544. * digest <b>from_id</b> to the OR with identity digest
  545. * <b>to_name</b>.
  546. */
  547. void
  548. rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
  549. {
  550. link_history_t *hist;
  551. /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
  552. hist = get_link_history(from_id, to_id);
  553. if (!hist)
  554. return;
  555. ++hist->n_extend_ok;
  556. hist->changed = time(NULL);
  557. }
  558. /** Remember that we tried to extend from the OR with identity digest
  559. * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
  560. * failed.
  561. */
  562. void
  563. rep_hist_note_extend_failed(const char *from_id, const char *to_id)
  564. {
  565. link_history_t *hist;
  566. /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
  567. hist = get_link_history(from_id, to_id);
  568. if (!hist)
  569. return;
  570. ++hist->n_extend_fail;
  571. hist->changed = time(NULL);
  572. }
  573. /** Log all the reliability data we have remembered, with the chosen
  574. * severity.
  575. */
  576. void
  577. rep_hist_dump_stats(time_t now, int severity)
  578. {
  579. digestmap_iter_t *lhist_it;
  580. digestmap_iter_t *orhist_it;
  581. const char *name1, *name2, *digest1, *digest2;
  582. char hexdigest1[HEX_DIGEST_LEN+1];
  583. char hexdigest2[HEX_DIGEST_LEN+1];
  584. or_history_t *or_history;
  585. link_history_t *link_history;
  586. void *or_history_p, *link_history_p;
  587. double uptime;
  588. char buffer[2048];
  589. size_t len;
  590. int ret;
  591. unsigned long upt, downt;
  592. const node_t *node;
  593. rep_history_clean(now - get_options()->RephistTrackTime);
  594. tor_log(severity, LD_HIST, "--------------- Dumping history information:");
  595. for (orhist_it = digestmap_iter_init(history_map);
  596. !digestmap_iter_done(orhist_it);
  597. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  598. double s;
  599. long stability;
  600. digestmap_iter_get(orhist_it, &digest1, &or_history_p);
  601. or_history = (or_history_t*) or_history_p;
  602. if ((node = node_get_by_id(digest1)) && node_get_nickname(node))
  603. name1 = node_get_nickname(node);
  604. else
  605. name1 = "(unknown)";
  606. base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
  607. update_or_history(or_history, now);
  608. upt = or_history->uptime;
  609. downt = or_history->downtime;
  610. s = get_stability(or_history, now);
  611. stability = (long)s;
  612. if (upt+downt) {
  613. uptime = ((double)upt) / (upt+downt);
  614. } else {
  615. uptime=1.0;
  616. }
  617. tor_log(severity, LD_HIST,
  618. "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
  619. "wmtbf %lu:%02lu:%02lu",
  620. name1, hexdigest1,
  621. or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
  622. upt, upt+downt, uptime*100.0,
  623. stability/3600, (stability/60)%60, stability%60);
  624. if (!digestmap_isempty(or_history->link_history_map)) {
  625. strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
  626. len = strlen(buffer);
  627. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  628. !digestmap_iter_done(lhist_it);
  629. lhist_it = digestmap_iter_next(or_history->link_history_map,
  630. lhist_it)) {
  631. digestmap_iter_get(lhist_it, &digest2, &link_history_p);
  632. if ((node = node_get_by_id(digest2)) && node_get_nickname(node))
  633. name2 = node_get_nickname(node);
  634. else
  635. name2 = "(unknown)";
  636. link_history = (link_history_t*) link_history_p;
  637. base16_encode(hexdigest2, sizeof(hexdigest2), digest2, DIGEST_LEN);
  638. ret = tor_snprintf(buffer+len, 2048-len, "%s [%s](%ld/%ld); ",
  639. name2,
  640. hexdigest2,
  641. link_history->n_extend_ok,
  642. link_history->n_extend_ok+link_history->n_extend_fail);
  643. if (ret<0)
  644. break;
  645. else
  646. len += ret;
  647. }
  648. tor_log(severity, LD_HIST, "%s", buffer);
  649. }
  650. }
  651. }
  652. /** Remove history info for routers/links that haven't changed since
  653. * <b>before</b>.
  654. */
  655. void
  656. rep_history_clean(time_t before)
  657. {
  658. int authority = authdir_mode(get_options());
  659. or_history_t *or_history;
  660. link_history_t *link_history;
  661. void *or_history_p, *link_history_p;
  662. digestmap_iter_t *orhist_it, *lhist_it;
  663. const char *d1, *d2;
  664. orhist_it = digestmap_iter_init(history_map);
  665. while (!digestmap_iter_done(orhist_it)) {
  666. int remove;
  667. digestmap_iter_get(orhist_it, &d1, &or_history_p);
  668. or_history = or_history_p;
  669. remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
  670. !or_history->start_of_run)
  671. : (or_history->changed < before);
  672. if (remove) {
  673. orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
  674. free_or_history(or_history);
  675. continue;
  676. }
  677. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  678. !digestmap_iter_done(lhist_it); ) {
  679. digestmap_iter_get(lhist_it, &d2, &link_history_p);
  680. link_history = link_history_p;
  681. if (link_history->changed < before) {
  682. lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
  683. lhist_it);
  684. rephist_total_alloc -= sizeof(link_history_t);
  685. tor_free(link_history);
  686. continue;
  687. }
  688. lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
  689. }
  690. orhist_it = digestmap_iter_next(history_map, orhist_it);
  691. }
  692. }
  693. /** Write MTBF data to disk. Return 0 on success, negative on failure.
  694. *
  695. * If <b>missing_means_down</b>, then if we're about to write an entry
  696. * that is still considered up but isn't in our routerlist, consider it
  697. * to be down. */
  698. int
  699. rep_hist_record_mtbf_data(time_t now, int missing_means_down)
  700. {
  701. char time_buf[ISO_TIME_LEN+1];
  702. digestmap_iter_t *orhist_it;
  703. const char *digest;
  704. void *or_history_p;
  705. or_history_t *hist;
  706. open_file_t *open_file = NULL;
  707. FILE *f;
  708. {
  709. char *filename = get_datadir_fname("router-stability");
  710. f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
  711. &open_file);
  712. tor_free(filename);
  713. if (!f)
  714. return -1;
  715. }
  716. /* File format is:
  717. * FormatLine *KeywordLine Data
  718. *
  719. * FormatLine = "format 1" NL
  720. * KeywordLine = Keyword SP Arguments NL
  721. * Data = "data" NL *RouterMTBFLine "." NL
  722. * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
  723. * TotalRunWeights [SP S=StartRunTime] NL
  724. */
  725. #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
  726. #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
  727. PUT("format 2\n");
  728. format_iso_time(time_buf, time(NULL));
  729. PRINTF((f, "stored-at %s\n", time_buf));
  730. if (started_tracking_stability) {
  731. format_iso_time(time_buf, started_tracking_stability);
  732. PRINTF((f, "tracked-since %s\n", time_buf));
  733. }
  734. if (stability_last_downrated) {
  735. format_iso_time(time_buf, stability_last_downrated);
  736. PRINTF((f, "last-downrated %s\n", time_buf));
  737. }
  738. PUT("data\n");
  739. /* XXX Nick: now bridge auths record this for all routers too.
  740. * Should we make them record it only for bridge routers? -RD
  741. * Not for 0.2.0. -NM */
  742. for (orhist_it = digestmap_iter_init(history_map);
  743. !digestmap_iter_done(orhist_it);
  744. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  745. char dbuf[HEX_DIGEST_LEN+1];
  746. const char *t = NULL;
  747. digestmap_iter_get(orhist_it, &digest, &or_history_p);
  748. hist = (or_history_t*) or_history_p;
  749. base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
  750. if (missing_means_down && hist->start_of_run &&
  751. !router_get_by_id_digest(digest)) {
  752. /* We think this relay is running, but it's not listed in our
  753. * routerlist. Somehow it fell out without telling us it went
  754. * down. Complain and also correct it. */
  755. log_info(LD_HIST,
  756. "Relay '%s' is listed as up in rephist, but it's not in "
  757. "our routerlist. Correcting.", dbuf);
  758. rep_hist_note_router_unreachable(digest, now);
  759. }
  760. PRINTF((f, "R %s\n", dbuf));
  761. if (hist->start_of_run > 0) {
  762. format_iso_time(time_buf, hist->start_of_run);
  763. t = time_buf;
  764. }
  765. PRINTF((f, "+MTBF %lu %.5f%s%s\n",
  766. hist->weighted_run_length, hist->total_run_weights,
  767. t ? " S=" : "", t ? t : ""));
  768. t = NULL;
  769. if (hist->start_of_downtime > 0) {
  770. format_iso_time(time_buf, hist->start_of_downtime);
  771. t = time_buf;
  772. }
  773. PRINTF((f, "+WFU %lu %lu%s%s\n",
  774. hist->weighted_uptime, hist->total_weighted_time,
  775. t ? " S=" : "", t ? t : ""));
  776. }
  777. PUT(".\n");
  778. #undef PUT
  779. #undef PRINTF
  780. return finish_writing_to_file(open_file);
  781. err:
  782. abort_writing_to_file(open_file);
  783. return -1;
  784. }
  785. /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
  786. * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
  787. * such line exists. */
  788. static int
  789. find_next_with(smartlist_t *sl, int i, const char *prefix)
  790. {
  791. for ( ; i < smartlist_len(sl); ++i) {
  792. const char *line = smartlist_get(sl, i);
  793. if (!strcmpstart(line, prefix))
  794. return i;
  795. if (!strcmpstart(line, "R "))
  796. return -1;
  797. }
  798. return -1;
  799. }
  800. /** How many bad times has parse_possibly_bad_iso_time() parsed? */
  801. static int n_bogus_times = 0;
  802. /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
  803. * round any pre-1970 date to Jan 1, 1970. */
  804. static int
  805. parse_possibly_bad_iso_time(const char *s, time_t *time_out)
  806. {
  807. int year;
  808. char b[5];
  809. strlcpy(b, s, sizeof(b));
  810. b[4] = '\0';
  811. year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
  812. if (year < 1970) {
  813. *time_out = 0;
  814. ++n_bogus_times;
  815. return 0;
  816. } else
  817. return parse_iso_time(s, time_out);
  818. }
  819. /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
  820. * says we started measuring at <b>started_measuring</b>. Return a new number
  821. * that's about as much before <b>now</b> as <b>t</b> was before
  822. * <b>stored_at</b>.
  823. */
  824. static inline time_t
  825. correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
  826. {
  827. if (t < started_measuring - 24*60*60*365)
  828. return 0;
  829. else if (t < started_measuring)
  830. return started_measuring;
  831. else if (t > stored_at)
  832. return 0;
  833. else {
  834. long run_length = stored_at - t;
  835. t = (time_t)(now - run_length);
  836. if (t < started_measuring)
  837. t = started_measuring;
  838. return t;
  839. }
  840. }
  841. /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
  842. * on failure. */
  843. int
  844. rep_hist_load_mtbf_data(time_t now)
  845. {
  846. /* XXXX won't handle being called while history is already populated. */
  847. smartlist_t *lines;
  848. const char *line = NULL;
  849. int r=0, i;
  850. time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
  851. time_t latest_possible_start = now;
  852. long format = -1;
  853. {
  854. char *filename = get_datadir_fname("router-stability");
  855. char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  856. tor_free(filename);
  857. if (!d)
  858. return -1;
  859. lines = smartlist_new();
  860. smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
  861. tor_free(d);
  862. }
  863. {
  864. const char *firstline;
  865. if (smartlist_len(lines)>4) {
  866. firstline = smartlist_get(lines, 0);
  867. if (!strcmpstart(firstline, "format "))
  868. format = tor_parse_long(firstline+strlen("format "),
  869. 10, -1, LONG_MAX, NULL, NULL);
  870. }
  871. }
  872. if (format != 1 && format != 2) {
  873. log_warn(LD_HIST,
  874. "Unrecognized format in mtbf history file. Skipping.");
  875. goto err;
  876. }
  877. for (i = 1; i < smartlist_len(lines); ++i) {
  878. line = smartlist_get(lines, i);
  879. if (!strcmp(line, "data"))
  880. break;
  881. if (!strcmpstart(line, "last-downrated ")) {
  882. if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
  883. log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
  884. "history file.");
  885. }
  886. if (!strcmpstart(line, "stored-at ")) {
  887. if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
  888. log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
  889. "history file.");
  890. }
  891. if (!strcmpstart(line, "tracked-since ")) {
  892. if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
  893. log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
  894. "history file.");
  895. }
  896. }
  897. if (last_downrated > now)
  898. last_downrated = now;
  899. if (tracked_since > now)
  900. tracked_since = now;
  901. if (!stored_at) {
  902. log_warn(LD_HIST, "No stored time recorded.");
  903. goto err;
  904. }
  905. if (line && !strcmp(line, "data"))
  906. ++i;
  907. n_bogus_times = 0;
  908. for (; i < smartlist_len(lines); ++i) {
  909. char digest[DIGEST_LEN];
  910. char hexbuf[HEX_DIGEST_LEN+1];
  911. char mtbf_timebuf[ISO_TIME_LEN+1];
  912. char wfu_timebuf[ISO_TIME_LEN+1];
  913. time_t start_of_run = 0;
  914. time_t start_of_downtime = 0;
  915. int have_mtbf = 0, have_wfu = 0;
  916. long wrl = 0;
  917. double trw = 0;
  918. long wt_uptime = 0, total_wt_time = 0;
  919. int n;
  920. or_history_t *hist;
  921. line = smartlist_get(lines, i);
  922. if (!strcmp(line, "."))
  923. break;
  924. mtbf_timebuf[0] = '\0';
  925. wfu_timebuf[0] = '\0';
  926. if (format == 1) {
  927. n = tor_sscanf(line, "%40s %ld %lf S=%10s %8s",
  928. hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
  929. if (n != 3 && n != 5) {
  930. log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
  931. continue;
  932. }
  933. have_mtbf = 1;
  934. } else {
  935. // format == 2.
  936. int mtbf_idx, wfu_idx;
  937. if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
  938. continue;
  939. strlcpy(hexbuf, line+2, sizeof(hexbuf));
  940. mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
  941. wfu_idx = find_next_with(lines, i+1, "+WFU ");
  942. if (mtbf_idx >= 0) {
  943. const char *mtbfline = smartlist_get(lines, mtbf_idx);
  944. n = tor_sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
  945. &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
  946. if (n == 2 || n == 4) {
  947. have_mtbf = 1;
  948. } else {
  949. log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
  950. escaped(mtbfline));
  951. }
  952. }
  953. if (wfu_idx >= 0) {
  954. const char *wfuline = smartlist_get(lines, wfu_idx);
  955. n = tor_sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
  956. &wt_uptime, &total_wt_time,
  957. wfu_timebuf, wfu_timebuf+11);
  958. if (n == 2 || n == 4) {
  959. have_wfu = 1;
  960. } else {
  961. log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
  962. }
  963. }
  964. if (wfu_idx > i)
  965. i = wfu_idx;
  966. if (mtbf_idx > i)
  967. i = mtbf_idx;
  968. }
  969. if (base16_decode(digest, DIGEST_LEN,
  970. hexbuf, HEX_DIGEST_LEN) != DIGEST_LEN) {
  971. log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
  972. continue;
  973. }
  974. hist = get_or_history(digest);
  975. if (!hist)
  976. continue;
  977. if (have_mtbf) {
  978. if (mtbf_timebuf[0]) {
  979. mtbf_timebuf[10] = ' ';
  980. if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
  981. log_warn(LD_HIST, "Couldn't parse time %s",
  982. escaped(mtbf_timebuf));
  983. }
  984. hist->start_of_run = correct_time(start_of_run, now, stored_at,
  985. tracked_since);
  986. if (hist->start_of_run < latest_possible_start + wrl)
  987. latest_possible_start = (time_t)(hist->start_of_run - wrl);
  988. hist->weighted_run_length = wrl;
  989. hist->total_run_weights = trw;
  990. }
  991. if (have_wfu) {
  992. if (wfu_timebuf[0]) {
  993. wfu_timebuf[10] = ' ';
  994. if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
  995. log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
  996. }
  997. }
  998. hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
  999. tracked_since);
  1000. hist->weighted_uptime = wt_uptime;
  1001. hist->total_weighted_time = total_wt_time;
  1002. }
  1003. if (strcmp(line, "."))
  1004. log_warn(LD_HIST, "Truncated MTBF file.");
  1005. if (tracked_since < 86400*365) /* Recover from insanely early value. */
  1006. tracked_since = latest_possible_start;
  1007. stability_last_downrated = last_downrated;
  1008. started_tracking_stability = tracked_since;
  1009. goto done;
  1010. err:
  1011. r = -1;
  1012. done:
  1013. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1014. smartlist_free(lines);
  1015. return r;
  1016. }
  1017. /** For how many seconds do we keep track of individual per-second bandwidth
  1018. * totals? */
  1019. #define NUM_SECS_ROLLING_MEASURE 10
  1020. /** How large are the intervals for which we track and report bandwidth use? */
  1021. #define NUM_SECS_BW_SUM_INTERVAL (4*60*60)
  1022. /** How far in the past do we remember and publish bandwidth use? */
  1023. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
  1024. /** How many bandwidth usage intervals do we remember? (derived) */
  1025. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  1026. /** Structure to track bandwidth use, and remember the maxima for a given
  1027. * time period.
  1028. */
  1029. typedef struct bw_array_t {
  1030. /** Observation array: Total number of bytes transferred in each of the last
  1031. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  1032. uint64_t obs[NUM_SECS_ROLLING_MEASURE];
  1033. int cur_obs_idx; /**< Current position in obs. */
  1034. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  1035. uint64_t total_obs; /**< Total for all members of obs except
  1036. * obs[cur_obs_idx] */
  1037. uint64_t max_total; /**< Largest value that total_obs has taken on in the
  1038. * current period. */
  1039. uint64_t total_in_period; /**< Total bytes transferred in the current
  1040. * period. */
  1041. /** When does the next period begin? */
  1042. time_t next_period;
  1043. /** Where in 'maxima' should the maximum bandwidth usage for the current
  1044. * period be stored? */
  1045. int next_max_idx;
  1046. /** How many values in maxima/totals have been set ever? */
  1047. int num_maxes_set;
  1048. /** Circular array of the maximum
  1049. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  1050. * NUM_TOTALS periods */
  1051. uint64_t maxima[NUM_TOTALS];
  1052. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  1053. * periods */
  1054. uint64_t totals[NUM_TOTALS];
  1055. } bw_array_t;
  1056. /** Shift the current period of b forward by one. */
  1057. static void
  1058. commit_max(bw_array_t *b)
  1059. {
  1060. /* Store total from current period. */
  1061. b->totals[b->next_max_idx] = b->total_in_period;
  1062. /* Store maximum from current period. */
  1063. b->maxima[b->next_max_idx++] = b->max_total;
  1064. /* Advance next_period and next_max_idx */
  1065. b->next_period += NUM_SECS_BW_SUM_INTERVAL;
  1066. if (b->next_max_idx == NUM_TOTALS)
  1067. b->next_max_idx = 0;
  1068. if (b->num_maxes_set < NUM_TOTALS)
  1069. ++b->num_maxes_set;
  1070. /* Reset max_total. */
  1071. b->max_total = 0;
  1072. /* Reset total_in_period. */
  1073. b->total_in_period = 0;
  1074. }
  1075. /** Shift the current observation time of <b>b</b> forward by one second. */
  1076. static inline void
  1077. advance_obs(bw_array_t *b)
  1078. {
  1079. int nextidx;
  1080. uint64_t total;
  1081. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  1082. * seconds; adjust max_total as needed.*/
  1083. total = b->total_obs + b->obs[b->cur_obs_idx];
  1084. if (total > b->max_total)
  1085. b->max_total = total;
  1086. nextidx = b->cur_obs_idx+1;
  1087. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  1088. nextidx = 0;
  1089. b->total_obs = total - b->obs[nextidx];
  1090. b->obs[nextidx]=0;
  1091. b->cur_obs_idx = nextidx;
  1092. if (++b->cur_obs_time >= b->next_period)
  1093. commit_max(b);
  1094. }
  1095. /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
  1096. * <b>when</b>. */
  1097. static inline void
  1098. add_obs(bw_array_t *b, time_t when, uint64_t n)
  1099. {
  1100. if (when < b->cur_obs_time)
  1101. return; /* Don't record data in the past. */
  1102. /* If we're currently adding observations for an earlier second than
  1103. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  1104. * appropriate number of seconds, and do all the other housekeeping. */
  1105. while (when > b->cur_obs_time) {
  1106. /* Doing this one second at a time is potentially inefficient, if we start
  1107. with a state file that is very old. Fortunately, it doesn't seem to
  1108. show up in profiles, so we can just ignore it for now. */
  1109. advance_obs(b);
  1110. }
  1111. b->obs[b->cur_obs_idx] += n;
  1112. b->total_in_period += n;
  1113. }
  1114. /** Allocate, initialize, and return a new bw_array. */
  1115. static bw_array_t *
  1116. bw_array_new(void)
  1117. {
  1118. bw_array_t *b;
  1119. time_t start;
  1120. b = tor_malloc_zero(sizeof(bw_array_t));
  1121. rephist_total_alloc += sizeof(bw_array_t);
  1122. start = time(NULL);
  1123. b->cur_obs_time = start;
  1124. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  1125. return b;
  1126. }
  1127. /** Free storage held by bandwidth array <b>b</b>. */
  1128. static void
  1129. bw_array_free(bw_array_t *b)
  1130. {
  1131. if (!b) {
  1132. return;
  1133. }
  1134. rephist_total_alloc -= sizeof(bw_array_t);
  1135. tor_free(b);
  1136. }
  1137. /** Recent history of bandwidth observations for read operations. */
  1138. static bw_array_t *read_array = NULL;
  1139. /** Recent history of bandwidth observations for write operations. */
  1140. static bw_array_t *write_array = NULL;
  1141. /** Recent history of bandwidth observations for read operations for the
  1142. directory protocol. */
  1143. static bw_array_t *dir_read_array = NULL;
  1144. /** Recent history of bandwidth observations for write operations for the
  1145. directory protocol. */
  1146. static bw_array_t *dir_write_array = NULL;
  1147. /** Set up [dir-]read_array and [dir-]write_array, freeing them if they
  1148. * already exist. */
  1149. static void
  1150. bw_arrays_init(void)
  1151. {
  1152. bw_array_free(read_array);
  1153. bw_array_free(write_array);
  1154. bw_array_free(dir_read_array);
  1155. bw_array_free(dir_write_array);
  1156. read_array = bw_array_new();
  1157. write_array = bw_array_new();
  1158. dir_read_array = bw_array_new();
  1159. dir_write_array = bw_array_new();
  1160. }
  1161. /** Remember that we read <b>num_bytes</b> bytes in second <b>when</b>.
  1162. *
  1163. * Add num_bytes to the current running total for <b>when</b>.
  1164. *
  1165. * <b>when</b> can go back to time, but it's safe to ignore calls
  1166. * earlier than the latest <b>when</b> you've heard of.
  1167. */
  1168. void
  1169. rep_hist_note_bytes_written(size_t num_bytes, time_t when)
  1170. {
  1171. /* Maybe a circular array for recent seconds, and step to a new point
  1172. * every time a new second shows up. Or simpler is to just to have
  1173. * a normal array and push down each item every second; it's short.
  1174. */
  1175. /* When a new second has rolled over, compute the sum of the bytes we've
  1176. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  1177. * somewhere. See rep_hist_bandwidth_assess() below.
  1178. */
  1179. add_obs(write_array, when, num_bytes);
  1180. }
  1181. /** Remember that we wrote <b>num_bytes</b> bytes in second <b>when</b>.
  1182. * (like rep_hist_note_bytes_written() above)
  1183. */
  1184. void
  1185. rep_hist_note_bytes_read(size_t num_bytes, time_t when)
  1186. {
  1187. /* if we're smart, we can make this func and the one above share code */
  1188. add_obs(read_array, when, num_bytes);
  1189. }
  1190. /** Remember that we wrote <b>num_bytes</b> directory bytes in second
  1191. * <b>when</b>. (like rep_hist_note_bytes_written() above)
  1192. */
  1193. void
  1194. rep_hist_note_dir_bytes_written(size_t num_bytes, time_t when)
  1195. {
  1196. add_obs(dir_write_array, when, num_bytes);
  1197. }
  1198. /** Remember that we read <b>num_bytes</b> directory bytes in second
  1199. * <b>when</b>. (like rep_hist_note_bytes_written() above)
  1200. */
  1201. void
  1202. rep_hist_note_dir_bytes_read(size_t num_bytes, time_t when)
  1203. {
  1204. add_obs(dir_read_array, when, num_bytes);
  1205. }
  1206. /** Helper: Return the largest value in b->maxima. (This is equal to the
  1207. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  1208. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  1209. */
  1210. static uint64_t
  1211. find_largest_max(bw_array_t *b)
  1212. {
  1213. int i;
  1214. uint64_t max;
  1215. max=0;
  1216. for (i=0; i<NUM_TOTALS; ++i) {
  1217. if (b->maxima[i]>max)
  1218. max = b->maxima[i];
  1219. }
  1220. return max;
  1221. }
  1222. /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  1223. * seconds. Find one sum for reading and one for writing. They don't have
  1224. * to be at the same time.
  1225. *
  1226. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  1227. */
  1228. int
  1229. rep_hist_bandwidth_assess(void)
  1230. {
  1231. uint64_t w,r;
  1232. r = find_largest_max(read_array);
  1233. w = find_largest_max(write_array);
  1234. if (r>w)
  1235. return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
  1236. else
  1237. return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
  1238. }
  1239. /** Print the bandwidth history of b (either [dir-]read_array or
  1240. * [dir-]write_array) into the buffer pointed to by buf. The format is
  1241. * simply comma separated numbers, from oldest to newest.
  1242. *
  1243. * It returns the number of bytes written.
  1244. */
  1245. static size_t
  1246. rep_hist_fill_bandwidth_history(char *buf, size_t len, const bw_array_t *b)
  1247. {
  1248. char *cp = buf;
  1249. int i, n;
  1250. const or_options_t *options = get_options();
  1251. uint64_t cutoff;
  1252. if (b->num_maxes_set <= b->next_max_idx) {
  1253. /* We haven't been through the circular array yet; time starts at i=0.*/
  1254. i = 0;
  1255. } else {
  1256. /* We've been around the array at least once. The next i to be
  1257. overwritten is the oldest. */
  1258. i = b->next_max_idx;
  1259. }
  1260. if (options->RelayBandwidthRate) {
  1261. /* We don't want to report that we used more bandwidth than the max we're
  1262. * willing to relay; otherwise everybody will know how much traffic
  1263. * we used ourself. */
  1264. cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
  1265. } else {
  1266. cutoff = UINT64_MAX;
  1267. }
  1268. for (n=0; n<b->num_maxes_set; ++n,++i) {
  1269. uint64_t total;
  1270. if (i >= NUM_TOTALS)
  1271. i -= NUM_TOTALS;
  1272. tor_assert(i < NUM_TOTALS);
  1273. /* Round the bandwidth used down to the nearest 1k. */
  1274. total = b->totals[i] & ~0x3ff;
  1275. if (total > cutoff)
  1276. total = cutoff;
  1277. if (n==(b->num_maxes_set-1))
  1278. tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
  1279. else
  1280. tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
  1281. cp += strlen(cp);
  1282. }
  1283. return cp-buf;
  1284. }
  1285. /** Allocate and return lines for representing this server's bandwidth
  1286. * history in its descriptor. We publish these lines in our extra-info
  1287. * descriptor.
  1288. */
  1289. char *
  1290. rep_hist_get_bandwidth_lines(void)
  1291. {
  1292. char *buf, *cp;
  1293. char t[ISO_TIME_LEN+1];
  1294. int r;
  1295. bw_array_t *b = NULL;
  1296. const char *desc = NULL;
  1297. size_t len;
  1298. /* [dirreq-](read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n... */
  1299. /* The n,n,n part above. Largest representation of a uint64_t is 20 chars
  1300. * long, plus the comma. */
  1301. #define MAX_HIST_VALUE_LEN (21*NUM_TOTALS)
  1302. len = (67+MAX_HIST_VALUE_LEN)*4;
  1303. buf = tor_malloc_zero(len);
  1304. cp = buf;
  1305. for (r=0;r<4;++r) {
  1306. char tmp[MAX_HIST_VALUE_LEN];
  1307. size_t slen;
  1308. switch (r) {
  1309. case 0:
  1310. b = write_array;
  1311. desc = "write-history";
  1312. break;
  1313. case 1:
  1314. b = read_array;
  1315. desc = "read-history";
  1316. break;
  1317. case 2:
  1318. b = dir_write_array;
  1319. desc = "dirreq-write-history";
  1320. break;
  1321. case 3:
  1322. b = dir_read_array;
  1323. desc = "dirreq-read-history";
  1324. break;
  1325. }
  1326. tor_assert(b);
  1327. slen = rep_hist_fill_bandwidth_history(tmp, MAX_HIST_VALUE_LEN, b);
  1328. /* If we don't have anything to write, skip to the next entry. */
  1329. if (slen == 0)
  1330. continue;
  1331. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  1332. tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ",
  1333. desc, t, NUM_SECS_BW_SUM_INTERVAL);
  1334. cp += strlen(cp);
  1335. strlcat(cp, tmp, len-(cp-buf));
  1336. cp += slen;
  1337. strlcat(cp, "\n", len-(cp-buf));
  1338. ++cp;
  1339. }
  1340. return buf;
  1341. }
  1342. /** Write a single bw_array_t into the Values, Ends, Interval, and Maximum
  1343. * entries of an or_state_t. Done before writing out a new state file. */
  1344. static void
  1345. rep_hist_update_bwhist_state_section(or_state_t *state,
  1346. const bw_array_t *b,
  1347. smartlist_t **s_values,
  1348. smartlist_t **s_maxima,
  1349. time_t *s_begins,
  1350. int *s_interval)
  1351. {
  1352. int i,j;
  1353. uint64_t maxval;
  1354. if (*s_values) {
  1355. SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
  1356. smartlist_free(*s_values);
  1357. }
  1358. if (*s_maxima) {
  1359. SMARTLIST_FOREACH(*s_maxima, char *, val, tor_free(val));
  1360. smartlist_free(*s_maxima);
  1361. }
  1362. if (! server_mode(get_options())) {
  1363. /* Clients don't need to store bandwidth history persistently;
  1364. * force these values to the defaults. */
  1365. /* FFFF we should pull the default out of config.c's state table,
  1366. * so we don't have two defaults. */
  1367. if (*s_begins != 0 || *s_interval != 900) {
  1368. time_t now = time(NULL);
  1369. time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
  1370. or_state_mark_dirty(state, save_at);
  1371. }
  1372. *s_begins = 0;
  1373. *s_interval = 900;
  1374. *s_values = smartlist_new();
  1375. *s_maxima = smartlist_new();
  1376. return;
  1377. }
  1378. *s_begins = b->next_period;
  1379. *s_interval = NUM_SECS_BW_SUM_INTERVAL;
  1380. *s_values = smartlist_new();
  1381. *s_maxima = smartlist_new();
  1382. /* Set i to first position in circular array */
  1383. i = (b->num_maxes_set <= b->next_max_idx) ? 0 : b->next_max_idx;
  1384. for (j=0; j < b->num_maxes_set; ++j,++i) {
  1385. if (i >= NUM_TOTALS)
  1386. i = 0;
  1387. smartlist_add_asprintf(*s_values, U64_FORMAT,
  1388. U64_PRINTF_ARG(b->totals[i] & ~0x3ff));
  1389. maxval = b->maxima[i] / NUM_SECS_ROLLING_MEASURE;
  1390. smartlist_add_asprintf(*s_maxima, U64_FORMAT,
  1391. U64_PRINTF_ARG(maxval & ~0x3ff));
  1392. }
  1393. smartlist_add_asprintf(*s_values, U64_FORMAT,
  1394. U64_PRINTF_ARG(b->total_in_period & ~0x3ff));
  1395. maxval = b->max_total / NUM_SECS_ROLLING_MEASURE;
  1396. smartlist_add_asprintf(*s_maxima, U64_FORMAT,
  1397. U64_PRINTF_ARG(maxval & ~0x3ff));
  1398. }
  1399. /** Update <b>state</b> with the newest bandwidth history. Done before
  1400. * writing out a new state file. */
  1401. void
  1402. rep_hist_update_state(or_state_t *state)
  1403. {
  1404. #define UPDATE(arrname,st) \
  1405. rep_hist_update_bwhist_state_section(state,\
  1406. (arrname),\
  1407. &state->BWHistory ## st ## Values, \
  1408. &state->BWHistory ## st ## Maxima, \
  1409. &state->BWHistory ## st ## Ends, \
  1410. &state->BWHistory ## st ## Interval)
  1411. UPDATE(write_array, Write);
  1412. UPDATE(read_array, Read);
  1413. UPDATE(dir_write_array, DirWrite);
  1414. UPDATE(dir_read_array, DirRead);
  1415. if (server_mode(get_options())) {
  1416. or_state_mark_dirty(state, time(NULL)+(2*3600));
  1417. }
  1418. #undef UPDATE
  1419. }
  1420. /** Load a single bw_array_t from its Values, Ends, Maxima, and Interval
  1421. * entries in an or_state_t. Done while reading the state file. */
  1422. static int
  1423. rep_hist_load_bwhist_state_section(bw_array_t *b,
  1424. const smartlist_t *s_values,
  1425. const smartlist_t *s_maxima,
  1426. const time_t s_begins,
  1427. const int s_interval)
  1428. {
  1429. time_t now = time(NULL);
  1430. int retval = 0;
  1431. time_t start;
  1432. uint64_t v, mv;
  1433. int i,ok,ok_m = 0;
  1434. int have_maxima = s_maxima && s_values &&
  1435. (smartlist_len(s_values) == smartlist_len(s_maxima));
  1436. if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
  1437. start = s_begins - s_interval*(smartlist_len(s_values));
  1438. if (start > now)
  1439. return 0;
  1440. b->cur_obs_time = start;
  1441. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  1442. SMARTLIST_FOREACH_BEGIN(s_values, const char *, cp) {
  1443. const char *maxstr = NULL;
  1444. v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
  1445. if (have_maxima) {
  1446. maxstr = smartlist_get(s_maxima, cp_sl_idx);
  1447. mv = tor_parse_uint64(maxstr, 10, 0, UINT64_MAX, &ok_m, NULL);
  1448. mv *= NUM_SECS_ROLLING_MEASURE;
  1449. } else {
  1450. /* No maxima known; guess average rate to be conservative. */
  1451. mv = (v / s_interval) * NUM_SECS_ROLLING_MEASURE;
  1452. }
  1453. if (!ok) {
  1454. retval = -1;
  1455. log_notice(LD_HIST, "Could not parse value '%s' into a number.'",cp);
  1456. }
  1457. if (maxstr && !ok_m) {
  1458. retval = -1;
  1459. log_notice(LD_HIST, "Could not parse maximum '%s' into a number.'",
  1460. maxstr);
  1461. }
  1462. if (start < now) {
  1463. time_t cur_start = start;
  1464. time_t actual_interval_len = s_interval;
  1465. uint64_t cur_val = 0;
  1466. /* Calculate the average per second. This is the best we can do
  1467. * because our state file doesn't have per-second resolution. */
  1468. if (start + s_interval > now)
  1469. actual_interval_len = now - start;
  1470. cur_val = v / actual_interval_len;
  1471. /* This is potentially inefficient, but since we don't do it very
  1472. * often it should be ok. */
  1473. while (cur_start < start + actual_interval_len) {
  1474. add_obs(b, cur_start, cur_val);
  1475. ++cur_start;
  1476. }
  1477. b->max_total = mv;
  1478. /* This will result in some fairly choppy history if s_interval
  1479. * is not the same as NUM_SECS_BW_SUM_INTERVAL. XXXX */
  1480. start += actual_interval_len;
  1481. }
  1482. } SMARTLIST_FOREACH_END(cp);
  1483. }
  1484. /* Clean up maxima and observed */
  1485. for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
  1486. b->obs[i] = 0;
  1487. }
  1488. b->total_obs = 0;
  1489. return retval;
  1490. }
  1491. /** Set bandwidth history from the state file we just loaded. */
  1492. int
  1493. rep_hist_load_state(or_state_t *state, char **err)
  1494. {
  1495. int all_ok = 1;
  1496. /* Assert they already have been malloced */
  1497. tor_assert(read_array && write_array);
  1498. tor_assert(dir_read_array && dir_write_array);
  1499. #define LOAD(arrname,st) \
  1500. if (rep_hist_load_bwhist_state_section( \
  1501. (arrname), \
  1502. state->BWHistory ## st ## Values, \
  1503. state->BWHistory ## st ## Maxima, \
  1504. state->BWHistory ## st ## Ends, \
  1505. state->BWHistory ## st ## Interval)<0) \
  1506. all_ok = 0
  1507. LOAD(write_array, Write);
  1508. LOAD(read_array, Read);
  1509. LOAD(dir_write_array, DirWrite);
  1510. LOAD(dir_read_array, DirRead);
  1511. #undef LOAD
  1512. if (!all_ok) {
  1513. *err = tor_strdup("Parsing of bandwidth history values failed");
  1514. /* and create fresh arrays */
  1515. bw_arrays_init();
  1516. return -1;
  1517. }
  1518. return 0;
  1519. }
  1520. /*********************************************************************/
  1521. /** A single predicted port: used to remember which ports we've made
  1522. * connections to, so that we can try to keep making circuits that can handle
  1523. * those ports. */
  1524. typedef struct predicted_port_t {
  1525. /** The port we connected to */
  1526. uint16_t port;
  1527. /** The time at which we last used it */
  1528. time_t time;
  1529. } predicted_port_t;
  1530. /** A list of port numbers that have been used recently. */
  1531. static smartlist_t *predicted_ports_list=NULL;
  1532. /** We just got an application request for a connection with
  1533. * port <b>port</b>. Remember it for the future, so we can keep
  1534. * some circuits open that will exit to this port.
  1535. */
  1536. static void
  1537. add_predicted_port(time_t now, uint16_t port)
  1538. {
  1539. predicted_port_t *pp = tor_malloc(sizeof(predicted_port_t));
  1540. pp->port = port;
  1541. pp->time = now;
  1542. rephist_total_alloc += sizeof(*pp);
  1543. smartlist_add(predicted_ports_list, pp);
  1544. }
  1545. /** Initialize whatever memory and structs are needed for predicting
  1546. * which ports will be used. Also seed it with port 80, so we'll build
  1547. * circuits on start-up.
  1548. */
  1549. static void
  1550. predicted_ports_init(void)
  1551. {
  1552. predicted_ports_list = smartlist_new();
  1553. add_predicted_port(time(NULL), 80); /* add one to kickstart us */
  1554. }
  1555. /** Free whatever memory is needed for predicting which ports will
  1556. * be used.
  1557. */
  1558. static void
  1559. predicted_ports_free(void)
  1560. {
  1561. rephist_total_alloc -=
  1562. smartlist_len(predicted_ports_list)*sizeof(predicted_port_t);
  1563. SMARTLIST_FOREACH(predicted_ports_list, predicted_port_t *,
  1564. pp, tor_free(pp));
  1565. smartlist_free(predicted_ports_list);
  1566. }
  1567. /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
  1568. * This is used for predicting what sorts of streams we'll make in the
  1569. * future and making exit circuits to anticipate that.
  1570. */
  1571. void
  1572. rep_hist_note_used_port(time_t now, uint16_t port)
  1573. {
  1574. tor_assert(predicted_ports_list);
  1575. if (!port) /* record nothing */
  1576. return;
  1577. SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
  1578. if (pp->port == port) {
  1579. pp->time = now;
  1580. return;
  1581. }
  1582. } SMARTLIST_FOREACH_END(pp);
  1583. /* it's not there yet; we need to add it */
  1584. add_predicted_port(now, port);
  1585. }
  1586. /** Return a newly allocated pointer to a list of uint16_t * for ports that
  1587. * are likely to be asked for in the near future.
  1588. */
  1589. smartlist_t *
  1590. rep_hist_get_predicted_ports(time_t now)
  1591. {
  1592. int predicted_circs_relevance_time;
  1593. smartlist_t *out = smartlist_new();
  1594. tor_assert(predicted_ports_list);
  1595. predicted_circs_relevance_time = get_options()->PredictedPortsRelevanceTime;
  1596. /* clean out obsolete entries */
  1597. SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
  1598. if (pp->time + predicted_circs_relevance_time < now) {
  1599. log_debug(LD_CIRC, "Expiring predicted port %d", pp->port);
  1600. rephist_total_alloc -= sizeof(predicted_port_t);
  1601. tor_free(pp);
  1602. SMARTLIST_DEL_CURRENT(predicted_ports_list, pp);
  1603. } else {
  1604. smartlist_add(out, tor_memdup(&pp->port, sizeof(uint16_t)));
  1605. }
  1606. } SMARTLIST_FOREACH_END(pp);
  1607. return out;
  1608. }
  1609. /**
  1610. * Take a list of uint16_t *, and remove every port in the list from the
  1611. * current list of predicted ports.
  1612. */
  1613. void
  1614. rep_hist_remove_predicted_ports(const smartlist_t *rmv_ports)
  1615. {
  1616. /* Let's do this on O(N), not O(N^2). */
  1617. bitarray_t *remove_ports = bitarray_init_zero(UINT16_MAX);
  1618. SMARTLIST_FOREACH(rmv_ports, const uint16_t *, p,
  1619. bitarray_set(remove_ports, *p));
  1620. SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
  1621. if (bitarray_is_set(remove_ports, pp->port)) {
  1622. tor_free(pp);
  1623. rephist_total_alloc -= sizeof(*pp);
  1624. SMARTLIST_DEL_CURRENT(predicted_ports_list, pp);
  1625. }
  1626. } SMARTLIST_FOREACH_END(pp);
  1627. bitarray_free(remove_ports);
  1628. }
  1629. /** The user asked us to do a resolve. Rather than keeping track of
  1630. * timings and such of resolves, we fake it for now by treating
  1631. * it the same way as a connection to port 80. This way we will continue
  1632. * to have circuits lying around if the user only uses Tor for resolves.
  1633. */
  1634. void
  1635. rep_hist_note_used_resolve(time_t now)
  1636. {
  1637. rep_hist_note_used_port(now, 80);
  1638. }
  1639. /** The last time at which we needed an internal circ. */
  1640. static time_t predicted_internal_time = 0;
  1641. /** The last time we needed an internal circ with good uptime. */
  1642. static time_t predicted_internal_uptime_time = 0;
  1643. /** The last time we needed an internal circ with good capacity. */
  1644. static time_t predicted_internal_capacity_time = 0;
  1645. /** Remember that we used an internal circ at time <b>now</b>. */
  1646. void
  1647. rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
  1648. {
  1649. predicted_internal_time = now;
  1650. if (need_uptime)
  1651. predicted_internal_uptime_time = now;
  1652. if (need_capacity)
  1653. predicted_internal_capacity_time = now;
  1654. }
  1655. /** Return 1 if we've used an internal circ recently; else return 0. */
  1656. int
  1657. rep_hist_get_predicted_internal(time_t now, int *need_uptime,
  1658. int *need_capacity)
  1659. {
  1660. int predicted_circs_relevance_time;
  1661. predicted_circs_relevance_time = get_options()->PredictedPortsRelevanceTime;
  1662. if (!predicted_internal_time) { /* initialize it */
  1663. predicted_internal_time = now;
  1664. predicted_internal_uptime_time = now;
  1665. predicted_internal_capacity_time = now;
  1666. }
  1667. if (predicted_internal_time + predicted_circs_relevance_time < now)
  1668. return 0; /* too long ago */
  1669. if (predicted_internal_uptime_time + predicted_circs_relevance_time >= now)
  1670. *need_uptime = 1;
  1671. // Always predict that we need capacity.
  1672. *need_capacity = 1;
  1673. return 1;
  1674. }
  1675. /** Any ports used lately? These are pre-seeded if we just started
  1676. * up or if we're running a hidden service. */
  1677. int
  1678. any_predicted_circuits(time_t now)
  1679. {
  1680. int predicted_circs_relevance_time;
  1681. predicted_circs_relevance_time = get_options()->PredictedPortsRelevanceTime;
  1682. return smartlist_len(predicted_ports_list) ||
  1683. predicted_internal_time + predicted_circs_relevance_time >= now;
  1684. }
  1685. /** Return 1 if we have no need for circuits currently, else return 0. */
  1686. int
  1687. rep_hist_circbuilding_dormant(time_t now)
  1688. {
  1689. const or_options_t *options = get_options();
  1690. if (any_predicted_circuits(now))
  1691. return 0;
  1692. /* see if we'll still need to build testing circuits */
  1693. if (server_mode(options) &&
  1694. (!check_whether_orport_reachable(options) ||
  1695. !circuit_enough_testing_circs()))
  1696. return 0;
  1697. if (!check_whether_dirport_reachable(options))
  1698. return 0;
  1699. return 1;
  1700. }
  1701. /** Structure to track how many times we've done each public key operation. */
  1702. static struct {
  1703. /** How many directory objects have we signed? */
  1704. unsigned long n_signed_dir_objs;
  1705. /** How many routerdescs have we signed? */
  1706. unsigned long n_signed_routerdescs;
  1707. /** How many directory objects have we verified? */
  1708. unsigned long n_verified_dir_objs;
  1709. /** How many routerdescs have we verified */
  1710. unsigned long n_verified_routerdescs;
  1711. /** How many onionskins have we encrypted to build circuits? */
  1712. unsigned long n_onionskins_encrypted;
  1713. /** How many onionskins have we decrypted to do circuit build requests? */
  1714. unsigned long n_onionskins_decrypted;
  1715. /** How many times have we done the TLS handshake as a client? */
  1716. unsigned long n_tls_client_handshakes;
  1717. /** How many times have we done the TLS handshake as a server? */
  1718. unsigned long n_tls_server_handshakes;
  1719. /** How many PK operations have we done as a hidden service client? */
  1720. unsigned long n_rend_client_ops;
  1721. /** How many PK operations have we done as a hidden service midpoint? */
  1722. unsigned long n_rend_mid_ops;
  1723. /** How many PK operations have we done as a hidden service provider? */
  1724. unsigned long n_rend_server_ops;
  1725. } pk_op_counts = {0,0,0,0,0,0,0,0,0,0,0};
  1726. /** Increment the count of the number of times we've done <b>operation</b>. */
  1727. void
  1728. note_crypto_pk_op(pk_op_t operation)
  1729. {
  1730. switch (operation)
  1731. {
  1732. case SIGN_DIR:
  1733. pk_op_counts.n_signed_dir_objs++;
  1734. break;
  1735. case SIGN_RTR:
  1736. pk_op_counts.n_signed_routerdescs++;
  1737. break;
  1738. case VERIFY_DIR:
  1739. pk_op_counts.n_verified_dir_objs++;
  1740. break;
  1741. case VERIFY_RTR:
  1742. pk_op_counts.n_verified_routerdescs++;
  1743. break;
  1744. case ENC_ONIONSKIN:
  1745. pk_op_counts.n_onionskins_encrypted++;
  1746. break;
  1747. case DEC_ONIONSKIN:
  1748. pk_op_counts.n_onionskins_decrypted++;
  1749. break;
  1750. case TLS_HANDSHAKE_C:
  1751. pk_op_counts.n_tls_client_handshakes++;
  1752. break;
  1753. case TLS_HANDSHAKE_S:
  1754. pk_op_counts.n_tls_server_handshakes++;
  1755. break;
  1756. case REND_CLIENT:
  1757. pk_op_counts.n_rend_client_ops++;
  1758. break;
  1759. case REND_MID:
  1760. pk_op_counts.n_rend_mid_ops++;
  1761. break;
  1762. case REND_SERVER:
  1763. pk_op_counts.n_rend_server_ops++;
  1764. break;
  1765. default:
  1766. log_warn(LD_BUG, "Unknown pk operation %d", operation);
  1767. }
  1768. }
  1769. /** Log the number of times we've done each public/private-key operation. */
  1770. void
  1771. dump_pk_ops(int severity)
  1772. {
  1773. tor_log(severity, LD_HIST,
  1774. "PK operations: %lu directory objects signed, "
  1775. "%lu directory objects verified, "
  1776. "%lu routerdescs signed, "
  1777. "%lu routerdescs verified, "
  1778. "%lu onionskins encrypted, "
  1779. "%lu onionskins decrypted, "
  1780. "%lu client-side TLS handshakes, "
  1781. "%lu server-side TLS handshakes, "
  1782. "%lu rendezvous client operations, "
  1783. "%lu rendezvous middle operations, "
  1784. "%lu rendezvous server operations.",
  1785. pk_op_counts.n_signed_dir_objs,
  1786. pk_op_counts.n_verified_dir_objs,
  1787. pk_op_counts.n_signed_routerdescs,
  1788. pk_op_counts.n_verified_routerdescs,
  1789. pk_op_counts.n_onionskins_encrypted,
  1790. pk_op_counts.n_onionskins_decrypted,
  1791. pk_op_counts.n_tls_client_handshakes,
  1792. pk_op_counts.n_tls_server_handshakes,
  1793. pk_op_counts.n_rend_client_ops,
  1794. pk_op_counts.n_rend_mid_ops,
  1795. pk_op_counts.n_rend_server_ops);
  1796. }
  1797. /*** Exit port statistics ***/
  1798. /* Some constants */
  1799. /** To what multiple should byte numbers be rounded up? */
  1800. #define EXIT_STATS_ROUND_UP_BYTES 1024
  1801. /** To what multiple should stream counts be rounded up? */
  1802. #define EXIT_STATS_ROUND_UP_STREAMS 4
  1803. /** Number of TCP ports */
  1804. #define EXIT_STATS_NUM_PORTS 65536
  1805. /** Top n ports that will be included in exit stats. */
  1806. #define EXIT_STATS_TOP_N_PORTS 10
  1807. /* The following data structures are arrays and no fancy smartlists or maps,
  1808. * so that all write operations can be done in constant time. This comes at
  1809. * the price of some memory (1.25 MB) and linear complexity when writing
  1810. * stats for measuring relays. */
  1811. /** Number of bytes read in current period by exit port */
  1812. static uint64_t *exit_bytes_read = NULL;
  1813. /** Number of bytes written in current period by exit port */
  1814. static uint64_t *exit_bytes_written = NULL;
  1815. /** Number of streams opened in current period by exit port */
  1816. static uint32_t *exit_streams = NULL;
  1817. /** Start time of exit stats or 0 if we're not collecting exit stats. */
  1818. static time_t start_of_exit_stats_interval;
  1819. /** Initialize exit port stats. */
  1820. void
  1821. rep_hist_exit_stats_init(time_t now)
  1822. {
  1823. start_of_exit_stats_interval = now;
  1824. exit_bytes_read = tor_calloc(EXIT_STATS_NUM_PORTS, sizeof(uint64_t));
  1825. exit_bytes_written = tor_calloc(EXIT_STATS_NUM_PORTS, sizeof(uint64_t));
  1826. exit_streams = tor_calloc(EXIT_STATS_NUM_PORTS, sizeof(uint32_t));
  1827. }
  1828. /** Reset counters for exit port statistics. */
  1829. void
  1830. rep_hist_reset_exit_stats(time_t now)
  1831. {
  1832. start_of_exit_stats_interval = now;
  1833. memset(exit_bytes_read, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
  1834. memset(exit_bytes_written, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
  1835. memset(exit_streams, 0, EXIT_STATS_NUM_PORTS * sizeof(uint32_t));
  1836. }
  1837. /** Stop collecting exit port stats in a way that we can re-start doing
  1838. * so in rep_hist_exit_stats_init(). */
  1839. void
  1840. rep_hist_exit_stats_term(void)
  1841. {
  1842. start_of_exit_stats_interval = 0;
  1843. tor_free(exit_bytes_read);
  1844. tor_free(exit_bytes_written);
  1845. tor_free(exit_streams);
  1846. }
  1847. /** Helper for qsort: compare two ints. Does not handle overflow properly,
  1848. * but works fine for sorting an array of port numbers, which is what we use
  1849. * it for. */
  1850. static int
  1851. compare_int_(const void *x, const void *y)
  1852. {
  1853. return (*(int*)x - *(int*)y);
  1854. }
  1855. /** Return a newly allocated string containing the exit port statistics
  1856. * until <b>now</b>, or NULL if we're not collecting exit stats. Caller
  1857. * must ensure start_of_exit_stats_interval is in the past. */
  1858. char *
  1859. rep_hist_format_exit_stats(time_t now)
  1860. {
  1861. int i, j, top_elements = 0, cur_min_idx = 0, cur_port;
  1862. uint64_t top_bytes[EXIT_STATS_TOP_N_PORTS];
  1863. int top_ports[EXIT_STATS_TOP_N_PORTS];
  1864. uint64_t cur_bytes = 0, other_read = 0, other_written = 0,
  1865. total_read = 0, total_written = 0;
  1866. uint32_t total_streams = 0, other_streams = 0;
  1867. smartlist_t *written_strings, *read_strings, *streams_strings;
  1868. char *written_string, *read_string, *streams_string;
  1869. char t[ISO_TIME_LEN+1];
  1870. char *result;
  1871. if (!start_of_exit_stats_interval)
  1872. return NULL; /* Not initialized. */
  1873. tor_assert(now >= start_of_exit_stats_interval);
  1874. /* Go through all ports to find the n ports that saw most written and
  1875. * read bytes.
  1876. *
  1877. * Invariant: at the end of the loop for iteration i,
  1878. * total_read is the sum of all exit_bytes_read[0..i]
  1879. * total_written is the sum of all exit_bytes_written[0..i]
  1880. * total_stream is the sum of all exit_streams[0..i]
  1881. *
  1882. * top_elements = MAX(EXIT_STATS_TOP_N_PORTS,
  1883. * #{j | 0 <= j <= i && volume(i) > 0})
  1884. *
  1885. * For all 0 <= j < top_elements,
  1886. * top_bytes[j] > 0
  1887. * 0 <= top_ports[j] <= 65535
  1888. * top_bytes[j] = volume(top_ports[j])
  1889. *
  1890. * There is no j in 0..i and k in 0..top_elements such that:
  1891. * volume(j) > top_bytes[k] AND j is not in top_ports[0..top_elements]
  1892. *
  1893. * There is no j!=cur_min_idx in 0..top_elements such that:
  1894. * top_bytes[j] < top_bytes[cur_min_idx]
  1895. *
  1896. * where volume(x) == exit_bytes_read[x]+exit_bytes_written[x]
  1897. *
  1898. * Worst case: O(EXIT_STATS_NUM_PORTS * EXIT_STATS_TOP_N_PORTS)
  1899. */
  1900. for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
  1901. total_read += exit_bytes_read[i];
  1902. total_written += exit_bytes_written[i];
  1903. total_streams += exit_streams[i];
  1904. cur_bytes = exit_bytes_read[i] + exit_bytes_written[i];
  1905. if (cur_bytes == 0) {
  1906. continue;
  1907. }
  1908. if (top_elements < EXIT_STATS_TOP_N_PORTS) {
  1909. top_bytes[top_elements] = cur_bytes;
  1910. top_ports[top_elements++] = i;
  1911. } else if (cur_bytes > top_bytes[cur_min_idx]) {
  1912. top_bytes[cur_min_idx] = cur_bytes;
  1913. top_ports[cur_min_idx] = i;
  1914. } else {
  1915. continue;
  1916. }
  1917. cur_min_idx = 0;
  1918. for (j = 1; j < top_elements; j++) {
  1919. if (top_bytes[j] < top_bytes[cur_min_idx]) {
  1920. cur_min_idx = j;
  1921. }
  1922. }
  1923. }
  1924. /* Add observations of top ports to smartlists. */
  1925. written_strings = smartlist_new();
  1926. read_strings = smartlist_new();
  1927. streams_strings = smartlist_new();
  1928. other_read = total_read;
  1929. other_written = total_written;
  1930. other_streams = total_streams;
  1931. /* Sort the ports; this puts them out of sync with top_bytes, but we
  1932. * won't be using top_bytes again anyway */
  1933. qsort(top_ports, top_elements, sizeof(int), compare_int_);
  1934. for (j = 0; j < top_elements; j++) {
  1935. cur_port = top_ports[j];
  1936. if (exit_bytes_written[cur_port] > 0) {
  1937. uint64_t num = round_uint64_to_next_multiple_of(
  1938. exit_bytes_written[cur_port],
  1939. EXIT_STATS_ROUND_UP_BYTES);
  1940. num /= 1024;
  1941. smartlist_add_asprintf(written_strings, "%d="U64_FORMAT,
  1942. cur_port, U64_PRINTF_ARG(num));
  1943. other_written -= exit_bytes_written[cur_port];
  1944. }
  1945. if (exit_bytes_read[cur_port] > 0) {
  1946. uint64_t num = round_uint64_to_next_multiple_of(
  1947. exit_bytes_read[cur_port],
  1948. EXIT_STATS_ROUND_UP_BYTES);
  1949. num /= 1024;
  1950. smartlist_add_asprintf(read_strings, "%d="U64_FORMAT,
  1951. cur_port, U64_PRINTF_ARG(num));
  1952. other_read -= exit_bytes_read[cur_port];
  1953. }
  1954. if (exit_streams[cur_port] > 0) {
  1955. uint32_t num = round_uint32_to_next_multiple_of(
  1956. exit_streams[cur_port],
  1957. EXIT_STATS_ROUND_UP_STREAMS);
  1958. smartlist_add_asprintf(streams_strings, "%d=%u", cur_port, num);
  1959. other_streams -= exit_streams[cur_port];
  1960. }
  1961. }
  1962. /* Add observations of other ports in a single element. */
  1963. other_written = round_uint64_to_next_multiple_of(other_written,
  1964. EXIT_STATS_ROUND_UP_BYTES);
  1965. other_written /= 1024;
  1966. smartlist_add_asprintf(written_strings, "other="U64_FORMAT,
  1967. U64_PRINTF_ARG(other_written));
  1968. other_read = round_uint64_to_next_multiple_of(other_read,
  1969. EXIT_STATS_ROUND_UP_BYTES);
  1970. other_read /= 1024;
  1971. smartlist_add_asprintf(read_strings, "other="U64_FORMAT,
  1972. U64_PRINTF_ARG(other_read));
  1973. other_streams = round_uint32_to_next_multiple_of(other_streams,
  1974. EXIT_STATS_ROUND_UP_STREAMS);
  1975. smartlist_add_asprintf(streams_strings, "other=%u", other_streams);
  1976. /* Join all observations in single strings. */
  1977. written_string = smartlist_join_strings(written_strings, ",", 0, NULL);
  1978. read_string = smartlist_join_strings(read_strings, ",", 0, NULL);
  1979. streams_string = smartlist_join_strings(streams_strings, ",", 0, NULL);
  1980. SMARTLIST_FOREACH(written_strings, char *, cp, tor_free(cp));
  1981. SMARTLIST_FOREACH(read_strings, char *, cp, tor_free(cp));
  1982. SMARTLIST_FOREACH(streams_strings, char *, cp, tor_free(cp));
  1983. smartlist_free(written_strings);
  1984. smartlist_free(read_strings);
  1985. smartlist_free(streams_strings);
  1986. /* Put everything together. */
  1987. format_iso_time(t, now);
  1988. tor_asprintf(&result, "exit-stats-end %s (%d s)\n"
  1989. "exit-kibibytes-written %s\n"
  1990. "exit-kibibytes-read %s\n"
  1991. "exit-streams-opened %s\n",
  1992. t, (unsigned) (now - start_of_exit_stats_interval),
  1993. written_string,
  1994. read_string,
  1995. streams_string);
  1996. tor_free(written_string);
  1997. tor_free(read_string);
  1998. tor_free(streams_string);
  1999. return result;
  2000. }
  2001. /** If 24 hours have passed since the beginning of the current exit port
  2002. * stats period, write exit stats to $DATADIR/stats/exit-stats (possibly
  2003. * overwriting an existing file) and reset counters. Return when we would
  2004. * next want to write exit stats or 0 if we never want to write. */
  2005. time_t
  2006. rep_hist_exit_stats_write(time_t now)
  2007. {
  2008. char *str = NULL;
  2009. if (!start_of_exit_stats_interval)
  2010. return 0; /* Not initialized. */
  2011. if (start_of_exit_stats_interval + WRITE_STATS_INTERVAL > now)
  2012. goto done; /* Not ready to write. */
  2013. log_info(LD_HIST, "Writing exit port statistics to disk.");
  2014. /* Generate history string. */
  2015. str = rep_hist_format_exit_stats(now);
  2016. /* Reset counters. */
  2017. rep_hist_reset_exit_stats(now);
  2018. /* Try to write to disk. */
  2019. if (!check_or_create_data_subdir("stats")) {
  2020. write_to_data_subdir("stats", "exit-stats", str, "exit port statistics");
  2021. }
  2022. done:
  2023. tor_free(str);
  2024. return start_of_exit_stats_interval + WRITE_STATS_INTERVAL;
  2025. }
  2026. /** Note that we wrote <b>num_written</b> bytes and read <b>num_read</b>
  2027. * bytes to/from an exit connection to <b>port</b>. */
  2028. void
  2029. rep_hist_note_exit_bytes(uint16_t port, size_t num_written,
  2030. size_t num_read)
  2031. {
  2032. if (!start_of_exit_stats_interval)
  2033. return; /* Not initialized. */
  2034. exit_bytes_written[port] += num_written;
  2035. exit_bytes_read[port] += num_read;
  2036. log_debug(LD_HIST, "Written %lu bytes and read %lu bytes to/from an "
  2037. "exit connection to port %d.",
  2038. (unsigned long)num_written, (unsigned long)num_read, port);
  2039. }
  2040. /** Note that we opened an exit stream to <b>port</b>. */
  2041. void
  2042. rep_hist_note_exit_stream_opened(uint16_t port)
  2043. {
  2044. if (!start_of_exit_stats_interval)
  2045. return; /* Not initialized. */
  2046. exit_streams[port]++;
  2047. log_debug(LD_HIST, "Opened exit stream to port %d", port);
  2048. }
  2049. /*** cell statistics ***/
  2050. /** Start of the current buffer stats interval or 0 if we're not
  2051. * collecting buffer statistics. */
  2052. static time_t start_of_buffer_stats_interval;
  2053. /** Initialize buffer stats. */
  2054. void
  2055. rep_hist_buffer_stats_init(time_t now)
  2056. {
  2057. start_of_buffer_stats_interval = now;
  2058. }
  2059. /** Statistics from a single circuit. Collected when the circuit closes, or
  2060. * when we flush statistics to disk. */
  2061. typedef struct circ_buffer_stats_t {
  2062. /** Average number of cells in the circuit's queue */
  2063. double mean_num_cells_in_queue;
  2064. /** Average time a cell waits in the queue. */
  2065. double mean_time_cells_in_queue;
  2066. /** Total number of cells sent over this circuit */
  2067. uint32_t processed_cells;
  2068. } circ_buffer_stats_t;
  2069. /** List of circ_buffer_stats_t. */
  2070. static smartlist_t *circuits_for_buffer_stats = NULL;
  2071. /** Remember cell statistics <b>mean_num_cells_in_queue</b>,
  2072. * <b>mean_time_cells_in_queue</b>, and <b>processed_cells</b> of a
  2073. * circuit. */
  2074. void
  2075. rep_hist_add_buffer_stats(double mean_num_cells_in_queue,
  2076. double mean_time_cells_in_queue, uint32_t processed_cells)
  2077. {
  2078. circ_buffer_stats_t *stat;
  2079. if (!start_of_buffer_stats_interval)
  2080. return; /* Not initialized. */
  2081. stat = tor_malloc_zero(sizeof(circ_buffer_stats_t));
  2082. stat->mean_num_cells_in_queue = mean_num_cells_in_queue;
  2083. stat->mean_time_cells_in_queue = mean_time_cells_in_queue;
  2084. stat->processed_cells = processed_cells;
  2085. if (!circuits_for_buffer_stats)
  2086. circuits_for_buffer_stats = smartlist_new();
  2087. smartlist_add(circuits_for_buffer_stats, stat);
  2088. }
  2089. /** Remember cell statistics for circuit <b>circ</b> at time
  2090. * <b>end_of_interval</b> and reset cell counters in case the circuit
  2091. * remains open in the next measurement interval. */
  2092. void
  2093. rep_hist_buffer_stats_add_circ(circuit_t *circ, time_t end_of_interval)
  2094. {
  2095. time_t start_of_interval;
  2096. int interval_length;
  2097. or_circuit_t *orcirc;
  2098. double mean_num_cells_in_queue, mean_time_cells_in_queue;
  2099. uint32_t processed_cells;
  2100. if (CIRCUIT_IS_ORIGIN(circ))
  2101. return;
  2102. orcirc = TO_OR_CIRCUIT(circ);
  2103. if (!orcirc->processed_cells)
  2104. return;
  2105. start_of_interval = (circ->timestamp_created.tv_sec >
  2106. start_of_buffer_stats_interval) ?
  2107. (time_t)circ->timestamp_created.tv_sec :
  2108. start_of_buffer_stats_interval;
  2109. interval_length = (int) (end_of_interval - start_of_interval);
  2110. if (interval_length <= 0)
  2111. return;
  2112. processed_cells = orcirc->processed_cells;
  2113. /* 1000.0 for s -> ms; 2.0 because of app-ward and exit-ward queues */
  2114. mean_num_cells_in_queue = (double) orcirc->total_cell_waiting_time /
  2115. (double) interval_length / 1000.0 / 2.0;
  2116. mean_time_cells_in_queue =
  2117. (double) orcirc->total_cell_waiting_time /
  2118. (double) orcirc->processed_cells;
  2119. orcirc->total_cell_waiting_time = 0;
  2120. orcirc->processed_cells = 0;
  2121. rep_hist_add_buffer_stats(mean_num_cells_in_queue,
  2122. mean_time_cells_in_queue,
  2123. processed_cells);
  2124. }
  2125. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  2126. * circ_buffer_stats_t */
  2127. static int
  2128. buffer_stats_compare_entries_(const void **_a, const void **_b)
  2129. {
  2130. const circ_buffer_stats_t *a = *_a, *b = *_b;
  2131. if (a->processed_cells < b->processed_cells)
  2132. return 1;
  2133. else if (a->processed_cells > b->processed_cells)
  2134. return -1;
  2135. else
  2136. return 0;
  2137. }
  2138. /** Stop collecting cell stats in a way that we can re-start doing so in
  2139. * rep_hist_buffer_stats_init(). */
  2140. void
  2141. rep_hist_buffer_stats_term(void)
  2142. {
  2143. rep_hist_reset_buffer_stats(0);
  2144. }
  2145. /** Clear history of circuit statistics and set the measurement interval
  2146. * start to <b>now</b>. */
  2147. void
  2148. rep_hist_reset_buffer_stats(time_t now)
  2149. {
  2150. if (!circuits_for_buffer_stats)
  2151. circuits_for_buffer_stats = smartlist_new();
  2152. SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
  2153. stat, tor_free(stat));
  2154. smartlist_clear(circuits_for_buffer_stats);
  2155. start_of_buffer_stats_interval = now;
  2156. }
  2157. /** Return a newly allocated string containing the buffer statistics until
  2158. * <b>now</b>, or NULL if we're not collecting buffer stats. Caller must
  2159. * ensure start_of_buffer_stats_interval is in the past. */
  2160. char *
  2161. rep_hist_format_buffer_stats(time_t now)
  2162. {
  2163. #define SHARES 10
  2164. uint64_t processed_cells[SHARES];
  2165. uint32_t circs_in_share[SHARES];
  2166. int number_of_circuits, i;
  2167. double queued_cells[SHARES], time_in_queue[SHARES];
  2168. smartlist_t *processed_cells_strings, *queued_cells_strings,
  2169. *time_in_queue_strings;
  2170. char *processed_cells_string, *queued_cells_string,
  2171. *time_in_queue_string;
  2172. char t[ISO_TIME_LEN+1];
  2173. char *result;
  2174. if (!start_of_buffer_stats_interval)
  2175. return NULL; /* Not initialized. */
  2176. tor_assert(now >= start_of_buffer_stats_interval);
  2177. /* Calculate deciles if we saw at least one circuit. */
  2178. memset(processed_cells, 0, SHARES * sizeof(uint64_t));
  2179. memset(circs_in_share, 0, SHARES * sizeof(uint32_t));
  2180. memset(queued_cells, 0, SHARES * sizeof(double));
  2181. memset(time_in_queue, 0, SHARES * sizeof(double));
  2182. if (!circuits_for_buffer_stats)
  2183. circuits_for_buffer_stats = smartlist_new();
  2184. number_of_circuits = smartlist_len(circuits_for_buffer_stats);
  2185. if (number_of_circuits > 0) {
  2186. smartlist_sort(circuits_for_buffer_stats,
  2187. buffer_stats_compare_entries_);
  2188. i = 0;
  2189. SMARTLIST_FOREACH_BEGIN(circuits_for_buffer_stats,
  2190. circ_buffer_stats_t *, stat)
  2191. {
  2192. int share = i++ * SHARES / number_of_circuits;
  2193. processed_cells[share] += stat->processed_cells;
  2194. queued_cells[share] += stat->mean_num_cells_in_queue;
  2195. time_in_queue[share] += stat->mean_time_cells_in_queue;
  2196. circs_in_share[share]++;
  2197. }
  2198. SMARTLIST_FOREACH_END(stat);
  2199. }
  2200. /* Write deciles to strings. */
  2201. processed_cells_strings = smartlist_new();
  2202. queued_cells_strings = smartlist_new();
  2203. time_in_queue_strings = smartlist_new();
  2204. for (i = 0; i < SHARES; i++) {
  2205. smartlist_add_asprintf(processed_cells_strings,
  2206. U64_FORMAT, !circs_in_share[i] ? 0 :
  2207. U64_PRINTF_ARG(processed_cells[i] /
  2208. circs_in_share[i]));
  2209. }
  2210. for (i = 0; i < SHARES; i++) {
  2211. smartlist_add_asprintf(queued_cells_strings, "%.2f",
  2212. circs_in_share[i] == 0 ? 0.0 :
  2213. queued_cells[i] / (double) circs_in_share[i]);
  2214. }
  2215. for (i = 0; i < SHARES; i++) {
  2216. smartlist_add_asprintf(time_in_queue_strings, "%.0f",
  2217. circs_in_share[i] == 0 ? 0.0 :
  2218. time_in_queue[i] / (double) circs_in_share[i]);
  2219. }
  2220. /* Join all observations in single strings. */
  2221. processed_cells_string = smartlist_join_strings(processed_cells_strings,
  2222. ",", 0, NULL);
  2223. queued_cells_string = smartlist_join_strings(queued_cells_strings,
  2224. ",", 0, NULL);
  2225. time_in_queue_string = smartlist_join_strings(time_in_queue_strings,
  2226. ",", 0, NULL);
  2227. SMARTLIST_FOREACH(processed_cells_strings, char *, cp, tor_free(cp));
  2228. SMARTLIST_FOREACH(queued_cells_strings, char *, cp, tor_free(cp));
  2229. SMARTLIST_FOREACH(time_in_queue_strings, char *, cp, tor_free(cp));
  2230. smartlist_free(processed_cells_strings);
  2231. smartlist_free(queued_cells_strings);
  2232. smartlist_free(time_in_queue_strings);
  2233. /* Put everything together. */
  2234. format_iso_time(t, now);
  2235. tor_asprintf(&result, "cell-stats-end %s (%d s)\n"
  2236. "cell-processed-cells %s\n"
  2237. "cell-queued-cells %s\n"
  2238. "cell-time-in-queue %s\n"
  2239. "cell-circuits-per-decile %d\n",
  2240. t, (unsigned) (now - start_of_buffer_stats_interval),
  2241. processed_cells_string,
  2242. queued_cells_string,
  2243. time_in_queue_string,
  2244. (number_of_circuits + SHARES - 1) / SHARES);
  2245. tor_free(processed_cells_string);
  2246. tor_free(queued_cells_string);
  2247. tor_free(time_in_queue_string);
  2248. return result;
  2249. #undef SHARES
  2250. }
  2251. /** If 24 hours have passed since the beginning of the current buffer
  2252. * stats period, write buffer stats to $DATADIR/stats/buffer-stats
  2253. * (possibly overwriting an existing file) and reset counters. Return
  2254. * when we would next want to write buffer stats or 0 if we never want to
  2255. * write. */
  2256. time_t
  2257. rep_hist_buffer_stats_write(time_t now)
  2258. {
  2259. char *str = NULL;
  2260. if (!start_of_buffer_stats_interval)
  2261. return 0; /* Not initialized. */
  2262. if (start_of_buffer_stats_interval + WRITE_STATS_INTERVAL > now)
  2263. goto done; /* Not ready to write */
  2264. /* Add open circuits to the history. */
  2265. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  2266. rep_hist_buffer_stats_add_circ(circ, now);
  2267. }
  2268. SMARTLIST_FOREACH_END(circ);
  2269. /* Generate history string. */
  2270. str = rep_hist_format_buffer_stats(now);
  2271. /* Reset both buffer history and counters of open circuits. */
  2272. rep_hist_reset_buffer_stats(now);
  2273. /* Try to write to disk. */
  2274. if (!check_or_create_data_subdir("stats")) {
  2275. write_to_data_subdir("stats", "buffer-stats", str, "buffer statistics");
  2276. }
  2277. done:
  2278. tor_free(str);
  2279. return start_of_buffer_stats_interval + WRITE_STATS_INTERVAL;
  2280. }
  2281. /*** Descriptor serving statistics ***/
  2282. /** Digestmap to track which descriptors were downloaded this stats
  2283. * collection interval. It maps descriptor digest to pointers to 1,
  2284. * effectively turning this into a list. */
  2285. static digestmap_t *served_descs = NULL;
  2286. /** Number of how many descriptors were downloaded in total during this
  2287. * interval. */
  2288. static unsigned long total_descriptor_downloads;
  2289. /** Start time of served descs stats or 0 if we're not collecting those. */
  2290. static time_t start_of_served_descs_stats_interval;
  2291. /** Initialize descriptor stats. */
  2292. void
  2293. rep_hist_desc_stats_init(time_t now)
  2294. {
  2295. if (served_descs) {
  2296. log_warn(LD_BUG, "Called rep_hist_desc_stats_init() when desc stats were "
  2297. "already initialized. This is probably harmless.");
  2298. return; // Already initialized
  2299. }
  2300. served_descs = digestmap_new();
  2301. total_descriptor_downloads = 0;
  2302. start_of_served_descs_stats_interval = now;
  2303. }
  2304. /** Reset served descs stats to empty, starting a new interval <b>now</b>. */
  2305. static void
  2306. rep_hist_reset_desc_stats(time_t now)
  2307. {
  2308. rep_hist_desc_stats_term();
  2309. rep_hist_desc_stats_init(now);
  2310. }
  2311. /** Stop collecting served descs stats, so that rep_hist_desc_stats_init() is
  2312. * safe to be called again. */
  2313. void
  2314. rep_hist_desc_stats_term(void)
  2315. {
  2316. digestmap_free(served_descs, NULL);
  2317. served_descs = NULL;
  2318. start_of_served_descs_stats_interval = 0;
  2319. total_descriptor_downloads = 0;
  2320. }
  2321. /** Helper for rep_hist_desc_stats_write(). Return a newly allocated string
  2322. * containing the served desc statistics until now, or NULL if we're not
  2323. * collecting served desc stats. Caller must ensure that now is not before
  2324. * start_of_served_descs_stats_interval. */
  2325. static char *
  2326. rep_hist_format_desc_stats(time_t now)
  2327. {
  2328. char t[ISO_TIME_LEN+1];
  2329. char *result;
  2330. digestmap_iter_t *iter;
  2331. const char *key;
  2332. void *val;
  2333. unsigned size;
  2334. int *vals, max = 0, q3 = 0, md = 0, q1 = 0, min = 0;
  2335. int n = 0;
  2336. if (!start_of_served_descs_stats_interval)
  2337. return NULL;
  2338. size = digestmap_size(served_descs);
  2339. if (size > 0) {
  2340. vals = tor_calloc(size, sizeof(int));
  2341. for (iter = digestmap_iter_init(served_descs);
  2342. !digestmap_iter_done(iter);
  2343. iter = digestmap_iter_next(served_descs, iter)) {
  2344. uintptr_t count;
  2345. digestmap_iter_get(iter, &key, &val);
  2346. count = (uintptr_t)val;
  2347. vals[n++] = (int)count;
  2348. (void)key;
  2349. }
  2350. max = find_nth_int(vals, size, size-1);
  2351. q3 = find_nth_int(vals, size, (3*size-1)/4);
  2352. md = find_nth_int(vals, size, (size-1)/2);
  2353. q1 = find_nth_int(vals, size, (size-1)/4);
  2354. min = find_nth_int(vals, size, 0);
  2355. tor_free(vals);
  2356. }
  2357. format_iso_time(t, now);
  2358. tor_asprintf(&result,
  2359. "served-descs-stats-end %s (%d s) total=%lu unique=%u "
  2360. "max=%d q3=%d md=%d q1=%d min=%d\n",
  2361. t,
  2362. (unsigned) (now - start_of_served_descs_stats_interval),
  2363. total_descriptor_downloads,
  2364. size, max, q3, md, q1, min);
  2365. return result;
  2366. }
  2367. /** If WRITE_STATS_INTERVAL seconds have passed since the beginning of
  2368. * the current served desc stats interval, write the stats to
  2369. * $DATADIR/stats/served-desc-stats (possibly appending to an existing file)
  2370. * and reset the state for the next interval. Return when we would next want
  2371. * to write served desc stats or 0 if we won't want to write. */
  2372. time_t
  2373. rep_hist_desc_stats_write(time_t now)
  2374. {
  2375. char *filename = NULL, *str = NULL;
  2376. if (!start_of_served_descs_stats_interval)
  2377. return 0; /* We're not collecting stats. */
  2378. if (start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL > now)
  2379. return start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL;
  2380. str = rep_hist_format_desc_stats(now);
  2381. tor_assert(str != NULL);
  2382. if (check_or_create_data_subdir("stats") < 0) {
  2383. goto done;
  2384. }
  2385. filename = get_datadir_fname2("stats", "served-desc-stats");
  2386. if (append_bytes_to_file(filename, str, strlen(str), 0) < 0)
  2387. log_warn(LD_HIST, "Unable to write served descs statistics to disk!");
  2388. rep_hist_reset_desc_stats(now);
  2389. done:
  2390. tor_free(filename);
  2391. tor_free(str);
  2392. return start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL;
  2393. }
  2394. /* DOCDOC rep_hist_note_desc_served */
  2395. void
  2396. rep_hist_note_desc_served(const char * desc)
  2397. {
  2398. void *val;
  2399. uintptr_t count;
  2400. if (!served_descs)
  2401. return; // We're not collecting stats
  2402. val = digestmap_get(served_descs, desc);
  2403. count = (uintptr_t)val;
  2404. if (count != INT_MAX)
  2405. ++count;
  2406. digestmap_set(served_descs, desc, (void*)count);
  2407. total_descriptor_downloads++;
  2408. }
  2409. /*** Connection statistics ***/
  2410. /** Start of the current connection stats interval or 0 if we're not
  2411. * collecting connection statistics. */
  2412. static time_t start_of_conn_stats_interval;
  2413. /** Initialize connection stats. */
  2414. void
  2415. rep_hist_conn_stats_init(time_t now)
  2416. {
  2417. start_of_conn_stats_interval = now;
  2418. }
  2419. /* Count connections that we read and wrote less than these many bytes
  2420. * from/to as below threshold. */
  2421. #define BIDI_THRESHOLD 20480
  2422. /* Count connections that we read or wrote at least this factor as many
  2423. * bytes from/to than we wrote or read to/from as mostly reading or
  2424. * writing. */
  2425. #define BIDI_FACTOR 10
  2426. /* Interval length in seconds for considering read and written bytes for
  2427. * connection stats. */
  2428. #define BIDI_INTERVAL 10
  2429. /** Start of next BIDI_INTERVAL second interval. */
  2430. static time_t bidi_next_interval = 0;
  2431. /** Number of connections that we read and wrote less than BIDI_THRESHOLD
  2432. * bytes from/to in BIDI_INTERVAL seconds. */
  2433. static uint32_t below_threshold = 0;
  2434. /** Number of connections that we read at least BIDI_FACTOR times more
  2435. * bytes from than we wrote to in BIDI_INTERVAL seconds. */
  2436. static uint32_t mostly_read = 0;
  2437. /** Number of connections that we wrote at least BIDI_FACTOR times more
  2438. * bytes to than we read from in BIDI_INTERVAL seconds. */
  2439. static uint32_t mostly_written = 0;
  2440. /** Number of connections that we read and wrote at least BIDI_THRESHOLD
  2441. * bytes from/to, but not BIDI_FACTOR times more in either direction in
  2442. * BIDI_INTERVAL seconds. */
  2443. static uint32_t both_read_and_written = 0;
  2444. /** Entry in a map from connection ID to the number of read and written
  2445. * bytes on this connection in a BIDI_INTERVAL second interval. */
  2446. typedef struct bidi_map_entry_t {
  2447. HT_ENTRY(bidi_map_entry_t) node;
  2448. uint64_t conn_id; /**< Connection ID */
  2449. size_t read; /**< Number of read bytes */
  2450. size_t written; /**< Number of written bytes */
  2451. } bidi_map_entry_t;
  2452. /** Map of OR connections together with the number of read and written
  2453. * bytes in the current BIDI_INTERVAL second interval. */
  2454. static HT_HEAD(bidimap, bidi_map_entry_t) bidi_map =
  2455. HT_INITIALIZER();
  2456. static int
  2457. bidi_map_ent_eq(const bidi_map_entry_t *a, const bidi_map_entry_t *b)
  2458. {
  2459. return a->conn_id == b->conn_id;
  2460. }
  2461. /* DOCDOC bidi_map_ent_hash */
  2462. static unsigned
  2463. bidi_map_ent_hash(const bidi_map_entry_t *entry)
  2464. {
  2465. return (unsigned) entry->conn_id;
  2466. }
  2467. HT_PROTOTYPE(bidimap, bidi_map_entry_t, node, bidi_map_ent_hash,
  2468. bidi_map_ent_eq)
  2469. HT_GENERATE2(bidimap, bidi_map_entry_t, node, bidi_map_ent_hash,
  2470. bidi_map_ent_eq, 0.6, tor_reallocarray_, tor_free_)
  2471. /* DOCDOC bidi_map_free */
  2472. static void
  2473. bidi_map_free(void)
  2474. {
  2475. bidi_map_entry_t **ptr, **next, *ent;
  2476. for (ptr = HT_START(bidimap, &bidi_map); ptr; ptr = next) {
  2477. ent = *ptr;
  2478. next = HT_NEXT_RMV(bidimap, &bidi_map, ptr);
  2479. tor_free(ent);
  2480. }
  2481. HT_CLEAR(bidimap, &bidi_map);
  2482. }
  2483. /** Reset counters for conn statistics. */
  2484. void
  2485. rep_hist_reset_conn_stats(time_t now)
  2486. {
  2487. start_of_conn_stats_interval = now;
  2488. below_threshold = 0;
  2489. mostly_read = 0;
  2490. mostly_written = 0;
  2491. both_read_and_written = 0;
  2492. bidi_map_free();
  2493. }
  2494. /** Stop collecting connection stats in a way that we can re-start doing
  2495. * so in rep_hist_conn_stats_init(). */
  2496. void
  2497. rep_hist_conn_stats_term(void)
  2498. {
  2499. rep_hist_reset_conn_stats(0);
  2500. }
  2501. /** We read <b>num_read</b> bytes and wrote <b>num_written</b> from/to OR
  2502. * connection <b>conn_id</b> in second <b>when</b>. If this is the first
  2503. * observation in a new interval, sum up the last observations. Add bytes
  2504. * for this connection. */
  2505. void
  2506. rep_hist_note_or_conn_bytes(uint64_t conn_id, size_t num_read,
  2507. size_t num_written, time_t when)
  2508. {
  2509. if (!start_of_conn_stats_interval)
  2510. return;
  2511. /* Initialize */
  2512. if (bidi_next_interval == 0)
  2513. bidi_next_interval = when + BIDI_INTERVAL;
  2514. /* Sum up last period's statistics */
  2515. if (when >= bidi_next_interval) {
  2516. bidi_map_entry_t **ptr, **next, *ent;
  2517. for (ptr = HT_START(bidimap, &bidi_map); ptr; ptr = next) {
  2518. ent = *ptr;
  2519. if (ent->read + ent->written < BIDI_THRESHOLD)
  2520. below_threshold++;
  2521. else if (ent->read >= ent->written * BIDI_FACTOR)
  2522. mostly_read++;
  2523. else if (ent->written >= ent->read * BIDI_FACTOR)
  2524. mostly_written++;
  2525. else
  2526. both_read_and_written++;
  2527. next = HT_NEXT_RMV(bidimap, &bidi_map, ptr);
  2528. tor_free(ent);
  2529. }
  2530. while (when >= bidi_next_interval)
  2531. bidi_next_interval += BIDI_INTERVAL;
  2532. log_info(LD_GENERAL, "%d below threshold, %d mostly read, "
  2533. "%d mostly written, %d both read and written.",
  2534. below_threshold, mostly_read, mostly_written,
  2535. both_read_and_written);
  2536. }
  2537. /* Add this connection's bytes. */
  2538. if (num_read > 0 || num_written > 0) {
  2539. bidi_map_entry_t *entry, lookup;
  2540. lookup.conn_id = conn_id;
  2541. entry = HT_FIND(bidimap, &bidi_map, &lookup);
  2542. if (entry) {
  2543. entry->written += num_written;
  2544. entry->read += num_read;
  2545. } else {
  2546. entry = tor_malloc_zero(sizeof(bidi_map_entry_t));
  2547. entry->conn_id = conn_id;
  2548. entry->written = num_written;
  2549. entry->read = num_read;
  2550. HT_INSERT(bidimap, &bidi_map, entry);
  2551. }
  2552. }
  2553. }
  2554. /** Return a newly allocated string containing the connection statistics
  2555. * until <b>now</b>, or NULL if we're not collecting conn stats. Caller must
  2556. * ensure start_of_conn_stats_interval is in the past. */
  2557. char *
  2558. rep_hist_format_conn_stats(time_t now)
  2559. {
  2560. char *result, written[ISO_TIME_LEN+1];
  2561. if (!start_of_conn_stats_interval)
  2562. return NULL; /* Not initialized. */
  2563. tor_assert(now >= start_of_conn_stats_interval);
  2564. format_iso_time(written, now);
  2565. tor_asprintf(&result, "conn-bi-direct %s (%d s) %d,%d,%d,%d\n",
  2566. written,
  2567. (unsigned) (now - start_of_conn_stats_interval),
  2568. below_threshold,
  2569. mostly_read,
  2570. mostly_written,
  2571. both_read_and_written);
  2572. return result;
  2573. }
  2574. /** If 24 hours have passed since the beginning of the current conn stats
  2575. * period, write conn stats to $DATADIR/stats/conn-stats (possibly
  2576. * overwriting an existing file) and reset counters. Return when we would
  2577. * next want to write conn stats or 0 if we never want to write. */
  2578. time_t
  2579. rep_hist_conn_stats_write(time_t now)
  2580. {
  2581. char *str = NULL;
  2582. if (!start_of_conn_stats_interval)
  2583. return 0; /* Not initialized. */
  2584. if (start_of_conn_stats_interval + WRITE_STATS_INTERVAL > now)
  2585. goto done; /* Not ready to write */
  2586. /* Generate history string. */
  2587. str = rep_hist_format_conn_stats(now);
  2588. /* Reset counters. */
  2589. rep_hist_reset_conn_stats(now);
  2590. /* Try to write to disk. */
  2591. if (!check_or_create_data_subdir("stats")) {
  2592. write_to_data_subdir("stats", "conn-stats", str, "connection statistics");
  2593. }
  2594. done:
  2595. tor_free(str);
  2596. return start_of_conn_stats_interval + WRITE_STATS_INTERVAL;
  2597. }
  2598. /** Internal statistics to track how many requests of each type of
  2599. * handshake we've received, and how many we've assigned to cpuworkers.
  2600. * Useful for seeing trends in cpu load.
  2601. * @{ */
  2602. STATIC int onion_handshakes_requested[MAX_ONION_HANDSHAKE_TYPE+1] = {0};
  2603. STATIC int onion_handshakes_assigned[MAX_ONION_HANDSHAKE_TYPE+1] = {0};
  2604. /**@}*/
  2605. /** A new onionskin (using the <b>type</b> handshake) has arrived. */
  2606. void
  2607. rep_hist_note_circuit_handshake_requested(uint16_t type)
  2608. {
  2609. if (type <= MAX_ONION_HANDSHAKE_TYPE)
  2610. onion_handshakes_requested[type]++;
  2611. }
  2612. /** We've sent an onionskin (using the <b>type</b> handshake) to a
  2613. * cpuworker. */
  2614. void
  2615. rep_hist_note_circuit_handshake_assigned(uint16_t type)
  2616. {
  2617. if (type <= MAX_ONION_HANDSHAKE_TYPE)
  2618. onion_handshakes_assigned[type]++;
  2619. }
  2620. /** Log our onionskin statistics since the last time we were called. */
  2621. void
  2622. rep_hist_log_circuit_handshake_stats(time_t now)
  2623. {
  2624. (void)now;
  2625. log_notice(LD_HEARTBEAT, "Circuit handshake stats since last time: "
  2626. "%d/%d TAP, %d/%d NTor.",
  2627. onion_handshakes_assigned[ONION_HANDSHAKE_TYPE_TAP],
  2628. onion_handshakes_requested[ONION_HANDSHAKE_TYPE_TAP],
  2629. onion_handshakes_assigned[ONION_HANDSHAKE_TYPE_NTOR],
  2630. onion_handshakes_requested[ONION_HANDSHAKE_TYPE_NTOR]);
  2631. memset(onion_handshakes_assigned, 0, sizeof(onion_handshakes_assigned));
  2632. memset(onion_handshakes_requested, 0, sizeof(onion_handshakes_requested));
  2633. }
  2634. /* Hidden service statistics section */
  2635. /** Start of the current hidden service stats interval or 0 if we're
  2636. * not collecting hidden service statistics. */
  2637. static time_t start_of_hs_stats_interval;
  2638. /** Carries the various hidden service statistics, and any other
  2639. * information needed. */
  2640. typedef struct hs_stats_t {
  2641. /** How many relay cells have we seen as rendezvous points? */
  2642. uint64_t rp_relay_cells_seen;
  2643. /** Set of unique public key digests we've seen this stat period
  2644. * (could also be implemented as sorted smartlist). */
  2645. digestmap_t *onions_seen_this_period;
  2646. } hs_stats_t;
  2647. /** Our statistics structure singleton. */
  2648. static hs_stats_t *hs_stats = NULL;
  2649. /** Allocate, initialize and return an hs_stats_t structure. */
  2650. static hs_stats_t *
  2651. hs_stats_new(void)
  2652. {
  2653. hs_stats_t * hs_stats = tor_malloc_zero(sizeof(hs_stats_t));
  2654. hs_stats->onions_seen_this_period = digestmap_new();
  2655. return hs_stats;
  2656. }
  2657. /** Free an hs_stats_t structure. */
  2658. static void
  2659. hs_stats_free(hs_stats_t *hs_stats)
  2660. {
  2661. if (!hs_stats) {
  2662. return;
  2663. }
  2664. digestmap_free(hs_stats->onions_seen_this_period, NULL);
  2665. tor_free(hs_stats);
  2666. }
  2667. /** Initialize hidden service statistics. */
  2668. void
  2669. rep_hist_hs_stats_init(time_t now)
  2670. {
  2671. if (!hs_stats) {
  2672. hs_stats = hs_stats_new();
  2673. }
  2674. start_of_hs_stats_interval = now;
  2675. }
  2676. /** Clear history of hidden service statistics and set the measurement
  2677. * interval start to <b>now</b>. */
  2678. static void
  2679. rep_hist_reset_hs_stats(time_t now)
  2680. {
  2681. if (!hs_stats) {
  2682. hs_stats = hs_stats_new();
  2683. }
  2684. hs_stats->rp_relay_cells_seen = 0;
  2685. digestmap_free(hs_stats->onions_seen_this_period, NULL);
  2686. hs_stats->onions_seen_this_period = digestmap_new();
  2687. start_of_hs_stats_interval = now;
  2688. }
  2689. /** Stop collecting hidden service stats in a way that we can re-start
  2690. * doing so in rep_hist_buffer_stats_init(). */
  2691. void
  2692. rep_hist_hs_stats_term(void)
  2693. {
  2694. rep_hist_reset_hs_stats(0);
  2695. }
  2696. /** We saw a new HS relay cell, Count it! */
  2697. void
  2698. rep_hist_seen_new_rp_cell(void)
  2699. {
  2700. if (!hs_stats) {
  2701. return; // We're not collecting stats
  2702. }
  2703. hs_stats->rp_relay_cells_seen++;
  2704. }
  2705. /** As HSDirs, we saw another hidden service with public key
  2706. * <b>pubkey</b>. Check whether we have counted it before, if not
  2707. * count it now! */
  2708. void
  2709. rep_hist_stored_maybe_new_hs(const crypto_pk_t *pubkey)
  2710. {
  2711. char pubkey_hash[DIGEST_LEN];
  2712. if (!hs_stats) {
  2713. return; // We're not collecting stats
  2714. }
  2715. /* Get the digest of the pubkey which will be used to detect whether
  2716. we've seen this hidden service before or not. */
  2717. if (crypto_pk_get_digest(pubkey, pubkey_hash) < 0) {
  2718. /* This fail should not happen; key has been validated by
  2719. descriptor parsing code first. */
  2720. return;
  2721. }
  2722. /* Check if this is the first time we've seen this hidden
  2723. service. If it is, count it as new. */
  2724. if (!digestmap_get(hs_stats->onions_seen_this_period,
  2725. pubkey_hash)) {
  2726. digestmap_set(hs_stats->onions_seen_this_period,
  2727. pubkey_hash, (void*)(uintptr_t)1);
  2728. }
  2729. }
  2730. /* The number of cells that are supposed to be hidden from the adversary
  2731. * by adding noise from the Laplace distribution. This value, divided by
  2732. * EPSILON, is Laplace parameter b. It must be greather than 0. */
  2733. #define REND_CELLS_DELTA_F 2048
  2734. /* Security parameter for obfuscating number of cells with a value between
  2735. * ]0.0, 1.0]. Smaller values obfuscate observations more, but at the same
  2736. * time make statistics less usable. */
  2737. #define REND_CELLS_EPSILON 0.3
  2738. /* The number of cells that are supposed to be hidden from the adversary
  2739. * by rounding up to the next multiple of this number. */
  2740. #define REND_CELLS_BIN_SIZE 1024
  2741. /* The number of service identities that are supposed to be hidden from the
  2742. * adversary by adding noise from the Laplace distribution. This value,
  2743. * divided by EPSILON, is Laplace parameter b. It must be greater than 0. */
  2744. #define ONIONS_SEEN_DELTA_F 8
  2745. /* Security parameter for obfuscating number of service identities with a
  2746. * value between ]0.0, 1.0]. Smaller values obfuscate observations more, but
  2747. * at the same time make statistics less usable. */
  2748. #define ONIONS_SEEN_EPSILON 0.3
  2749. /* The number of service identities that are supposed to be hidden from
  2750. * the adversary by rounding up to the next multiple of this number. */
  2751. #define ONIONS_SEEN_BIN_SIZE 8
  2752. /** Allocate and return a string containing hidden service stats that
  2753. * are meant to be placed in the extra-info descriptor. */
  2754. static char *
  2755. rep_hist_format_hs_stats(time_t now)
  2756. {
  2757. char t[ISO_TIME_LEN+1];
  2758. char *hs_stats_string;
  2759. int64_t obfuscated_cells_seen;
  2760. int64_t obfuscated_onions_seen;
  2761. uint64_t rounded_cells_seen
  2762. = round_uint64_to_next_multiple_of(hs_stats->rp_relay_cells_seen,
  2763. REND_CELLS_BIN_SIZE);
  2764. rounded_cells_seen = MIN(rounded_cells_seen, INT64_MAX);
  2765. obfuscated_cells_seen = add_laplace_noise((int64_t)rounded_cells_seen,
  2766. crypto_rand_double(),
  2767. REND_CELLS_DELTA_F, REND_CELLS_EPSILON);
  2768. uint64_t rounded_onions_seen =
  2769. round_uint64_to_next_multiple_of((size_t)digestmap_size(
  2770. hs_stats->onions_seen_this_period),
  2771. ONIONS_SEEN_BIN_SIZE);
  2772. rounded_onions_seen = MIN(rounded_onions_seen, INT64_MAX);
  2773. obfuscated_onions_seen = add_laplace_noise((int64_t)rounded_onions_seen,
  2774. crypto_rand_double(), ONIONS_SEEN_DELTA_F,
  2775. ONIONS_SEEN_EPSILON);
  2776. format_iso_time(t, now);
  2777. tor_asprintf(&hs_stats_string, "hidserv-stats-end %s (%d s)\n"
  2778. "hidserv-rend-relayed-cells "I64_FORMAT" delta_f=%d "
  2779. "epsilon=%.2f bin_size=%d\n"
  2780. "hidserv-dir-onions-seen "I64_FORMAT" delta_f=%d "
  2781. "epsilon=%.2f bin_size=%d\n",
  2782. t, (unsigned) (now - start_of_hs_stats_interval),
  2783. I64_PRINTF_ARG(obfuscated_cells_seen), REND_CELLS_DELTA_F,
  2784. REND_CELLS_EPSILON, REND_CELLS_BIN_SIZE,
  2785. I64_PRINTF_ARG(obfuscated_onions_seen),
  2786. ONIONS_SEEN_DELTA_F,
  2787. ONIONS_SEEN_EPSILON, ONIONS_SEEN_BIN_SIZE);
  2788. return hs_stats_string;
  2789. }
  2790. /** If 24 hours have passed since the beginning of the current HS
  2791. * stats period, write buffer stats to $DATADIR/stats/hidserv-stats
  2792. * (possibly overwriting an existing file) and reset counters. Return
  2793. * when we would next want to write buffer stats or 0 if we never want to
  2794. * write. */
  2795. time_t
  2796. rep_hist_hs_stats_write(time_t now)
  2797. {
  2798. char *str = NULL;
  2799. if (!start_of_hs_stats_interval) {
  2800. return 0; /* Not initialized. */
  2801. }
  2802. if (start_of_hs_stats_interval + WRITE_STATS_INTERVAL > now) {
  2803. goto done; /* Not ready to write */
  2804. }
  2805. /* Generate history string. */
  2806. str = rep_hist_format_hs_stats(now);
  2807. /* Reset HS history. */
  2808. rep_hist_reset_hs_stats(now);
  2809. /* Try to write to disk. */
  2810. if (!check_or_create_data_subdir("stats")) {
  2811. write_to_data_subdir("stats", "hidserv-stats", str,
  2812. "hidden service stats");
  2813. }
  2814. done:
  2815. tor_free(str);
  2816. return start_of_hs_stats_interval + WRITE_STATS_INTERVAL;
  2817. }
  2818. #define MAX_LINK_PROTO_TO_LOG 4
  2819. static uint64_t link_proto_count[MAX_LINK_PROTO_TO_LOG+1][2];
  2820. /** Note that we negotiated link protocol version <b>link_proto</b>, on
  2821. * a connection that started here iff <b>started_here</b> is true.
  2822. */
  2823. void
  2824. rep_hist_note_negotiated_link_proto(unsigned link_proto, int started_here)
  2825. {
  2826. started_here = !!started_here; /* force to 0 or 1 */
  2827. if (link_proto > MAX_LINK_PROTO_TO_LOG) {
  2828. log_warn(LD_BUG, "Can't log link protocol %u", link_proto);
  2829. return;
  2830. }
  2831. link_proto_count[link_proto][started_here]++;
  2832. }
  2833. /** Log a heartbeat message explaining how many connections of each link
  2834. * protocol version we have used.
  2835. */
  2836. void
  2837. rep_hist_log_link_protocol_counts(void)
  2838. {
  2839. log_notice(LD_HEARTBEAT,
  2840. "Since startup, we have initiated "
  2841. U64_FORMAT" v1 connections, "
  2842. U64_FORMAT" v2 connections, "
  2843. U64_FORMAT" v3 connections, and "
  2844. U64_FORMAT" v4 connections; and received "
  2845. U64_FORMAT" v1 connections, "
  2846. U64_FORMAT" v2 connections, "
  2847. U64_FORMAT" v3 connections, and "
  2848. U64_FORMAT" v4 connections.",
  2849. U64_PRINTF_ARG(link_proto_count[1][1]),
  2850. U64_PRINTF_ARG(link_proto_count[2][1]),
  2851. U64_PRINTF_ARG(link_proto_count[3][1]),
  2852. U64_PRINTF_ARG(link_proto_count[4][1]),
  2853. U64_PRINTF_ARG(link_proto_count[1][0]),
  2854. U64_PRINTF_ARG(link_proto_count[2][0]),
  2855. U64_PRINTF_ARG(link_proto_count[3][0]),
  2856. U64_PRINTF_ARG(link_proto_count[4][0]));
  2857. }
  2858. /** Free all storage held by the OR/link history caches, by the
  2859. * bandwidth history arrays, by the port history, or by statistics . */
  2860. void
  2861. rep_hist_free_all(void)
  2862. {
  2863. hs_stats_free(hs_stats);
  2864. digestmap_free(history_map, free_or_history);
  2865. bw_array_free(read_array);
  2866. read_array = NULL;
  2867. bw_array_free(write_array);
  2868. write_array = NULL;
  2869. bw_array_free(dir_read_array);
  2870. dir_read_array = NULL;
  2871. bw_array_free(dir_write_array);
  2872. dir_write_array = NULL;
  2873. tor_free(exit_bytes_read);
  2874. tor_free(exit_bytes_written);
  2875. tor_free(exit_streams);
  2876. predicted_ports_free();
  2877. bidi_map_free();
  2878. if (circuits_for_buffer_stats) {
  2879. SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *, s,
  2880. tor_free(s));
  2881. smartlist_free(circuits_for_buffer_stats);
  2882. circuits_for_buffer_stats = NULL;
  2883. }
  2884. rep_hist_desc_stats_term();
  2885. total_descriptor_downloads = 0;
  2886. tor_assert_nonfatal(rephist_total_alloc == 0);
  2887. tor_assert_nonfatal_once(rephist_total_num == 0);
  2888. }