rephist.c 104 KB

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