rephist.c 68 KB

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