rephist.c 104 KB

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