rephist.c 104 KB

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