rephist.c 82 KB

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