rephist.c 104 KB

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