rephist.c 103 KB

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