rephist.c 113 KB

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