rephist.c 69 KB

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