rephist.c 95 KB

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