rephist.c 104 KB

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