rephist.c 91 KB

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