rephist.c 104 KB

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