rephist.c 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2009, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rephist.c
  6. * \brief Basic history and "reputation" functionality to remember
  7. * which servers have worked in the past, how much bandwidth we've
  8. * been using, which ports we tend to want, and so on.
  9. **/
  10. #include "or.h"
  11. #include "ht.h"
  12. static void bw_arrays_init(void);
  13. static void predicted_ports_init(void);
  14. static void hs_usage_init(void);
  15. /** Total number of bytes currently allocated in fields used by rephist.c. */
  16. uint64_t rephist_total_alloc=0;
  17. /** Number of or_history_t objects currently allocated. */
  18. uint32_t rephist_total_num=0;
  19. /** If the total weighted run count of all runs for a router ever falls
  20. * below this amount, the router can be treated as having 0 MTBF. */
  21. #define STABILITY_EPSILON 0.0001
  22. /** Value by which to discount all old intervals for MTBF purposes. This
  23. * is compounded every STABILITY_INTERVAL. */
  24. #define STABILITY_ALPHA 0.95
  25. /** Interval at which to discount all old intervals for MTBF purposes. */
  26. #define STABILITY_INTERVAL (12*60*60)
  27. /* (This combination of ALPHA, INTERVAL, and EPSILON makes it so that an
  28. * interval that just ended counts twice as much as one that ended a week ago,
  29. * 20X as much as one that ended a month ago, and routers that have had no
  30. * uptime data for about half a year will get forgotten.) */
  31. /** History of an OR-\>OR link. */
  32. typedef struct link_history_t {
  33. /** When did we start tracking this list? */
  34. time_t since;
  35. /** When did we most recently note a change to this link */
  36. time_t changed;
  37. /** How many times did extending from OR1 to OR2 succeed? */
  38. unsigned long n_extend_ok;
  39. /** How many times did extending from OR1 to OR2 fail? */
  40. unsigned long n_extend_fail;
  41. } link_history_t;
  42. /** History of an OR. */
  43. typedef struct or_history_t {
  44. /** When did we start tracking this OR? */
  45. time_t since;
  46. /** When did we most recently note a change to this OR? */
  47. time_t changed;
  48. /** How many times did we successfully connect? */
  49. unsigned long n_conn_ok;
  50. /** How many times did we try to connect and fail?*/
  51. unsigned long n_conn_fail;
  52. /** How many seconds have we been connected to this OR before
  53. * 'up_since'? */
  54. unsigned long uptime;
  55. /** How many seconds have we been unable to connect to this OR before
  56. * 'down_since'? */
  57. unsigned long downtime;
  58. /** If nonzero, we have been connected since this time. */
  59. time_t up_since;
  60. /** If nonzero, we have been unable to connect since this time. */
  61. time_t down_since;
  62. /* === For MTBF tracking: */
  63. /** Weighted sum total of all times that this router has been online.
  64. */
  65. unsigned long weighted_run_length;
  66. /** If the router is now online (according to stability-checking rules),
  67. * when did it come online? */
  68. time_t start_of_run;
  69. /** Sum of weights for runs in weighted_run_length. */
  70. double total_run_weights;
  71. /* === For fractional uptime tracking: */
  72. time_t start_of_downtime;
  73. unsigned long weighted_uptime;
  74. unsigned long total_weighted_time;
  75. /** Map from hex OR2 identity digest to a link_history_t for the link
  76. * from this OR to OR2. */
  77. digestmap_t *link_history_map;
  78. } or_history_t;
  79. /** When did we last multiply all routers' weighted_run_length and
  80. * total_run_weights by STABILITY_ALPHA? */
  81. static time_t stability_last_downrated = 0;
  82. /** */
  83. static time_t started_tracking_stability = 0;
  84. /** Map from hex OR identity digest to or_history_t. */
  85. static digestmap_t *history_map = NULL;
  86. /** Return the or_history_t for the OR with identity digest <b>id</b>,
  87. * creating it if necessary. */
  88. static or_history_t *
  89. get_or_history(const char* id)
  90. {
  91. or_history_t *hist;
  92. if (tor_mem_is_zero(id, DIGEST_LEN))
  93. return NULL;
  94. hist = digestmap_get(history_map, id);
  95. if (!hist) {
  96. hist = tor_malloc_zero(sizeof(or_history_t));
  97. rephist_total_alloc += sizeof(or_history_t);
  98. rephist_total_num++;
  99. hist->link_history_map = digestmap_new();
  100. hist->since = hist->changed = time(NULL);
  101. digestmap_set(history_map, id, hist);
  102. }
  103. return hist;
  104. }
  105. /** Return the link_history_t for the link from the first named OR to
  106. * the second, creating it if necessary. (ORs are identified by
  107. * identity digest.)
  108. */
  109. static link_history_t *
  110. get_link_history(const char *from_id, const char *to_id)
  111. {
  112. or_history_t *orhist;
  113. link_history_t *lhist;
  114. orhist = get_or_history(from_id);
  115. if (!orhist)
  116. return NULL;
  117. if (tor_mem_is_zero(to_id, DIGEST_LEN))
  118. return NULL;
  119. lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
  120. if (!lhist) {
  121. lhist = tor_malloc_zero(sizeof(link_history_t));
  122. rephist_total_alloc += sizeof(link_history_t);
  123. lhist->since = lhist->changed = time(NULL);
  124. digestmap_set(orhist->link_history_map, to_id, lhist);
  125. }
  126. return lhist;
  127. }
  128. /** Helper: free storage held by a single link history entry. */
  129. static void
  130. _free_link_history(void *val)
  131. {
  132. rephist_total_alloc -= sizeof(link_history_t);
  133. tor_free(val);
  134. }
  135. /** Helper: free storage held by a single OR history entry. */
  136. static void
  137. free_or_history(void *_hist)
  138. {
  139. or_history_t *hist = _hist;
  140. digestmap_free(hist->link_history_map, _free_link_history);
  141. rephist_total_alloc -= sizeof(or_history_t);
  142. rephist_total_num--;
  143. tor_free(hist);
  144. }
  145. /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
  146. * count is up-to-date as of <b>when</b>.
  147. */
  148. static void
  149. update_or_history(or_history_t *hist, time_t when)
  150. {
  151. tor_assert(hist);
  152. if (hist->up_since) {
  153. tor_assert(!hist->down_since);
  154. hist->uptime += (when - hist->up_since);
  155. hist->up_since = when;
  156. } else if (hist->down_since) {
  157. hist->downtime += (when - hist->down_since);
  158. hist->down_since = when;
  159. }
  160. }
  161. /** Initialize the static data structures for tracking history. */
  162. void
  163. rep_hist_init(void)
  164. {
  165. history_map = digestmap_new();
  166. bw_arrays_init();
  167. predicted_ports_init();
  168. hs_usage_init();
  169. }
  170. /** Helper: note that we are no longer connected to the router with history
  171. * <b>hist</b>. If <b>failed</b>, the connection failed; otherwise, it was
  172. * closed correctly. */
  173. static void
  174. mark_or_down(or_history_t *hist, time_t when, int failed)
  175. {
  176. if (hist->up_since) {
  177. hist->uptime += (when - hist->up_since);
  178. hist->up_since = 0;
  179. }
  180. if (failed && !hist->down_since) {
  181. hist->down_since = when;
  182. }
  183. }
  184. /** Helper: note that we are connected to the router with history
  185. * <b>hist</b>. */
  186. static void
  187. mark_or_up(or_history_t *hist, time_t when)
  188. {
  189. if (hist->down_since) {
  190. hist->downtime += (when - hist->down_since);
  191. hist->down_since = 0;
  192. }
  193. if (!hist->up_since) {
  194. hist->up_since = when;
  195. }
  196. }
  197. /** Remember that an attempt to connect to the OR with identity digest
  198. * <b>id</b> failed at <b>when</b>.
  199. */
  200. void
  201. rep_hist_note_connect_failed(const char* id, time_t when)
  202. {
  203. or_history_t *hist;
  204. hist = get_or_history(id);
  205. if (!hist)
  206. return;
  207. ++hist->n_conn_fail;
  208. mark_or_down(hist, when, 1);
  209. hist->changed = when;
  210. }
  211. /** Remember that an attempt to connect to the OR with identity digest
  212. * <b>id</b> succeeded at <b>when</b>.
  213. */
  214. void
  215. rep_hist_note_connect_succeeded(const char* id, time_t when)
  216. {
  217. or_history_t *hist;
  218. hist = get_or_history(id);
  219. if (!hist)
  220. return;
  221. ++hist->n_conn_ok;
  222. mark_or_up(hist, when);
  223. hist->changed = when;
  224. }
  225. /** Remember that we intentionally closed our connection to the OR
  226. * with identity digest <b>id</b> at <b>when</b>.
  227. */
  228. void
  229. rep_hist_note_disconnect(const char* id, time_t when)
  230. {
  231. or_history_t *hist;
  232. hist = get_or_history(id);
  233. if (!hist)
  234. return;
  235. mark_or_down(hist, when, 0);
  236. hist->changed = when;
  237. }
  238. /** Remember that our connection to the OR with identity digest
  239. * <b>id</b> had an error and stopped working at <b>when</b>.
  240. */
  241. void
  242. rep_hist_note_connection_died(const char* id, time_t when)
  243. {
  244. or_history_t *hist;
  245. if (!id) {
  246. /* If conn has no identity, it didn't complete its handshake, or something
  247. * went wrong. Ignore it.
  248. */
  249. return;
  250. }
  251. hist = get_or_history(id);
  252. if (!hist)
  253. return;
  254. mark_or_down(hist, when, 1);
  255. hist->changed = when;
  256. }
  257. /** We have just decided that this router with identity digest <b>id</b> is
  258. * reachable, meaning we will give it a "Running" flag for the next while. */
  259. void
  260. rep_hist_note_router_reachable(const char *id, time_t when)
  261. {
  262. or_history_t *hist = get_or_history(id);
  263. int was_in_run = 1;
  264. char tbuf[ISO_TIME_LEN+1];
  265. tor_assert(hist);
  266. if (!started_tracking_stability)
  267. started_tracking_stability = time(NULL);
  268. if (!hist->start_of_run) {
  269. hist->start_of_run = when;
  270. was_in_run = 0;
  271. }
  272. if (hist->start_of_downtime) {
  273. long down_length;
  274. format_local_iso_time(tbuf, hist->start_of_downtime);
  275. log_info(LD_HIST, "Router %s is now Running; it had been down since %s.",
  276. hex_str(id, DIGEST_LEN), tbuf);
  277. if (was_in_run)
  278. log_info(LD_HIST, " (Paradoxically, it was already Running too.)");
  279. down_length = when - hist->start_of_downtime;
  280. hist->total_weighted_time += down_length;
  281. hist->start_of_downtime = 0;
  282. } else {
  283. format_local_iso_time(tbuf, hist->start_of_run);
  284. if (was_in_run)
  285. log_debug(LD_HIST, "Router %s is still Running; it has been Running "
  286. "since %s", hex_str(id, DIGEST_LEN), tbuf);
  287. else
  288. log_info(LD_HIST,"Router %s is now Running; it was previously untracked",
  289. hex_str(id, DIGEST_LEN));
  290. }
  291. }
  292. /** We have just decided that this router is unreachable, meaning
  293. * we are taking away its "Running" flag. */
  294. void
  295. rep_hist_note_router_unreachable(const char *id, time_t when)
  296. {
  297. or_history_t *hist = get_or_history(id);
  298. char tbuf[ISO_TIME_LEN+1];
  299. int was_running = 0;
  300. if (!started_tracking_stability)
  301. started_tracking_stability = time(NULL);
  302. tor_assert(hist);
  303. if (hist->start_of_run) {
  304. /*XXXX We could treat failed connections differently from failed
  305. * connect attempts. */
  306. long run_length = when - hist->start_of_run;
  307. format_local_iso_time(tbuf, hist->start_of_run);
  308. hist->weighted_run_length += run_length;
  309. hist->total_run_weights += 1.0;
  310. hist->start_of_run = 0;
  311. hist->weighted_uptime += run_length;
  312. hist->total_weighted_time += run_length;
  313. was_running = 1;
  314. log_info(LD_HIST, "Router %s is now non-Running: it had previously been "
  315. "Running since %s. Its total weighted uptime is %lu/%lu.",
  316. hex_str(id, DIGEST_LEN), tbuf, hist->weighted_uptime,
  317. hist->total_weighted_time);
  318. }
  319. if (!hist->start_of_downtime) {
  320. hist->start_of_downtime = when;
  321. if (!was_running)
  322. log_info(LD_HIST, "Router %s is now non-Running; it was previously "
  323. "untracked.", hex_str(id, DIGEST_LEN));
  324. } else {
  325. if (!was_running) {
  326. format_local_iso_time(tbuf, hist->start_of_downtime);
  327. log_info(LD_HIST, "Router %s is still non-Running; it has been "
  328. "non-Running since %s.", hex_str(id, DIGEST_LEN), tbuf);
  329. }
  330. }
  331. }
  332. /** Helper: Discount all old MTBF data, if it is time to do so. Return
  333. * the time at which we should next discount MTBF data. */
  334. time_t
  335. rep_hist_downrate_old_runs(time_t now)
  336. {
  337. digestmap_iter_t *orhist_it;
  338. const char *digest1;
  339. or_history_t *hist;
  340. void *hist_p;
  341. double alpha = 1.0;
  342. if (!history_map)
  343. history_map = digestmap_new();
  344. if (!stability_last_downrated)
  345. stability_last_downrated = now;
  346. if (stability_last_downrated + STABILITY_INTERVAL > now)
  347. return stability_last_downrated + STABILITY_INTERVAL;
  348. /* Okay, we should downrate the data. By how much? */
  349. while (stability_last_downrated + STABILITY_INTERVAL < now) {
  350. stability_last_downrated += STABILITY_INTERVAL;
  351. alpha *= STABILITY_ALPHA;
  352. }
  353. log_info(LD_HIST, "Discounting all old stability info by a factor of %lf",
  354. alpha);
  355. /* Multiply every w_r_l, t_r_w pair by alpha. */
  356. for (orhist_it = digestmap_iter_init(history_map);
  357. !digestmap_iter_done(orhist_it);
  358. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  359. digestmap_iter_get(orhist_it, &digest1, &hist_p);
  360. hist = hist_p;
  361. hist->weighted_run_length =
  362. (unsigned long)(hist->weighted_run_length * alpha);
  363. hist->total_run_weights *= alpha;
  364. hist->weighted_uptime = (unsigned long)(hist->weighted_uptime * alpha);
  365. hist->total_weighted_time = (unsigned long)
  366. (hist->total_weighted_time * alpha);
  367. }
  368. return stability_last_downrated + STABILITY_INTERVAL;
  369. }
  370. /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
  371. static double
  372. get_stability(or_history_t *hist, time_t when)
  373. {
  374. unsigned long total = hist->weighted_run_length;
  375. double total_weights = hist->total_run_weights;
  376. if (hist->start_of_run) {
  377. /* We're currently in a run. Let total and total_weights hold the values
  378. * they would hold if the current run were to end now. */
  379. total += (when-hist->start_of_run);
  380. total_weights += 1.0;
  381. }
  382. if (total_weights < STABILITY_EPSILON) {
  383. /* Round down to zero, and avoid divide-by-zero. */
  384. return 0.0;
  385. }
  386. return total / total_weights;
  387. }
  388. /** Return the total amount of time we've been observing, with each run of
  389. * time downrated by the appropriate factor. */
  390. static long
  391. get_total_weighted_time(or_history_t *hist, time_t when)
  392. {
  393. long total = hist->total_weighted_time;
  394. if (hist->start_of_run) {
  395. total += (when - hist->start_of_run);
  396. } else if (hist->start_of_downtime) {
  397. total += (when - hist->start_of_downtime);
  398. }
  399. return total;
  400. }
  401. /** Helper: Return the weighted percent-of-time-online of the router with
  402. * history <b>hist</b>. */
  403. static double
  404. get_weighted_fractional_uptime(or_history_t *hist, time_t when)
  405. {
  406. unsigned long total = hist->total_weighted_time;
  407. unsigned long up = hist->weighted_uptime;
  408. if (hist->start_of_run) {
  409. long run_length = (when - hist->start_of_run);
  410. up += run_length;
  411. total += run_length;
  412. } else if (hist->start_of_downtime) {
  413. total += (when - hist->start_of_downtime);
  414. }
  415. if (!total) {
  416. /* Avoid calling anybody's uptime infinity (which should be impossible if
  417. * the code is working), or NaN (which can happen for any router we haven't
  418. * observed up or down yet). */
  419. return 0.0;
  420. }
  421. return ((double) up) / total;
  422. }
  423. /** Return an estimated MTBF for the router whose identity digest is
  424. * <b>id</b>. Return 0 if the router is unknown. */
  425. double
  426. rep_hist_get_stability(const char *id, time_t when)
  427. {
  428. or_history_t *hist = get_or_history(id);
  429. if (!hist)
  430. return 0.0;
  431. return get_stability(hist, when);
  432. }
  433. /** Return an estimated percent-of-time-online for the router whose identity
  434. * digest is <b>id</b>. Return 0 if the router is unknown. */
  435. double
  436. rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
  437. {
  438. or_history_t *hist = get_or_history(id);
  439. if (!hist)
  440. return 0.0;
  441. return get_weighted_fractional_uptime(hist, when);
  442. }
  443. /** Return a number representing how long we've known about the router whose
  444. * digest is <b>id</b>. Return 0 if the router is unknown.
  445. *
  446. * Be careful: this measure increases monotonically as we know the router for
  447. * longer and longer, but it doesn't increase linearly.
  448. */
  449. long
  450. rep_hist_get_weighted_time_known(const char *id, time_t when)
  451. {
  452. or_history_t *hist = get_or_history(id);
  453. if (!hist)
  454. return 0;
  455. return get_total_weighted_time(hist, when);
  456. }
  457. /** Return true if we've been measuring MTBFs for long enough to
  458. * pronounce on Stability. */
  459. int
  460. rep_hist_have_measured_enough_stability(void)
  461. {
  462. /* XXXX021 This doesn't do so well when we change our opinion
  463. * as to whether we're tracking router stability. */
  464. return started_tracking_stability < time(NULL) - 4*60*60;
  465. }
  466. /** Remember that we successfully extended from the OR with identity
  467. * digest <b>from_id</b> to the OR with identity digest
  468. * <b>to_name</b>.
  469. */
  470. void
  471. rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
  472. {
  473. link_history_t *hist;
  474. /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
  475. hist = get_link_history(from_id, to_id);
  476. if (!hist)
  477. return;
  478. ++hist->n_extend_ok;
  479. hist->changed = time(NULL);
  480. }
  481. /** Remember that we tried to extend from the OR with identity digest
  482. * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
  483. * failed.
  484. */
  485. void
  486. rep_hist_note_extend_failed(const char *from_id, const char *to_id)
  487. {
  488. link_history_t *hist;
  489. /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
  490. hist = get_link_history(from_id, to_id);
  491. if (!hist)
  492. return;
  493. ++hist->n_extend_fail;
  494. hist->changed = time(NULL);
  495. }
  496. /** Log all the reliability data we have remembered, with the chosen
  497. * severity.
  498. */
  499. void
  500. rep_hist_dump_stats(time_t now, int severity)
  501. {
  502. digestmap_iter_t *lhist_it;
  503. digestmap_iter_t *orhist_it;
  504. const char *name1, *name2, *digest1, *digest2;
  505. char hexdigest1[HEX_DIGEST_LEN+1];
  506. or_history_t *or_history;
  507. link_history_t *link_history;
  508. void *or_history_p, *link_history_p;
  509. double uptime;
  510. char buffer[2048];
  511. size_t len;
  512. int ret;
  513. unsigned long upt, downt;
  514. routerinfo_t *r;
  515. rep_history_clean(now - get_options()->RephistTrackTime);
  516. log(severity, LD_HIST, "--------------- Dumping history information:");
  517. for (orhist_it = digestmap_iter_init(history_map);
  518. !digestmap_iter_done(orhist_it);
  519. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  520. double s;
  521. long stability;
  522. digestmap_iter_get(orhist_it, &digest1, &or_history_p);
  523. or_history = (or_history_t*) or_history_p;
  524. if ((r = router_get_by_digest(digest1)))
  525. name1 = r->nickname;
  526. else
  527. name1 = "(unknown)";
  528. base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
  529. update_or_history(or_history, now);
  530. upt = or_history->uptime;
  531. downt = or_history->downtime;
  532. s = get_stability(or_history, now);
  533. stability = (long)s;
  534. if (upt+downt) {
  535. uptime = ((double)upt) / (upt+downt);
  536. } else {
  537. uptime=1.0;
  538. }
  539. log(severity, LD_HIST,
  540. "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
  541. "wmtbf %lu:%02lu:%02lu",
  542. name1, hexdigest1,
  543. or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
  544. upt, upt+downt, uptime*100.0,
  545. stability/3600, (stability/60)%60, stability%60);
  546. if (!digestmap_isempty(or_history->link_history_map)) {
  547. strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
  548. len = strlen(buffer);
  549. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  550. !digestmap_iter_done(lhist_it);
  551. lhist_it = digestmap_iter_next(or_history->link_history_map,
  552. lhist_it)) {
  553. digestmap_iter_get(lhist_it, &digest2, &link_history_p);
  554. if ((r = router_get_by_digest(digest2)))
  555. name2 = r->nickname;
  556. else
  557. name2 = "(unknown)";
  558. link_history = (link_history_t*) link_history_p;
  559. ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
  560. link_history->n_extend_ok,
  561. link_history->n_extend_ok+link_history->n_extend_fail);
  562. if (ret<0)
  563. break;
  564. else
  565. len += ret;
  566. }
  567. log(severity, LD_HIST, "%s", buffer);
  568. }
  569. }
  570. }
  571. /** Remove history info for routers/links that haven't changed since
  572. * <b>before</b>.
  573. */
  574. void
  575. rep_history_clean(time_t before)
  576. {
  577. int authority = authdir_mode(get_options());
  578. or_history_t *or_history;
  579. link_history_t *link_history;
  580. void *or_history_p, *link_history_p;
  581. digestmap_iter_t *orhist_it, *lhist_it;
  582. const char *d1, *d2;
  583. orhist_it = digestmap_iter_init(history_map);
  584. while (!digestmap_iter_done(orhist_it)) {
  585. int remove;
  586. digestmap_iter_get(orhist_it, &d1, &or_history_p);
  587. or_history = or_history_p;
  588. remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
  589. !or_history->start_of_run)
  590. : (or_history->changed < before);
  591. if (remove) {
  592. orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
  593. free_or_history(or_history);
  594. continue;
  595. }
  596. for (lhist_it = digestmap_iter_init(or_history->link_history_map);
  597. !digestmap_iter_done(lhist_it); ) {
  598. digestmap_iter_get(lhist_it, &d2, &link_history_p);
  599. link_history = link_history_p;
  600. if (link_history->changed < before) {
  601. lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
  602. lhist_it);
  603. rephist_total_alloc -= sizeof(link_history_t);
  604. tor_free(link_history);
  605. continue;
  606. }
  607. lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
  608. }
  609. orhist_it = digestmap_iter_next(history_map, orhist_it);
  610. }
  611. }
  612. /** Write MTBF data to disk. Return 0 on success, negative on failure.
  613. *
  614. * If <b>missing_means_down</b>, then if we're about to write an entry
  615. * that is still considered up but isn't in our routerlist, consider it
  616. * to be down. */
  617. int
  618. rep_hist_record_mtbf_data(time_t now, int missing_means_down)
  619. {
  620. char time_buf[ISO_TIME_LEN+1];
  621. digestmap_iter_t *orhist_it;
  622. const char *digest;
  623. void *or_history_p;
  624. or_history_t *hist;
  625. open_file_t *open_file = NULL;
  626. FILE *f;
  627. {
  628. char *filename = get_datadir_fname("router-stability");
  629. f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
  630. &open_file);
  631. tor_free(filename);
  632. if (!f)
  633. return -1;
  634. }
  635. /* File format is:
  636. * FormatLine *KeywordLine Data
  637. *
  638. * FormatLine = "format 1" NL
  639. * KeywordLine = Keyword SP Arguments NL
  640. * Data = "data" NL *RouterMTBFLine "." NL
  641. * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
  642. * TotalRunWeights [SP S=StartRunTime] NL
  643. */
  644. #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
  645. #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
  646. PUT("format 2\n");
  647. format_iso_time(time_buf, time(NULL));
  648. PRINTF((f, "stored-at %s\n", time_buf));
  649. if (started_tracking_stability) {
  650. format_iso_time(time_buf, started_tracking_stability);
  651. PRINTF((f, "tracked-since %s\n", time_buf));
  652. }
  653. if (stability_last_downrated) {
  654. format_iso_time(time_buf, stability_last_downrated);
  655. PRINTF((f, "last-downrated %s\n", time_buf));
  656. }
  657. PUT("data\n");
  658. /* XXX Nick: now bridge auths record this for all routers too.
  659. * Should we make them record it only for bridge routers? -RD
  660. * Not for 0.2.0. -NM */
  661. for (orhist_it = digestmap_iter_init(history_map);
  662. !digestmap_iter_done(orhist_it);
  663. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  664. char dbuf[HEX_DIGEST_LEN+1];
  665. const char *t = NULL;
  666. digestmap_iter_get(orhist_it, &digest, &or_history_p);
  667. hist = (or_history_t*) or_history_p;
  668. base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
  669. if (missing_means_down && hist->start_of_run &&
  670. !router_get_by_digest(digest)) {
  671. /* We think this relay is running, but it's not listed in our
  672. * routerlist. Somehow it fell out without telling us it went
  673. * down. Complain and also correct it. */
  674. log_info(LD_HIST,
  675. "Relay '%s' is listed as up in rephist, but it's not in "
  676. "our routerlist. Correcting.", dbuf);
  677. rep_hist_note_router_unreachable(digest, now);
  678. }
  679. PRINTF((f, "R %s\n", dbuf));
  680. if (hist->start_of_run > 0) {
  681. format_iso_time(time_buf, hist->start_of_run);
  682. t = time_buf;
  683. }
  684. PRINTF((f, "+MTBF %lu %.5lf%s%s\n",
  685. hist->weighted_run_length, hist->total_run_weights,
  686. t ? " S=" : "", t ? t : ""));
  687. t = NULL;
  688. if (hist->start_of_downtime > 0) {
  689. format_iso_time(time_buf, hist->start_of_downtime);
  690. t = time_buf;
  691. }
  692. PRINTF((f, "+WFU %lu %lu%s%s\n",
  693. hist->weighted_uptime, hist->total_weighted_time,
  694. t ? " S=" : "", t ? t : ""));
  695. }
  696. PUT(".\n");
  697. #undef PUT
  698. #undef PRINTF
  699. return finish_writing_to_file(open_file);
  700. err:
  701. abort_writing_to_file(open_file);
  702. return -1;
  703. }
  704. /** Format the current tracked status of the router in <b>hist</b> at time
  705. * <b>now</b> for analysis; return it in a newly allocated string. */
  706. static char *
  707. rep_hist_format_router_status(or_history_t *hist, time_t now)
  708. {
  709. char buf[1024];
  710. char sor_buf[ISO_TIME_LEN+1];
  711. char sod_buf[ISO_TIME_LEN+1];
  712. double wfu;
  713. double mtbf;
  714. int up = 0, down = 0;
  715. if (hist->start_of_run) {
  716. format_iso_time(sor_buf, hist->start_of_run);
  717. up = 1;
  718. }
  719. if (hist->start_of_downtime) {
  720. format_iso_time(sod_buf, hist->start_of_downtime);
  721. down = 1;
  722. }
  723. wfu = get_weighted_fractional_uptime(hist, now);
  724. mtbf = get_stability(hist, now);
  725. tor_snprintf(buf, sizeof(buf),
  726. "%s%s%s"
  727. "%s%s%s"
  728. "wfu %0.3lf\n"
  729. " weighted-time %lu\n"
  730. " weighted-uptime %lu\n"
  731. "mtbf %0.1lf\n"
  732. " weighted-run-length %lu\n"
  733. " total-run-weights %lf\n",
  734. up?"uptime-started ":"", up?sor_buf:"", up?" UTC\n":"",
  735. down?"downtime-started ":"", down?sod_buf:"", down?" UTC\n":"",
  736. wfu,
  737. hist->total_weighted_time,
  738. hist->weighted_uptime,
  739. mtbf,
  740. hist->weighted_run_length,
  741. hist->total_run_weights
  742. );
  743. return tor_strdup(buf);
  744. }
  745. /** The last stability analysis document that we created, or NULL if we never
  746. * have created one. */
  747. static char *last_stability_doc = NULL;
  748. /** The last time we created a stability analysis document, or 0 if we never
  749. * have created one. */
  750. static time_t built_last_stability_doc_at = 0;
  751. /** Shortest allowable time between building two stability documents. */
  752. #define MAX_STABILITY_DOC_BUILD_RATE (3*60)
  753. /** Return a pointer to a NUL-terminated document describing our view of the
  754. * stability of the routers we've been tracking. Return NULL on failure. */
  755. const char *
  756. rep_hist_get_router_stability_doc(time_t now)
  757. {
  758. char *result;
  759. smartlist_t *chunks;
  760. if (built_last_stability_doc_at + MAX_STABILITY_DOC_BUILD_RATE > now)
  761. return last_stability_doc;
  762. if (!history_map)
  763. return NULL;
  764. tor_free(last_stability_doc);
  765. chunks = smartlist_create();
  766. if (rep_hist_have_measured_enough_stability()) {
  767. smartlist_add(chunks, tor_strdup("we-have-enough-measurements\n"));
  768. } else {
  769. smartlist_add(chunks, tor_strdup("we-do-not-have-enough-measurements\n"));
  770. }
  771. DIGESTMAP_FOREACH(history_map, id, or_history_t *, hist) {
  772. routerinfo_t *ri;
  773. char dbuf[BASE64_DIGEST_LEN+1];
  774. char header_buf[512];
  775. char *info;
  776. digest_to_base64(dbuf, id);
  777. ri = router_get_by_digest(id);
  778. if (ri) {
  779. char *ip = tor_dup_ip(ri->addr);
  780. char tbuf[ISO_TIME_LEN+1];
  781. format_iso_time(tbuf, ri->cache_info.published_on);
  782. tor_snprintf(header_buf, sizeof(header_buf),
  783. "router %s %s %s\n"
  784. "published %s\n"
  785. "relevant-flags %s%s%s\n"
  786. "declared-uptime %ld\n",
  787. dbuf, ri->nickname, ip,
  788. tbuf,
  789. ri->is_running ? "Running " : "",
  790. ri->is_valid ? "Valid " : "",
  791. ri->is_hibernating ? "Hibernating " : "",
  792. ri->uptime);
  793. tor_free(ip);
  794. } else {
  795. tor_snprintf(header_buf, sizeof(header_buf),
  796. "router %s {no descriptor}\n", dbuf);
  797. }
  798. smartlist_add(chunks, tor_strdup(header_buf));
  799. info = rep_hist_format_router_status(hist, now);
  800. if (info)
  801. smartlist_add(chunks, info);
  802. } DIGESTMAP_FOREACH_END;
  803. result = smartlist_join_strings(chunks, "", 0, NULL);
  804. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  805. smartlist_free(chunks);
  806. last_stability_doc = result;
  807. built_last_stability_doc_at = time(NULL);
  808. return result;
  809. }
  810. /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
  811. * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
  812. * such line exists. */
  813. static int
  814. find_next_with(smartlist_t *sl, int i, const char *prefix)
  815. {
  816. for ( ; i < smartlist_len(sl); ++i) {
  817. const char *line = smartlist_get(sl, i);
  818. if (!strcmpstart(line, prefix))
  819. return i;
  820. if (!strcmpstart(line, "R "))
  821. return -1;
  822. }
  823. return -1;
  824. }
  825. /** How many bad times has parse_possibly_bad_iso_time parsed? */
  826. static int n_bogus_times = 0;
  827. /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
  828. * rounds any pre-1970 date to Jan 1, 1970. */
  829. static int
  830. parse_possibly_bad_iso_time(const char *s, time_t *time_out)
  831. {
  832. int year;
  833. char b[5];
  834. strlcpy(b, s, sizeof(b));
  835. b[4] = '\0';
  836. year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
  837. if (year < 1970) {
  838. *time_out = 0;
  839. ++n_bogus_times;
  840. return 0;
  841. } else
  842. return parse_iso_time(s, time_out);
  843. }
  844. /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
  845. * says we started measuring at <b>started_measuring</b>. Return a new number
  846. * that's about as much before <b>now</b> as <b>t</b> was before
  847. * <b>stored_at</b>.
  848. */
  849. static INLINE time_t
  850. correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
  851. {
  852. if (t < started_measuring - 24*60*60*365)
  853. return 0;
  854. else if (t < started_measuring)
  855. return started_measuring;
  856. else if (t > stored_at)
  857. return 0;
  858. else {
  859. long run_length = stored_at - t;
  860. t = now - run_length;
  861. if (t < started_measuring)
  862. t = started_measuring;
  863. return t;
  864. }
  865. }
  866. /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
  867. * on failure. */
  868. int
  869. rep_hist_load_mtbf_data(time_t now)
  870. {
  871. /* XXXX won't handle being called while history is already populated. */
  872. smartlist_t *lines;
  873. const char *line = NULL;
  874. int r=0, i;
  875. time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
  876. time_t latest_possible_start = now;
  877. long format = -1;
  878. {
  879. char *filename = get_datadir_fname("router-stability");
  880. char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  881. tor_free(filename);
  882. if (!d)
  883. return -1;
  884. lines = smartlist_create();
  885. smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
  886. tor_free(d);
  887. }
  888. {
  889. const char *firstline;
  890. if (smartlist_len(lines)>4) {
  891. firstline = smartlist_get(lines, 0);
  892. if (!strcmpstart(firstline, "format "))
  893. format = tor_parse_long(firstline+strlen("format "),
  894. 10, -1, LONG_MAX, NULL, NULL);
  895. }
  896. }
  897. if (format != 1 && format != 2) {
  898. log_warn(LD_HIST,
  899. "Unrecognized format in mtbf history file. Skipping.");
  900. goto err;
  901. }
  902. for (i = 1; i < smartlist_len(lines); ++i) {
  903. line = smartlist_get(lines, i);
  904. if (!strcmp(line, "data"))
  905. break;
  906. if (!strcmpstart(line, "last-downrated ")) {
  907. if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
  908. log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
  909. "history file.");
  910. }
  911. if (!strcmpstart(line, "stored-at ")) {
  912. if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
  913. log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
  914. "history file.");
  915. }
  916. if (!strcmpstart(line, "tracked-since ")) {
  917. if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
  918. log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
  919. "history file.");
  920. }
  921. }
  922. if (last_downrated > now)
  923. last_downrated = now;
  924. if (tracked_since > now)
  925. tracked_since = now;
  926. if (!stored_at) {
  927. log_warn(LD_HIST, "No stored time recorded.");
  928. goto err;
  929. }
  930. if (line && !strcmp(line, "data"))
  931. ++i;
  932. n_bogus_times = 0;
  933. for (; i < smartlist_len(lines); ++i) {
  934. char digest[DIGEST_LEN];
  935. char hexbuf[HEX_DIGEST_LEN+1];
  936. char mtbf_timebuf[ISO_TIME_LEN+1];
  937. char wfu_timebuf[ISO_TIME_LEN+1];
  938. time_t start_of_run = 0;
  939. time_t start_of_downtime = 0;
  940. int have_mtbf = 0, have_wfu = 0;
  941. long wrl = 0;
  942. double trw = 0;
  943. long wt_uptime = 0, total_wt_time = 0;
  944. int n;
  945. or_history_t *hist;
  946. line = smartlist_get(lines, i);
  947. if (!strcmp(line, "."))
  948. break;
  949. mtbf_timebuf[0] = '\0';
  950. wfu_timebuf[0] = '\0';
  951. if (format == 1) {
  952. n = sscanf(line, "%40s %ld %lf S=%10s %8s",
  953. hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
  954. if (n != 3 && n != 5) {
  955. log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
  956. continue;
  957. }
  958. have_mtbf = 1;
  959. } else {
  960. // format == 2.
  961. int mtbf_idx, wfu_idx;
  962. if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
  963. continue;
  964. strlcpy(hexbuf, line+2, sizeof(hexbuf));
  965. mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
  966. wfu_idx = find_next_with(lines, i+1, "+WFU ");
  967. if (mtbf_idx >= 0) {
  968. const char *mtbfline = smartlist_get(lines, mtbf_idx);
  969. n = sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
  970. &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
  971. if (n == 2 || n == 4) {
  972. have_mtbf = 1;
  973. } else {
  974. log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
  975. escaped(mtbfline));
  976. }
  977. }
  978. if (wfu_idx >= 0) {
  979. const char *wfuline = smartlist_get(lines, wfu_idx);
  980. n = sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
  981. &wt_uptime, &total_wt_time,
  982. wfu_timebuf, wfu_timebuf+11);
  983. if (n == 2 || n == 4) {
  984. have_wfu = 1;
  985. } else {
  986. log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
  987. }
  988. }
  989. if (wfu_idx > i)
  990. i = wfu_idx;
  991. if (mtbf_idx > i)
  992. i = mtbf_idx;
  993. }
  994. if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
  995. log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
  996. continue;
  997. }
  998. hist = get_or_history(digest);
  999. if (!hist)
  1000. continue;
  1001. if (have_mtbf) {
  1002. if (mtbf_timebuf[0]) {
  1003. mtbf_timebuf[10] = ' ';
  1004. if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
  1005. log_warn(LD_HIST, "Couldn't parse time %s",
  1006. escaped(mtbf_timebuf));
  1007. }
  1008. hist->start_of_run = correct_time(start_of_run, now, stored_at,
  1009. tracked_since);
  1010. if (hist->start_of_run < latest_possible_start + wrl)
  1011. latest_possible_start = hist->start_of_run - wrl;
  1012. hist->weighted_run_length = wrl;
  1013. hist->total_run_weights = trw;
  1014. }
  1015. if (have_wfu) {
  1016. if (wfu_timebuf[0]) {
  1017. wfu_timebuf[10] = ' ';
  1018. if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
  1019. log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
  1020. }
  1021. }
  1022. hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
  1023. tracked_since);
  1024. hist->weighted_uptime = wt_uptime;
  1025. hist->total_weighted_time = total_wt_time;
  1026. }
  1027. if (strcmp(line, "."))
  1028. log_warn(LD_HIST, "Truncated MTBF file.");
  1029. if (tracked_since < 86400*365) /* Recover from insanely early value. */
  1030. tracked_since = latest_possible_start;
  1031. stability_last_downrated = last_downrated;
  1032. started_tracking_stability = tracked_since;
  1033. goto done;
  1034. err:
  1035. r = -1;
  1036. done:
  1037. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1038. smartlist_free(lines);
  1039. return r;
  1040. }
  1041. /** For how many seconds do we keep track of individual per-second bandwidth
  1042. * totals? */
  1043. #define NUM_SECS_ROLLING_MEASURE 10
  1044. /** How large are the intervals for which we track and report bandwidth use? */
  1045. #define NUM_SECS_BW_SUM_INTERVAL (15*60)
  1046. /** How far in the past do we remember and publish bandwidth use? */
  1047. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
  1048. /** How many bandwidth usage intervals do we remember? (derived) */
  1049. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  1050. /** Structure to track bandwidth use, and remember the maxima for a given
  1051. * time period.
  1052. */
  1053. typedef struct bw_array_t {
  1054. /** Observation array: Total number of bytes transferred in each of the last
  1055. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  1056. uint64_t obs[NUM_SECS_ROLLING_MEASURE];
  1057. int cur_obs_idx; /**< Current position in obs. */
  1058. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  1059. uint64_t total_obs; /**< Total for all members of obs except
  1060. * obs[cur_obs_idx] */
  1061. uint64_t max_total; /**< Largest value that total_obs has taken on in the
  1062. * current period. */
  1063. uint64_t total_in_period; /**< Total bytes transferred in the current
  1064. * period. */
  1065. /** When does the next period begin? */
  1066. time_t next_period;
  1067. /** Where in 'maxima' should the maximum bandwidth usage for the current
  1068. * period be stored? */
  1069. int next_max_idx;
  1070. /** How many values in maxima/totals have been set ever? */
  1071. int num_maxes_set;
  1072. /** Circular array of the maximum
  1073. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  1074. * NUM_TOTALS periods */
  1075. uint64_t maxima[NUM_TOTALS];
  1076. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  1077. * periods */
  1078. uint64_t totals[NUM_TOTALS];
  1079. } bw_array_t;
  1080. /** Shift the current period of b forward by one. */
  1081. static void
  1082. commit_max(bw_array_t *b)
  1083. {
  1084. /* Store total from current period. */
  1085. b->totals[b->next_max_idx] = b->total_in_period;
  1086. /* Store maximum from current period. */
  1087. b->maxima[b->next_max_idx++] = b->max_total;
  1088. /* Advance next_period and next_max_idx */
  1089. b->next_period += NUM_SECS_BW_SUM_INTERVAL;
  1090. if (b->next_max_idx == NUM_TOTALS)
  1091. b->next_max_idx = 0;
  1092. if (b->num_maxes_set < NUM_TOTALS)
  1093. ++b->num_maxes_set;
  1094. /* Reset max_total. */
  1095. b->max_total = 0;
  1096. /* Reset total_in_period. */
  1097. b->total_in_period = 0;
  1098. }
  1099. /** Shift the current observation time of 'b' forward by one second. */
  1100. static INLINE void
  1101. advance_obs(bw_array_t *b)
  1102. {
  1103. int nextidx;
  1104. uint64_t total;
  1105. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  1106. * seconds; adjust max_total as needed.*/
  1107. total = b->total_obs + b->obs[b->cur_obs_idx];
  1108. if (total > b->max_total)
  1109. b->max_total = total;
  1110. nextidx = b->cur_obs_idx+1;
  1111. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  1112. nextidx = 0;
  1113. b->total_obs = total - b->obs[nextidx];
  1114. b->obs[nextidx]=0;
  1115. b->cur_obs_idx = nextidx;
  1116. if (++b->cur_obs_time >= b->next_period)
  1117. commit_max(b);
  1118. }
  1119. /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
  1120. * <b>when</b>. */
  1121. static INLINE void
  1122. add_obs(bw_array_t *b, time_t when, uint64_t n)
  1123. {
  1124. /* Don't record data in the past. */
  1125. if (when<b->cur_obs_time)
  1126. return;
  1127. /* If we're currently adding observations for an earlier second than
  1128. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  1129. * appropriate number of seconds, and do all the other housekeeping */
  1130. while (when>b->cur_obs_time)
  1131. advance_obs(b);
  1132. b->obs[b->cur_obs_idx] += n;
  1133. b->total_in_period += n;
  1134. }
  1135. /** Allocate, initialize, and return a new bw_array. */
  1136. static bw_array_t *
  1137. bw_array_new(void)
  1138. {
  1139. bw_array_t *b;
  1140. time_t start;
  1141. b = tor_malloc_zero(sizeof(bw_array_t));
  1142. rephist_total_alloc += sizeof(bw_array_t);
  1143. start = time(NULL);
  1144. b->cur_obs_time = start;
  1145. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  1146. return b;
  1147. }
  1148. /** Recent history of bandwidth observations for read operations. */
  1149. static bw_array_t *read_array = NULL;
  1150. /** Recent history of bandwidth observations for write operations. */
  1151. static bw_array_t *write_array = NULL;
  1152. /** Set up read_array and write_array. */
  1153. static void
  1154. bw_arrays_init(void)
  1155. {
  1156. read_array = bw_array_new();
  1157. write_array = bw_array_new();
  1158. }
  1159. /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
  1160. *
  1161. * Add num_bytes to the current running total for <b>when</b>.
  1162. *
  1163. * <b>when</b> can go back to time, but it's safe to ignore calls
  1164. * earlier than the latest <b>when</b> you've heard of.
  1165. */
  1166. void
  1167. rep_hist_note_bytes_written(size_t num_bytes, time_t when)
  1168. {
  1169. /* Maybe a circular array for recent seconds, and step to a new point
  1170. * every time a new second shows up. Or simpler is to just to have
  1171. * a normal array and push down each item every second; it's short.
  1172. */
  1173. /* When a new second has rolled over, compute the sum of the bytes we've
  1174. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  1175. * somewhere. See rep_hist_bandwidth_assess() below.
  1176. */
  1177. add_obs(write_array, when, num_bytes);
  1178. }
  1179. /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
  1180. * (like rep_hist_note_bytes_written() above)
  1181. */
  1182. void
  1183. rep_hist_note_bytes_read(size_t num_bytes, time_t when)
  1184. {
  1185. /* if we're smart, we can make this func and the one above share code */
  1186. add_obs(read_array, when, num_bytes);
  1187. }
  1188. /* Some constants */
  1189. /** How long are the intervals for measuring exit stats? */
  1190. #define EXIT_STATS_INTERVAL_SEC (24 * 60 * 60)
  1191. /** To what multiple should byte numbers be rounded up? */
  1192. #define EXIT_STATS_ROUND_UP_BYTES 1024
  1193. /** To what multiple should stream counts be rounded up? */
  1194. #define EXIT_STATS_ROUND_UP_STREAMS 4
  1195. /** Number of TCP ports */
  1196. #define EXIT_STATS_NUM_PORTS 65536
  1197. /** Reciprocal of threshold (= 0.01%) of total bytes that a port needs to
  1198. * see in order to be included in exit stats. */
  1199. #define EXIT_STATS_THRESHOLD_RECIPROCAL 10000
  1200. /* The following data structures are arrays and no fancy smartlists or maps,
  1201. * so that all write operations can be done in constant time. This comes at
  1202. * the price of some memory (1.25 MB) and linear complexity when writing
  1203. * stats. */
  1204. /** Number of bytes read in current period by exit port */
  1205. static uint64_t *exit_bytes_read = NULL;
  1206. /** Number of bytes written in current period by exit port */
  1207. static uint64_t *exit_bytes_written = NULL;
  1208. /** Number of streams opened in current period by exit port */
  1209. static uint32_t *exit_streams = NULL;
  1210. /** Set up arrays for exit port statistics. */
  1211. static void
  1212. exit_stats_init(void)
  1213. {
  1214. exit_bytes_read = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
  1215. sizeof(uint64_t));
  1216. exit_bytes_written = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
  1217. sizeof(uint64_t));
  1218. exit_streams = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
  1219. sizeof(uint32_t));
  1220. }
  1221. /** When does the current exit stats period end? */
  1222. static time_t end_of_current_exit_stats_period = 0;
  1223. /** Write exit stats for the current period to disk and reset counters. */
  1224. static void
  1225. write_exit_stats(time_t when)
  1226. {
  1227. char t[ISO_TIME_LEN+1];
  1228. int r, i, comma;
  1229. uint64_t *b, total_bytes, threshold_bytes, other_bytes;
  1230. uint32_t other_streams;
  1231. char *filename = get_datadir_fname("exit-stats");
  1232. open_file_t *open_file = NULL;
  1233. FILE *out = NULL;
  1234. log_debug(LD_HIST, "Considering writing exit port statistics to disk..");
  1235. if (!exit_bytes_read)
  1236. exit_stats_init();
  1237. while (when > end_of_current_exit_stats_period) {
  1238. format_iso_time(t, end_of_current_exit_stats_period);
  1239. log_info(LD_HIST, "Writing exit port statistics to disk for period "
  1240. "ending at %s.", t);
  1241. if (!open_file) {
  1242. out = start_writing_to_stdio_file(filename, OPEN_FLAGS_APPEND,
  1243. 0600, &open_file);
  1244. if (!out) {
  1245. log_warn(LD_HIST, "Couldn't open '%s'.", filename);
  1246. goto done;
  1247. }
  1248. }
  1249. /* written yyyy-mm-dd HH:MM:SS (n s) */
  1250. if (fprintf(out, "written %s (%d s)\n", t, EXIT_STATS_INTERVAL_SEC) < 0)
  1251. goto done;
  1252. /* Count the total number of bytes, so that we can attribute all
  1253. * observations below a threshold of 1 / EXIT_STATS_THRESHOLD_RECIPROCAL
  1254. * of all bytes to a special port 'other'. */
  1255. total_bytes = 0;
  1256. for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
  1257. total_bytes += exit_bytes_read[i];
  1258. total_bytes += exit_bytes_written[i];
  1259. }
  1260. threshold_bytes = total_bytes / EXIT_STATS_THRESHOLD_RECIPROCAL;
  1261. /* kibibytes-(read|written) port=kibibytes,.. */
  1262. for (r = 0; r < 2; r++) {
  1263. b = r ? exit_bytes_read : exit_bytes_written;
  1264. tor_assert(b);
  1265. if (fprintf(out, "%s ",
  1266. r ? "kibibytes-read" : "kibibytes-written")<0)
  1267. goto done;
  1268. comma = 0;
  1269. other_bytes = 0;
  1270. for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
  1271. if (b[i] > 0) {
  1272. if (exit_bytes_read[i] + exit_bytes_written[i] > threshold_bytes) {
  1273. uint64_t num = round_uint64_to_next_multiple_of(b[i],
  1274. EXIT_STATS_ROUND_UP_BYTES);
  1275. num /= 1024;
  1276. if (fprintf(out, "%s%d="U64_FORMAT,
  1277. comma++ ? "," : "", i,
  1278. U64_PRINTF_ARG(num)) < 0)
  1279. goto done;
  1280. } else
  1281. other_bytes += b[i];
  1282. }
  1283. }
  1284. other_bytes = round_uint64_to_next_multiple_of(other_bytes,
  1285. EXIT_STATS_ROUND_UP_BYTES);
  1286. other_bytes /= 1024;
  1287. if (fprintf(out, "%sother="U64_FORMAT"\n",
  1288. comma ? "," : "", U64_PRINTF_ARG(other_bytes))<0)
  1289. goto done;
  1290. }
  1291. /* streams-opened port=num,.. */
  1292. if (fprintf(out, "streams-opened ")<0)
  1293. goto done;
  1294. comma = 0;
  1295. other_streams = 0;
  1296. for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
  1297. if (exit_streams[i] > 0) {
  1298. if (exit_bytes_read[i] + exit_bytes_written[i] > threshold_bytes) {
  1299. uint32_t num = round_uint32_to_next_multiple_of(exit_streams[i],
  1300. EXIT_STATS_ROUND_UP_STREAMS);
  1301. if (fprintf(out, "%s%d=%u",
  1302. comma++ ? "," : "", i, num)<0)
  1303. goto done;
  1304. } else
  1305. other_streams += exit_streams[i];
  1306. }
  1307. }
  1308. other_streams = round_uint32_to_next_multiple_of(other_streams,
  1309. EXIT_STATS_ROUND_UP_STREAMS);
  1310. if (fprintf(out, "%sother=%u\n",
  1311. comma ? "," : "", other_streams)<0)
  1312. goto done;
  1313. /* Reset counters */
  1314. memset(exit_bytes_read, 0, sizeof(exit_bytes_read));
  1315. memset(exit_bytes_written, 0, sizeof(exit_bytes_written));
  1316. memset(exit_streams, 0, sizeof(exit_streams));
  1317. end_of_current_exit_stats_period += EXIT_STATS_INTERVAL_SEC;
  1318. }
  1319. if (open_file)
  1320. finish_writing_to_file(open_file);
  1321. open_file = NULL;
  1322. done:
  1323. if (open_file)
  1324. abort_writing_to_file(open_file);
  1325. tor_free(filename);
  1326. }
  1327. /** Prepare to add an exit stats observation at second <b>when</b> by
  1328. * checking whether this observation lies in the current observation
  1329. * period; if not, shift the current period forward by one until the
  1330. * reported event fits it and write all results in between to disk. */
  1331. static void
  1332. add_exit_obs(time_t when)
  1333. {
  1334. if (!exit_bytes_read)
  1335. exit_stats_init();
  1336. if (when > end_of_current_exit_stats_period) {
  1337. if (end_of_current_exit_stats_period)
  1338. write_exit_stats(when);
  1339. else
  1340. end_of_current_exit_stats_period = when + EXIT_STATS_INTERVAL_SEC;
  1341. }
  1342. }
  1343. /** Note that we wrote <b>num_bytes</b> to an exit connection to
  1344. * <b>port</b> in second <b>when</b>. */
  1345. void
  1346. rep_hist_note_exit_bytes_written(uint16_t port, size_t num_bytes,
  1347. time_t when)
  1348. {
  1349. if (!get_options()->ExitPortStatistics)
  1350. return;
  1351. add_exit_obs(when);
  1352. exit_bytes_written[port] += num_bytes;
  1353. log_debug(LD_HIST, "Written %lu bytes to exit connection to port %d.",
  1354. (unsigned long)num_bytes, port);
  1355. }
  1356. /** Note that we read <b>num_bytes</b> from an exit connection to
  1357. * <b>port</b> in second <b>when</b>. */
  1358. void
  1359. rep_hist_note_exit_bytes_read(uint16_t port, size_t num_bytes,
  1360. time_t when)
  1361. {
  1362. if (!get_options()->ExitPortStatistics)
  1363. return;
  1364. add_exit_obs(when);
  1365. exit_bytes_read[port] += num_bytes;
  1366. log_debug(LD_HIST, "Read %lu bytes from exit connection to port %d.",
  1367. (unsigned long)num_bytes, port);
  1368. }
  1369. /** Note that we opened an exit stream to <b>port</b> in second
  1370. * <b>when</b>. */
  1371. void
  1372. rep_hist_note_exit_stream_opened(uint16_t port, time_t when)
  1373. {
  1374. if (!get_options()->ExitPortStatistics)
  1375. return;
  1376. add_exit_obs(when);
  1377. exit_streams[port]++;
  1378. log_debug(LD_HIST, "Opened exit stream to port %d", port);
  1379. }
  1380. /** Helper: Return the largest value in b->maxima. (This is equal to the
  1381. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  1382. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  1383. */
  1384. static uint64_t
  1385. find_largest_max(bw_array_t *b)
  1386. {
  1387. int i;
  1388. uint64_t max;
  1389. max=0;
  1390. for (i=0; i<NUM_TOTALS; ++i) {
  1391. if (b->maxima[i]>max)
  1392. max = b->maxima[i];
  1393. }
  1394. return max;
  1395. }
  1396. /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  1397. * seconds. Find one sum for reading and one for writing. They don't have
  1398. * to be at the same time.
  1399. *
  1400. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  1401. */
  1402. int
  1403. rep_hist_bandwidth_assess(void)
  1404. {
  1405. uint64_t w,r;
  1406. r = find_largest_max(read_array);
  1407. w = find_largest_max(write_array);
  1408. if (r>w)
  1409. return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
  1410. else
  1411. return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
  1412. }
  1413. /** Print the bandwidth history of b (either read_array or write_array)
  1414. * into the buffer pointed to by buf. The format is simply comma
  1415. * separated numbers, from oldest to newest.
  1416. *
  1417. * It returns the number of bytes written.
  1418. */
  1419. static size_t
  1420. rep_hist_fill_bandwidth_history(char *buf, size_t len, bw_array_t *b)
  1421. {
  1422. char *cp = buf;
  1423. int i, n;
  1424. or_options_t *options = get_options();
  1425. uint64_t cutoff;
  1426. if (b->num_maxes_set <= b->next_max_idx) {
  1427. /* We haven't been through the circular array yet; time starts at i=0.*/
  1428. i = 0;
  1429. } else {
  1430. /* We've been around the array at least once. The next i to be
  1431. overwritten is the oldest. */
  1432. i = b->next_max_idx;
  1433. }
  1434. if (options->RelayBandwidthRate) {
  1435. /* We don't want to report that we used more bandwidth than the max we're
  1436. * willing to relay; otherwise everybody will know how much traffic
  1437. * we used ourself. */
  1438. cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
  1439. } else {
  1440. cutoff = UINT64_MAX;
  1441. }
  1442. for (n=0; n<b->num_maxes_set; ++n,++i) {
  1443. uint64_t total;
  1444. if (i >= NUM_TOTALS)
  1445. i -= NUM_TOTALS;
  1446. tor_assert(i < NUM_TOTALS);
  1447. /* Round the bandwidth used down to the nearest 1k. */
  1448. total = b->totals[i] & ~0x3ff;
  1449. if (total > cutoff)
  1450. total = cutoff;
  1451. if (n==(b->num_maxes_set-1))
  1452. tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
  1453. else
  1454. tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
  1455. cp += strlen(cp);
  1456. }
  1457. return cp-buf;
  1458. }
  1459. /** Allocate and return lines for representing this server's bandwidth
  1460. * history in its descriptor.
  1461. */
  1462. char *
  1463. rep_hist_get_bandwidth_lines(int for_extrainfo)
  1464. {
  1465. char *buf, *cp;
  1466. char t[ISO_TIME_LEN+1];
  1467. int r;
  1468. bw_array_t *b;
  1469. size_t len;
  1470. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  1471. len = (60+20*NUM_TOTALS)*2;
  1472. buf = tor_malloc_zero(len);
  1473. cp = buf;
  1474. for (r=0;r<2;++r) {
  1475. b = r?read_array:write_array;
  1476. tor_assert(b);
  1477. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  1478. tor_snprintf(cp, len-(cp-buf), "%s%s %s (%d s) ",
  1479. for_extrainfo ? "" : "opt ",
  1480. r ? "read-history" : "write-history", t,
  1481. NUM_SECS_BW_SUM_INTERVAL);
  1482. cp += strlen(cp);
  1483. cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
  1484. strlcat(cp, "\n", len-(cp-buf));
  1485. ++cp;
  1486. }
  1487. return buf;
  1488. }
  1489. /** Update <b>state</b> with the newest bandwidth history. */
  1490. void
  1491. rep_hist_update_state(or_state_t *state)
  1492. {
  1493. int len, r;
  1494. char *buf, *cp;
  1495. smartlist_t **s_values;
  1496. time_t *s_begins;
  1497. int *s_interval;
  1498. bw_array_t *b;
  1499. len = 20*NUM_TOTALS+1;
  1500. buf = tor_malloc_zero(len);
  1501. for (r=0;r<2;++r) {
  1502. b = r?read_array:write_array;
  1503. s_begins = r?&state->BWHistoryReadEnds :&state->BWHistoryWriteEnds;
  1504. s_interval= r?&state->BWHistoryReadInterval:&state->BWHistoryWriteInterval;
  1505. s_values = r?&state->BWHistoryReadValues :&state->BWHistoryWriteValues;
  1506. if (*s_values) {
  1507. SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
  1508. smartlist_free(*s_values);
  1509. }
  1510. if (! server_mode(get_options())) {
  1511. /* Clients don't need to store bandwidth history persistently;
  1512. * force these values to the defaults. */
  1513. /* FFFF we should pull the default out of config.c's state table,
  1514. * so we don't have two defaults. */
  1515. if (*s_begins != 0 || *s_interval != 900) {
  1516. time_t now = time(NULL);
  1517. time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
  1518. or_state_mark_dirty(state, save_at);
  1519. }
  1520. *s_begins = 0;
  1521. *s_interval = 900;
  1522. *s_values = smartlist_create();
  1523. continue;
  1524. }
  1525. *s_begins = b->next_period;
  1526. *s_interval = NUM_SECS_BW_SUM_INTERVAL;
  1527. cp = buf;
  1528. cp += rep_hist_fill_bandwidth_history(cp, len, b);
  1529. tor_snprintf(cp, len-(cp-buf), cp == buf ? U64_FORMAT : ","U64_FORMAT,
  1530. U64_PRINTF_ARG(b->total_in_period));
  1531. *s_values = smartlist_create();
  1532. if (server_mode(get_options()))
  1533. smartlist_split_string(*s_values, buf, ",", SPLIT_SKIP_SPACE, 0);
  1534. }
  1535. tor_free(buf);
  1536. if (server_mode(get_options())) {
  1537. or_state_mark_dirty(get_or_state(), time(NULL)+(2*3600));
  1538. }
  1539. }
  1540. /** Set bandwidth history from our saved state. */
  1541. int
  1542. rep_hist_load_state(or_state_t *state, char **err)
  1543. {
  1544. time_t s_begins, start;
  1545. time_t now = time(NULL);
  1546. uint64_t v;
  1547. int r,i,ok;
  1548. int all_ok = 1;
  1549. int s_interval;
  1550. smartlist_t *s_values;
  1551. bw_array_t *b;
  1552. /* Assert they already have been malloced */
  1553. tor_assert(read_array && write_array);
  1554. for (r=0;r<2;++r) {
  1555. b = r?read_array:write_array;
  1556. s_begins = r?state->BWHistoryReadEnds:state->BWHistoryWriteEnds;
  1557. s_interval = r?state->BWHistoryReadInterval:state->BWHistoryWriteInterval;
  1558. s_values = r?state->BWHistoryReadValues:state->BWHistoryWriteValues;
  1559. if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
  1560. start = s_begins - s_interval*(smartlist_len(s_values));
  1561. if (start > now)
  1562. continue;
  1563. b->cur_obs_time = start;
  1564. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  1565. SMARTLIST_FOREACH(s_values, char *, cp, {
  1566. v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
  1567. if (!ok) {
  1568. all_ok=0;
  1569. log_notice(LD_HIST, "Could not parse '%s' into a number.'", cp);
  1570. }
  1571. if (start < now) {
  1572. add_obs(b, start, v);
  1573. start += NUM_SECS_BW_SUM_INTERVAL;
  1574. }
  1575. });
  1576. }
  1577. /* Clean up maxima and observed */
  1578. /* Do we really want to zero this for the purpose of max capacity? */
  1579. for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
  1580. b->obs[i] = 0;
  1581. }
  1582. b->total_obs = 0;
  1583. for (i=0; i<NUM_TOTALS; ++i) {
  1584. b->maxima[i] = 0;
  1585. }
  1586. b->max_total = 0;
  1587. }
  1588. if (!all_ok) {
  1589. *err = tor_strdup("Parsing of bandwidth history values failed");
  1590. /* and create fresh arrays */
  1591. tor_free(read_array);
  1592. tor_free(write_array);
  1593. read_array = bw_array_new();
  1594. write_array = bw_array_new();
  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. */
  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. if (predicted_internal_capacity_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
  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. /** Free all storage held by the OR/link history caches, by the
  1864. * bandwidth history arrays, or by the port history. */
  1865. void
  1866. rep_hist_free_all(void)
  1867. {
  1868. digestmap_free(history_map, free_or_history);
  1869. tor_free(read_array);
  1870. tor_free(write_array);
  1871. tor_free(last_stability_doc);
  1872. tor_free(exit_bytes_read);
  1873. tor_free(exit_bytes_written);
  1874. tor_free(exit_streams);
  1875. built_last_stability_doc_at = 0;
  1876. predicted_ports_free();
  1877. }
  1878. /****************** hidden service usage statistics ******************/
  1879. /** How large are the intervals for which we track and report hidden service
  1880. * use? */
  1881. #define NUM_SECS_HS_USAGE_SUM_INTERVAL (15*60)
  1882. /** How far in the past do we remember and publish hidden service use? */
  1883. #define NUM_SECS_HS_USAGE_SUM_IS_VALID (24*60*60)
  1884. /** How many hidden service usage intervals do we remember? (derived) */
  1885. #define NUM_TOTALS_HS_USAGE (NUM_SECS_HS_USAGE_SUM_IS_VALID/ \
  1886. NUM_SECS_HS_USAGE_SUM_INTERVAL)
  1887. /** List element containing a service id and the count. */
  1888. typedef struct hs_usage_list_elem_t {
  1889. /** Service id of this elem. */
  1890. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  1891. /** Number of occurrences for the given service id. */
  1892. uint32_t count;
  1893. /* Pointer to next list elem */
  1894. struct hs_usage_list_elem_t *next;
  1895. } hs_usage_list_elem_t;
  1896. /** Ordered list that stores service ids and the number of observations. It is
  1897. * ordered by the number of occurrences in descending order. Its purpose is to
  1898. * calculate the frequency distribution when the period is over. */
  1899. typedef struct hs_usage_list_t {
  1900. /* Pointer to the first element in the list. */
  1901. hs_usage_list_elem_t *start;
  1902. /* Number of total occurrences for all list elements. */
  1903. uint32_t total_count;
  1904. /* Number of service ids, i.e. number of list elements. */
  1905. uint32_t total_service_ids;
  1906. } hs_usage_list_t;
  1907. /** Tracks service-related observations in the current period and their
  1908. * history. */
  1909. typedef struct hs_usage_service_related_observation_t {
  1910. /** Ordered list that stores service ids and the number of observations in
  1911. * the current period. It is ordered by the number of occurrences in
  1912. * descending order. Its purpose is to calculate the frequency distribution
  1913. * when the period is over. */
  1914. hs_usage_list_t *list;
  1915. /** Circular arrays that store the history of observations. totals stores all
  1916. * observations, twenty (ten, five) the number of observations related to a
  1917. * service id being accounted for the top 20 (10, 5) percent of all
  1918. * observations. */
  1919. uint32_t totals[NUM_TOTALS_HS_USAGE];
  1920. uint32_t five[NUM_TOTALS_HS_USAGE];
  1921. uint32_t ten[NUM_TOTALS_HS_USAGE];
  1922. uint32_t twenty[NUM_TOTALS_HS_USAGE];
  1923. } hs_usage_service_related_observation_t;
  1924. /** Tracks the history of general period-related observations, i.e. those that
  1925. * cannot be related to a specific service id. */
  1926. typedef struct hs_usage_general_period_related_observations_t {
  1927. /** Circular array that stores the history of observations. */
  1928. uint32_t totals[NUM_TOTALS_HS_USAGE];
  1929. } hs_usage_general_period_related_observations_t;
  1930. /** Keeps information about the current observation period and its relation to
  1931. * the histories of observations. */
  1932. typedef struct hs_usage_current_observation_period_t {
  1933. /** Where do we write the next history entry? */
  1934. int next_idx;
  1935. /** How many values in history have been set ever? (upper bound!) */
  1936. int num_set;
  1937. /** When did this period begin? */
  1938. time_t start_of_current_period;
  1939. /** When does the next period begin? */
  1940. time_t start_of_next_period;
  1941. } hs_usage_current_observation_period_t;
  1942. /** Usage statistics for the current observation period. */
  1943. static hs_usage_current_observation_period_t *current_period = NULL;
  1944. /** Total number of descriptor publish requests in the current observation
  1945. * period. */
  1946. static hs_usage_service_related_observation_t *publish_total = NULL;
  1947. /** Number of descriptor publish requests for services that have not been
  1948. * seen before in the current observation period. */
  1949. static hs_usage_service_related_observation_t *publish_novel = NULL;
  1950. /** Total number of descriptor fetch requests in the current observation
  1951. * period. */
  1952. static hs_usage_service_related_observation_t *fetch_total = NULL;
  1953. /** Number of successful descriptor fetch requests in the current
  1954. * observation period. */
  1955. static hs_usage_service_related_observation_t *fetch_successful = NULL;
  1956. /** Number of descriptors stored in the current observation period. */
  1957. static hs_usage_general_period_related_observations_t *descs = NULL;
  1958. /** Creates an empty ordered list element. */
  1959. static hs_usage_list_elem_t *
  1960. hs_usage_list_elem_new(void)
  1961. {
  1962. hs_usage_list_elem_t *e;
  1963. e = tor_malloc_zero(sizeof(hs_usage_list_elem_t));
  1964. rephist_total_alloc += sizeof(hs_usage_list_elem_t);
  1965. e->count = 1;
  1966. e->next = NULL;
  1967. return e;
  1968. }
  1969. /** Creates an empty ordered list. */
  1970. static hs_usage_list_t *
  1971. hs_usage_list_new(void)
  1972. {
  1973. hs_usage_list_t *l;
  1974. l = tor_malloc_zero(sizeof(hs_usage_list_t));
  1975. rephist_total_alloc += sizeof(hs_usage_list_t);
  1976. l->start = NULL;
  1977. l->total_count = 0;
  1978. l->total_service_ids = 0;
  1979. return l;
  1980. }
  1981. /** Creates an empty structure for storing service-related observations. */
  1982. static hs_usage_service_related_observation_t *
  1983. hs_usage_service_related_observation_new(void)
  1984. {
  1985. hs_usage_service_related_observation_t *h;
  1986. h = tor_malloc_zero(sizeof(hs_usage_service_related_observation_t));
  1987. rephist_total_alloc += sizeof(hs_usage_service_related_observation_t);
  1988. h->list = hs_usage_list_new();
  1989. return h;
  1990. }
  1991. /** Creates an empty structure for storing general period-related
  1992. * observations. */
  1993. static hs_usage_general_period_related_observations_t *
  1994. hs_usage_general_period_related_observations_new(void)
  1995. {
  1996. hs_usage_general_period_related_observations_t *p;
  1997. p = tor_malloc_zero(sizeof(hs_usage_general_period_related_observations_t));
  1998. rephist_total_alloc+= sizeof(hs_usage_general_period_related_observations_t);
  1999. return p;
  2000. }
  2001. /** Creates an empty structure for storing period-specific information. */
  2002. static hs_usage_current_observation_period_t *
  2003. hs_usage_current_observation_period_new(void)
  2004. {
  2005. hs_usage_current_observation_period_t *c;
  2006. time_t now;
  2007. c = tor_malloc_zero(sizeof(hs_usage_current_observation_period_t));
  2008. rephist_total_alloc += sizeof(hs_usage_current_observation_period_t);
  2009. now = time(NULL);
  2010. c->start_of_current_period = now;
  2011. c->start_of_next_period = now + NUM_SECS_HS_USAGE_SUM_INTERVAL;
  2012. return c;
  2013. }
  2014. /** Initializes the structures for collecting hidden service usage data. */
  2015. static void
  2016. hs_usage_init(void)
  2017. {
  2018. current_period = hs_usage_current_observation_period_new();
  2019. publish_total = hs_usage_service_related_observation_new();
  2020. publish_novel = hs_usage_service_related_observation_new();
  2021. fetch_total = hs_usage_service_related_observation_new();
  2022. fetch_successful = hs_usage_service_related_observation_new();
  2023. descs = hs_usage_general_period_related_observations_new();
  2024. }
  2025. /** Clears the given ordered list by resetting its attributes and releasing
  2026. * the memory allocated by its elements. */
  2027. static void
  2028. hs_usage_list_clear(hs_usage_list_t *lst)
  2029. {
  2030. /* walk through elements and free memory */
  2031. hs_usage_list_elem_t *current = lst->start;
  2032. hs_usage_list_elem_t *tmp;
  2033. while (current != NULL) {
  2034. tmp = current->next;
  2035. rephist_total_alloc -= sizeof(hs_usage_list_elem_t);
  2036. tor_free(current);
  2037. current = tmp;
  2038. }
  2039. /* reset attributes */
  2040. lst->start = NULL;
  2041. lst->total_count = 0;
  2042. lst->total_service_ids = 0;
  2043. return;
  2044. }
  2045. /** Frees the memory used by the given list. */
  2046. static void
  2047. hs_usage_list_free(hs_usage_list_t *lst)
  2048. {
  2049. if (!lst)
  2050. return;
  2051. hs_usage_list_clear(lst);
  2052. rephist_total_alloc -= sizeof(hs_usage_list_t);
  2053. tor_free(lst);
  2054. }
  2055. /** Frees the memory used by the given service-related observations. */
  2056. static void
  2057. hs_usage_service_related_observation_free(
  2058. hs_usage_service_related_observation_t *s)
  2059. {
  2060. if (!s)
  2061. return;
  2062. hs_usage_list_free(s->list);
  2063. rephist_total_alloc -= sizeof(hs_usage_service_related_observation_t);
  2064. tor_free(s);
  2065. }
  2066. /** Frees the memory used by the given period-specific observations. */
  2067. static void
  2068. hs_usage_general_period_related_observations_free(
  2069. hs_usage_general_period_related_observations_t *s)
  2070. {
  2071. rephist_total_alloc-=sizeof(hs_usage_general_period_related_observations_t);
  2072. tor_free(s);
  2073. }
  2074. /** Frees the memory used by period-specific information. */
  2075. static void
  2076. hs_usage_current_observation_period_free(
  2077. hs_usage_current_observation_period_t *s)
  2078. {
  2079. rephist_total_alloc -= sizeof(hs_usage_current_observation_period_t);
  2080. tor_free(s);
  2081. }
  2082. /** Frees all memory that was used for collecting hidden service usage data. */
  2083. void
  2084. hs_usage_free_all(void)
  2085. {
  2086. hs_usage_general_period_related_observations_free(descs);
  2087. descs = NULL;
  2088. hs_usage_service_related_observation_free(fetch_successful);
  2089. hs_usage_service_related_observation_free(fetch_total);
  2090. hs_usage_service_related_observation_free(publish_novel);
  2091. hs_usage_service_related_observation_free(publish_total);
  2092. fetch_successful = fetch_total = publish_novel = publish_total = NULL;
  2093. hs_usage_current_observation_period_free(current_period);
  2094. current_period = NULL;
  2095. }
  2096. /** Inserts a new occurrence for the given service id to the given ordered
  2097. * list. */
  2098. static void
  2099. hs_usage_insert_value(hs_usage_list_t *lst, const char *service_id)
  2100. {
  2101. /* search if there is already an elem with same service_id in list */
  2102. hs_usage_list_elem_t *current = lst->start;
  2103. hs_usage_list_elem_t *previous = NULL;
  2104. while (current != NULL && strcasecmp(current->service_id,service_id)) {
  2105. previous = current;
  2106. current = current->next;
  2107. }
  2108. /* found an element with same service_id? */
  2109. if (current == NULL) {
  2110. /* not found! append to end (which could also be the end of a zero-length
  2111. * list), don't need to sort (1 is smallest value). */
  2112. /* create elem */
  2113. hs_usage_list_elem_t *e = hs_usage_list_elem_new();
  2114. /* update list attributes (one new elem, one new occurrence) */
  2115. lst->total_count++;
  2116. lst->total_service_ids++;
  2117. /* copy service id to elem */
  2118. strlcpy(e->service_id,service_id,sizeof(e->service_id));
  2119. /* let either l->start or previously last elem point to new elem */
  2120. if (lst->start == NULL) {
  2121. /* this is the first elem */
  2122. lst->start = e;
  2123. } else {
  2124. /* there were elems in the list before */
  2125. previous->next = e;
  2126. }
  2127. } else {
  2128. /* found! add occurrence to elem and consider resorting */
  2129. /* update list attributes (no new elem, but one new occurrence) */
  2130. lst->total_count++;
  2131. /* add occurrence to elem */
  2132. current->count++;
  2133. /* is it another than the first list elem? and has previous elem fewer
  2134. * count than current? then we need to resort */
  2135. if (previous != NULL && previous->count < current->count) {
  2136. /* yes! we need to resort */
  2137. /* remove current elem first */
  2138. previous->next = current->next;
  2139. /* can we prepend elem to all other elements? */
  2140. if (lst->start->count <= current->count) {
  2141. /* yes! prepend elem */
  2142. current->next = lst->start;
  2143. lst->start = current;
  2144. } else {
  2145. /* no! walk through list a second time and insert at correct place */
  2146. hs_usage_list_elem_t *insert_current = lst->start->next;
  2147. hs_usage_list_elem_t *insert_previous = lst->start;
  2148. while (insert_current != NULL &&
  2149. insert_current->count > current->count) {
  2150. insert_previous = insert_current;
  2151. insert_current = insert_current->next;
  2152. }
  2153. /* insert here */
  2154. current->next = insert_current;
  2155. insert_previous->next = current;
  2156. }
  2157. }
  2158. }
  2159. }
  2160. /** Writes the current service-related observations to the history array and
  2161. * clears the observations of the current period. */
  2162. static void
  2163. hs_usage_write_service_related_observations_to_history(
  2164. hs_usage_current_observation_period_t *p,
  2165. hs_usage_service_related_observation_t *h)
  2166. {
  2167. /* walk through the first 20 % of list elements and calculate frequency
  2168. * distributions */
  2169. /* maximum indices for the three frequencies */
  2170. int five_percent_idx = h->list->total_service_ids/20;
  2171. int ten_percent_idx = h->list->total_service_ids/10;
  2172. int twenty_percent_idx = h->list->total_service_ids/5;
  2173. /* temp values */
  2174. uint32_t five_percent = 0;
  2175. uint32_t ten_percent = 0;
  2176. uint32_t twenty_percent = 0;
  2177. /* walk through list */
  2178. hs_usage_list_elem_t *current = h->list->start;
  2179. int i=0;
  2180. while (current != NULL && i <= twenty_percent_idx) {
  2181. twenty_percent += current->count;
  2182. if (i <= ten_percent_idx)
  2183. ten_percent += current->count;
  2184. if (i <= five_percent_idx)
  2185. five_percent += current->count;
  2186. current = current->next;
  2187. i++;
  2188. }
  2189. /* copy frequencies */
  2190. h->twenty[p->next_idx] = twenty_percent;
  2191. h->ten[p->next_idx] = ten_percent;
  2192. h->five[p->next_idx] = five_percent;
  2193. /* copy total number of observations */
  2194. h->totals[p->next_idx] = h->list->total_count;
  2195. /* free memory of old list */
  2196. hs_usage_list_clear(h->list);
  2197. }
  2198. /** Advances to next observation period. */
  2199. static void
  2200. hs_usage_advance_current_observation_period(void)
  2201. {
  2202. /* aggregate observations to history, including frequency distribution
  2203. * arrays */
  2204. hs_usage_write_service_related_observations_to_history(
  2205. current_period, publish_total);
  2206. hs_usage_write_service_related_observations_to_history(
  2207. current_period, publish_novel);
  2208. hs_usage_write_service_related_observations_to_history(
  2209. current_period, fetch_total);
  2210. hs_usage_write_service_related_observations_to_history(
  2211. current_period, fetch_successful);
  2212. /* write current number of descriptors to descs history */
  2213. descs->totals[current_period->next_idx] = rend_cache_size();
  2214. /* advance to next period */
  2215. current_period->next_idx++;
  2216. if (current_period->next_idx == NUM_TOTALS_HS_USAGE)
  2217. current_period->next_idx = 0;
  2218. if (current_period->num_set < NUM_TOTALS_HS_USAGE)
  2219. ++current_period->num_set;
  2220. current_period->start_of_current_period=current_period->start_of_next_period;
  2221. current_period->start_of_next_period += NUM_SECS_HS_USAGE_SUM_INTERVAL;
  2222. }
  2223. /** Checks if the current period is up to date, and if not, advances it. */
  2224. static void
  2225. hs_usage_check_if_current_period_is_up_to_date(time_t now)
  2226. {
  2227. while (now > current_period->start_of_next_period) {
  2228. hs_usage_advance_current_observation_period();
  2229. }
  2230. }
  2231. /** Adds a service-related observation, maybe after advancing to next
  2232. * observation period. */
  2233. static void
  2234. hs_usage_add_service_related_observation(
  2235. hs_usage_service_related_observation_t *h,
  2236. time_t now,
  2237. const char *service_id)
  2238. {
  2239. if (now < current_period->start_of_current_period) {
  2240. /* don't record old data */
  2241. return;
  2242. }
  2243. /* check if we are up-to-date */
  2244. hs_usage_check_if_current_period_is_up_to_date(now);
  2245. /* add observation */
  2246. hs_usage_insert_value(h->list, service_id);
  2247. }
  2248. /** Adds the observation of storing a rendezvous service descriptor to our
  2249. * cache in our role as HS authoritative directory. */
  2250. void
  2251. hs_usage_note_publish_total(const char *service_id, time_t now)
  2252. {
  2253. hs_usage_add_service_related_observation(publish_total, now, service_id);
  2254. }
  2255. /** Adds the observation of storing a novel rendezvous service descriptor to
  2256. * our cache in our role as HS authoritative directory. */
  2257. void
  2258. hs_usage_note_publish_novel(const char *service_id, time_t now)
  2259. {
  2260. hs_usage_add_service_related_observation(publish_novel, now, service_id);
  2261. }
  2262. /** Adds the observation of being requested for a rendezvous service descriptor
  2263. * in our role as HS authoritative directory. */
  2264. void
  2265. hs_usage_note_fetch_total(const char *service_id, time_t now)
  2266. {
  2267. hs_usage_add_service_related_observation(fetch_total, now, service_id);
  2268. }
  2269. /** Adds the observation of being requested for a rendezvous service descriptor
  2270. * in our role as HS authoritative directory and being able to answer that
  2271. * request successfully. */
  2272. void
  2273. hs_usage_note_fetch_successful(const char *service_id, time_t now)
  2274. {
  2275. hs_usage_add_service_related_observation(fetch_successful, now, service_id);
  2276. }
  2277. /** Writes the given circular array to a string. */
  2278. static size_t
  2279. hs_usage_format_history(char *buf, size_t len, uint32_t *data)
  2280. {
  2281. char *cp = buf; /* pointer where we are in the buffer */
  2282. int i, n;
  2283. if (current_period->num_set <= current_period->next_idx) {
  2284. i = 0; /* not been through circular array */
  2285. } else {
  2286. i = current_period->next_idx;
  2287. }
  2288. for (n = 0; n < current_period->num_set; ++n,++i) {
  2289. if (i >= NUM_TOTALS_HS_USAGE)
  2290. i -= NUM_TOTALS_HS_USAGE;
  2291. tor_assert(i < NUM_TOTALS_HS_USAGE);
  2292. if (n == (current_period->num_set-1))
  2293. tor_snprintf(cp, len-(cp-buf), "%d", data[i]);
  2294. else
  2295. tor_snprintf(cp, len-(cp-buf), "%d,", data[i]);
  2296. cp += strlen(cp);
  2297. }
  2298. return cp-buf;
  2299. }
  2300. /** Writes the complete usage history as hidden service authoritative directory
  2301. * to a string. */
  2302. static char *
  2303. hs_usage_format_statistics(void)
  2304. {
  2305. char *buf, *cp, *s = NULL;
  2306. char t[ISO_TIME_LEN+1];
  2307. int r;
  2308. uint32_t *data = NULL;
  2309. size_t len;
  2310. len = (70+20*NUM_TOTALS_HS_USAGE)*11;
  2311. buf = tor_malloc_zero(len);
  2312. cp = buf;
  2313. for (r = 0; r < 11; ++r) {
  2314. switch (r) {
  2315. case 0:
  2316. s = (char*) "publish-total-history";
  2317. data = publish_total->totals;
  2318. break;
  2319. case 1:
  2320. s = (char*) "publish-novel-history";
  2321. data = publish_novel->totals;
  2322. break;
  2323. case 2:
  2324. s = (char*) "publish-top-5-percent-history";
  2325. data = publish_total->five;
  2326. break;
  2327. case 3:
  2328. s = (char*) "publish-top-10-percent-history";
  2329. data = publish_total->ten;
  2330. break;
  2331. case 4:
  2332. s = (char*) "publish-top-20-percent-history";
  2333. data = publish_total->twenty;
  2334. break;
  2335. case 5:
  2336. s = (char*) "fetch-total-history";
  2337. data = fetch_total->totals;
  2338. break;
  2339. case 6:
  2340. s = (char*) "fetch-successful-history";
  2341. data = fetch_successful->totals;
  2342. break;
  2343. case 7:
  2344. s = (char*) "fetch-top-5-percent-history";
  2345. data = fetch_total->five;
  2346. break;
  2347. case 8:
  2348. s = (char*) "fetch-top-10-percent-history";
  2349. data = fetch_total->ten;
  2350. break;
  2351. case 9:
  2352. s = (char*) "fetch-top-20-percent-history";
  2353. data = fetch_total->twenty;
  2354. break;
  2355. case 10:
  2356. s = (char*) "desc-total-history";
  2357. data = descs->totals;
  2358. break;
  2359. }
  2360. format_iso_time(t, current_period->start_of_current_period);
  2361. tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ", s, t,
  2362. NUM_SECS_HS_USAGE_SUM_INTERVAL);
  2363. cp += strlen(cp);
  2364. cp += hs_usage_format_history(cp, len-(cp-buf), data);
  2365. strlcat(cp, "\n", len-(cp-buf));
  2366. ++cp;
  2367. }
  2368. return buf;
  2369. }
  2370. /** Write current statistics about hidden service usage to file. */
  2371. void
  2372. hs_usage_write_statistics_to_file(time_t now)
  2373. {
  2374. char *buf;
  2375. size_t len;
  2376. char *fname;
  2377. or_options_t *options = get_options();
  2378. /* check if we are up-to-date */
  2379. hs_usage_check_if_current_period_is_up_to_date(now);
  2380. buf = hs_usage_format_statistics();
  2381. len = strlen(options->DataDirectory) + 16;
  2382. fname = tor_malloc(len);
  2383. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"hsusage",
  2384. options->DataDirectory);
  2385. write_str_to_file(fname,buf,0);
  2386. tor_free(buf);
  2387. tor_free(fname);
  2388. }
  2389. /*** cell statistics ***/
  2390. #ifdef ENABLE_BUFFER_STATS
  2391. /** Start of the current buffer stats interval. */
  2392. time_t start_of_buffer_stats_interval;
  2393. typedef struct circ_buffer_stats_t {
  2394. uint32_t processed_cells;
  2395. double mean_num_cells_in_queue;
  2396. double mean_time_cells_in_queue;
  2397. uint32_t local_circ_id;
  2398. } circ_buffer_stats_t;
  2399. /** Holds stats. */
  2400. smartlist_t *circuits_for_buffer_stats = NULL;
  2401. /** Remember cell statistics for circuit <b>circ</b> at time
  2402. * <b>end_of_interval</b> and reset cell counters in case the circuit
  2403. * remains open in the next measurement interval. */
  2404. void
  2405. add_circ_to_buffer_stats(circuit_t *circ, time_t end_of_interval)
  2406. {
  2407. circ_buffer_stats_t *stat;
  2408. time_t start_of_interval;
  2409. int interval_length;
  2410. or_circuit_t *orcirc;
  2411. if (CIRCUIT_IS_ORIGIN(circ))
  2412. return;
  2413. orcirc = TO_OR_CIRCUIT(circ);
  2414. if (!orcirc->processed_cells)
  2415. return;
  2416. if (!circuits_for_buffer_stats)
  2417. circuits_for_buffer_stats = smartlist_create();
  2418. start_of_interval = circ->timestamp_created >
  2419. start_of_buffer_stats_interval ?
  2420. circ->timestamp_created :
  2421. start_of_buffer_stats_interval;
  2422. interval_length = (int) (end_of_interval - start_of_interval);
  2423. stat = tor_malloc_zero(sizeof(circ_buffer_stats_t));
  2424. stat->processed_cells = orcirc->processed_cells;
  2425. /* 1000.0 for s -> ms; 2.0 because of app-ward and exit-ward queues */
  2426. stat->mean_num_cells_in_queue = interval_length == 0 ? 0.0 :
  2427. (double) orcirc->total_cell_waiting_time /
  2428. (double) interval_length / 1000.0 / 2.0;
  2429. stat->mean_time_cells_in_queue =
  2430. (double) orcirc->total_cell_waiting_time /
  2431. (double) orcirc->processed_cells;
  2432. smartlist_add(circuits_for_buffer_stats, stat);
  2433. orcirc->total_cell_waiting_time = 0;
  2434. orcirc->processed_cells = 0;
  2435. }
  2436. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  2437. * circ_buffer_stats_t */
  2438. static int
  2439. _buffer_stats_compare_entries(const void **_a, const void **_b)
  2440. {
  2441. const circ_buffer_stats_t *a = *_a, *b = *_b;
  2442. if (a->processed_cells < b->processed_cells)
  2443. return 1;
  2444. else if (a->processed_cells > b->processed_cells)
  2445. return -1;
  2446. else
  2447. return 0;
  2448. }
  2449. /** Append buffer statistics to local file. */
  2450. void
  2451. dump_buffer_stats(void)
  2452. {
  2453. time_t now = time(NULL);
  2454. char *filename;
  2455. char written[ISO_TIME_LEN+1];
  2456. open_file_t *open_file = NULL;
  2457. FILE *out;
  2458. #define SHARES 10
  2459. int processed_cells[SHARES], circs_in_share[SHARES],
  2460. number_of_circuits, i;
  2461. double queued_cells[SHARES], time_in_queue[SHARES];
  2462. smartlist_t *str_build = smartlist_create();
  2463. char *str = NULL;
  2464. char buf[32];
  2465. circuit_t *circ;
  2466. /* add current circuits to stats */
  2467. for (circ = _circuit_get_global_list(); circ; circ = circ->next)
  2468. add_circ_to_buffer_stats(circ, now);
  2469. /* calculate deciles */
  2470. memset(processed_cells, 0, SHARES * sizeof(int));
  2471. memset(circs_in_share, 0, SHARES * sizeof(int));
  2472. memset(queued_cells, 0, SHARES * sizeof(double));
  2473. memset(time_in_queue, 0, SHARES * sizeof(double));
  2474. smartlist_sort(circuits_for_buffer_stats,
  2475. _buffer_stats_compare_entries);
  2476. number_of_circuits = smartlist_len(circuits_for_buffer_stats);
  2477. i = 0;
  2478. SMARTLIST_FOREACH_BEGIN(circuits_for_buffer_stats,
  2479. circ_buffer_stats_t *, stat)
  2480. {
  2481. int share = i++ * SHARES / number_of_circuits;
  2482. processed_cells[share] += stat->processed_cells;
  2483. queued_cells[share] += stat->mean_num_cells_in_queue;
  2484. time_in_queue[share] += stat->mean_time_cells_in_queue;
  2485. circs_in_share[share]++;
  2486. }
  2487. SMARTLIST_FOREACH_END(stat);
  2488. /* clear buffer stats history */
  2489. SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
  2490. stat, tor_free(stat));
  2491. smartlist_clear(circuits_for_buffer_stats);
  2492. /* write to file */
  2493. filename = get_datadir_fname("buffer-stats");
  2494. out = start_writing_to_stdio_file(filename, OPEN_FLAGS_APPEND,
  2495. 0600, &open_file);
  2496. if (!out)
  2497. goto done;
  2498. format_iso_time(written, now);
  2499. if (fprintf(out, "written %s (%d s)\n", written,
  2500. DUMP_BUFFER_STATS_INTERVAL) < 0)
  2501. goto done;
  2502. for (i = 0; i < SHARES; i++) {
  2503. tor_snprintf(buf, sizeof(buf), "%d", !circs_in_share[i] ? 0 :
  2504. processed_cells[i] / circs_in_share[i]);
  2505. smartlist_add(str_build, tor_strdup(buf));
  2506. }
  2507. str = smartlist_join_strings(str_build, ",", 0, NULL);
  2508. if (fprintf(out, "processed-cells %s\n", str) < 0)
  2509. goto done;
  2510. tor_free(str);
  2511. SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
  2512. smartlist_clear(str_build);
  2513. for (i = 0; i < SHARES; i++) {
  2514. tor_snprintf(buf, sizeof(buf), "%.2f", circs_in_share[i] == 0 ? 0.0 :
  2515. queued_cells[i] / (double) circs_in_share[i]);
  2516. smartlist_add(str_build, tor_strdup(buf));
  2517. }
  2518. str = smartlist_join_strings(str_build, ",", 0, NULL);
  2519. if (fprintf(out, "queued-cells %s\n", str) < 0)
  2520. goto done;
  2521. tor_free(str);
  2522. SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
  2523. smartlist_clear(str_build);
  2524. for (i = 0; i < SHARES; i++) {
  2525. tor_snprintf(buf, sizeof(buf), "%.0f", circs_in_share[i] == 0 ? 0.0 :
  2526. time_in_queue[i] / (double) circs_in_share[i]);
  2527. smartlist_add(str_build, tor_strdup(buf));
  2528. }
  2529. str = smartlist_join_strings(str_build, ",", 0, NULL);
  2530. if (fprintf(out, "time-in-queue %s\n", str) < 0)
  2531. goto done;
  2532. tor_free(str);
  2533. SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
  2534. smartlist_free(str_build);
  2535. str_build = NULL;
  2536. if (fprintf(out, "number-of-circuits-per-share %d\n",
  2537. (number_of_circuits + SHARES - 1) / SHARES) < 0)
  2538. goto done;
  2539. finish_writing_to_file(open_file);
  2540. open_file = NULL;
  2541. done:
  2542. if (open_file)
  2543. abort_writing_to_file(open_file);
  2544. tor_free(filename);
  2545. if (str_build) {
  2546. SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
  2547. smartlist_free(str_build);
  2548. }
  2549. tor_free(str);
  2550. #undef SHARES
  2551. }
  2552. #endif