rephist.c 74 KB

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