rephist.c 72 KB

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