In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / rephist.c
blob72de54c0c926953ec306a7afb80d4765f44b2479
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2013, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rephist.c
7 * \brief Basic history and "reputation" functionality to remember
8 * which servers have worked in the past, how much bandwidth we've
9 * been using, which ports we tend to want, and so on; further,
10 * exit port statistics, cell statistics, and connection statistics.
11 **/
13 #include "or.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
16 #include "config.h"
17 #include "networkstatus.h"
18 #include "nodelist.h"
19 #include "rephist.h"
20 #include "router.h"
21 #include "routerlist.h"
22 #include "ht.h"
24 static void bw_arrays_init(void);
25 static void predicted_ports_init(void);
27 /** Total number of bytes currently allocated in fields used by rephist.c. */
28 uint64_t rephist_total_alloc=0;
29 /** Number of or_history_t objects currently allocated. */
30 uint32_t rephist_total_num=0;
32 /** If the total weighted run count of all runs for a router ever falls
33 * below this amount, the router can be treated as having 0 MTBF. */
34 #define STABILITY_EPSILON 0.0001
35 /** Value by which to discount all old intervals for MTBF purposes. This
36 * is compounded every STABILITY_INTERVAL. */
37 #define STABILITY_ALPHA 0.95
38 /** Interval at which to discount all old intervals for MTBF purposes. */
39 #define STABILITY_INTERVAL (12*60*60)
40 /* (This combination of ALPHA, INTERVAL, and EPSILON makes it so that an
41 * interval that just ended counts twice as much as one that ended a week ago,
42 * 20X as much as one that ended a month ago, and routers that have had no
43 * uptime data for about half a year will get forgotten.) */
45 /** History of an OR-\>OR link. */
46 typedef struct link_history_t {
47 /** When did we start tracking this list? */
48 time_t since;
49 /** When did we most recently note a change to this link */
50 time_t changed;
51 /** How many times did extending from OR1 to OR2 succeed? */
52 unsigned long n_extend_ok;
53 /** How many times did extending from OR1 to OR2 fail? */
54 unsigned long n_extend_fail;
55 } link_history_t;
57 /** History of an OR. */
58 typedef struct or_history_t {
59 /** When did we start tracking this OR? */
60 time_t since;
61 /** When did we most recently note a change to this OR? */
62 time_t changed;
63 /** How many times did we successfully connect? */
64 unsigned long n_conn_ok;
65 /** How many times did we try to connect and fail?*/
66 unsigned long n_conn_fail;
67 /** How many seconds have we been connected to this OR before
68 * 'up_since'? */
69 unsigned long uptime;
70 /** How many seconds have we been unable to connect to this OR before
71 * 'down_since'? */
72 unsigned long downtime;
73 /** If nonzero, we have been connected since this time. */
74 time_t up_since;
75 /** If nonzero, we have been unable to connect since this time. */
76 time_t down_since;
78 /** The address at which we most recently connected to this OR
79 * successfully. */
80 tor_addr_t last_reached_addr;
82 /** The port at which we most recently connected to this OR successfully */
83 uint16_t last_reached_port;
85 /* === For MTBF tracking: */
86 /** Weighted sum total of all times that this router has been online.
88 unsigned long weighted_run_length;
89 /** If the router is now online (according to stability-checking rules),
90 * when did it come online? */
91 time_t start_of_run;
92 /** Sum of weights for runs in weighted_run_length. */
93 double total_run_weights;
94 /* === For fractional uptime tracking: */
95 time_t start_of_downtime;
96 unsigned long weighted_uptime;
97 unsigned long total_weighted_time;
99 /** Map from hex OR2 identity digest to a link_history_t for the link
100 * from this OR to OR2. */
101 digestmap_t *link_history_map;
102 } or_history_t;
104 /** When did we last multiply all routers' weighted_run_length and
105 * total_run_weights by STABILITY_ALPHA? */
106 static time_t stability_last_downrated = 0;
108 /** */
109 static time_t started_tracking_stability = 0;
111 /** Map from hex OR identity digest to or_history_t. */
112 static digestmap_t *history_map = NULL;
114 /** Return the or_history_t for the OR with identity digest <b>id</b>,
115 * creating it if necessary. */
116 static or_history_t *
117 get_or_history(const char* id)
119 or_history_t *hist;
121 if (tor_digest_is_zero(id))
122 return NULL;
124 hist = digestmap_get(history_map, id);
125 if (!hist) {
126 hist = tor_malloc_zero(sizeof(or_history_t));
127 rephist_total_alloc += sizeof(or_history_t);
128 rephist_total_num++;
129 hist->link_history_map = digestmap_new();
130 hist->since = hist->changed = time(NULL);
131 tor_addr_make_unspec(&hist->last_reached_addr);
132 digestmap_set(history_map, id, hist);
134 return hist;
137 /** Return the link_history_t for the link from the first named OR to
138 * the second, creating it if necessary. (ORs are identified by
139 * identity digest.)
141 static link_history_t *
142 get_link_history(const char *from_id, const char *to_id)
144 or_history_t *orhist;
145 link_history_t *lhist;
146 orhist = get_or_history(from_id);
147 if (!orhist)
148 return NULL;
149 if (tor_digest_is_zero(to_id))
150 return NULL;
151 lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
152 if (!lhist) {
153 lhist = tor_malloc_zero(sizeof(link_history_t));
154 rephist_total_alloc += sizeof(link_history_t);
155 lhist->since = lhist->changed = time(NULL);
156 digestmap_set(orhist->link_history_map, to_id, lhist);
158 return lhist;
161 /** Helper: free storage held by a single link history entry. */
162 static void
163 free_link_history_(void *val)
165 rephist_total_alloc -= sizeof(link_history_t);
166 tor_free(val);
169 /** Helper: free storage held by a single OR history entry. */
170 static void
171 free_or_history(void *_hist)
173 or_history_t *hist = _hist;
174 digestmap_free(hist->link_history_map, free_link_history_);
175 rephist_total_alloc -= sizeof(or_history_t);
176 rephist_total_num--;
177 tor_free(hist);
180 /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
181 * count is up-to-date as of <b>when</b>.
183 static void
184 update_or_history(or_history_t *hist, time_t when)
186 tor_assert(hist);
187 if (hist->up_since) {
188 tor_assert(!hist->down_since);
189 hist->uptime += (when - hist->up_since);
190 hist->up_since = when;
191 } else if (hist->down_since) {
192 hist->downtime += (when - hist->down_since);
193 hist->down_since = when;
197 /** Initialize the static data structures for tracking history. */
198 void
199 rep_hist_init(void)
201 history_map = digestmap_new();
202 bw_arrays_init();
203 predicted_ports_init();
206 /** Helper: note that we are no longer connected to the router with history
207 * <b>hist</b>. If <b>failed</b>, the connection failed; otherwise, it was
208 * closed correctly. */
209 static void
210 mark_or_down(or_history_t *hist, time_t when, int failed)
212 if (hist->up_since) {
213 hist->uptime += (when - hist->up_since);
214 hist->up_since = 0;
216 if (failed && !hist->down_since) {
217 hist->down_since = when;
221 /** Helper: note that we are connected to the router with history
222 * <b>hist</b>. */
223 static void
224 mark_or_up(or_history_t *hist, time_t when)
226 if (hist->down_since) {
227 hist->downtime += (when - hist->down_since);
228 hist->down_since = 0;
230 if (!hist->up_since) {
231 hist->up_since = when;
235 /** Remember that an attempt to connect to the OR with identity digest
236 * <b>id</b> failed at <b>when</b>.
238 void
239 rep_hist_note_connect_failed(const char* id, time_t when)
241 or_history_t *hist;
242 hist = get_or_history(id);
243 if (!hist)
244 return;
245 ++hist->n_conn_fail;
246 mark_or_down(hist, when, 1);
247 hist->changed = when;
250 /** Remember that an attempt to connect to the OR with identity digest
251 * <b>id</b> succeeded at <b>when</b>.
253 void
254 rep_hist_note_connect_succeeded(const char* id, time_t when)
256 or_history_t *hist;
257 hist = get_or_history(id);
258 if (!hist)
259 return;
260 ++hist->n_conn_ok;
261 mark_or_up(hist, when);
262 hist->changed = when;
265 /** Remember that we intentionally closed our connection to the OR
266 * with identity digest <b>id</b> at <b>when</b>.
268 void
269 rep_hist_note_disconnect(const char* id, time_t when)
271 or_history_t *hist;
272 hist = get_or_history(id);
273 if (!hist)
274 return;
275 mark_or_down(hist, when, 0);
276 hist->changed = when;
279 /** Remember that our connection to the OR with identity digest
280 * <b>id</b> had an error and stopped working at <b>when</b>.
282 void
283 rep_hist_note_connection_died(const char* id, time_t when)
285 or_history_t *hist;
286 if (!id) {
287 /* If conn has no identity, it didn't complete its handshake, or something
288 * went wrong. Ignore it.
290 return;
292 hist = get_or_history(id);
293 if (!hist)
294 return;
295 mark_or_down(hist, when, 1);
296 hist->changed = when;
299 /** We have just decided that this router with identity digest <b>id</b> is
300 * reachable, meaning we will give it a "Running" flag for the next while. */
301 void
302 rep_hist_note_router_reachable(const char *id, const tor_addr_t *at_addr,
303 const uint16_t at_port, time_t when)
305 or_history_t *hist = get_or_history(id);
306 int was_in_run = 1;
307 char tbuf[ISO_TIME_LEN+1];
308 int addr_changed, port_changed;
310 tor_assert(hist);
311 tor_assert((!at_addr && !at_port) || (at_addr && at_port));
313 addr_changed = at_addr && !tor_addr_is_null(&hist->last_reached_addr) &&
314 tor_addr_compare(at_addr, &hist->last_reached_addr, CMP_EXACT) != 0;
315 port_changed = at_port && hist->last_reached_port &&
316 at_port != hist->last_reached_port;
318 if (!started_tracking_stability)
319 started_tracking_stability = time(NULL);
320 if (!hist->start_of_run) {
321 hist->start_of_run = when;
322 was_in_run = 0;
324 if (hist->start_of_downtime) {
325 long down_length;
327 format_local_iso_time(tbuf, hist->start_of_downtime);
328 log_info(LD_HIST, "Router %s is now Running; it had been down since %s.",
329 hex_str(id, DIGEST_LEN), tbuf);
330 if (was_in_run)
331 log_info(LD_HIST, " (Paradoxically, it was already Running too.)");
333 down_length = when - hist->start_of_downtime;
334 hist->total_weighted_time += down_length;
335 hist->start_of_downtime = 0;
336 } else if (addr_changed || port_changed) {
337 /* If we're reachable, but the address changed, treat this as some
338 * downtime. */
339 int penalty = get_options()->TestingTorNetwork ? 240 : 3600;
340 networkstatus_t *ns;
342 if ((ns = networkstatus_get_latest_consensus())) {
343 int fresh_interval = (int)(ns->fresh_until - ns->valid_after);
344 int live_interval = (int)(ns->valid_until - ns->valid_after);
345 /* on average, a descriptor addr change takes .5 intervals to make it
346 * into a consensus, and half a liveness period to make it to
347 * clients. */
348 penalty = (int)(fresh_interval + live_interval) / 2;
350 format_local_iso_time(tbuf, hist->start_of_run);
351 log_info(LD_HIST,"Router %s still seems Running, but its address appears "
352 "to have changed since the last time it was reachable. I'm "
353 "going to treat it as having been down for %d seconds",
354 hex_str(id, DIGEST_LEN), penalty);
355 rep_hist_note_router_unreachable(id, when-penalty);
356 rep_hist_note_router_reachable(id, NULL, 0, when);
357 } else {
358 format_local_iso_time(tbuf, hist->start_of_run);
359 if (was_in_run)
360 log_debug(LD_HIST, "Router %s is still Running; it has been Running "
361 "since %s", hex_str(id, DIGEST_LEN), tbuf);
362 else
363 log_info(LD_HIST,"Router %s is now Running; it was previously untracked",
364 hex_str(id, DIGEST_LEN));
366 if (at_addr)
367 tor_addr_copy(&hist->last_reached_addr, at_addr);
368 if (at_port)
369 hist->last_reached_port = at_port;
372 /** We have just decided that this router is unreachable, meaning
373 * we are taking away its "Running" flag. */
374 void
375 rep_hist_note_router_unreachable(const char *id, time_t when)
377 or_history_t *hist = get_or_history(id);
378 char tbuf[ISO_TIME_LEN+1];
379 int was_running = 0;
380 if (!started_tracking_stability)
381 started_tracking_stability = time(NULL);
383 tor_assert(hist);
384 if (hist->start_of_run) {
385 /*XXXX We could treat failed connections differently from failed
386 * connect attempts. */
387 long run_length = when - hist->start_of_run;
388 format_local_iso_time(tbuf, hist->start_of_run);
390 hist->total_run_weights += 1.0;
391 hist->start_of_run = 0;
392 if (run_length < 0) {
393 unsigned long penalty = -run_length;
394 #define SUBTRACT_CLAMPED(var, penalty) \
395 do { (var) = (var) < (penalty) ? 0 : (var) - (penalty); } while (0)
397 SUBTRACT_CLAMPED(hist->weighted_run_length, penalty);
398 SUBTRACT_CLAMPED(hist->weighted_uptime, penalty);
399 } else {
400 hist->weighted_run_length += run_length;
401 hist->weighted_uptime += run_length;
402 hist->total_weighted_time += run_length;
404 was_running = 1;
405 log_info(LD_HIST, "Router %s is now non-Running: it had previously been "
406 "Running since %s. Its total weighted uptime is %lu/%lu.",
407 hex_str(id, DIGEST_LEN), tbuf, hist->weighted_uptime,
408 hist->total_weighted_time);
410 if (!hist->start_of_downtime) {
411 hist->start_of_downtime = when;
413 if (!was_running)
414 log_info(LD_HIST, "Router %s is now non-Running; it was previously "
415 "untracked.", hex_str(id, DIGEST_LEN));
416 } else {
417 if (!was_running) {
418 format_local_iso_time(tbuf, hist->start_of_downtime);
420 log_info(LD_HIST, "Router %s is still non-Running; it has been "
421 "non-Running since %s.", hex_str(id, DIGEST_LEN), tbuf);
426 /** Mark a router with ID <b>id</b> as non-Running, and retroactively declare
427 * that it has never been running: give it no stability and no WFU. */
428 void
429 rep_hist_make_router_pessimal(const char *id, time_t when)
431 or_history_t *hist = get_or_history(id);
432 tor_assert(hist);
434 rep_hist_note_router_unreachable(id, when);
435 mark_or_down(hist, when, 1);
437 hist->weighted_run_length = 0;
438 hist->weighted_uptime = 0;
441 /** Helper: Discount all old MTBF data, if it is time to do so. Return
442 * the time at which we should next discount MTBF data. */
443 time_t
444 rep_hist_downrate_old_runs(time_t now)
446 digestmap_iter_t *orhist_it;
447 const char *digest1;
448 or_history_t *hist;
449 void *hist_p;
450 double alpha = 1.0;
452 if (!history_map)
453 history_map = digestmap_new();
454 if (!stability_last_downrated)
455 stability_last_downrated = now;
456 if (stability_last_downrated + STABILITY_INTERVAL > now)
457 return stability_last_downrated + STABILITY_INTERVAL;
459 /* Okay, we should downrate the data. By how much? */
460 while (stability_last_downrated + STABILITY_INTERVAL < now) {
461 stability_last_downrated += STABILITY_INTERVAL;
462 alpha *= STABILITY_ALPHA;
465 log_info(LD_HIST, "Discounting all old stability info by a factor of %f",
466 alpha);
468 /* Multiply every w_r_l, t_r_w pair by alpha. */
469 for (orhist_it = digestmap_iter_init(history_map);
470 !digestmap_iter_done(orhist_it);
471 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
472 digestmap_iter_get(orhist_it, &digest1, &hist_p);
473 hist = hist_p;
475 hist->weighted_run_length =
476 (unsigned long)(hist->weighted_run_length * alpha);
477 hist->total_run_weights *= alpha;
479 hist->weighted_uptime = (unsigned long)(hist->weighted_uptime * alpha);
480 hist->total_weighted_time = (unsigned long)
481 (hist->total_weighted_time * alpha);
484 return stability_last_downrated + STABILITY_INTERVAL;
487 /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
488 static double
489 get_stability(or_history_t *hist, time_t when)
491 long total = hist->weighted_run_length;
492 double total_weights = hist->total_run_weights;
494 if (hist->start_of_run) {
495 /* We're currently in a run. Let total and total_weights hold the values
496 * they would hold if the current run were to end now. */
497 total += (when-hist->start_of_run);
498 total_weights += 1.0;
500 if (total_weights < STABILITY_EPSILON) {
501 /* Round down to zero, and avoid divide-by-zero. */
502 return 0.0;
505 return total / total_weights;
508 /** Return the total amount of time we've been observing, with each run of
509 * time downrated by the appropriate factor. */
510 static long
511 get_total_weighted_time(or_history_t *hist, time_t when)
513 long total = hist->total_weighted_time;
514 if (hist->start_of_run) {
515 total += (when - hist->start_of_run);
516 } else if (hist->start_of_downtime) {
517 total += (when - hist->start_of_downtime);
519 return total;
522 /** Helper: Return the weighted percent-of-time-online of the router with
523 * history <b>hist</b>. */
524 static double
525 get_weighted_fractional_uptime(or_history_t *hist, time_t when)
527 long total = hist->total_weighted_time;
528 long up = hist->weighted_uptime;
530 if (hist->start_of_run) {
531 long run_length = (when - hist->start_of_run);
532 up += run_length;
533 total += run_length;
534 } else if (hist->start_of_downtime) {
535 total += (when - hist->start_of_downtime);
538 if (!total) {
539 /* Avoid calling anybody's uptime infinity (which should be impossible if
540 * the code is working), or NaN (which can happen for any router we haven't
541 * observed up or down yet). */
542 return 0.0;
545 return ((double) up) / total;
548 /** Return how long the router whose identity digest is <b>id</b> has
549 * been reachable. Return 0 if the router is unknown or currently deemed
550 * unreachable. */
551 long
552 rep_hist_get_uptime(const char *id, time_t when)
554 or_history_t *hist = get_or_history(id);
555 if (!hist)
556 return 0;
557 if (!hist->start_of_run || when < hist->start_of_run)
558 return 0;
559 return when - hist->start_of_run;
562 /** Return an estimated MTBF for the router whose identity digest is
563 * <b>id</b>. Return 0 if the router is unknown. */
564 double
565 rep_hist_get_stability(const char *id, time_t when)
567 or_history_t *hist = get_or_history(id);
568 if (!hist)
569 return 0.0;
571 return get_stability(hist, when);
574 /** Return an estimated percent-of-time-online for the router whose identity
575 * digest is <b>id</b>. Return 0 if the router is unknown. */
576 double
577 rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
579 or_history_t *hist = get_or_history(id);
580 if (!hist)
581 return 0.0;
583 return get_weighted_fractional_uptime(hist, when);
586 /** Return a number representing how long we've known about the router whose
587 * digest is <b>id</b>. Return 0 if the router is unknown.
589 * Be careful: this measure increases monotonically as we know the router for
590 * longer and longer, but it doesn't increase linearly.
592 long
593 rep_hist_get_weighted_time_known(const char *id, time_t when)
595 or_history_t *hist = get_or_history(id);
596 if (!hist)
597 return 0;
599 return get_total_weighted_time(hist, when);
602 /** Return true if we've been measuring MTBFs for long enough to
603 * pronounce on Stability. */
605 rep_hist_have_measured_enough_stability(void)
607 /* XXXX023 This doesn't do so well when we change our opinion
608 * as to whether we're tracking router stability. */
609 return started_tracking_stability < time(NULL) - 4*60*60;
612 /** Remember that we successfully extended from the OR with identity
613 * digest <b>from_id</b> to the OR with identity digest
614 * <b>to_name</b>.
616 void
617 rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
619 link_history_t *hist;
620 /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
621 hist = get_link_history(from_id, to_id);
622 if (!hist)
623 return;
624 ++hist->n_extend_ok;
625 hist->changed = time(NULL);
628 /** Remember that we tried to extend from the OR with identity digest
629 * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
630 * failed.
632 void
633 rep_hist_note_extend_failed(const char *from_id, const char *to_id)
635 link_history_t *hist;
636 /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
637 hist = get_link_history(from_id, to_id);
638 if (!hist)
639 return;
640 ++hist->n_extend_fail;
641 hist->changed = time(NULL);
644 /** Log all the reliability data we have remembered, with the chosen
645 * severity.
647 void
648 rep_hist_dump_stats(time_t now, int severity)
650 digestmap_iter_t *lhist_it;
651 digestmap_iter_t *orhist_it;
652 const char *name1, *name2, *digest1, *digest2;
653 char hexdigest1[HEX_DIGEST_LEN+1];
654 char hexdigest2[HEX_DIGEST_LEN+1];
655 or_history_t *or_history;
656 link_history_t *link_history;
657 void *or_history_p, *link_history_p;
658 double uptime;
659 char buffer[2048];
660 size_t len;
661 int ret;
662 unsigned long upt, downt;
663 const node_t *node;
665 rep_history_clean(now - get_options()->RephistTrackTime);
667 tor_log(severity, LD_HIST, "--------------- Dumping history information:");
669 for (orhist_it = digestmap_iter_init(history_map);
670 !digestmap_iter_done(orhist_it);
671 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
672 double s;
673 long stability;
674 digestmap_iter_get(orhist_it, &digest1, &or_history_p);
675 or_history = (or_history_t*) or_history_p;
677 if ((node = node_get_by_id(digest1)) && node_get_nickname(node))
678 name1 = node_get_nickname(node);
679 else
680 name1 = "(unknown)";
681 base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
682 update_or_history(or_history, now);
683 upt = or_history->uptime;
684 downt = or_history->downtime;
685 s = get_stability(or_history, now);
686 stability = (long)s;
687 if (upt+downt) {
688 uptime = ((double)upt) / (upt+downt);
689 } else {
690 uptime=1.0;
692 tor_log(severity, LD_HIST,
693 "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
694 "wmtbf %lu:%02lu:%02lu",
695 name1, hexdigest1,
696 or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
697 upt, upt+downt, uptime*100.0,
698 stability/3600, (stability/60)%60, stability%60);
700 if (!digestmap_isempty(or_history->link_history_map)) {
701 strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
702 len = strlen(buffer);
703 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
704 !digestmap_iter_done(lhist_it);
705 lhist_it = digestmap_iter_next(or_history->link_history_map,
706 lhist_it)) {
707 digestmap_iter_get(lhist_it, &digest2, &link_history_p);
708 if ((node = node_get_by_id(digest2)) && node_get_nickname(node))
709 name2 = node_get_nickname(node);
710 else
711 name2 = "(unknown)";
713 link_history = (link_history_t*) link_history_p;
715 base16_encode(hexdigest2, sizeof(hexdigest2), digest2, DIGEST_LEN);
716 ret = tor_snprintf(buffer+len, 2048-len, "%s [%s](%ld/%ld); ",
717 name2,
718 hexdigest2,
719 link_history->n_extend_ok,
720 link_history->n_extend_ok+link_history->n_extend_fail);
721 if (ret<0)
722 break;
723 else
724 len += ret;
726 tor_log(severity, LD_HIST, "%s", buffer);
731 /** Remove history info for routers/links that haven't changed since
732 * <b>before</b>.
734 void
735 rep_history_clean(time_t before)
737 int authority = authdir_mode(get_options());
738 or_history_t *or_history;
739 link_history_t *link_history;
740 void *or_history_p, *link_history_p;
741 digestmap_iter_t *orhist_it, *lhist_it;
742 const char *d1, *d2;
744 orhist_it = digestmap_iter_init(history_map);
745 while (!digestmap_iter_done(orhist_it)) {
746 int remove;
747 digestmap_iter_get(orhist_it, &d1, &or_history_p);
748 or_history = or_history_p;
750 remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
751 !or_history->start_of_run)
752 : (or_history->changed < before);
753 if (remove) {
754 orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
755 free_or_history(or_history);
756 continue;
758 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
759 !digestmap_iter_done(lhist_it); ) {
760 digestmap_iter_get(lhist_it, &d2, &link_history_p);
761 link_history = link_history_p;
762 if (link_history->changed < before) {
763 lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
764 lhist_it);
765 rephist_total_alloc -= sizeof(link_history_t);
766 tor_free(link_history);
767 continue;
769 lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
771 orhist_it = digestmap_iter_next(history_map, orhist_it);
775 /** Write MTBF data to disk. Return 0 on success, negative on failure.
777 * If <b>missing_means_down</b>, then if we're about to write an entry
778 * that is still considered up but isn't in our routerlist, consider it
779 * to be down. */
781 rep_hist_record_mtbf_data(time_t now, int missing_means_down)
783 char time_buf[ISO_TIME_LEN+1];
785 digestmap_iter_t *orhist_it;
786 const char *digest;
787 void *or_history_p;
788 or_history_t *hist;
789 open_file_t *open_file = NULL;
790 FILE *f;
793 char *filename = get_datadir_fname("router-stability");
794 f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
795 &open_file);
796 tor_free(filename);
797 if (!f)
798 return -1;
801 /* File format is:
802 * FormatLine *KeywordLine Data
804 * FormatLine = "format 1" NL
805 * KeywordLine = Keyword SP Arguments NL
806 * Data = "data" NL *RouterMTBFLine "." NL
807 * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
808 * TotalRunWeights [SP S=StartRunTime] NL
810 #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
811 #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
813 PUT("format 2\n");
815 format_iso_time(time_buf, time(NULL));
816 PRINTF((f, "stored-at %s\n", time_buf));
818 if (started_tracking_stability) {
819 format_iso_time(time_buf, started_tracking_stability);
820 PRINTF((f, "tracked-since %s\n", time_buf));
822 if (stability_last_downrated) {
823 format_iso_time(time_buf, stability_last_downrated);
824 PRINTF((f, "last-downrated %s\n", time_buf));
827 PUT("data\n");
829 /* XXX Nick: now bridge auths record this for all routers too.
830 * Should we make them record it only for bridge routers? -RD
831 * Not for 0.2.0. -NM */
832 for (orhist_it = digestmap_iter_init(history_map);
833 !digestmap_iter_done(orhist_it);
834 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
835 char dbuf[HEX_DIGEST_LEN+1];
836 const char *t = NULL;
837 digestmap_iter_get(orhist_it, &digest, &or_history_p);
838 hist = (or_history_t*) or_history_p;
840 base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
842 if (missing_means_down && hist->start_of_run &&
843 !router_get_by_id_digest(digest)) {
844 /* We think this relay is running, but it's not listed in our
845 * routerlist. Somehow it fell out without telling us it went
846 * down. Complain and also correct it. */
847 log_info(LD_HIST,
848 "Relay '%s' is listed as up in rephist, but it's not in "
849 "our routerlist. Correcting.", dbuf);
850 rep_hist_note_router_unreachable(digest, now);
853 PRINTF((f, "R %s\n", dbuf));
854 if (hist->start_of_run > 0) {
855 format_iso_time(time_buf, hist->start_of_run);
856 t = time_buf;
858 PRINTF((f, "+MTBF %lu %.5f%s%s\n",
859 hist->weighted_run_length, hist->total_run_weights,
860 t ? " S=" : "", t ? t : ""));
861 t = NULL;
862 if (hist->start_of_downtime > 0) {
863 format_iso_time(time_buf, hist->start_of_downtime);
864 t = time_buf;
866 PRINTF((f, "+WFU %lu %lu%s%s\n",
867 hist->weighted_uptime, hist->total_weighted_time,
868 t ? " S=" : "", t ? t : ""));
871 PUT(".\n");
873 #undef PUT
874 #undef PRINTF
876 return finish_writing_to_file(open_file);
877 err:
878 abort_writing_to_file(open_file);
879 return -1;
882 /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
883 * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
884 * such line exists. */
885 static int
886 find_next_with(smartlist_t *sl, int i, const char *prefix)
888 for ( ; i < smartlist_len(sl); ++i) {
889 const char *line = smartlist_get(sl, i);
890 if (!strcmpstart(line, prefix))
891 return i;
892 if (!strcmpstart(line, "R "))
893 return -1;
895 return -1;
898 /** How many bad times has parse_possibly_bad_iso_time() parsed? */
899 static int n_bogus_times = 0;
900 /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
901 * round any pre-1970 date to Jan 1, 1970. */
902 static int
903 parse_possibly_bad_iso_time(const char *s, time_t *time_out)
905 int year;
906 char b[5];
907 strlcpy(b, s, sizeof(b));
908 b[4] = '\0';
909 year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
910 if (year < 1970) {
911 *time_out = 0;
912 ++n_bogus_times;
913 return 0;
914 } else
915 return parse_iso_time(s, time_out);
918 /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
919 * says we started measuring at <b>started_measuring</b>. Return a new number
920 * that's about as much before <b>now</b> as <b>t</b> was before
921 * <b>stored_at</b>.
923 static INLINE time_t
924 correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
926 if (t < started_measuring - 24*60*60*365)
927 return 0;
928 else if (t < started_measuring)
929 return started_measuring;
930 else if (t > stored_at)
931 return 0;
932 else {
933 long run_length = stored_at - t;
934 t = (time_t)(now - run_length);
935 if (t < started_measuring)
936 t = started_measuring;
937 return t;
941 /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
942 * on failure. */
944 rep_hist_load_mtbf_data(time_t now)
946 /* XXXX won't handle being called while history is already populated. */
947 smartlist_t *lines;
948 const char *line = NULL;
949 int r=0, i;
950 time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
951 time_t latest_possible_start = now;
952 long format = -1;
955 char *filename = get_datadir_fname("router-stability");
956 char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
957 tor_free(filename);
958 if (!d)
959 return -1;
960 lines = smartlist_new();
961 smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
962 tor_free(d);
966 const char *firstline;
967 if (smartlist_len(lines)>4) {
968 firstline = smartlist_get(lines, 0);
969 if (!strcmpstart(firstline, "format "))
970 format = tor_parse_long(firstline+strlen("format "),
971 10, -1, LONG_MAX, NULL, NULL);
974 if (format != 1 && format != 2) {
975 log_warn(LD_HIST,
976 "Unrecognized format in mtbf history file. Skipping.");
977 goto err;
979 for (i = 1; i < smartlist_len(lines); ++i) {
980 line = smartlist_get(lines, i);
981 if (!strcmp(line, "data"))
982 break;
983 if (!strcmpstart(line, "last-downrated ")) {
984 if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
985 log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
986 "history file.");
988 if (!strcmpstart(line, "stored-at ")) {
989 if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
990 log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
991 "history file.");
993 if (!strcmpstart(line, "tracked-since ")) {
994 if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
995 log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
996 "history file.");
999 if (last_downrated > now)
1000 last_downrated = now;
1001 if (tracked_since > now)
1002 tracked_since = now;
1004 if (!stored_at) {
1005 log_warn(LD_HIST, "No stored time recorded.");
1006 goto err;
1009 if (line && !strcmp(line, "data"))
1010 ++i;
1012 n_bogus_times = 0;
1014 for (; i < smartlist_len(lines); ++i) {
1015 char digest[DIGEST_LEN];
1016 char hexbuf[HEX_DIGEST_LEN+1];
1017 char mtbf_timebuf[ISO_TIME_LEN+1];
1018 char wfu_timebuf[ISO_TIME_LEN+1];
1019 time_t start_of_run = 0;
1020 time_t start_of_downtime = 0;
1021 int have_mtbf = 0, have_wfu = 0;
1022 long wrl = 0;
1023 double trw = 0;
1024 long wt_uptime = 0, total_wt_time = 0;
1025 int n;
1026 or_history_t *hist;
1027 line = smartlist_get(lines, i);
1028 if (!strcmp(line, "."))
1029 break;
1031 mtbf_timebuf[0] = '\0';
1032 wfu_timebuf[0] = '\0';
1034 if (format == 1) {
1035 n = tor_sscanf(line, "%40s %ld %lf S=%10s %8s",
1036 hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1037 if (n != 3 && n != 5) {
1038 log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
1039 continue;
1041 have_mtbf = 1;
1042 } else {
1043 // format == 2.
1044 int mtbf_idx, wfu_idx;
1045 if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
1046 continue;
1047 strlcpy(hexbuf, line+2, sizeof(hexbuf));
1048 mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
1049 wfu_idx = find_next_with(lines, i+1, "+WFU ");
1050 if (mtbf_idx >= 0) {
1051 const char *mtbfline = smartlist_get(lines, mtbf_idx);
1052 n = tor_sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
1053 &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1054 if (n == 2 || n == 4) {
1055 have_mtbf = 1;
1056 } else {
1057 log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
1058 escaped(mtbfline));
1061 if (wfu_idx >= 0) {
1062 const char *wfuline = smartlist_get(lines, wfu_idx);
1063 n = tor_sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
1064 &wt_uptime, &total_wt_time,
1065 wfu_timebuf, wfu_timebuf+11);
1066 if (n == 2 || n == 4) {
1067 have_wfu = 1;
1068 } else {
1069 log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
1072 if (wfu_idx > i)
1073 i = wfu_idx;
1074 if (mtbf_idx > i)
1075 i = mtbf_idx;
1077 if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
1078 log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
1079 continue;
1081 hist = get_or_history(digest);
1082 if (!hist)
1083 continue;
1085 if (have_mtbf) {
1086 if (mtbf_timebuf[0]) {
1087 mtbf_timebuf[10] = ' ';
1088 if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
1089 log_warn(LD_HIST, "Couldn't parse time %s",
1090 escaped(mtbf_timebuf));
1092 hist->start_of_run = correct_time(start_of_run, now, stored_at,
1093 tracked_since);
1094 if (hist->start_of_run < latest_possible_start + wrl)
1095 latest_possible_start = (time_t)(hist->start_of_run - wrl);
1097 hist->weighted_run_length = wrl;
1098 hist->total_run_weights = trw;
1100 if (have_wfu) {
1101 if (wfu_timebuf[0]) {
1102 wfu_timebuf[10] = ' ';
1103 if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
1104 log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
1107 hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
1108 tracked_since);
1109 hist->weighted_uptime = wt_uptime;
1110 hist->total_weighted_time = total_wt_time;
1112 if (strcmp(line, "."))
1113 log_warn(LD_HIST, "Truncated MTBF file.");
1115 if (tracked_since < 86400*365) /* Recover from insanely early value. */
1116 tracked_since = latest_possible_start;
1118 stability_last_downrated = last_downrated;
1119 started_tracking_stability = tracked_since;
1121 goto done;
1122 err:
1123 r = -1;
1124 done:
1125 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1126 smartlist_free(lines);
1127 return r;
1130 /** For how many seconds do we keep track of individual per-second bandwidth
1131 * totals? */
1132 #define NUM_SECS_ROLLING_MEASURE 10
1133 /** How large are the intervals for which we track and report bandwidth use? */
1134 /* XXXX Watch out! Before Tor 0.2.2.21-alpha, using any other value here would
1135 * generate an unparseable state file. */
1136 #define NUM_SECS_BW_SUM_INTERVAL (15*60)
1137 /** How far in the past do we remember and publish bandwidth use? */
1138 #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
1139 /** How many bandwidth usage intervals do we remember? (derived) */
1140 #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
1142 /** Structure to track bandwidth use, and remember the maxima for a given
1143 * time period.
1145 typedef struct bw_array_t {
1146 /** Observation array: Total number of bytes transferred in each of the last
1147 * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
1148 uint64_t obs[NUM_SECS_ROLLING_MEASURE];
1149 int cur_obs_idx; /**< Current position in obs. */
1150 time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
1151 uint64_t total_obs; /**< Total for all members of obs except
1152 * obs[cur_obs_idx] */
1153 uint64_t max_total; /**< Largest value that total_obs has taken on in the
1154 * current period. */
1155 uint64_t total_in_period; /**< Total bytes transferred in the current
1156 * period. */
1158 /** When does the next period begin? */
1159 time_t next_period;
1160 /** Where in 'maxima' should the maximum bandwidth usage for the current
1161 * period be stored? */
1162 int next_max_idx;
1163 /** How many values in maxima/totals have been set ever? */
1164 int num_maxes_set;
1165 /** Circular array of the maximum
1166 * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
1167 * NUM_TOTALS periods */
1168 uint64_t maxima[NUM_TOTALS];
1169 /** Circular array of the total bandwidth usage for the last NUM_TOTALS
1170 * periods */
1171 uint64_t totals[NUM_TOTALS];
1172 } bw_array_t;
1174 /** Shift the current period of b forward by one. */
1175 static void
1176 commit_max(bw_array_t *b)
1178 /* Store total from current period. */
1179 b->totals[b->next_max_idx] = b->total_in_period;
1180 /* Store maximum from current period. */
1181 b->maxima[b->next_max_idx++] = b->max_total;
1182 /* Advance next_period and next_max_idx */
1183 b->next_period += NUM_SECS_BW_SUM_INTERVAL;
1184 if (b->next_max_idx == NUM_TOTALS)
1185 b->next_max_idx = 0;
1186 if (b->num_maxes_set < NUM_TOTALS)
1187 ++b->num_maxes_set;
1188 /* Reset max_total. */
1189 b->max_total = 0;
1190 /* Reset total_in_period. */
1191 b->total_in_period = 0;
1194 /** Shift the current observation time of <b>b</b> forward by one second. */
1195 static INLINE void
1196 advance_obs(bw_array_t *b)
1198 int nextidx;
1199 uint64_t total;
1201 /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
1202 * seconds; adjust max_total as needed.*/
1203 total = b->total_obs + b->obs[b->cur_obs_idx];
1204 if (total > b->max_total)
1205 b->max_total = total;
1207 nextidx = b->cur_obs_idx+1;
1208 if (nextidx == NUM_SECS_ROLLING_MEASURE)
1209 nextidx = 0;
1211 b->total_obs = total - b->obs[nextidx];
1212 b->obs[nextidx]=0;
1213 b->cur_obs_idx = nextidx;
1215 if (++b->cur_obs_time >= b->next_period)
1216 commit_max(b);
1219 /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
1220 * <b>when</b>. */
1221 static INLINE void
1222 add_obs(bw_array_t *b, time_t when, uint64_t n)
1224 if (when < b->cur_obs_time)
1225 return; /* Don't record data in the past. */
1227 /* If we're currently adding observations for an earlier second than
1228 * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
1229 * appropriate number of seconds, and do all the other housekeeping. */
1230 while (when > b->cur_obs_time) {
1231 /* Doing this one second at a time is potentially inefficient, if we start
1232 with a state file that is very old. Fortunately, it doesn't seem to
1233 show up in profiles, so we can just ignore it for now. */
1234 advance_obs(b);
1237 b->obs[b->cur_obs_idx] += n;
1238 b->total_in_period += n;
1241 /** Allocate, initialize, and return a new bw_array. */
1242 static bw_array_t *
1243 bw_array_new(void)
1245 bw_array_t *b;
1246 time_t start;
1247 b = tor_malloc_zero(sizeof(bw_array_t));
1248 rephist_total_alloc += sizeof(bw_array_t);
1249 start = time(NULL);
1250 b->cur_obs_time = start;
1251 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1252 return b;
1255 /** Recent history of bandwidth observations for read operations. */
1256 static bw_array_t *read_array = NULL;
1257 /** Recent history of bandwidth observations for write operations. */
1258 static bw_array_t *write_array = NULL;
1259 /** Recent history of bandwidth observations for read operations for the
1260 directory protocol. */
1261 static bw_array_t *dir_read_array = NULL;
1262 /** Recent history of bandwidth observations for write operations for the
1263 directory protocol. */
1264 static bw_array_t *dir_write_array = NULL;
1266 /** Set up [dir-]read_array and [dir-]write_array, freeing them if they
1267 * already exist. */
1268 static void
1269 bw_arrays_init(void)
1271 tor_free(read_array);
1272 tor_free(write_array);
1273 tor_free(dir_read_array);
1274 tor_free(dir_write_array);
1275 read_array = bw_array_new();
1276 write_array = bw_array_new();
1277 dir_read_array = bw_array_new();
1278 dir_write_array = bw_array_new();
1281 /** Remember that we read <b>num_bytes</b> bytes in second <b>when</b>.
1283 * Add num_bytes to the current running total for <b>when</b>.
1285 * <b>when</b> can go back to time, but it's safe to ignore calls
1286 * earlier than the latest <b>when</b> you've heard of.
1288 void
1289 rep_hist_note_bytes_written(size_t num_bytes, time_t when)
1291 /* Maybe a circular array for recent seconds, and step to a new point
1292 * every time a new second shows up. Or simpler is to just to have
1293 * a normal array and push down each item every second; it's short.
1295 /* When a new second has rolled over, compute the sum of the bytes we've
1296 * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
1297 * somewhere. See rep_hist_bandwidth_assess() below.
1299 add_obs(write_array, when, num_bytes);
1302 /** Remember that we wrote <b>num_bytes</b> bytes in second <b>when</b>.
1303 * (like rep_hist_note_bytes_written() above)
1305 void
1306 rep_hist_note_bytes_read(size_t num_bytes, time_t when)
1308 /* if we're smart, we can make this func and the one above share code */
1309 add_obs(read_array, when, num_bytes);
1312 /** Remember that we wrote <b>num_bytes</b> directory bytes in second
1313 * <b>when</b>. (like rep_hist_note_bytes_written() above)
1315 void
1316 rep_hist_note_dir_bytes_written(size_t num_bytes, time_t when)
1318 add_obs(dir_write_array, when, num_bytes);
1321 /** Remember that we read <b>num_bytes</b> directory bytes in second
1322 * <b>when</b>. (like rep_hist_note_bytes_written() above)
1324 void
1325 rep_hist_note_dir_bytes_read(size_t num_bytes, time_t when)
1327 add_obs(dir_read_array, when, num_bytes);
1330 /** Helper: Return the largest value in b->maxima. (This is equal to the
1331 * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
1332 * NUM_SECS_BW_SUM_IS_VALID seconds.)
1334 static uint64_t
1335 find_largest_max(bw_array_t *b)
1337 int i;
1338 uint64_t max;
1339 max=0;
1340 for (i=0; i<NUM_TOTALS; ++i) {
1341 if (b->maxima[i]>max)
1342 max = b->maxima[i];
1344 return max;
1347 /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
1348 * seconds. Find one sum for reading and one for writing. They don't have
1349 * to be at the same time.
1351 * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
1354 rep_hist_bandwidth_assess(void)
1356 uint64_t w,r;
1357 r = find_largest_max(read_array);
1358 w = find_largest_max(write_array);
1359 if (r>w)
1360 return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
1361 else
1362 return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
1365 /** Print the bandwidth history of b (either [dir-]read_array or
1366 * [dir-]write_array) into the buffer pointed to by buf. The format is
1367 * simply comma separated numbers, from oldest to newest.
1369 * It returns the number of bytes written.
1371 static size_t
1372 rep_hist_fill_bandwidth_history(char *buf, size_t len, const bw_array_t *b)
1374 char *cp = buf;
1375 int i, n;
1376 const or_options_t *options = get_options();
1377 uint64_t cutoff;
1379 if (b->num_maxes_set <= b->next_max_idx) {
1380 /* We haven't been through the circular array yet; time starts at i=0.*/
1381 i = 0;
1382 } else {
1383 /* We've been around the array at least once. The next i to be
1384 overwritten is the oldest. */
1385 i = b->next_max_idx;
1388 if (options->RelayBandwidthRate) {
1389 /* We don't want to report that we used more bandwidth than the max we're
1390 * willing to relay; otherwise everybody will know how much traffic
1391 * we used ourself. */
1392 cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
1393 } else {
1394 cutoff = UINT64_MAX;
1397 for (n=0; n<b->num_maxes_set; ++n,++i) {
1398 uint64_t total;
1399 if (i >= NUM_TOTALS)
1400 i -= NUM_TOTALS;
1401 tor_assert(i < NUM_TOTALS);
1402 /* Round the bandwidth used down to the nearest 1k. */
1403 total = b->totals[i] & ~0x3ff;
1404 if (total > cutoff)
1405 total = cutoff;
1407 if (n==(b->num_maxes_set-1))
1408 tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
1409 else
1410 tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
1411 cp += strlen(cp);
1413 return cp-buf;
1416 /** Allocate and return lines for representing this server's bandwidth
1417 * history in its descriptor. We publish these lines in our extra-info
1418 * descriptor.
1420 char *
1421 rep_hist_get_bandwidth_lines(void)
1423 char *buf, *cp;
1424 char t[ISO_TIME_LEN+1];
1425 int r;
1426 bw_array_t *b = NULL;
1427 const char *desc = NULL;
1428 size_t len;
1430 /* [dirreq-](read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n... */
1431 /* The n,n,n part above. Largest representation of a uint64_t is 20 chars
1432 * long, plus the comma. */
1433 #define MAX_HIST_VALUE_LEN (21*NUM_TOTALS)
1434 len = (67+MAX_HIST_VALUE_LEN)*4;
1435 buf = tor_malloc_zero(len);
1436 cp = buf;
1437 for (r=0;r<4;++r) {
1438 char tmp[MAX_HIST_VALUE_LEN];
1439 size_t slen;
1440 switch (r) {
1441 case 0:
1442 b = write_array;
1443 desc = "write-history";
1444 break;
1445 case 1:
1446 b = read_array;
1447 desc = "read-history";
1448 break;
1449 case 2:
1450 b = dir_write_array;
1451 desc = "dirreq-write-history";
1452 break;
1453 case 3:
1454 b = dir_read_array;
1455 desc = "dirreq-read-history";
1456 break;
1458 tor_assert(b);
1459 slen = rep_hist_fill_bandwidth_history(tmp, MAX_HIST_VALUE_LEN, b);
1460 /* If we don't have anything to write, skip to the next entry. */
1461 if (slen == 0)
1462 continue;
1463 format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
1464 tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ",
1465 desc, t, NUM_SECS_BW_SUM_INTERVAL);
1466 cp += strlen(cp);
1467 strlcat(cp, tmp, len-(cp-buf));
1468 cp += slen;
1469 strlcat(cp, "\n", len-(cp-buf));
1470 ++cp;
1472 return buf;
1475 /** Write a single bw_array_t into the Values, Ends, Interval, and Maximum
1476 * entries of an or_state_t. Done before writing out a new state file. */
1477 static void
1478 rep_hist_update_bwhist_state_section(or_state_t *state,
1479 const bw_array_t *b,
1480 smartlist_t **s_values,
1481 smartlist_t **s_maxima,
1482 time_t *s_begins,
1483 int *s_interval)
1485 int i,j;
1486 uint64_t maxval;
1488 if (*s_values) {
1489 SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
1490 smartlist_free(*s_values);
1492 if (*s_maxima) {
1493 SMARTLIST_FOREACH(*s_maxima, char *, val, tor_free(val));
1494 smartlist_free(*s_maxima);
1496 if (! server_mode(get_options())) {
1497 /* Clients don't need to store bandwidth history persistently;
1498 * force these values to the defaults. */
1499 /* FFFF we should pull the default out of config.c's state table,
1500 * so we don't have two defaults. */
1501 if (*s_begins != 0 || *s_interval != 900) {
1502 time_t now = time(NULL);
1503 time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
1504 or_state_mark_dirty(state, save_at);
1506 *s_begins = 0;
1507 *s_interval = 900;
1508 *s_values = smartlist_new();
1509 *s_maxima = smartlist_new();
1510 return;
1512 *s_begins = b->next_period;
1513 *s_interval = NUM_SECS_BW_SUM_INTERVAL;
1515 *s_values = smartlist_new();
1516 *s_maxima = smartlist_new();
1517 /* Set i to first position in circular array */
1518 i = (b->num_maxes_set <= b->next_max_idx) ? 0 : b->next_max_idx;
1519 for (j=0; j < b->num_maxes_set; ++j,++i) {
1520 if (i >= NUM_TOTALS)
1521 i = 0;
1522 smartlist_add_asprintf(*s_values, U64_FORMAT,
1523 U64_PRINTF_ARG(b->totals[i] & ~0x3ff));
1524 maxval = b->maxima[i] / NUM_SECS_ROLLING_MEASURE;
1525 smartlist_add_asprintf(*s_maxima, U64_FORMAT,
1526 U64_PRINTF_ARG(maxval & ~0x3ff));
1528 smartlist_add_asprintf(*s_values, U64_FORMAT,
1529 U64_PRINTF_ARG(b->total_in_period & ~0x3ff));
1530 maxval = b->max_total / NUM_SECS_ROLLING_MEASURE;
1531 smartlist_add_asprintf(*s_maxima, U64_FORMAT,
1532 U64_PRINTF_ARG(maxval & ~0x3ff));
1535 /** Update <b>state</b> with the newest bandwidth history. Done before
1536 * writing out a new state file. */
1537 void
1538 rep_hist_update_state(or_state_t *state)
1540 #define UPDATE(arrname,st) \
1541 rep_hist_update_bwhist_state_section(state,\
1542 (arrname),\
1543 &state->BWHistory ## st ## Values, \
1544 &state->BWHistory ## st ## Maxima, \
1545 &state->BWHistory ## st ## Ends, \
1546 &state->BWHistory ## st ## Interval)
1548 UPDATE(write_array, Write);
1549 UPDATE(read_array, Read);
1550 UPDATE(dir_write_array, DirWrite);
1551 UPDATE(dir_read_array, DirRead);
1553 if (server_mode(get_options())) {
1554 or_state_mark_dirty(state, time(NULL)+(2*3600));
1556 #undef UPDATE
1559 /** Load a single bw_array_t from its Values, Ends, Maxima, and Interval
1560 * entries in an or_state_t. Done while reading the state file. */
1561 static int
1562 rep_hist_load_bwhist_state_section(bw_array_t *b,
1563 const smartlist_t *s_values,
1564 const smartlist_t *s_maxima,
1565 const time_t s_begins,
1566 const int s_interval)
1568 time_t now = time(NULL);
1569 int retval = 0;
1570 time_t start;
1572 uint64_t v, mv;
1573 int i,ok,ok_m = 0;
1574 int have_maxima = s_maxima && s_values &&
1575 (smartlist_len(s_values) == smartlist_len(s_maxima));
1577 if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
1578 start = s_begins - s_interval*(smartlist_len(s_values));
1579 if (start > now)
1580 return 0;
1581 b->cur_obs_time = start;
1582 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1583 SMARTLIST_FOREACH_BEGIN(s_values, const char *, cp) {
1584 const char *maxstr = NULL;
1585 v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
1586 if (have_maxima) {
1587 maxstr = smartlist_get(s_maxima, cp_sl_idx);
1588 mv = tor_parse_uint64(maxstr, 10, 0, UINT64_MAX, &ok_m, NULL);
1589 mv *= NUM_SECS_ROLLING_MEASURE;
1590 } else {
1591 /* No maxima known; guess average rate to be conservative. */
1592 mv = (v / s_interval) * NUM_SECS_ROLLING_MEASURE;
1594 if (!ok) {
1595 retval = -1;
1596 log_notice(LD_HIST, "Could not parse value '%s' into a number.'",cp);
1598 if (maxstr && !ok_m) {
1599 retval = -1;
1600 log_notice(LD_HIST, "Could not parse maximum '%s' into a number.'",
1601 maxstr);
1604 if (start < now) {
1605 time_t cur_start = start;
1606 time_t actual_interval_len = s_interval;
1607 uint64_t cur_val = 0;
1608 /* Calculate the average per second. This is the best we can do
1609 * because our state file doesn't have per-second resolution. */
1610 if (start + s_interval > now)
1611 actual_interval_len = now - start;
1612 cur_val = v / actual_interval_len;
1613 /* This is potentially inefficient, but since we don't do it very
1614 * often it should be ok. */
1615 while (cur_start < start + actual_interval_len) {
1616 add_obs(b, cur_start, cur_val);
1617 ++cur_start;
1619 b->max_total = mv;
1620 /* This will result in some fairly choppy history if s_interval
1621 * is not the same as NUM_SECS_BW_SUM_INTERVAL. XXXX */
1622 start += actual_interval_len;
1624 } SMARTLIST_FOREACH_END(cp);
1627 /* Clean up maxima and observed */
1628 for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
1629 b->obs[i] = 0;
1631 b->total_obs = 0;
1633 return retval;
1636 /** Set bandwidth history from the state file we just loaded. */
1638 rep_hist_load_state(or_state_t *state, char **err)
1640 int all_ok = 1;
1642 /* Assert they already have been malloced */
1643 tor_assert(read_array && write_array);
1644 tor_assert(dir_read_array && dir_write_array);
1646 #define LOAD(arrname,st) \
1647 if (rep_hist_load_bwhist_state_section( \
1648 (arrname), \
1649 state->BWHistory ## st ## Values, \
1650 state->BWHistory ## st ## Maxima, \
1651 state->BWHistory ## st ## Ends, \
1652 state->BWHistory ## st ## Interval)<0) \
1653 all_ok = 0
1655 LOAD(write_array, Write);
1656 LOAD(read_array, Read);
1657 LOAD(dir_write_array, DirWrite);
1658 LOAD(dir_read_array, DirRead);
1660 #undef LOAD
1661 if (!all_ok) {
1662 *err = tor_strdup("Parsing of bandwidth history values failed");
1663 /* and create fresh arrays */
1664 bw_arrays_init();
1665 return -1;
1667 return 0;
1670 /*********************************************************************/
1672 /** A single predicted port: used to remember which ports we've made
1673 * connections to, so that we can try to keep making circuits that can handle
1674 * those ports. */
1675 typedef struct predicted_port_t {
1676 /** The port we connected to */
1677 uint16_t port;
1678 /** The time at which we last used it */
1679 time_t time;
1680 } predicted_port_t;
1682 /** A list of port numbers that have been used recently. */
1683 static smartlist_t *predicted_ports_list=NULL;
1685 /** We just got an application request for a connection with
1686 * port <b>port</b>. Remember it for the future, so we can keep
1687 * some circuits open that will exit to this port.
1689 static void
1690 add_predicted_port(time_t now, uint16_t port)
1692 predicted_port_t *pp = tor_malloc(sizeof(predicted_port_t));
1693 pp->port = port;
1694 pp->time = now;
1695 rephist_total_alloc += sizeof(*pp);
1696 smartlist_add(predicted_ports_list, pp);
1699 /** Initialize whatever memory and structs are needed for predicting
1700 * which ports will be used. Also seed it with port 80, so we'll build
1701 * circuits on start-up.
1703 static void
1704 predicted_ports_init(void)
1706 predicted_ports_list = smartlist_new();
1707 add_predicted_port(time(NULL), 80); /* add one to kickstart us */
1710 /** Free whatever memory is needed for predicting which ports will
1711 * be used.
1713 static void
1714 predicted_ports_free(void)
1716 rephist_total_alloc -=
1717 smartlist_len(predicted_ports_list)*sizeof(predicted_port_t);
1718 SMARTLIST_FOREACH(predicted_ports_list, predicted_port_t *,
1719 pp, tor_free(pp));
1720 smartlist_free(predicted_ports_list);
1723 /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
1724 * This is used for predicting what sorts of streams we'll make in the
1725 * future and making exit circuits to anticipate that.
1727 void
1728 rep_hist_note_used_port(time_t now, uint16_t port)
1730 tor_assert(predicted_ports_list);
1732 if (!port) /* record nothing */
1733 return;
1735 SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
1736 if (pp->port == port) {
1737 pp->time = now;
1738 return;
1740 } SMARTLIST_FOREACH_END(pp);
1741 /* it's not there yet; we need to add it */
1742 add_predicted_port(now, port);
1745 /** Return a newly allocated pointer to a list of uint16_t * for ports that
1746 * are likely to be asked for in the near future.
1748 smartlist_t *
1749 rep_hist_get_predicted_ports(time_t now)
1751 int predicted_circs_relevance_time;
1752 smartlist_t *out = smartlist_new();
1753 tor_assert(predicted_ports_list);
1754 predicted_circs_relevance_time = get_options()->PredictedPortsRelevanceTime;
1756 /* clean out obsolete entries */
1757 SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
1758 if (pp->time + predicted_circs_relevance_time < now) {
1759 log_debug(LD_CIRC, "Expiring predicted port %d", pp->port);
1761 rephist_total_alloc -= sizeof(predicted_port_t);
1762 tor_free(pp);
1763 SMARTLIST_DEL_CURRENT(predicted_ports_list, pp);
1764 } else {
1765 smartlist_add(out, tor_memdup(&pp->port, sizeof(uint16_t)));
1767 } SMARTLIST_FOREACH_END(pp);
1768 return out;
1772 * Take a list of uint16_t *, and remove every port in the list from the
1773 * current list of predicted ports.
1775 void
1776 rep_hist_remove_predicted_ports(const smartlist_t *rmv_ports)
1778 /* Let's do this on O(N), not O(N^2). */
1779 bitarray_t *remove_ports = bitarray_init_zero(UINT16_MAX);
1780 SMARTLIST_FOREACH(rmv_ports, const uint16_t *, p,
1781 bitarray_set(remove_ports, *p));
1782 SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
1783 if (bitarray_is_set(remove_ports, pp->port)) {
1784 tor_free(pp);
1785 SMARTLIST_DEL_CURRENT(predicted_ports_list, pp);
1787 } SMARTLIST_FOREACH_END(pp);
1788 bitarray_free(remove_ports);
1791 /** The user asked us to do a resolve. Rather than keeping track of
1792 * timings and such of resolves, we fake it for now by treating
1793 * it the same way as a connection to port 80. This way we will continue
1794 * to have circuits lying around if the user only uses Tor for resolves.
1796 void
1797 rep_hist_note_used_resolve(time_t now)
1799 rep_hist_note_used_port(now, 80);
1802 /** The last time at which we needed an internal circ. */
1803 static time_t predicted_internal_time = 0;
1804 /** The last time we needed an internal circ with good uptime. */
1805 static time_t predicted_internal_uptime_time = 0;
1806 /** The last time we needed an internal circ with good capacity. */
1807 static time_t predicted_internal_capacity_time = 0;
1809 /** Remember that we used an internal circ at time <b>now</b>. */
1810 void
1811 rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
1813 predicted_internal_time = now;
1814 if (need_uptime)
1815 predicted_internal_uptime_time = now;
1816 if (need_capacity)
1817 predicted_internal_capacity_time = now;
1820 /** Return 1 if we've used an internal circ recently; else return 0. */
1822 rep_hist_get_predicted_internal(time_t now, int *need_uptime,
1823 int *need_capacity)
1825 int predicted_circs_relevance_time;
1826 predicted_circs_relevance_time = get_options()->PredictedPortsRelevanceTime;
1828 if (!predicted_internal_time) { /* initialize it */
1829 predicted_internal_time = now;
1830 predicted_internal_uptime_time = now;
1831 predicted_internal_capacity_time = now;
1833 if (predicted_internal_time + predicted_circs_relevance_time < now)
1834 return 0; /* too long ago */
1835 if (predicted_internal_uptime_time + predicted_circs_relevance_time >= now)
1836 *need_uptime = 1;
1837 // Always predict that we need capacity.
1838 *need_capacity = 1;
1839 return 1;
1842 /** Any ports used lately? These are pre-seeded if we just started
1843 * up or if we're running a hidden service. */
1845 any_predicted_circuits(time_t now)
1847 int predicted_circs_relevance_time;
1848 predicted_circs_relevance_time = get_options()->PredictedPortsRelevanceTime;
1850 return smartlist_len(predicted_ports_list) ||
1851 predicted_internal_time + predicted_circs_relevance_time >= now;
1854 /** Return 1 if we have no need for circuits currently, else return 0. */
1856 rep_hist_circbuilding_dormant(time_t now)
1858 if (any_predicted_circuits(now))
1859 return 0;
1861 /* see if we'll still need to build testing circuits */
1862 if (server_mode(get_options()) &&
1863 (!check_whether_orport_reachable() || !circuit_enough_testing_circs()))
1864 return 0;
1865 if (!check_whether_dirport_reachable())
1866 return 0;
1868 return 1;
1871 /** Structure to track how many times we've done each public key operation. */
1872 static struct {
1873 /** How many directory objects have we signed? */
1874 unsigned long n_signed_dir_objs;
1875 /** How many routerdescs have we signed? */
1876 unsigned long n_signed_routerdescs;
1877 /** How many directory objects have we verified? */
1878 unsigned long n_verified_dir_objs;
1879 /** How many routerdescs have we verified */
1880 unsigned long n_verified_routerdescs;
1881 /** How many onionskins have we encrypted to build circuits? */
1882 unsigned long n_onionskins_encrypted;
1883 /** How many onionskins have we decrypted to do circuit build requests? */
1884 unsigned long n_onionskins_decrypted;
1885 /** How many times have we done the TLS handshake as a client? */
1886 unsigned long n_tls_client_handshakes;
1887 /** How many times have we done the TLS handshake as a server? */
1888 unsigned long n_tls_server_handshakes;
1889 /** How many PK operations have we done as a hidden service client? */
1890 unsigned long n_rend_client_ops;
1891 /** How many PK operations have we done as a hidden service midpoint? */
1892 unsigned long n_rend_mid_ops;
1893 /** How many PK operations have we done as a hidden service provider? */
1894 unsigned long n_rend_server_ops;
1895 } pk_op_counts = {0,0,0,0,0,0,0,0,0,0,0};
1897 /** Increment the count of the number of times we've done <b>operation</b>. */
1898 void
1899 note_crypto_pk_op(pk_op_t operation)
1901 switch (operation)
1903 case SIGN_DIR:
1904 pk_op_counts.n_signed_dir_objs++;
1905 break;
1906 case SIGN_RTR:
1907 pk_op_counts.n_signed_routerdescs++;
1908 break;
1909 case VERIFY_DIR:
1910 pk_op_counts.n_verified_dir_objs++;
1911 break;
1912 case VERIFY_RTR:
1913 pk_op_counts.n_verified_routerdescs++;
1914 break;
1915 case ENC_ONIONSKIN:
1916 pk_op_counts.n_onionskins_encrypted++;
1917 break;
1918 case DEC_ONIONSKIN:
1919 pk_op_counts.n_onionskins_decrypted++;
1920 break;
1921 case TLS_HANDSHAKE_C:
1922 pk_op_counts.n_tls_client_handshakes++;
1923 break;
1924 case TLS_HANDSHAKE_S:
1925 pk_op_counts.n_tls_server_handshakes++;
1926 break;
1927 case REND_CLIENT:
1928 pk_op_counts.n_rend_client_ops++;
1929 break;
1930 case REND_MID:
1931 pk_op_counts.n_rend_mid_ops++;
1932 break;
1933 case REND_SERVER:
1934 pk_op_counts.n_rend_server_ops++;
1935 break;
1936 default:
1937 log_warn(LD_BUG, "Unknown pk operation %d", operation);
1941 /** Log the number of times we've done each public/private-key operation. */
1942 void
1943 dump_pk_ops(int severity)
1945 tor_log(severity, LD_HIST,
1946 "PK operations: %lu directory objects signed, "
1947 "%lu directory objects verified, "
1948 "%lu routerdescs signed, "
1949 "%lu routerdescs verified, "
1950 "%lu onionskins encrypted, "
1951 "%lu onionskins decrypted, "
1952 "%lu client-side TLS handshakes, "
1953 "%lu server-side TLS handshakes, "
1954 "%lu rendezvous client operations, "
1955 "%lu rendezvous middle operations, "
1956 "%lu rendezvous server operations.",
1957 pk_op_counts.n_signed_dir_objs,
1958 pk_op_counts.n_verified_dir_objs,
1959 pk_op_counts.n_signed_routerdescs,
1960 pk_op_counts.n_verified_routerdescs,
1961 pk_op_counts.n_onionskins_encrypted,
1962 pk_op_counts.n_onionskins_decrypted,
1963 pk_op_counts.n_tls_client_handshakes,
1964 pk_op_counts.n_tls_server_handshakes,
1965 pk_op_counts.n_rend_client_ops,
1966 pk_op_counts.n_rend_mid_ops,
1967 pk_op_counts.n_rend_server_ops);
1970 /*** Exit port statistics ***/
1972 /* Some constants */
1973 /** To what multiple should byte numbers be rounded up? */
1974 #define EXIT_STATS_ROUND_UP_BYTES 1024
1975 /** To what multiple should stream counts be rounded up? */
1976 #define EXIT_STATS_ROUND_UP_STREAMS 4
1977 /** Number of TCP ports */
1978 #define EXIT_STATS_NUM_PORTS 65536
1979 /** Top n ports that will be included in exit stats. */
1980 #define EXIT_STATS_TOP_N_PORTS 10
1982 /* The following data structures are arrays and no fancy smartlists or maps,
1983 * so that all write operations can be done in constant time. This comes at
1984 * the price of some memory (1.25 MB) and linear complexity when writing
1985 * stats for measuring relays. */
1986 /** Number of bytes read in current period by exit port */
1987 static uint64_t *exit_bytes_read = NULL;
1988 /** Number of bytes written in current period by exit port */
1989 static uint64_t *exit_bytes_written = NULL;
1990 /** Number of streams opened in current period by exit port */
1991 static uint32_t *exit_streams = NULL;
1993 /** Start time of exit stats or 0 if we're not collecting exit stats. */
1994 static time_t start_of_exit_stats_interval;
1996 /** Initialize exit port stats. */
1997 void
1998 rep_hist_exit_stats_init(time_t now)
2000 start_of_exit_stats_interval = now;
2001 exit_bytes_read = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2002 sizeof(uint64_t));
2003 exit_bytes_written = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2004 sizeof(uint64_t));
2005 exit_streams = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2006 sizeof(uint32_t));
2009 /** Reset counters for exit port statistics. */
2010 void
2011 rep_hist_reset_exit_stats(time_t now)
2013 start_of_exit_stats_interval = now;
2014 memset(exit_bytes_read, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2015 memset(exit_bytes_written, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2016 memset(exit_streams, 0, EXIT_STATS_NUM_PORTS * sizeof(uint32_t));
2019 /** Stop collecting exit port stats in a way that we can re-start doing
2020 * so in rep_hist_exit_stats_init(). */
2021 void
2022 rep_hist_exit_stats_term(void)
2024 start_of_exit_stats_interval = 0;
2025 tor_free(exit_bytes_read);
2026 tor_free(exit_bytes_written);
2027 tor_free(exit_streams);
2030 /** Helper for qsort: compare two ints. Does not handle overflow properly,
2031 * but works fine for sorting an array of port numbers, which is what we use
2032 * it for. */
2033 static int
2034 compare_int_(const void *x, const void *y)
2036 return (*(int*)x - *(int*)y);
2039 /** Return a newly allocated string containing the exit port statistics
2040 * until <b>now</b>, or NULL if we're not collecting exit stats. Caller
2041 * must ensure start_of_exit_stats_interval is in the past. */
2042 char *
2043 rep_hist_format_exit_stats(time_t now)
2045 int i, j, top_elements = 0, cur_min_idx = 0, cur_port;
2046 uint64_t top_bytes[EXIT_STATS_TOP_N_PORTS];
2047 int top_ports[EXIT_STATS_TOP_N_PORTS];
2048 uint64_t cur_bytes = 0, other_read = 0, other_written = 0,
2049 total_read = 0, total_written = 0;
2050 uint32_t total_streams = 0, other_streams = 0;
2051 smartlist_t *written_strings, *read_strings, *streams_strings;
2052 char *written_string, *read_string, *streams_string;
2053 char t[ISO_TIME_LEN+1];
2054 char *result;
2056 if (!start_of_exit_stats_interval)
2057 return NULL; /* Not initialized. */
2059 tor_assert(now >= start_of_exit_stats_interval);
2061 /* Go through all ports to find the n ports that saw most written and
2062 * read bytes.
2064 * Invariant: at the end of the loop for iteration i,
2065 * total_read is the sum of all exit_bytes_read[0..i]
2066 * total_written is the sum of all exit_bytes_written[0..i]
2067 * total_stream is the sum of all exit_streams[0..i]
2069 * top_elements = MAX(EXIT_STATS_TOP_N_PORTS,
2070 * #{j | 0 <= j <= i && volume(i) > 0})
2072 * For all 0 <= j < top_elements,
2073 * top_bytes[j] > 0
2074 * 0 <= top_ports[j] <= 65535
2075 * top_bytes[j] = volume(top_ports[j])
2077 * There is no j in 0..i and k in 0..top_elements such that:
2078 * volume(j) > top_bytes[k] AND j is not in top_ports[0..top_elements]
2080 * There is no j!=cur_min_idx in 0..top_elements such that:
2081 * top_bytes[j] < top_bytes[cur_min_idx]
2083 * where volume(x) == exit_bytes_read[x]+exit_bytes_written[x]
2085 * Worst case: O(EXIT_STATS_NUM_PORTS * EXIT_STATS_TOP_N_PORTS)
2087 for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
2088 total_read += exit_bytes_read[i];
2089 total_written += exit_bytes_written[i];
2090 total_streams += exit_streams[i];
2091 cur_bytes = exit_bytes_read[i] + exit_bytes_written[i];
2092 if (cur_bytes == 0) {
2093 continue;
2095 if (top_elements < EXIT_STATS_TOP_N_PORTS) {
2096 top_bytes[top_elements] = cur_bytes;
2097 top_ports[top_elements++] = i;
2098 } else if (cur_bytes > top_bytes[cur_min_idx]) {
2099 top_bytes[cur_min_idx] = cur_bytes;
2100 top_ports[cur_min_idx] = i;
2101 } else {
2102 continue;
2104 cur_min_idx = 0;
2105 for (j = 1; j < top_elements; j++) {
2106 if (top_bytes[j] < top_bytes[cur_min_idx]) {
2107 cur_min_idx = j;
2112 /* Add observations of top ports to smartlists. */
2113 written_strings = smartlist_new();
2114 read_strings = smartlist_new();
2115 streams_strings = smartlist_new();
2116 other_read = total_read;
2117 other_written = total_written;
2118 other_streams = total_streams;
2119 /* Sort the ports; this puts them out of sync with top_bytes, but we
2120 * won't be using top_bytes again anyway */
2121 qsort(top_ports, top_elements, sizeof(int), compare_int_);
2122 for (j = 0; j < top_elements; j++) {
2123 cur_port = top_ports[j];
2124 if (exit_bytes_written[cur_port] > 0) {
2125 uint64_t num = round_uint64_to_next_multiple_of(
2126 exit_bytes_written[cur_port],
2127 EXIT_STATS_ROUND_UP_BYTES);
2128 num /= 1024;
2129 smartlist_add_asprintf(written_strings, "%d="U64_FORMAT,
2130 cur_port, U64_PRINTF_ARG(num));
2131 other_written -= exit_bytes_written[cur_port];
2133 if (exit_bytes_read[cur_port] > 0) {
2134 uint64_t num = round_uint64_to_next_multiple_of(
2135 exit_bytes_read[cur_port],
2136 EXIT_STATS_ROUND_UP_BYTES);
2137 num /= 1024;
2138 smartlist_add_asprintf(read_strings, "%d="U64_FORMAT,
2139 cur_port, U64_PRINTF_ARG(num));
2140 other_read -= exit_bytes_read[cur_port];
2142 if (exit_streams[cur_port] > 0) {
2143 uint32_t num = round_uint32_to_next_multiple_of(
2144 exit_streams[cur_port],
2145 EXIT_STATS_ROUND_UP_STREAMS);
2146 smartlist_add_asprintf(streams_strings, "%d=%u", cur_port, num);
2147 other_streams -= exit_streams[cur_port];
2151 /* Add observations of other ports in a single element. */
2152 other_written = round_uint64_to_next_multiple_of(other_written,
2153 EXIT_STATS_ROUND_UP_BYTES);
2154 other_written /= 1024;
2155 smartlist_add_asprintf(written_strings, "other="U64_FORMAT,
2156 U64_PRINTF_ARG(other_written));
2157 other_read = round_uint64_to_next_multiple_of(other_read,
2158 EXIT_STATS_ROUND_UP_BYTES);
2159 other_read /= 1024;
2160 smartlist_add_asprintf(read_strings, "other="U64_FORMAT,
2161 U64_PRINTF_ARG(other_read));
2162 other_streams = round_uint32_to_next_multiple_of(other_streams,
2163 EXIT_STATS_ROUND_UP_STREAMS);
2164 smartlist_add_asprintf(streams_strings, "other=%u", other_streams);
2166 /* Join all observations in single strings. */
2167 written_string = smartlist_join_strings(written_strings, ",", 0, NULL);
2168 read_string = smartlist_join_strings(read_strings, ",", 0, NULL);
2169 streams_string = smartlist_join_strings(streams_strings, ",", 0, NULL);
2170 SMARTLIST_FOREACH(written_strings, char *, cp, tor_free(cp));
2171 SMARTLIST_FOREACH(read_strings, char *, cp, tor_free(cp));
2172 SMARTLIST_FOREACH(streams_strings, char *, cp, tor_free(cp));
2173 smartlist_free(written_strings);
2174 smartlist_free(read_strings);
2175 smartlist_free(streams_strings);
2177 /* Put everything together. */
2178 format_iso_time(t, now);
2179 tor_asprintf(&result, "exit-stats-end %s (%d s)\n"
2180 "exit-kibibytes-written %s\n"
2181 "exit-kibibytes-read %s\n"
2182 "exit-streams-opened %s\n",
2183 t, (unsigned) (now - start_of_exit_stats_interval),
2184 written_string,
2185 read_string,
2186 streams_string);
2187 tor_free(written_string);
2188 tor_free(read_string);
2189 tor_free(streams_string);
2190 return result;
2193 /** If 24 hours have passed since the beginning of the current exit port
2194 * stats period, write exit stats to $DATADIR/stats/exit-stats (possibly
2195 * overwriting an existing file) and reset counters. Return when we would
2196 * next want to write exit stats or 0 if we never want to write. */
2197 time_t
2198 rep_hist_exit_stats_write(time_t now)
2200 char *str = NULL;
2202 if (!start_of_exit_stats_interval)
2203 return 0; /* Not initialized. */
2204 if (start_of_exit_stats_interval + WRITE_STATS_INTERVAL > now)
2205 goto done; /* Not ready to write. */
2207 log_info(LD_HIST, "Writing exit port statistics to disk.");
2209 /* Generate history string. */
2210 str = rep_hist_format_exit_stats(now);
2212 /* Reset counters. */
2213 rep_hist_reset_exit_stats(now);
2215 /* Try to write to disk. */
2216 if (!check_or_create_data_subdir("stats")) {
2217 write_to_data_subdir("stats", "exit-stats", str, "exit port statistics");
2220 done:
2221 tor_free(str);
2222 return start_of_exit_stats_interval + WRITE_STATS_INTERVAL;
2225 /** Note that we wrote <b>num_written</b> bytes and read <b>num_read</b>
2226 * bytes to/from an exit connection to <b>port</b>. */
2227 void
2228 rep_hist_note_exit_bytes(uint16_t port, size_t num_written,
2229 size_t num_read)
2231 if (!start_of_exit_stats_interval)
2232 return; /* Not initialized. */
2233 exit_bytes_written[port] += num_written;
2234 exit_bytes_read[port] += num_read;
2235 log_debug(LD_HIST, "Written %lu bytes and read %lu bytes to/from an "
2236 "exit connection to port %d.",
2237 (unsigned long)num_written, (unsigned long)num_read, port);
2240 /** Note that we opened an exit stream to <b>port</b>. */
2241 void
2242 rep_hist_note_exit_stream_opened(uint16_t port)
2244 if (!start_of_exit_stats_interval)
2245 return; /* Not initialized. */
2246 exit_streams[port]++;
2247 log_debug(LD_HIST, "Opened exit stream to port %d", port);
2250 /*** cell statistics ***/
2252 /** Start of the current buffer stats interval or 0 if we're not
2253 * collecting buffer statistics. */
2254 static time_t start_of_buffer_stats_interval;
2256 /** Initialize buffer stats. */
2257 void
2258 rep_hist_buffer_stats_init(time_t now)
2260 start_of_buffer_stats_interval = now;
2263 /** Statistics from a single circuit. Collected when the circuit closes, or
2264 * when we flush statistics to disk. */
2265 typedef struct circ_buffer_stats_t {
2266 /** Average number of cells in the circuit's queue */
2267 double mean_num_cells_in_queue;
2268 /** Average time a cell waits in the queue. */
2269 double mean_time_cells_in_queue;
2270 /** Total number of cells sent over this circuit */
2271 uint32_t processed_cells;
2272 } circ_buffer_stats_t;
2274 /** List of circ_buffer_stats_t. */
2275 static smartlist_t *circuits_for_buffer_stats = NULL;
2277 /** Remember cell statistics <b>mean_num_cells_in_queue</b>,
2278 * <b>mean_time_cells_in_queue</b>, and <b>processed_cells</b> of a
2279 * circuit. */
2280 void
2281 rep_hist_add_buffer_stats(double mean_num_cells_in_queue,
2282 double mean_time_cells_in_queue, uint32_t processed_cells)
2284 circ_buffer_stats_t *stat;
2285 if (!start_of_buffer_stats_interval)
2286 return; /* Not initialized. */
2287 stat = tor_malloc_zero(sizeof(circ_buffer_stats_t));
2288 stat->mean_num_cells_in_queue = mean_num_cells_in_queue;
2289 stat->mean_time_cells_in_queue = mean_time_cells_in_queue;
2290 stat->processed_cells = processed_cells;
2291 if (!circuits_for_buffer_stats)
2292 circuits_for_buffer_stats = smartlist_new();
2293 smartlist_add(circuits_for_buffer_stats, stat);
2296 /** Remember cell statistics for circuit <b>circ</b> at time
2297 * <b>end_of_interval</b> and reset cell counters in case the circuit
2298 * remains open in the next measurement interval. */
2299 void
2300 rep_hist_buffer_stats_add_circ(circuit_t *circ, time_t end_of_interval)
2302 time_t start_of_interval;
2303 int interval_length;
2304 or_circuit_t *orcirc;
2305 double mean_num_cells_in_queue, mean_time_cells_in_queue;
2306 uint32_t processed_cells;
2307 if (CIRCUIT_IS_ORIGIN(circ))
2308 return;
2309 orcirc = TO_OR_CIRCUIT(circ);
2310 if (!orcirc->processed_cells)
2311 return;
2312 start_of_interval = (circ->timestamp_created.tv_sec >
2313 start_of_buffer_stats_interval) ?
2314 (time_t)circ->timestamp_created.tv_sec :
2315 start_of_buffer_stats_interval;
2316 interval_length = (int) (end_of_interval - start_of_interval);
2317 if (interval_length <= 0)
2318 return;
2319 processed_cells = orcirc->processed_cells;
2320 /* 1000.0 for s -> ms; 2.0 because of app-ward and exit-ward queues */
2321 mean_num_cells_in_queue = (double) orcirc->total_cell_waiting_time /
2322 (double) interval_length / 1000.0 / 2.0;
2323 mean_time_cells_in_queue =
2324 (double) orcirc->total_cell_waiting_time /
2325 (double) orcirc->processed_cells;
2326 orcirc->total_cell_waiting_time = 0;
2327 orcirc->processed_cells = 0;
2328 rep_hist_add_buffer_stats(mean_num_cells_in_queue,
2329 mean_time_cells_in_queue,
2330 processed_cells);
2333 /** Sorting helper: return -1, 1, or 0 based on comparison of two
2334 * circ_buffer_stats_t */
2335 static int
2336 buffer_stats_compare_entries_(const void **_a, const void **_b)
2338 const circ_buffer_stats_t *a = *_a, *b = *_b;
2339 if (a->processed_cells < b->processed_cells)
2340 return 1;
2341 else if (a->processed_cells > b->processed_cells)
2342 return -1;
2343 else
2344 return 0;
2347 /** Stop collecting cell stats in a way that we can re-start doing so in
2348 * rep_hist_buffer_stats_init(). */
2349 void
2350 rep_hist_buffer_stats_term(void)
2352 rep_hist_reset_buffer_stats(0);
2355 /** Clear history of circuit statistics and set the measurement interval
2356 * start to <b>now</b>. */
2357 void
2358 rep_hist_reset_buffer_stats(time_t now)
2360 if (!circuits_for_buffer_stats)
2361 circuits_for_buffer_stats = smartlist_new();
2362 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
2363 stat, tor_free(stat));
2364 smartlist_clear(circuits_for_buffer_stats);
2365 start_of_buffer_stats_interval = now;
2368 /** Return a newly allocated string containing the buffer statistics until
2369 * <b>now</b>, or NULL if we're not collecting buffer stats. Caller must
2370 * ensure start_of_buffer_stats_interval is in the past. */
2371 char *
2372 rep_hist_format_buffer_stats(time_t now)
2374 #define SHARES 10
2375 uint64_t processed_cells[SHARES];
2376 uint32_t circs_in_share[SHARES];
2377 int number_of_circuits, i;
2378 double queued_cells[SHARES], time_in_queue[SHARES];
2379 smartlist_t *processed_cells_strings, *queued_cells_strings,
2380 *time_in_queue_strings;
2381 char *processed_cells_string, *queued_cells_string,
2382 *time_in_queue_string;
2383 char t[ISO_TIME_LEN+1];
2384 char *result;
2386 if (!start_of_buffer_stats_interval)
2387 return NULL; /* Not initialized. */
2389 tor_assert(now >= start_of_buffer_stats_interval);
2391 /* Calculate deciles if we saw at least one circuit. */
2392 memset(processed_cells, 0, SHARES * sizeof(uint64_t));
2393 memset(circs_in_share, 0, SHARES * sizeof(uint32_t));
2394 memset(queued_cells, 0, SHARES * sizeof(double));
2395 memset(time_in_queue, 0, SHARES * sizeof(double));
2396 if (!circuits_for_buffer_stats)
2397 circuits_for_buffer_stats = smartlist_new();
2398 number_of_circuits = smartlist_len(circuits_for_buffer_stats);
2399 if (number_of_circuits > 0) {
2400 smartlist_sort(circuits_for_buffer_stats,
2401 buffer_stats_compare_entries_);
2402 i = 0;
2403 SMARTLIST_FOREACH_BEGIN(circuits_for_buffer_stats,
2404 circ_buffer_stats_t *, stat)
2406 int share = i++ * SHARES / number_of_circuits;
2407 processed_cells[share] += stat->processed_cells;
2408 queued_cells[share] += stat->mean_num_cells_in_queue;
2409 time_in_queue[share] += stat->mean_time_cells_in_queue;
2410 circs_in_share[share]++;
2412 SMARTLIST_FOREACH_END(stat);
2415 /* Write deciles to strings. */
2416 processed_cells_strings = smartlist_new();
2417 queued_cells_strings = smartlist_new();
2418 time_in_queue_strings = smartlist_new();
2419 for (i = 0; i < SHARES; i++) {
2420 smartlist_add_asprintf(processed_cells_strings,
2421 U64_FORMAT, !circs_in_share[i] ? 0 :
2422 U64_PRINTF_ARG(processed_cells[i] /
2423 circs_in_share[i]));
2425 for (i = 0; i < SHARES; i++) {
2426 smartlist_add_asprintf(queued_cells_strings, "%.2f",
2427 circs_in_share[i] == 0 ? 0.0 :
2428 queued_cells[i] / (double) circs_in_share[i]);
2430 for (i = 0; i < SHARES; i++) {
2431 smartlist_add_asprintf(time_in_queue_strings, "%.0f",
2432 circs_in_share[i] == 0 ? 0.0 :
2433 time_in_queue[i] / (double) circs_in_share[i]);
2436 /* Join all observations in single strings. */
2437 processed_cells_string = smartlist_join_strings(processed_cells_strings,
2438 ",", 0, NULL);
2439 queued_cells_string = smartlist_join_strings(queued_cells_strings,
2440 ",", 0, NULL);
2441 time_in_queue_string = smartlist_join_strings(time_in_queue_strings,
2442 ",", 0, NULL);
2443 SMARTLIST_FOREACH(processed_cells_strings, char *, cp, tor_free(cp));
2444 SMARTLIST_FOREACH(queued_cells_strings, char *, cp, tor_free(cp));
2445 SMARTLIST_FOREACH(time_in_queue_strings, char *, cp, tor_free(cp));
2446 smartlist_free(processed_cells_strings);
2447 smartlist_free(queued_cells_strings);
2448 smartlist_free(time_in_queue_strings);
2450 /* Put everything together. */
2451 format_iso_time(t, now);
2452 tor_asprintf(&result, "cell-stats-end %s (%d s)\n"
2453 "cell-processed-cells %s\n"
2454 "cell-queued-cells %s\n"
2455 "cell-time-in-queue %s\n"
2456 "cell-circuits-per-decile %d\n",
2457 t, (unsigned) (now - start_of_buffer_stats_interval),
2458 processed_cells_string,
2459 queued_cells_string,
2460 time_in_queue_string,
2461 (number_of_circuits + SHARES - 1) / SHARES);
2462 tor_free(processed_cells_string);
2463 tor_free(queued_cells_string);
2464 tor_free(time_in_queue_string);
2465 return result;
2466 #undef SHARES
2469 /** If 24 hours have passed since the beginning of the current buffer
2470 * stats period, write buffer stats to $DATADIR/stats/buffer-stats
2471 * (possibly overwriting an existing file) and reset counters. Return
2472 * when we would next want to write buffer stats or 0 if we never want to
2473 * write. */
2474 time_t
2475 rep_hist_buffer_stats_write(time_t now)
2477 circuit_t *circ;
2478 char *str = NULL;
2480 if (!start_of_buffer_stats_interval)
2481 return 0; /* Not initialized. */
2482 if (start_of_buffer_stats_interval + WRITE_STATS_INTERVAL > now)
2483 goto done; /* Not ready to write */
2485 /* Add open circuits to the history. */
2486 TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
2487 rep_hist_buffer_stats_add_circ(circ, now);
2490 /* Generate history string. */
2491 str = rep_hist_format_buffer_stats(now);
2493 /* Reset both buffer history and counters of open circuits. */
2494 rep_hist_reset_buffer_stats(now);
2496 /* Try to write to disk. */
2497 if (!check_or_create_data_subdir("stats")) {
2498 write_to_data_subdir("stats", "buffer-stats", str, "buffer statistics");
2501 done:
2502 tor_free(str);
2503 return start_of_buffer_stats_interval + WRITE_STATS_INTERVAL;
2506 /*** Descriptor serving statistics ***/
2508 /** Digestmap to track which descriptors were downloaded this stats
2509 * collection interval. It maps descriptor digest to pointers to 1,
2510 * effectively turning this into a list. */
2511 static digestmap_t *served_descs = NULL;
2513 /** Number of how many descriptors were downloaded in total during this
2514 * interval. */
2515 static unsigned long total_descriptor_downloads;
2517 /** Start time of served descs stats or 0 if we're not collecting those. */
2518 static time_t start_of_served_descs_stats_interval;
2520 /** Initialize descriptor stats. */
2521 void
2522 rep_hist_desc_stats_init(time_t now)
2524 if (served_descs) {
2525 log_warn(LD_BUG, "Called rep_hist_desc_stats_init() when desc stats were "
2526 "already initialized. This is probably harmless.");
2527 return; // Already initialized
2529 served_descs = digestmap_new();
2530 total_descriptor_downloads = 0;
2531 start_of_served_descs_stats_interval = now;
2534 /** Reset served descs stats to empty, starting a new interval <b>now</b>. */
2535 static void
2536 rep_hist_reset_desc_stats(time_t now)
2538 rep_hist_desc_stats_term();
2539 rep_hist_desc_stats_init(now);
2542 /** Stop collecting served descs stats, so that rep_hist_desc_stats_init() is
2543 * safe to be called again. */
2544 void
2545 rep_hist_desc_stats_term(void)
2547 digestmap_free(served_descs, NULL);
2548 served_descs = NULL;
2549 start_of_served_descs_stats_interval = 0;
2550 total_descriptor_downloads = 0;
2553 /** Helper for rep_hist_desc_stats_write(). Return a newly allocated string
2554 * containing the served desc statistics until now, or NULL if we're not
2555 * collecting served desc stats. Caller must ensure that now is not before
2556 * start_of_served_descs_stats_interval. */
2557 static char *
2558 rep_hist_format_desc_stats(time_t now)
2560 char t[ISO_TIME_LEN+1];
2561 char *result;
2563 digestmap_iter_t *iter;
2564 const char *key;
2565 void *val;
2566 unsigned size;
2567 int *vals, max = 0, q3 = 0, md = 0, q1 = 0, min = 0;
2568 int n = 0;
2570 if (!start_of_served_descs_stats_interval)
2571 return NULL;
2573 size = digestmap_size(served_descs);
2574 if (size > 0) {
2575 vals = tor_malloc(size * sizeof(int));
2576 for (iter = digestmap_iter_init(served_descs);
2577 !digestmap_iter_done(iter);
2578 iter = digestmap_iter_next(served_descs, iter)) {
2579 uintptr_t count;
2580 digestmap_iter_get(iter, &key, &val);
2581 count = (uintptr_t)val;
2582 vals[n++] = (int)count;
2583 (void)key;
2585 max = find_nth_int(vals, size, size-1);
2586 q3 = find_nth_int(vals, size, (3*size-1)/4);
2587 md = find_nth_int(vals, size, (size-1)/2);
2588 q1 = find_nth_int(vals, size, (size-1)/4);
2589 min = find_nth_int(vals, size, 0);
2590 tor_free(vals);
2593 format_iso_time(t, now);
2595 tor_asprintf(&result,
2596 "served-descs-stats-end %s (%d s) total=%lu unique=%u "
2597 "max=%d q3=%d md=%d q1=%d min=%d\n",
2599 (unsigned) (now - start_of_served_descs_stats_interval),
2600 total_descriptor_downloads,
2601 size, max, q3, md, q1, min);
2603 return result;
2606 /** If WRITE_STATS_INTERVAL seconds have passed since the beginning of
2607 * the current served desc stats interval, write the stats to
2608 * $DATADIR/stats/served-desc-stats (possibly appending to an existing file)
2609 * and reset the state for the next interval. Return when we would next want
2610 * to write served desc stats or 0 if we won't want to write. */
2611 time_t
2612 rep_hist_desc_stats_write(time_t now)
2614 char *filename = NULL, *str = NULL;
2616 if (!start_of_served_descs_stats_interval)
2617 return 0; /* We're not collecting stats. */
2618 if (start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL > now)
2619 return start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL;
2621 str = rep_hist_format_desc_stats(now);
2622 tor_assert(str != NULL);
2624 if (check_or_create_data_subdir("stats") < 0) {
2625 goto done;
2627 filename = get_datadir_fname2("stats", "served-desc-stats");
2628 if (append_bytes_to_file(filename, str, strlen(str), 0) < 0)
2629 log_warn(LD_HIST, "Unable to write served descs statistics to disk!");
2631 rep_hist_reset_desc_stats(now);
2633 done:
2634 tor_free(filename);
2635 tor_free(str);
2636 return start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL;
2639 /* DOCDOC rep_hist_note_desc_served */
2640 void
2641 rep_hist_note_desc_served(const char * desc)
2643 void *val;
2644 uintptr_t count;
2645 if (!served_descs)
2646 return; // We're not collecting stats
2647 val = digestmap_get(served_descs, desc);
2648 count = (uintptr_t)val;
2649 if (count != INT_MAX)
2650 ++count;
2651 digestmap_set(served_descs, desc, (void*)count);
2652 total_descriptor_downloads++;
2655 /*** Connection statistics ***/
2657 /** Start of the current connection stats interval or 0 if we're not
2658 * collecting connection statistics. */
2659 static time_t start_of_conn_stats_interval;
2661 /** Initialize connection stats. */
2662 void
2663 rep_hist_conn_stats_init(time_t now)
2665 start_of_conn_stats_interval = now;
2668 /* Count connections that we read and wrote less than these many bytes
2669 * from/to as below threshold. */
2670 #define BIDI_THRESHOLD 20480
2672 /* Count connections that we read or wrote at least this factor as many
2673 * bytes from/to than we wrote or read to/from as mostly reading or
2674 * writing. */
2675 #define BIDI_FACTOR 10
2677 /* Interval length in seconds for considering read and written bytes for
2678 * connection stats. */
2679 #define BIDI_INTERVAL 10
2681 /** Start of next BIDI_INTERVAL second interval. */
2682 static time_t bidi_next_interval = 0;
2684 /** Number of connections that we read and wrote less than BIDI_THRESHOLD
2685 * bytes from/to in BIDI_INTERVAL seconds. */
2686 static uint32_t below_threshold = 0;
2688 /** Number of connections that we read at least BIDI_FACTOR times more
2689 * bytes from than we wrote to in BIDI_INTERVAL seconds. */
2690 static uint32_t mostly_read = 0;
2692 /** Number of connections that we wrote at least BIDI_FACTOR times more
2693 * bytes to than we read from in BIDI_INTERVAL seconds. */
2694 static uint32_t mostly_written = 0;
2696 /** Number of connections that we read and wrote at least BIDI_THRESHOLD
2697 * bytes from/to, but not BIDI_FACTOR times more in either direction in
2698 * BIDI_INTERVAL seconds. */
2699 static uint32_t both_read_and_written = 0;
2701 /** Entry in a map from connection ID to the number of read and written
2702 * bytes on this connection in a BIDI_INTERVAL second interval. */
2703 typedef struct bidi_map_entry_t {
2704 HT_ENTRY(bidi_map_entry_t) node;
2705 uint64_t conn_id; /**< Connection ID */
2706 size_t read; /**< Number of read bytes */
2707 size_t written; /**< Number of written bytes */
2708 } bidi_map_entry_t;
2710 /** Map of OR connections together with the number of read and written
2711 * bytes in the current BIDI_INTERVAL second interval. */
2712 static HT_HEAD(bidimap, bidi_map_entry_t) bidi_map =
2713 HT_INITIALIZER();
2715 static int
2716 bidi_map_ent_eq(const bidi_map_entry_t *a, const bidi_map_entry_t *b)
2718 return a->conn_id == b->conn_id;
2721 /* DOCDOC bidi_map_ent_hash */
2722 static unsigned
2723 bidi_map_ent_hash(const bidi_map_entry_t *entry)
2725 return (unsigned) entry->conn_id;
2728 HT_PROTOTYPE(bidimap, bidi_map_entry_t, node, bidi_map_ent_hash,
2729 bidi_map_ent_eq);
2730 HT_GENERATE(bidimap, bidi_map_entry_t, node, bidi_map_ent_hash,
2731 bidi_map_ent_eq, 0.6, malloc, realloc, free);
2733 /* DOCDOC bidi_map_free */
2734 static void
2735 bidi_map_free(void)
2737 bidi_map_entry_t **ptr, **next, *ent;
2738 for (ptr = HT_START(bidimap, &bidi_map); ptr; ptr = next) {
2739 ent = *ptr;
2740 next = HT_NEXT_RMV(bidimap, &bidi_map, ptr);
2741 tor_free(ent);
2743 HT_CLEAR(bidimap, &bidi_map);
2746 /** Reset counters for conn statistics. */
2747 void
2748 rep_hist_reset_conn_stats(time_t now)
2750 start_of_conn_stats_interval = now;
2751 below_threshold = 0;
2752 mostly_read = 0;
2753 mostly_written = 0;
2754 both_read_and_written = 0;
2755 bidi_map_free();
2758 /** Stop collecting connection stats in a way that we can re-start doing
2759 * so in rep_hist_conn_stats_init(). */
2760 void
2761 rep_hist_conn_stats_term(void)
2763 rep_hist_reset_conn_stats(0);
2766 /** We read <b>num_read</b> bytes and wrote <b>num_written</b> from/to OR
2767 * connection <b>conn_id</b> in second <b>when</b>. If this is the first
2768 * observation in a new interval, sum up the last observations. Add bytes
2769 * for this connection. */
2770 void
2771 rep_hist_note_or_conn_bytes(uint64_t conn_id, size_t num_read,
2772 size_t num_written, time_t when)
2774 if (!start_of_conn_stats_interval)
2775 return;
2776 /* Initialize */
2777 if (bidi_next_interval == 0)
2778 bidi_next_interval = when + BIDI_INTERVAL;
2779 /* Sum up last period's statistics */
2780 if (when >= bidi_next_interval) {
2781 bidi_map_entry_t **ptr, **next, *ent;
2782 for (ptr = HT_START(bidimap, &bidi_map); ptr; ptr = next) {
2783 ent = *ptr;
2784 if (ent->read + ent->written < BIDI_THRESHOLD)
2785 below_threshold++;
2786 else if (ent->read >= ent->written * BIDI_FACTOR)
2787 mostly_read++;
2788 else if (ent->written >= ent->read * BIDI_FACTOR)
2789 mostly_written++;
2790 else
2791 both_read_and_written++;
2792 next = HT_NEXT_RMV(bidimap, &bidi_map, ptr);
2793 tor_free(ent);
2795 while (when >= bidi_next_interval)
2796 bidi_next_interval += BIDI_INTERVAL;
2797 log_info(LD_GENERAL, "%d below threshold, %d mostly read, "
2798 "%d mostly written, %d both read and written.",
2799 below_threshold, mostly_read, mostly_written,
2800 both_read_and_written);
2802 /* Add this connection's bytes. */
2803 if (num_read > 0 || num_written > 0) {
2804 bidi_map_entry_t *entry, lookup;
2805 lookup.conn_id = conn_id;
2806 entry = HT_FIND(bidimap, &bidi_map, &lookup);
2807 if (entry) {
2808 entry->written += num_written;
2809 entry->read += num_read;
2810 } else {
2811 entry = tor_malloc_zero(sizeof(bidi_map_entry_t));
2812 entry->conn_id = conn_id;
2813 entry->written = num_written;
2814 entry->read = num_read;
2815 HT_INSERT(bidimap, &bidi_map, entry);
2820 /** Return a newly allocated string containing the connection statistics
2821 * until <b>now</b>, or NULL if we're not collecting conn stats. Caller must
2822 * ensure start_of_conn_stats_interval is in the past. */
2823 char *
2824 rep_hist_format_conn_stats(time_t now)
2826 char *result, written[ISO_TIME_LEN+1];
2828 if (!start_of_conn_stats_interval)
2829 return NULL; /* Not initialized. */
2831 tor_assert(now >= start_of_conn_stats_interval);
2833 format_iso_time(written, now);
2834 tor_asprintf(&result, "conn-bi-direct %s (%d s) %d,%d,%d,%d\n",
2835 written,
2836 (unsigned) (now - start_of_conn_stats_interval),
2837 below_threshold,
2838 mostly_read,
2839 mostly_written,
2840 both_read_and_written);
2841 return result;
2844 /** If 24 hours have passed since the beginning of the current conn stats
2845 * period, write conn stats to $DATADIR/stats/conn-stats (possibly
2846 * overwriting an existing file) and reset counters. Return when we would
2847 * next want to write conn stats or 0 if we never want to write. */
2848 time_t
2849 rep_hist_conn_stats_write(time_t now)
2851 char *str = NULL;
2853 if (!start_of_conn_stats_interval)
2854 return 0; /* Not initialized. */
2855 if (start_of_conn_stats_interval + WRITE_STATS_INTERVAL > now)
2856 goto done; /* Not ready to write */
2858 /* Generate history string. */
2859 str = rep_hist_format_conn_stats(now);
2861 /* Reset counters. */
2862 rep_hist_reset_conn_stats(now);
2864 /* Try to write to disk. */
2865 if (!check_or_create_data_subdir("stats")) {
2866 write_to_data_subdir("stats", "conn-stats", str, "connection statistics");
2869 done:
2870 tor_free(str);
2871 return start_of_conn_stats_interval + WRITE_STATS_INTERVAL;
2874 /** Internal statistics to track how many requests of each type of
2875 * handshake we've received, and how many we've assigned to cpuworkers.
2876 * Useful for seeing trends in cpu load.
2877 * @{ */
2878 STATIC int onion_handshakes_requested[MAX_ONION_HANDSHAKE_TYPE+1] = {0};
2879 STATIC int onion_handshakes_assigned[MAX_ONION_HANDSHAKE_TYPE+1] = {0};
2880 /**@}*/
2882 /** A new onionskin (using the <b>type</b> handshake) has arrived. */
2883 void
2884 rep_hist_note_circuit_handshake_requested(uint16_t type)
2886 if (type <= MAX_ONION_HANDSHAKE_TYPE)
2887 onion_handshakes_requested[type]++;
2890 /** We've sent an onionskin (using the <b>type</b> handshake) to a
2891 * cpuworker. */
2892 void
2893 rep_hist_note_circuit_handshake_assigned(uint16_t type)
2895 if (type <= MAX_ONION_HANDSHAKE_TYPE)
2896 onion_handshakes_assigned[type]++;
2899 /** Log our onionskin statistics since the last time we were called. */
2900 void
2901 rep_hist_log_circuit_handshake_stats(time_t now)
2903 (void)now;
2904 log_notice(LD_HEARTBEAT, "Circuit handshake stats since last time: "
2905 "%d/%d TAP, %d/%d NTor.",
2906 onion_handshakes_assigned[ONION_HANDSHAKE_TYPE_TAP],
2907 onion_handshakes_requested[ONION_HANDSHAKE_TYPE_TAP],
2908 onion_handshakes_assigned[ONION_HANDSHAKE_TYPE_NTOR],
2909 onion_handshakes_requested[ONION_HANDSHAKE_TYPE_NTOR]);
2910 memset(onion_handshakes_assigned, 0, sizeof(onion_handshakes_assigned));
2911 memset(onion_handshakes_requested, 0, sizeof(onion_handshakes_requested));
2914 /** Free all storage held by the OR/link history caches, by the
2915 * bandwidth history arrays, by the port history, or by statistics . */
2916 void
2917 rep_hist_free_all(void)
2919 digestmap_free(history_map, free_or_history);
2920 tor_free(read_array);
2921 tor_free(write_array);
2922 tor_free(dir_read_array);
2923 tor_free(dir_write_array);
2924 tor_free(exit_bytes_read);
2925 tor_free(exit_bytes_written);
2926 tor_free(exit_streams);
2927 predicted_ports_free();
2928 bidi_map_free();
2930 if (circuits_for_buffer_stats) {
2931 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *, s,
2932 tor_free(s));
2933 smartlist_free(circuits_for_buffer_stats);
2934 circuits_for_buffer_stats = NULL;
2936 rep_hist_desc_stats_term();
2937 total_descriptor_downloads = 0;