rephist.c 104 KB

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