rephist.c 65 KB

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