rephist.c 104 KB

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