rephist.c 104 KB

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