rephist.c 112 KB

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