rephist.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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. int
  457. rep_hist_record_mtbf_data(const char *filename)
  458. {
  459. char buf[128];
  460. char time_buf[ISO_TIME_LEN+1];
  461. smartlist_t *lines;
  462. digestmap_iter_t *orhist_it;
  463. const char *digest;
  464. void *or_history_p;
  465. or_history_t *hist;
  466. lines = smartlist_create();
  467. smartlist_add(lines, tor_strdup("format 1\n"));
  468. if (stability_last_downrated) {
  469. format_iso_time(time_buf, stability_last_downrated);
  470. tor_snprintf(buf, sizeof(buf), "last-downrated %s\n", time_buf);
  471. smartlist_add(lines, tor_strdup(buf));
  472. }
  473. smartlist_add(lines, tor_strdup("data\n"));
  474. for (orhist_it = digestmap_iter_init(history_map);
  475. !digestmap_iter_done(orhist_it);
  476. orhist_it = digestmap_iter_next(history_map,orhist_it)) {
  477. char dbuf[HEX_DIGEST_LEN+1];
  478. const char *t = NULL;
  479. digestmap_iter_get(orhist_it, &digest, &or_history_p);
  480. hist = (or_history_t*) or_history_p;
  481. base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
  482. if (hist->start_of_run) {
  483. format_iso_time(time_buf, hist->start_of_run);
  484. t = time_buf;
  485. }
  486. tor_snprintf(buf, sizeof(buf), "%s %lu %.5lf%s%s\n",
  487. dbuf, hist->weighted_run_length, hist->total_run_weights,
  488. t ? " S=" : "", t ? t : "");
  489. smartlist_add(lines, tor_strdup(buf));
  490. }
  491. smartlist_add(lines, tor_strdup(".\n"));
  492. {
  493. size_t sz;
  494. /* XXXX This isn't terribly efficient; line-at-a-time would be
  495. * way faster. */
  496. char *data = smartlist_join_strings(lines, "", 0, &sz);
  497. int r = write_bytes_to_file(filename, data, sz, 0);
  498. tor_free(data);
  499. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  500. smartlist_free(lines);
  501. return r;
  502. }
  503. }
  504. /** DOCDOC */
  505. int
  506. rep_hist_load_mtbf_data(const char *filename, time_t now)
  507. {
  508. /* XXXX won't handle being called while history is already populated. */
  509. smartlist_t *lines;
  510. const char *line = NULL;
  511. int r=0, i;
  512. time_t last_downrated = 0;
  513. {
  514. char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  515. if (!d)
  516. return -1;
  517. lines = smartlist_create();
  518. smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
  519. tor_free(d);
  520. }
  521. if (smartlist_len(lines)<4 || strcmp(smartlist_get(lines, 0), "format 1")) {
  522. log_warn(LD_GENERAL,"Unrecognized format in mtbf history file. Skipping.");
  523. goto err;
  524. }
  525. for (i = 1; i < smartlist_len(lines); ++i) {
  526. line = smartlist_get(lines, i);
  527. if (!strcmp(line, "data"))
  528. break;
  529. if (!strcmpstart(line, "last-downrated ")) {
  530. if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
  531. log_warn(LD_GENERAL,"Couldn't parse downrate time in mtbf "
  532. "history file.");
  533. }
  534. if (last_downrated > now)
  535. last_downrated = now;
  536. }
  537. if (line && !strcmp(line, "data"))
  538. ++i;
  539. for (; i < smartlist_len(lines); ++i) {
  540. char digest[DIGEST_LEN];
  541. char hexbuf[HEX_DIGEST_LEN+1];
  542. char timebuf[ISO_TIME_LEN+1];
  543. time_t start_of_run = 0;
  544. unsigned long wrl;
  545. double trw;
  546. int n;
  547. or_history_t *hist;
  548. line = smartlist_get(lines, i);
  549. if (!strcmp(line, "."))
  550. break;
  551. /* XXXX020 audit the heck out of my scanf usage. */
  552. n = sscanf(line, "%40s %lu %lf S=%10s %8s",
  553. hexbuf, &wrl, &trw, timebuf, timebuf+11);
  554. if (n != 3 && n != 5) {
  555. log_warn(LD_GENERAL, "Couldn't scan line %s", escaped(line));
  556. continue;
  557. }
  558. if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
  559. log_warn(LD_GENERAL, "Couldn't hex string %s", escaped(hexbuf));
  560. continue;
  561. }
  562. if (n == 5) {
  563. timebuf[10] = ' ';
  564. if (parse_iso_time(timebuf, &start_of_run)<0)
  565. log_warn(LD_GENERAL, "Couldn't parse time %s", escaped(timebuf));
  566. }
  567. hist = get_or_history(digest);
  568. if (!hist)
  569. continue;
  570. if (start_of_run > now)
  571. start_of_run = now;
  572. hist->start_of_run = start_of_run;
  573. hist->weighted_run_length = wrl;
  574. hist->total_run_weights = trw;
  575. /* Subtract time in which */
  576. }
  577. if (strcmp(line, "."))
  578. log_warn(LD_GENERAL, "Truncated MTBF file %s", escaped(filename));
  579. stability_last_downrated = last_downrated;
  580. goto done;
  581. err:
  582. r = -1;
  583. done:
  584. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  585. smartlist_free(lines);
  586. return r;
  587. }
  588. /** For how many seconds do we keep track of individual per-second bandwidth
  589. * totals? */
  590. #define NUM_SECS_ROLLING_MEASURE 10
  591. /** How large are the intervals for which we track and report bandwidth use? */
  592. #define NUM_SECS_BW_SUM_INTERVAL (15*60)
  593. /** How far in the past do we remember and publish bandwidth use? */
  594. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
  595. /** How many bandwidth usage intervals do we remember? (derived) */
  596. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  597. /** Structure to track bandwidth use, and remember the maxima for a given
  598. * time period.
  599. */
  600. typedef struct bw_array_t {
  601. /** Observation array: Total number of bytes transferred in each of the last
  602. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  603. uint64_t obs[NUM_SECS_ROLLING_MEASURE];
  604. int cur_obs_idx; /**< Current position in obs. */
  605. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  606. uint64_t total_obs; /**< Total for all members of obs except
  607. * obs[cur_obs_idx] */
  608. uint64_t max_total; /**< Largest value that total_obs has taken on in the
  609. * current period. */
  610. uint64_t total_in_period; /**< Total bytes transferred in the current
  611. * period. */
  612. /** When does the next period begin? */
  613. time_t next_period;
  614. /** Where in 'maxima' should the maximum bandwidth usage for the current
  615. * period be stored? */
  616. int next_max_idx;
  617. /** How many values in maxima/totals have been set ever? */
  618. int num_maxes_set;
  619. /** Circular array of the maximum
  620. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  621. * NUM_TOTALS periods */
  622. uint64_t maxima[NUM_TOTALS];
  623. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  624. * periods */
  625. uint64_t totals[NUM_TOTALS];
  626. } bw_array_t;
  627. /** Shift the current period of b forward by one. */
  628. static void
  629. commit_max(bw_array_t *b)
  630. {
  631. /* Store total from current period. */
  632. b->totals[b->next_max_idx] = b->total_in_period;
  633. /* Store maximum from current period. */
  634. b->maxima[b->next_max_idx++] = b->max_total;
  635. /* Advance next_period and next_max_idx */
  636. b->next_period += NUM_SECS_BW_SUM_INTERVAL;
  637. if (b->next_max_idx == NUM_TOTALS)
  638. b->next_max_idx = 0;
  639. if (b->num_maxes_set < NUM_TOTALS)
  640. ++b->num_maxes_set;
  641. /* Reset max_total. */
  642. b->max_total = 0;
  643. /* Reset total_in_period. */
  644. b->total_in_period = 0;
  645. }
  646. /** Shift the current observation time of 'b' forward by one second. */
  647. static INLINE void
  648. advance_obs(bw_array_t *b)
  649. {
  650. int nextidx;
  651. uint64_t total;
  652. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  653. * seconds; adjust max_total as needed.*/
  654. total = b->total_obs + b->obs[b->cur_obs_idx];
  655. if (total > b->max_total)
  656. b->max_total = total;
  657. nextidx = b->cur_obs_idx+1;
  658. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  659. nextidx = 0;
  660. b->total_obs = total - b->obs[nextidx];
  661. b->obs[nextidx]=0;
  662. b->cur_obs_idx = nextidx;
  663. if (++b->cur_obs_time >= b->next_period)
  664. commit_max(b);
  665. }
  666. /** Add 'n' bytes to the number of bytes in b for second 'when'. */
  667. static INLINE void
  668. add_obs(bw_array_t *b, time_t when, uint64_t n)
  669. {
  670. /* Don't record data in the past. */
  671. if (when<b->cur_obs_time)
  672. return;
  673. /* If we're currently adding observations for an earlier second than
  674. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  675. * appropriate number of seconds, and do all the other housekeeping */
  676. while (when>b->cur_obs_time)
  677. advance_obs(b);
  678. b->obs[b->cur_obs_idx] += n;
  679. b->total_in_period += n;
  680. }
  681. /** Allocate, initialize, and return a new bw_array. */
  682. static bw_array_t *
  683. bw_array_new(void)
  684. {
  685. bw_array_t *b;
  686. time_t start;
  687. b = tor_malloc_zero(sizeof(bw_array_t));
  688. rephist_total_alloc += sizeof(bw_array_t);
  689. start = time(NULL);
  690. b->cur_obs_time = start;
  691. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  692. return b;
  693. }
  694. static bw_array_t *read_array = NULL;
  695. static bw_array_t *write_array = NULL;
  696. /** Set up read_array and write_array. */
  697. static void
  698. bw_arrays_init(void)
  699. {
  700. read_array = bw_array_new();
  701. write_array = bw_array_new();
  702. }
  703. /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
  704. *
  705. * Add num_bytes to the current running total for <b>when</b>.
  706. *
  707. * <b>when</b> can go back to time, but it's safe to ignore calls
  708. * earlier than the latest <b>when</b> you've heard of.
  709. */
  710. void
  711. rep_hist_note_bytes_written(int num_bytes, time_t when)
  712. {
  713. /* Maybe a circular array for recent seconds, and step to a new point
  714. * every time a new second shows up. Or simpler is to just to have
  715. * a normal array and push down each item every second; it's short.
  716. */
  717. /* When a new second has rolled over, compute the sum of the bytes we've
  718. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  719. * somewhere. See rep_hist_bandwidth_assess() below.
  720. */
  721. add_obs(write_array, when, num_bytes);
  722. }
  723. /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
  724. * (like rep_hist_note_bytes_written() above)
  725. */
  726. void
  727. rep_hist_note_bytes_read(int num_bytes, time_t when)
  728. {
  729. /* if we're smart, we can make this func and the one above share code */
  730. add_obs(read_array, when, num_bytes);
  731. }
  732. /** Helper: Return the largest value in b->maxima. (This is equal to the
  733. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  734. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  735. */
  736. static uint64_t
  737. find_largest_max(bw_array_t *b)
  738. {
  739. int i;
  740. uint64_t max;
  741. max=0;
  742. for (i=0; i<NUM_TOTALS; ++i) {
  743. if (b->maxima[i]>max)
  744. max = b->maxima[i];
  745. }
  746. return max;
  747. }
  748. /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  749. * seconds. Find one sum for reading and one for writing. They don't have
  750. * to be at the same time).
  751. *
  752. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  753. */
  754. int
  755. rep_hist_bandwidth_assess(void)
  756. {
  757. uint64_t w,r;
  758. r = find_largest_max(read_array);
  759. w = find_largest_max(write_array);
  760. if (r>w)
  761. return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
  762. else
  763. return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
  764. }
  765. /** Print the bandwidth history of b (either read_array or write_array)
  766. * into the buffer pointed to by buf. The format is simply comma
  767. * separated numbers, from oldest to newest.
  768. *
  769. * It returns the number of bytes written.
  770. */
  771. static size_t
  772. rep_hist_fill_bandwidth_history(char *buf, size_t len, bw_array_t *b)
  773. {
  774. char *cp = buf;
  775. int i, n;
  776. if (b->num_maxes_set <= b->next_max_idx) {
  777. /* We haven't been through the circular array yet; time starts at i=0.*/
  778. i = 0;
  779. } else {
  780. /* We've been around the array at least once. The next i to be
  781. overwritten is the oldest. */
  782. i = b->next_max_idx;
  783. }
  784. for (n=0; n<b->num_maxes_set; ++n,++i) {
  785. uint64_t total;
  786. if (i >= NUM_TOTALS)
  787. i -= NUM_TOTALS;
  788. tor_assert(i < NUM_TOTALS);
  789. /* Round the bandwidth used down to the nearest 1k. */
  790. total = b->totals[i] & ~0x3ff;
  791. if (n==(b->num_maxes_set-1))
  792. tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
  793. else
  794. tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
  795. cp += strlen(cp);
  796. }
  797. return cp-buf;
  798. }
  799. /** Allocate and return lines for representing this server's bandwidth
  800. * history in its descriptor.
  801. */
  802. char *
  803. rep_hist_get_bandwidth_lines(int for_extrainfo)
  804. {
  805. char *buf, *cp;
  806. char t[ISO_TIME_LEN+1];
  807. int r;
  808. bw_array_t *b;
  809. size_t len;
  810. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  811. len = (60+20*NUM_TOTALS)*2;
  812. buf = tor_malloc_zero(len);
  813. cp = buf;
  814. for (r=0;r<2;++r) {
  815. b = r?read_array:write_array;
  816. tor_assert(b);
  817. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  818. tor_snprintf(cp, len-(cp-buf), "%s%s %s (%d s) ",
  819. for_extrainfo ? "" : "opt ",
  820. r ? "read-history" : "write-history", t,
  821. NUM_SECS_BW_SUM_INTERVAL);
  822. cp += strlen(cp);
  823. cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
  824. strlcat(cp, "\n", len-(cp-buf));
  825. ++cp;
  826. }
  827. return buf;
  828. }
  829. /** Update <b>state</b> with the newest bandwidth history. */
  830. void
  831. rep_hist_update_state(or_state_t *state)
  832. {
  833. int len, r;
  834. char *buf, *cp;
  835. smartlist_t **s_values;
  836. time_t *s_begins;
  837. int *s_interval;
  838. bw_array_t *b;
  839. len = 20*NUM_TOTALS+1;
  840. buf = tor_malloc_zero(len);
  841. for (r=0;r<2;++r) {
  842. b = r?read_array:write_array;
  843. s_begins = r?&state->BWHistoryReadEnds :&state->BWHistoryWriteEnds;
  844. s_interval= r?&state->BWHistoryReadInterval:&state->BWHistoryWriteInterval;
  845. s_values = r?&state->BWHistoryReadValues :&state->BWHistoryWriteValues;
  846. if (*s_values) {
  847. SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
  848. smartlist_free(*s_values);
  849. }
  850. if (! server_mode(get_options())) {
  851. /* Clients don't need to store bandwidth history persistently;
  852. * force these values to the defaults. */
  853. /* FFFF we should pull the default out of config.c's state table,
  854. * so we don't have two defaults. */
  855. if (*s_begins != 0 || *s_interval != 900) {
  856. time_t now = time(NULL);
  857. time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
  858. or_state_mark_dirty(state, save_at);
  859. }
  860. *s_begins = 0;
  861. *s_interval = 900;
  862. *s_values = smartlist_create();
  863. continue;
  864. }
  865. *s_begins = b->next_period;
  866. *s_interval = NUM_SECS_BW_SUM_INTERVAL;
  867. cp = buf;
  868. cp += rep_hist_fill_bandwidth_history(cp, len, b);
  869. tor_snprintf(cp, len-(cp-buf), cp == buf ? U64_FORMAT : ","U64_FORMAT,
  870. U64_PRINTF_ARG(b->total_in_period));
  871. *s_values = smartlist_create();
  872. if (server_mode(get_options()))
  873. smartlist_split_string(*s_values, buf, ",", SPLIT_SKIP_SPACE, 0);
  874. }
  875. tor_free(buf);
  876. if (server_mode(get_options())) {
  877. or_state_mark_dirty(get_or_state(), time(NULL)+(2*3600));
  878. }
  879. }
  880. /** Set bandwidth history from our saved state. */
  881. int
  882. rep_hist_load_state(or_state_t *state, char **err)
  883. {
  884. time_t s_begins, start;
  885. time_t now = time(NULL);
  886. uint64_t v;
  887. int r,i,ok;
  888. int all_ok = 1;
  889. int s_interval;
  890. smartlist_t *s_values;
  891. bw_array_t *b;
  892. /* Assert they already have been malloced */
  893. tor_assert(read_array && write_array);
  894. for (r=0;r<2;++r) {
  895. b = r?read_array:write_array;
  896. s_begins = r?state->BWHistoryReadEnds:state->BWHistoryWriteEnds;
  897. s_interval = r?state->BWHistoryReadInterval:state->BWHistoryWriteInterval;
  898. s_values = r?state->BWHistoryReadValues:state->BWHistoryWriteValues;
  899. if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
  900. start = s_begins - s_interval*(smartlist_len(s_values));
  901. b->cur_obs_time = start;
  902. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  903. SMARTLIST_FOREACH(s_values, char *, cp, {
  904. v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
  905. if (!ok) {
  906. all_ok=0;
  907. log_notice(LD_GENERAL, "Could not parse '%s' into a number.'", cp);
  908. }
  909. add_obs(b, start, v);
  910. start += NUM_SECS_BW_SUM_INTERVAL;
  911. });
  912. }
  913. /* Clean up maxima and observed */
  914. /* Do we really want to zero this for the purpose of max capacity? */
  915. for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
  916. b->obs[i] = 0;
  917. }
  918. b->total_obs = 0;
  919. for (i=0; i<NUM_TOTALS; ++i) {
  920. b->maxima[i] = 0;
  921. }
  922. b->max_total = 0;
  923. }
  924. if (!all_ok) {
  925. *err = tor_strdup("Parsing of bandwidth history values failed");
  926. /* and create fresh arrays */
  927. tor_free(read_array);
  928. tor_free(write_array);
  929. read_array = bw_array_new();
  930. write_array = bw_array_new();
  931. return -1;
  932. }
  933. return 0;
  934. }
  935. /*********************************************************************/
  936. /** A list of port numbers that have been used recently. */
  937. static smartlist_t *predicted_ports_list=NULL;
  938. /** The corresponding most recently used time for each port. */
  939. static smartlist_t *predicted_ports_times=NULL;
  940. /** We just got an application request for a connection with
  941. * port <b>port</b>. Remember it for the future, so we can keep
  942. * some circuits open that will exit to this port.
  943. */
  944. static void
  945. add_predicted_port(uint16_t port, time_t now)
  946. {
  947. /* XXXX we could just use uintptr_t here, I think. */
  948. uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
  949. time_t *tmp_time = tor_malloc(sizeof(time_t));
  950. *tmp_port = port;
  951. *tmp_time = now;
  952. rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
  953. smartlist_add(predicted_ports_list, tmp_port);
  954. smartlist_add(predicted_ports_times, tmp_time);
  955. }
  956. /** Initialize whatever memory and structs are needed for predicting
  957. * which ports will be used. Also seed it with port 80, so we'll build
  958. * circuits on start-up.
  959. */
  960. static void
  961. predicted_ports_init(void)
  962. {
  963. predicted_ports_list = smartlist_create();
  964. predicted_ports_times = smartlist_create();
  965. add_predicted_port(80, time(NULL)); /* add one to kickstart us */
  966. }
  967. /** Free whatever memory is needed for predicting which ports will
  968. * be used.
  969. */
  970. static void
  971. predicted_ports_free(void)
  972. {
  973. rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
  974. SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
  975. smartlist_free(predicted_ports_list);
  976. rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
  977. SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
  978. smartlist_free(predicted_ports_times);
  979. }
  980. /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
  981. * This is used for predicting what sorts of streams we'll make in the
  982. * future and making exit circuits to anticipate that.
  983. */
  984. void
  985. rep_hist_note_used_port(uint16_t port, time_t now)
  986. {
  987. int i;
  988. uint16_t *tmp_port;
  989. time_t *tmp_time;
  990. tor_assert(predicted_ports_list);
  991. tor_assert(predicted_ports_times);
  992. if (!port) /* record nothing */
  993. return;
  994. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  995. tmp_port = smartlist_get(predicted_ports_list, i);
  996. tmp_time = smartlist_get(predicted_ports_times, i);
  997. if (*tmp_port == port) {
  998. *tmp_time = now;
  999. return;
  1000. }
  1001. }
  1002. /* it's not there yet; we need to add it */
  1003. add_predicted_port(port, now);
  1004. }
  1005. /** For this long after we've seen a request for a given port, assume that
  1006. * we'll want to make connections to the same port in the future. */
  1007. #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
  1008. /** Return a pointer to the list of port numbers that
  1009. * are likely to be asked for in the near future.
  1010. *
  1011. * The caller promises not to mess with it.
  1012. */
  1013. smartlist_t *
  1014. rep_hist_get_predicted_ports(time_t now)
  1015. {
  1016. int i;
  1017. uint16_t *tmp_port;
  1018. time_t *tmp_time;
  1019. tor_assert(predicted_ports_list);
  1020. tor_assert(predicted_ports_times);
  1021. /* clean out obsolete entries */
  1022. for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
  1023. tmp_time = smartlist_get(predicted_ports_times, i);
  1024. if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
  1025. tmp_port = smartlist_get(predicted_ports_list, i);
  1026. log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
  1027. smartlist_del(predicted_ports_list, i);
  1028. smartlist_del(predicted_ports_times, i);
  1029. rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
  1030. tor_free(tmp_port);
  1031. tor_free(tmp_time);
  1032. i--;
  1033. }
  1034. }
  1035. return predicted_ports_list;
  1036. }
  1037. /** The user asked us to do a resolve. Rather than keeping track of
  1038. * timings and such of resolves, we fake it for now by making treating
  1039. * it the same way as a connection to port 80. This way we will continue
  1040. * to have circuits lying around if the user only uses Tor for resolves.
  1041. */
  1042. void
  1043. rep_hist_note_used_resolve(time_t now)
  1044. {
  1045. rep_hist_note_used_port(80, now);
  1046. }
  1047. /** The last time at which we needed an internal circ. */
  1048. static time_t predicted_internal_time = 0;
  1049. /** The last time we needed an internal circ with good uptime. */
  1050. static time_t predicted_internal_uptime_time = 0;
  1051. /** The last time we needed an internal circ with good capacity. */
  1052. static time_t predicted_internal_capacity_time = 0;
  1053. /** Remember that we used an internal circ at time <b>now</b>. */
  1054. void
  1055. rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
  1056. {
  1057. predicted_internal_time = now;
  1058. if (need_uptime)
  1059. predicted_internal_uptime_time = now;
  1060. if (need_capacity)
  1061. predicted_internal_capacity_time = now;
  1062. }
  1063. /** Return 1 if we've used an internal circ recently; else return 0. */
  1064. int
  1065. rep_hist_get_predicted_internal(time_t now, int *need_uptime,
  1066. int *need_capacity)
  1067. {
  1068. if (!predicted_internal_time) { /* initialize it */
  1069. predicted_internal_time = now;
  1070. predicted_internal_uptime_time = now;
  1071. predicted_internal_capacity_time = now;
  1072. }
  1073. if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
  1074. return 0; /* too long ago */
  1075. if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
  1076. *need_uptime = 1;
  1077. if (predicted_internal_capacity_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
  1078. *need_capacity = 1;
  1079. return 1;
  1080. }
  1081. /** Any ports used lately? These are pre-seeded if we just started
  1082. * up or if we're running a hidden service. */
  1083. int
  1084. any_predicted_circuits(time_t now)
  1085. {
  1086. return smartlist_len(predicted_ports_list) ||
  1087. predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now;
  1088. }
  1089. /** Return 1 if we have no need for circuits currently, else return 0. */
  1090. int
  1091. rep_hist_circbuilding_dormant(time_t now)
  1092. {
  1093. if (any_predicted_circuits(now))
  1094. return 0;
  1095. /* see if we'll still need to build testing circuits */
  1096. if (server_mode(get_options()) && !check_whether_orport_reachable())
  1097. return 0;
  1098. if (!check_whether_dirport_reachable())
  1099. return 0;
  1100. return 1;
  1101. }
  1102. static uint32_t n_signed_dir_objs = 0;
  1103. static uint32_t n_signed_routerdescs = 0;
  1104. static uint32_t n_verified_dir_objs = 0;
  1105. static uint32_t n_verified_routerdescs = 0;
  1106. static uint32_t n_onionskins_encrypted = 0;
  1107. static uint32_t n_onionskins_decrypted = 0;
  1108. static uint32_t n_tls_client_handshakes = 0;
  1109. static uint32_t n_tls_server_handshakes = 0;
  1110. static uint32_t n_rend_client_ops = 0;
  1111. static uint32_t n_rend_mid_ops = 0;
  1112. static uint32_t n_rend_server_ops = 0;
  1113. /** Increment the count of the number of times we've done <b>operation</b>. */
  1114. void
  1115. note_crypto_pk_op(pk_op_t operation)
  1116. {
  1117. switch (operation)
  1118. {
  1119. case SIGN_DIR:
  1120. n_signed_dir_objs++;
  1121. break;
  1122. case SIGN_RTR:
  1123. n_signed_routerdescs++;
  1124. break;
  1125. case VERIFY_DIR:
  1126. n_verified_dir_objs++;
  1127. break;
  1128. case VERIFY_RTR:
  1129. n_verified_routerdescs++;
  1130. break;
  1131. case ENC_ONIONSKIN:
  1132. n_onionskins_encrypted++;
  1133. break;
  1134. case DEC_ONIONSKIN:
  1135. n_onionskins_decrypted++;
  1136. break;
  1137. case TLS_HANDSHAKE_C:
  1138. n_tls_client_handshakes++;
  1139. break;
  1140. case TLS_HANDSHAKE_S:
  1141. n_tls_server_handshakes++;
  1142. break;
  1143. case REND_CLIENT:
  1144. n_rend_client_ops++;
  1145. break;
  1146. case REND_MID:
  1147. n_rend_mid_ops++;
  1148. break;
  1149. case REND_SERVER:
  1150. n_rend_server_ops++;
  1151. break;
  1152. default:
  1153. log_warn(LD_BUG, "Unknown pk operation %d", operation);
  1154. }
  1155. }
  1156. /** Log the number of times we've done each public/private-key operation. */
  1157. void
  1158. dump_pk_ops(int severity)
  1159. {
  1160. log(severity, LD_GENERAL,
  1161. "PK operations: %lu directory objects signed, "
  1162. "%lu directory objects verified, "
  1163. "%lu routerdescs signed, "
  1164. "%lu routerdescs verified, "
  1165. "%lu onionskins encrypted, "
  1166. "%lu onionskins decrypted, "
  1167. "%lu client-side TLS handshakes, "
  1168. "%lu server-side TLS handshakes, "
  1169. "%lu rendezvous client operations, "
  1170. "%lu rendezvous middle operations, "
  1171. "%lu rendezvous server operations.",
  1172. (unsigned long) n_signed_dir_objs,
  1173. (unsigned long) n_verified_dir_objs,
  1174. (unsigned long) n_signed_routerdescs,
  1175. (unsigned long) n_verified_routerdescs,
  1176. (unsigned long) n_onionskins_encrypted,
  1177. (unsigned long) n_onionskins_decrypted,
  1178. (unsigned long) n_tls_client_handshakes,
  1179. (unsigned long) n_tls_server_handshakes,
  1180. (unsigned long) n_rend_client_ops,
  1181. (unsigned long) n_rend_mid_ops,
  1182. (unsigned long) n_rend_server_ops);
  1183. }
  1184. /** Free all storage held by the OR/link history caches, by the
  1185. * bandwidth history arrays, or by the port history. */
  1186. void
  1187. rep_hist_free_all(void)
  1188. {
  1189. digestmap_free(history_map, free_or_history);
  1190. tor_free(read_array);
  1191. tor_free(write_array);
  1192. predicted_ports_free();
  1193. }
  1194. /****************** hidden service usage statistics ******************/
  1195. /** How large are the intervals for which we track and report hidden service
  1196. * use? */
  1197. #define NUM_SECS_HS_USAGE_SUM_INTERVAL (15*60)
  1198. /** How far in the past do we remember and publish hidden service use? */
  1199. #define NUM_SECS_HS_USAGE_SUM_IS_VALID (24*60*60)
  1200. /** How many hidden service usage intervals do we remember? (derived) */
  1201. #define NUM_TOTALS_HS_USAGE (NUM_SECS_HS_USAGE_SUM_IS_VALID/ \
  1202. NUM_SECS_HS_USAGE_SUM_INTERVAL)
  1203. /** List element containing a service id and the count. */
  1204. typedef struct hs_usage_list_elem_t {
  1205. /** Service id of this elem. */
  1206. char service_id[REND_SERVICE_ID_LEN+1];
  1207. /** Number of occurrences for the given service id. */
  1208. uint32_t count;
  1209. /* Pointer to next list elem */
  1210. struct hs_usage_list_elem_t *next;
  1211. } hs_usage_list_elem_t;
  1212. /* Ordered list that stores service ids and the number of observations. It is
  1213. * ordered by the number of occurrences in descending order. Its purpose is to
  1214. * calculate the frequency distribution when the period is over. */
  1215. typedef struct hs_usage_list_t {
  1216. /* Pointer to the first element in the list. */
  1217. hs_usage_list_elem_t *start;
  1218. /* Number of total occurrences for all list elements. */
  1219. uint32_t total_count;
  1220. /* Number of service ids, i.e. number of list elements. */
  1221. uint32_t total_service_ids;
  1222. } hs_usage_list_t;
  1223. /** Tracks service-related observations in the current period and their
  1224. * history. */
  1225. typedef struct hs_usage_service_related_observation_t {
  1226. /** Ordered list that stores service ids and the number of observations in
  1227. * the current period. It is ordered by the number of occurrences in
  1228. * descending order. Its purpose is to calculate the frequency distribution
  1229. * when the period is over. */
  1230. hs_usage_list_t *list;
  1231. /** Circular arrays that store the history of observations. totals stores all
  1232. * observations, twenty (ten, five) the number of observations related to a
  1233. * service id being accounted for the top 20 (10, 5) percent of all
  1234. * observations. */
  1235. uint32_t totals[NUM_TOTALS_HS_USAGE];
  1236. uint32_t five[NUM_TOTALS_HS_USAGE];
  1237. uint32_t ten[NUM_TOTALS_HS_USAGE];
  1238. uint32_t twenty[NUM_TOTALS_HS_USAGE];
  1239. } hs_usage_service_related_observation_t;
  1240. /** Tracks the history of general period-related observations, i.e. those that
  1241. * cannot be related to a specific service id. */
  1242. typedef struct hs_usage_general_period_related_observations_t {
  1243. /** Circular array that stores the history of observations. */
  1244. uint32_t totals[NUM_TOTALS_HS_USAGE];
  1245. } hs_usage_general_period_related_observations_t;
  1246. /** Keeps information about the current observation period and its relation to
  1247. * the histories of observations. */
  1248. typedef struct hs_usage_current_observation_period_t {
  1249. /** Where do we write the next history entry? */
  1250. int next_idx;
  1251. /** How many values in history have been set ever? (upper bound!) */
  1252. int num_set;
  1253. /** When did this period begin? */
  1254. time_t start_of_current_period;
  1255. /** When does the next period begin? */
  1256. time_t start_of_next_period;
  1257. } hs_usage_current_observation_period_t;
  1258. static hs_usage_current_observation_period_t *current_period = NULL;
  1259. static hs_usage_service_related_observation_t *publish_total = NULL;
  1260. static hs_usage_service_related_observation_t *publish_novel = NULL;
  1261. static hs_usage_service_related_observation_t *fetch_total = NULL;
  1262. static hs_usage_service_related_observation_t *fetch_successful = NULL;
  1263. static hs_usage_general_period_related_observations_t *descs = NULL;
  1264. /** Creates an empty ordered list element. */
  1265. static hs_usage_list_elem_t *
  1266. hs_usage_list_elem_new(void)
  1267. {
  1268. hs_usage_list_elem_t *e;
  1269. e = tor_malloc_zero(sizeof(hs_usage_list_elem_t));
  1270. rephist_total_alloc += sizeof(hs_usage_list_elem_t);
  1271. e->count = 1;
  1272. e->next = NULL;
  1273. return e;
  1274. }
  1275. /** Creates an empty ordered list. */
  1276. static hs_usage_list_t *
  1277. hs_usage_list_new(void)
  1278. {
  1279. hs_usage_list_t *l;
  1280. l = tor_malloc_zero(sizeof(hs_usage_list_t));
  1281. rephist_total_alloc += sizeof(hs_usage_list_t);
  1282. l->start = NULL;
  1283. l->total_count = 0;
  1284. l->total_service_ids = 0;
  1285. return l;
  1286. }
  1287. /** Creates an empty structure for storing service-related observations. */
  1288. static hs_usage_service_related_observation_t *
  1289. hs_usage_service_related_observation_new(void)
  1290. {
  1291. hs_usage_service_related_observation_t *h;
  1292. h = tor_malloc_zero(sizeof(hs_usage_service_related_observation_t));
  1293. rephist_total_alloc += sizeof(hs_usage_service_related_observation_t);
  1294. h->list = hs_usage_list_new();
  1295. return h;
  1296. }
  1297. /** Creates an empty structure for storing general period-related
  1298. * observations. */
  1299. static hs_usage_general_period_related_observations_t *
  1300. hs_usage_general_period_related_observations_new(void)
  1301. {
  1302. hs_usage_general_period_related_observations_t *p;
  1303. p = tor_malloc_zero(sizeof(hs_usage_general_period_related_observations_t));
  1304. rephist_total_alloc+= sizeof(hs_usage_general_period_related_observations_t);
  1305. return p;
  1306. }
  1307. /** Creates an empty structure for storing period-specific information. */
  1308. static hs_usage_current_observation_period_t *
  1309. hs_usage_current_observation_period_new(void)
  1310. {
  1311. hs_usage_current_observation_period_t *c;
  1312. time_t now;
  1313. c = tor_malloc_zero(sizeof(hs_usage_current_observation_period_t));
  1314. rephist_total_alloc += sizeof(hs_usage_current_observation_period_t);
  1315. now = time(NULL);
  1316. c->start_of_current_period = now;
  1317. c->start_of_next_period = now + NUM_SECS_HS_USAGE_SUM_INTERVAL;
  1318. return c;
  1319. }
  1320. /** Initializes the structures for collecting hidden service usage data. */
  1321. static void
  1322. hs_usage_init(void)
  1323. {
  1324. current_period = hs_usage_current_observation_period_new();
  1325. publish_total = hs_usage_service_related_observation_new();
  1326. publish_novel = hs_usage_service_related_observation_new();
  1327. fetch_total = hs_usage_service_related_observation_new();
  1328. fetch_successful = hs_usage_service_related_observation_new();
  1329. descs = hs_usage_general_period_related_observations_new();
  1330. }
  1331. /** Clears the given ordered list by resetting its attributes and releasing
  1332. * the memory allocated by its elements. */
  1333. static void
  1334. hs_usage_list_clear(hs_usage_list_t *lst)
  1335. {
  1336. /* walk through elements and free memory */
  1337. hs_usage_list_elem_t *current = lst->start;
  1338. hs_usage_list_elem_t *tmp;
  1339. while (current != NULL) {
  1340. tmp = current->next;
  1341. rephist_total_alloc -= sizeof(hs_usage_list_elem_t);
  1342. tor_free(current);
  1343. current = tmp;
  1344. }
  1345. /* reset attributes */
  1346. lst->start = NULL;
  1347. lst->total_count = 0;
  1348. lst->total_service_ids = 0;
  1349. return;
  1350. }
  1351. /** Frees the memory used by the given list. */
  1352. static void
  1353. hs_usage_list_free(hs_usage_list_t *lst)
  1354. {
  1355. if (!lst)
  1356. return;
  1357. hs_usage_list_clear(lst);
  1358. rephist_total_alloc -= sizeof(hs_usage_list_t);
  1359. tor_free(lst);
  1360. }
  1361. /** Frees the memory used by the given service-related observations. */
  1362. static void
  1363. hs_usage_service_related_observation_free(
  1364. hs_usage_service_related_observation_t *s)
  1365. {
  1366. if (!s)
  1367. return;
  1368. hs_usage_list_free(s->list);
  1369. rephist_total_alloc -= sizeof(hs_usage_service_related_observation_t);
  1370. tor_free(s);
  1371. }
  1372. /** Frees the memory used by the given period-specific observations. */
  1373. static void
  1374. hs_usage_general_period_related_observations_free(
  1375. hs_usage_general_period_related_observations_t *s)
  1376. {
  1377. rephist_total_alloc-=sizeof(hs_usage_general_period_related_observations_t);
  1378. tor_free(s);
  1379. }
  1380. /** Frees the memory used by period-specific information. */
  1381. static void
  1382. hs_usage_current_observation_period_free(
  1383. hs_usage_current_observation_period_t *s)
  1384. {
  1385. rephist_total_alloc -= sizeof(hs_usage_current_observation_period_t);
  1386. tor_free(s);
  1387. }
  1388. /** Frees all memory that was used for collecting hidden service usage data. */
  1389. void
  1390. hs_usage_free_all(void)
  1391. {
  1392. hs_usage_general_period_related_observations_free(descs);
  1393. descs = NULL;
  1394. hs_usage_service_related_observation_free(fetch_successful);
  1395. hs_usage_service_related_observation_free(fetch_total);
  1396. hs_usage_service_related_observation_free(publish_novel);
  1397. hs_usage_service_related_observation_free(publish_total);
  1398. fetch_successful = fetch_total = publish_novel = publish_total = NULL;
  1399. hs_usage_current_observation_period_free(current_period);
  1400. current_period = NULL;
  1401. }
  1402. /** Inserts a new occurrence for the given service id to the given ordered
  1403. * list. */
  1404. static void
  1405. hs_usage_insert_value(hs_usage_list_t *lst, const char *service_id)
  1406. {
  1407. /* search if there is already an elem with same service_id in list */
  1408. hs_usage_list_elem_t *current = lst->start;
  1409. hs_usage_list_elem_t *previous = NULL;
  1410. while (current != NULL && strcasecmp(current->service_id,service_id)) {
  1411. previous = current;
  1412. current = current->next;
  1413. }
  1414. /* found an element with same service_id? */
  1415. if (current == NULL) {
  1416. /* not found! append to end (which could also be the end of a zero-length
  1417. * list), don't need to sort (1 is smallest value). */
  1418. /* create elem */
  1419. hs_usage_list_elem_t *e = hs_usage_list_elem_new();
  1420. /* update list attributes (one new elem, one new occurrence) */
  1421. lst->total_count++;
  1422. lst->total_service_ids++;
  1423. /* copy service id to elem */
  1424. strlcpy(e->service_id,service_id,sizeof(e->service_id));
  1425. /* let either l->start or previously last elem point to new elem */
  1426. if (lst->start == NULL) {
  1427. /* this is the first elem */
  1428. lst->start = e;
  1429. } else {
  1430. /* there were elems in the list before */
  1431. previous->next = e;
  1432. }
  1433. } else {
  1434. /* found! add occurrence to elem and consider resorting */
  1435. /* update list attributes (no new elem, but one new occurrence) */
  1436. lst->total_count++;
  1437. /* add occurrence to elem */
  1438. current->count++;
  1439. /* is it another than the first list elem? and has previous elem fewer
  1440. * count than current? then we need to resort */
  1441. if (previous != NULL && previous->count < current->count) {
  1442. /* yes! we need to resort */
  1443. /* remove current elem first */
  1444. previous->next = current->next;
  1445. /* can we prepend elem to all other elements? */
  1446. if (lst->start->count <= current->count) {
  1447. /* yes! prepend elem */
  1448. current->next = lst->start;
  1449. lst->start = current;
  1450. } else {
  1451. /* no! walk through list a second time and insert at correct place */
  1452. hs_usage_list_elem_t *insert_current = lst->start->next;
  1453. hs_usage_list_elem_t *insert_previous = lst->start;
  1454. while (insert_current != NULL &&
  1455. insert_current->count > current->count) {
  1456. insert_previous = insert_current;
  1457. insert_current = insert_current->next;
  1458. }
  1459. /* insert here */
  1460. current->next = insert_current;
  1461. insert_previous->next = current;
  1462. }
  1463. }
  1464. }
  1465. }
  1466. /** Writes the current service-related observations to the history array and
  1467. * clears the observations of the current period. */
  1468. static void
  1469. hs_usage_write_service_related_observations_to_history(
  1470. hs_usage_current_observation_period_t *p,
  1471. hs_usage_service_related_observation_t *h)
  1472. {
  1473. /* walk through the first 20 % of list elements and calculate frequency
  1474. * distributions */
  1475. /* maximum indices for the three frequencies */
  1476. int five_percent_idx = h->list->total_service_ids/20;
  1477. int ten_percent_idx = h->list->total_service_ids/10;
  1478. int twenty_percent_idx = h->list->total_service_ids/5;
  1479. /* temp values */
  1480. uint32_t five_percent = 0;
  1481. uint32_t ten_percent = 0;
  1482. uint32_t twenty_percent = 0;
  1483. /* walk through list */
  1484. hs_usage_list_elem_t *current = h->list->start;
  1485. int i=0;
  1486. while (current != NULL && i <= twenty_percent_idx) {
  1487. twenty_percent += current->count;
  1488. if (i <= ten_percent_idx)
  1489. ten_percent += current->count;
  1490. if (i <= five_percent_idx)
  1491. five_percent += current->count;
  1492. current = current->next;
  1493. i++;
  1494. }
  1495. /* copy frequencies */
  1496. h->twenty[p->next_idx] = twenty_percent;
  1497. h->ten[p->next_idx] = ten_percent;
  1498. h->five[p->next_idx] = five_percent;
  1499. /* copy total number of observations */
  1500. h->totals[p->next_idx] = h->list->total_count;
  1501. /* free memory of old list */
  1502. hs_usage_list_clear(h->list);
  1503. }
  1504. /** Advances to next observation period. */
  1505. static void
  1506. hs_usage_advance_current_observation_period(void)
  1507. {
  1508. /* aggregate observations to history, including frequency distribution
  1509. * arrays */
  1510. hs_usage_write_service_related_observations_to_history(
  1511. current_period, publish_total);
  1512. hs_usage_write_service_related_observations_to_history(
  1513. current_period, publish_novel);
  1514. hs_usage_write_service_related_observations_to_history(
  1515. current_period, fetch_total);
  1516. hs_usage_write_service_related_observations_to_history(
  1517. current_period, fetch_successful);
  1518. /* write current number of descriptors to descs history */
  1519. descs->totals[current_period->next_idx] = rend_cache_size();
  1520. /* advance to next period */
  1521. current_period->next_idx++;
  1522. if (current_period->next_idx == NUM_TOTALS_HS_USAGE)
  1523. current_period->next_idx = 0;
  1524. if (current_period->num_set < NUM_TOTALS_HS_USAGE)
  1525. ++current_period->num_set;
  1526. current_period->start_of_current_period=current_period->start_of_next_period;
  1527. current_period->start_of_next_period += NUM_SECS_HS_USAGE_SUM_INTERVAL;
  1528. }
  1529. /** Checks if the current period is up to date, and if not, advances it. */
  1530. static void
  1531. hs_usage_check_if_current_period_is_up_to_date(time_t now)
  1532. {
  1533. while (now > current_period->start_of_next_period) {
  1534. hs_usage_advance_current_observation_period();
  1535. }
  1536. }
  1537. /** Adds a service-related observation, maybe after advancing to next
  1538. * observation period. */
  1539. static void
  1540. hs_usage_add_service_related_observation(
  1541. hs_usage_service_related_observation_t *h,
  1542. time_t now,
  1543. const char *service_id)
  1544. {
  1545. if (now < current_period->start_of_current_period) {
  1546. /* don't record old data */
  1547. return;
  1548. }
  1549. /* check if we are up-to-date */
  1550. hs_usage_check_if_current_period_is_up_to_date(now);
  1551. /* add observation */
  1552. hs_usage_insert_value(h->list, service_id);
  1553. }
  1554. /** Adds the observation of storing a rendezvous service descriptor to our
  1555. * cache in our role as HS authoritative directory. */
  1556. void
  1557. hs_usage_note_publish_total(const char *service_id, time_t now)
  1558. {
  1559. hs_usage_add_service_related_observation(publish_total, now, service_id);
  1560. }
  1561. /** Adds the observation of storing a novel rendezvous service descriptor to
  1562. * our cache in our role as HS authoritative directory. */
  1563. void
  1564. hs_usage_note_publish_novel(const char *service_id, time_t now)
  1565. {
  1566. hs_usage_add_service_related_observation(publish_novel, now, service_id);
  1567. }
  1568. /** Adds the observation of being requested for a rendezvous service descriptor
  1569. * in our role as HS authoritative directory. */
  1570. void
  1571. hs_usage_note_fetch_total(const char *service_id, time_t now)
  1572. {
  1573. hs_usage_add_service_related_observation(fetch_total, now, service_id);
  1574. }
  1575. /** Adds the observation of being requested for a rendezvous service descriptor
  1576. * in our role as HS authoritative directory and being able to answer that
  1577. * request successfully. */
  1578. void
  1579. hs_usage_note_fetch_successful(const char *service_id, time_t now)
  1580. {
  1581. hs_usage_add_service_related_observation(fetch_successful, now, service_id);
  1582. }
  1583. /** Writes the given circular array to a string. */
  1584. static size_t
  1585. hs_usage_format_history(char *buf, size_t len, uint32_t *data)
  1586. {
  1587. char *cp = buf; /* pointer where we are in the buffer */
  1588. int i, n;
  1589. if (current_period->num_set <= current_period->next_idx) {
  1590. i = 0; /* not been through circular array */
  1591. } else {
  1592. i = current_period->next_idx;
  1593. }
  1594. for (n = 0; n < current_period->num_set; ++n,++i) {
  1595. if (i >= NUM_TOTALS_HS_USAGE)
  1596. i -= NUM_TOTALS_HS_USAGE;
  1597. tor_assert(i < NUM_TOTALS_HS_USAGE);
  1598. if (n == (current_period->num_set-1))
  1599. tor_snprintf(cp, len-(cp-buf), "%d", data[i]);
  1600. else
  1601. tor_snprintf(cp, len-(cp-buf), "%d,", data[i]);
  1602. cp += strlen(cp);
  1603. }
  1604. return cp-buf;
  1605. }
  1606. /** Writes the complete usage history as hidden service authoritative directory
  1607. * to a string. */
  1608. static char *
  1609. hs_usage_format_statistics(void)
  1610. {
  1611. char *buf, *cp, *s = NULL;
  1612. char t[ISO_TIME_LEN+1];
  1613. int r;
  1614. uint32_t *data = NULL;
  1615. size_t len;
  1616. len = (70+20*NUM_TOTALS_HS_USAGE)*11;
  1617. buf = tor_malloc_zero(len);
  1618. cp = buf;
  1619. for (r = 0; r < 11; ++r) {
  1620. switch (r) {
  1621. case 0:
  1622. s = (char*) "publish-total-history";
  1623. data = publish_total->totals;
  1624. break;
  1625. case 1:
  1626. s = (char*) "publish-novel-history";
  1627. data = publish_novel->totals;
  1628. break;
  1629. case 2:
  1630. s = (char*) "publish-top-5-percent-history";
  1631. data = publish_total->five;
  1632. break;
  1633. case 3:
  1634. s = (char*) "publish-top-10-percent-history";
  1635. data = publish_total->ten;
  1636. break;
  1637. case 4:
  1638. s = (char*) "publish-top-20-percent-history";
  1639. data = publish_total->twenty;
  1640. break;
  1641. case 5:
  1642. s = (char*) "fetch-total-history";
  1643. data = fetch_total->totals;
  1644. break;
  1645. case 6:
  1646. s = (char*) "fetch-successful-history";
  1647. data = fetch_successful->totals;
  1648. break;
  1649. case 7:
  1650. s = (char*) "fetch-top-5-percent-history";
  1651. data = fetch_total->five;
  1652. break;
  1653. case 8:
  1654. s = (char*) "fetch-top-10-percent-history";
  1655. data = fetch_total->ten;
  1656. break;
  1657. case 9:
  1658. s = (char*) "fetch-top-20-percent-history";
  1659. data = fetch_total->twenty;
  1660. break;
  1661. case 10:
  1662. s = (char*) "desc-total-history";
  1663. data = descs->totals;
  1664. break;
  1665. }
  1666. format_iso_time(t, current_period->start_of_current_period);
  1667. tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ", s, t,
  1668. NUM_SECS_HS_USAGE_SUM_INTERVAL);
  1669. cp += strlen(cp);
  1670. cp += hs_usage_format_history(cp, len-(cp-buf), data);
  1671. strlcat(cp, "\n", len-(cp-buf));
  1672. ++cp;
  1673. }
  1674. return buf;
  1675. }
  1676. /** Writes current statistics to file. */
  1677. void
  1678. hs_usage_write_statistics_to_file(time_t now)
  1679. {
  1680. char *buf;
  1681. size_t len;
  1682. char *fname;
  1683. or_options_t *options;
  1684. /* check if we are up-to-date */
  1685. hs_usage_check_if_current_period_is_up_to_date(now);
  1686. buf = hs_usage_format_statistics();
  1687. options = get_options();
  1688. len = strlen(options->DataDirectory) + 16;
  1689. fname = tor_malloc(len);
  1690. tor_snprintf(fname,len, "%s"PATH_SEPARATOR"hsusage", options->DataDirectory);
  1691. write_str_to_file(fname,buf,0);
  1692. tor_free(buf);
  1693. tor_free(fname);
  1694. }