rephist.c 56 KB

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