rephist.c 115 KB

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