rephist.c 66 KB

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