rephist.c 76 KB

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