rephist.c 72 KB

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