rephist.c 75 KB

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