rephist.c 104 KB

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