rephist.c 104 KB

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