rephist.c 67 KB

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