rephist.c 75 KB

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