rephist.c 106 KB

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