rephist.c 104 KB

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