rephist.c 76 KB

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