rephist.c 69 KB

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