rephist.c 57 KB

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