Merge remote branch 'sebastian/bug1035' into maint-0.2.2
[tor/rransom.git] / src / or / rephist.c
blob53214d61efa0c683fbb5cb11dbbec1fcf604c8d9
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, 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 and cell statistics.
11 **/
13 #include "or.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
16 #include "config.h"
17 #include "networkstatus.h"
18 #include "rephist.h"
19 #include "router.h"
20 #include "routerlist.h"
21 #include "ht.h"
23 static void bw_arrays_init(void);
24 static void predicted_ports_init(void);
26 /** Total number of bytes currently allocated in fields used by rephist.c. */
27 uint64_t rephist_total_alloc=0;
28 /** Number of or_history_t objects currently allocated. */
29 uint32_t rephist_total_num=0;
31 /** If the total weighted run count of all runs for a router ever falls
32 * below this amount, the router can be treated as having 0 MTBF. */
33 #define STABILITY_EPSILON 0.0001
34 /** Value by which to discount all old intervals for MTBF purposes. This
35 * is compounded every STABILITY_INTERVAL. */
36 #define STABILITY_ALPHA 0.95
37 /** Interval at which to discount all old intervals for MTBF purposes. */
38 #define STABILITY_INTERVAL (12*60*60)
39 /* (This combination of ALPHA, INTERVAL, and EPSILON makes it so that an
40 * interval that just ended counts twice as much as one that ended a week ago,
41 * 20X as much as one that ended a month ago, and routers that have had no
42 * uptime data for about half a year will get forgotten.) */
44 /** History of an OR-\>OR link. */
45 typedef struct link_history_t {
46 /** When did we start tracking this list? */
47 time_t since;
48 /** When did we most recently note a change to this link */
49 time_t changed;
50 /** How many times did extending from OR1 to OR2 succeed? */
51 unsigned long n_extend_ok;
52 /** How many times did extending from OR1 to OR2 fail? */
53 unsigned long n_extend_fail;
54 } link_history_t;
56 /** History of an OR. */
57 typedef struct or_history_t {
58 /** When did we start tracking this OR? */
59 time_t since;
60 /** When did we most recently note a change to this OR? */
61 time_t changed;
62 /** How many times did we successfully connect? */
63 unsigned long n_conn_ok;
64 /** How many times did we try to connect and fail?*/
65 unsigned long n_conn_fail;
66 /** How many seconds have we been connected to this OR before
67 * 'up_since'? */
68 unsigned long uptime;
69 /** How many seconds have we been unable to connect to this OR before
70 * 'down_since'? */
71 unsigned long downtime;
72 /** If nonzero, we have been connected since this time. */
73 time_t up_since;
74 /** If nonzero, we have been unable to connect since this time. */
75 time_t down_since;
77 /** The address at which we most recently connected to this OR
78 * successfully. */
79 tor_addr_t last_reached_addr;
81 /** The port at which we most recently connected to this OR successfully */
82 uint16_t last_reached_port;
84 /* === For MTBF tracking: */
85 /** Weighted sum total of all times that this router has been online.
87 unsigned long weighted_run_length;
88 /** If the router is now online (according to stability-checking rules),
89 * when did it come online? */
90 time_t start_of_run;
91 /** Sum of weights for runs in weighted_run_length. */
92 double total_run_weights;
93 /* === For fractional uptime tracking: */
94 time_t start_of_downtime;
95 unsigned long weighted_uptime;
96 unsigned long total_weighted_time;
98 /** Map from hex OR2 identity digest to a link_history_t for the link
99 * from this OR to OR2. */
100 digestmap_t *link_history_map;
101 } or_history_t;
103 /** When did we last multiply all routers' weighted_run_length and
104 * total_run_weights by STABILITY_ALPHA? */
105 static time_t stability_last_downrated = 0;
107 /** */
108 static time_t started_tracking_stability = 0;
110 /** Map from hex OR identity digest to or_history_t. */
111 static digestmap_t *history_map = NULL;
113 /** Return the or_history_t for the OR with identity digest <b>id</b>,
114 * creating it if necessary. */
115 static or_history_t *
116 get_or_history(const char* id)
118 or_history_t *hist;
120 if (tor_mem_is_zero(id, DIGEST_LEN))
121 return NULL;
123 hist = digestmap_get(history_map, id);
124 if (!hist) {
125 hist = tor_malloc_zero(sizeof(or_history_t));
126 rephist_total_alloc += sizeof(or_history_t);
127 rephist_total_num++;
128 hist->link_history_map = digestmap_new();
129 hist->since = hist->changed = time(NULL);
130 tor_addr_make_unspec(&hist->last_reached_addr);
131 digestmap_set(history_map, id, hist);
133 return hist;
136 /** Return the link_history_t for the link from the first named OR to
137 * the second, creating it if necessary. (ORs are identified by
138 * identity digest.)
140 static link_history_t *
141 get_link_history(const char *from_id, const char *to_id)
143 or_history_t *orhist;
144 link_history_t *lhist;
145 orhist = get_or_history(from_id);
146 if (!orhist)
147 return NULL;
148 if (tor_mem_is_zero(to_id, DIGEST_LEN))
149 return NULL;
150 lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
151 if (!lhist) {
152 lhist = tor_malloc_zero(sizeof(link_history_t));
153 rephist_total_alloc += sizeof(link_history_t);
154 lhist->since = lhist->changed = time(NULL);
155 digestmap_set(orhist->link_history_map, to_id, lhist);
157 return lhist;
160 /** Helper: free storage held by a single link history entry. */
161 static void
162 _free_link_history(void *val)
164 rephist_total_alloc -= sizeof(link_history_t);
165 tor_free(val);
168 /** Helper: free storage held by a single OR history entry. */
169 static void
170 free_or_history(void *_hist)
172 or_history_t *hist = _hist;
173 digestmap_free(hist->link_history_map, _free_link_history);
174 rephist_total_alloc -= sizeof(or_history_t);
175 rephist_total_num--;
176 tor_free(hist);
179 /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
180 * count is up-to-date as of <b>when</b>.
182 static void
183 update_or_history(or_history_t *hist, time_t when)
185 tor_assert(hist);
186 if (hist->up_since) {
187 tor_assert(!hist->down_since);
188 hist->uptime += (when - hist->up_since);
189 hist->up_since = when;
190 } else if (hist->down_since) {
191 hist->downtime += (when - hist->down_since);
192 hist->down_since = when;
196 /** Initialize the static data structures for tracking history. */
197 void
198 rep_hist_init(void)
200 history_map = digestmap_new();
201 bw_arrays_init();
202 predicted_ports_init();
205 /** Helper: note that we are no longer connected to the router with history
206 * <b>hist</b>. If <b>failed</b>, the connection failed; otherwise, it was
207 * closed correctly. */
208 static void
209 mark_or_down(or_history_t *hist, time_t when, int failed)
211 if (hist->up_since) {
212 hist->uptime += (when - hist->up_since);
213 hist->up_since = 0;
215 if (failed && !hist->down_since) {
216 hist->down_since = when;
220 /** Helper: note that we are connected to the router with history
221 * <b>hist</b>. */
222 static void
223 mark_or_up(or_history_t *hist, time_t when)
225 if (hist->down_since) {
226 hist->downtime += (when - hist->down_since);
227 hist->down_since = 0;
229 if (!hist->up_since) {
230 hist->up_since = when;
234 /** Remember that an attempt to connect to the OR with identity digest
235 * <b>id</b> failed at <b>when</b>.
237 void
238 rep_hist_note_connect_failed(const char* id, time_t when)
240 or_history_t *hist;
241 hist = get_or_history(id);
242 if (!hist)
243 return;
244 ++hist->n_conn_fail;
245 mark_or_down(hist, when, 1);
246 hist->changed = when;
249 /** Remember that an attempt to connect to the OR with identity digest
250 * <b>id</b> succeeded at <b>when</b>.
252 void
253 rep_hist_note_connect_succeeded(const char* id, time_t when)
255 or_history_t *hist;
256 hist = get_or_history(id);
257 if (!hist)
258 return;
259 ++hist->n_conn_ok;
260 mark_or_up(hist, when);
261 hist->changed = when;
264 /** Remember that we intentionally closed our connection to the OR
265 * with identity digest <b>id</b> at <b>when</b>.
267 void
268 rep_hist_note_disconnect(const char* id, time_t when)
270 or_history_t *hist;
271 hist = get_or_history(id);
272 if (!hist)
273 return;
274 mark_or_down(hist, when, 0);
275 hist->changed = when;
278 /** Remember that our connection to the OR with identity digest
279 * <b>id</b> had an error and stopped working at <b>when</b>.
281 void
282 rep_hist_note_connection_died(const char* id, time_t when)
284 or_history_t *hist;
285 if (!id) {
286 /* If conn has no identity, it didn't complete its handshake, or something
287 * went wrong. Ignore it.
289 return;
291 hist = get_or_history(id);
292 if (!hist)
293 return;
294 mark_or_down(hist, when, 1);
295 hist->changed = when;
298 /** We have just decided that this router with identity digest <b>id</b> is
299 * reachable, meaning we will give it a "Running" flag for the next while. */
300 void
301 rep_hist_note_router_reachable(const char *id, const tor_addr_t *at_addr,
302 const uint16_t at_port, time_t when)
304 or_history_t *hist = get_or_history(id);
305 int was_in_run = 1;
306 char tbuf[ISO_TIME_LEN+1];
307 int addr_changed, port_changed;
309 tor_assert(hist);
310 tor_assert((!at_addr && !at_port) || (at_addr && at_port));
312 addr_changed = at_addr &&
313 tor_addr_compare(at_addr, &hist->last_reached_addr, CMP_EXACT) != 0;
314 port_changed = at_port && at_port != hist->last_reached_port;
316 if (!started_tracking_stability)
317 started_tracking_stability = time(NULL);
318 if (!hist->start_of_run) {
319 hist->start_of_run = when;
320 was_in_run = 0;
322 if (hist->start_of_downtime) {
323 long down_length;
325 format_local_iso_time(tbuf, hist->start_of_downtime);
326 log_info(LD_HIST, "Router %s is now Running; it had been down since %s.",
327 hex_str(id, DIGEST_LEN), tbuf);
328 if (was_in_run)
329 log_info(LD_HIST, " (Paradoxically, it was already Running too.)");
331 down_length = when - hist->start_of_downtime;
332 hist->total_weighted_time += down_length;
333 hist->start_of_downtime = 0;
334 } else if (addr_changed || port_changed) {
335 /* If we're reachable, but the address changed, treat this as some
336 * downtime. */
337 int penalty = get_options()->TestingTorNetwork ? 240 : 3600;
338 networkstatus_t *ns;
340 if ((ns = networkstatus_get_latest_consensus())) {
341 int fresh_interval = (int)(ns->fresh_until - ns->valid_after);
342 int live_interval = (int)(ns->valid_until - ns->valid_after);
343 /* on average, a descriptor addr change takes .5 intervals to make it
344 * into a consensus, and half a liveness period to make it to
345 * clients. */
346 penalty = (int)(fresh_interval + live_interval) / 2;
348 format_local_iso_time(tbuf, hist->start_of_run);
349 log_info(LD_HIST,"Router %s still seems Running, but its address appears "
350 "to have changed since the last time it was reachable. I'm "
351 "going to treat it as having been down for %d seconds",
352 hex_str(id, DIGEST_LEN), penalty);
353 rep_hist_note_router_unreachable(id, when-penalty);
354 rep_hist_note_router_reachable(id, NULL, 0, when);
355 } else {
356 format_local_iso_time(tbuf, hist->start_of_run);
357 if (was_in_run)
358 log_debug(LD_HIST, "Router %s is still Running; it has been Running "
359 "since %s", hex_str(id, DIGEST_LEN), tbuf);
360 else
361 log_info(LD_HIST,"Router %s is now Running; it was previously untracked",
362 hex_str(id, DIGEST_LEN));
364 if (at_addr)
365 tor_addr_copy(&hist->last_reached_addr, at_addr);
366 if (at_port)
367 hist->last_reached_port = at_port;
370 /** We have just decided that this router is unreachable, meaning
371 * we are taking away its "Running" flag. */
372 void
373 rep_hist_note_router_unreachable(const char *id, time_t when)
375 or_history_t *hist = get_or_history(id);
376 char tbuf[ISO_TIME_LEN+1];
377 int was_running = 0;
378 if (!started_tracking_stability)
379 started_tracking_stability = time(NULL);
381 tor_assert(hist);
382 if (hist->start_of_run) {
383 /*XXXX We could treat failed connections differently from failed
384 * connect attempts. */
385 long run_length = when - hist->start_of_run;
386 format_local_iso_time(tbuf, hist->start_of_run);
388 hist->total_run_weights += 1.0;
389 hist->start_of_run = 0;
390 if (run_length < 0) {
391 unsigned long penalty = -run_length;
392 #define SUBTRACT_CLAMPED(var, penalty) \
393 do { (var) = (var) < (penalty) ? 0 : (var) - (penalty); } while (0)
395 SUBTRACT_CLAMPED(hist->weighted_run_length, penalty);
396 SUBTRACT_CLAMPED(hist->weighted_uptime, penalty);
397 } else {
398 hist->weighted_run_length += run_length;
399 hist->weighted_uptime += run_length;
400 hist->total_weighted_time += run_length;
402 was_running = 1;
403 log_info(LD_HIST, "Router %s is now non-Running: it had previously been "
404 "Running since %s. Its total weighted uptime is %lu/%lu.",
405 hex_str(id, DIGEST_LEN), tbuf, hist->weighted_uptime,
406 hist->total_weighted_time);
408 if (!hist->start_of_downtime) {
409 hist->start_of_downtime = when;
411 if (!was_running)
412 log_info(LD_HIST, "Router %s is now non-Running; it was previously "
413 "untracked.", hex_str(id, DIGEST_LEN));
414 } else {
415 if (!was_running) {
416 format_local_iso_time(tbuf, hist->start_of_downtime);
418 log_info(LD_HIST, "Router %s is still non-Running; it has been "
419 "non-Running since %s.", hex_str(id, DIGEST_LEN), tbuf);
424 /** Helper: Discount all old MTBF data, if it is time to do so. Return
425 * the time at which we should next discount MTBF data. */
426 time_t
427 rep_hist_downrate_old_runs(time_t now)
429 digestmap_iter_t *orhist_it;
430 const char *digest1;
431 or_history_t *hist;
432 void *hist_p;
433 double alpha = 1.0;
435 if (!history_map)
436 history_map = digestmap_new();
437 if (!stability_last_downrated)
438 stability_last_downrated = now;
439 if (stability_last_downrated + STABILITY_INTERVAL > now)
440 return stability_last_downrated + STABILITY_INTERVAL;
442 /* Okay, we should downrate the data. By how much? */
443 while (stability_last_downrated + STABILITY_INTERVAL < now) {
444 stability_last_downrated += STABILITY_INTERVAL;
445 alpha *= STABILITY_ALPHA;
448 log_info(LD_HIST, "Discounting all old stability info by a factor of %lf",
449 alpha);
451 /* Multiply every w_r_l, t_r_w pair by alpha. */
452 for (orhist_it = digestmap_iter_init(history_map);
453 !digestmap_iter_done(orhist_it);
454 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
455 digestmap_iter_get(orhist_it, &digest1, &hist_p);
456 hist = hist_p;
458 hist->weighted_run_length =
459 (unsigned long)(hist->weighted_run_length * alpha);
460 hist->total_run_weights *= alpha;
462 hist->weighted_uptime = (unsigned long)(hist->weighted_uptime * alpha);
463 hist->total_weighted_time = (unsigned long)
464 (hist->total_weighted_time * alpha);
467 return stability_last_downrated + STABILITY_INTERVAL;
470 /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
471 static double
472 get_stability(or_history_t *hist, time_t when)
474 long total = hist->weighted_run_length;
475 double total_weights = hist->total_run_weights;
477 if (hist->start_of_run) {
478 /* We're currently in a run. Let total and total_weights hold the values
479 * they would hold if the current run were to end now. */
480 total += (when-hist->start_of_run);
481 total_weights += 1.0;
483 if (total_weights < STABILITY_EPSILON) {
484 /* Round down to zero, and avoid divide-by-zero. */
485 return 0.0;
488 return total / total_weights;
491 /** Return the total amount of time we've been observing, with each run of
492 * time downrated by the appropriate factor. */
493 static long
494 get_total_weighted_time(or_history_t *hist, time_t when)
496 long total = hist->total_weighted_time;
497 if (hist->start_of_run) {
498 total += (when - hist->start_of_run);
499 } else if (hist->start_of_downtime) {
500 total += (when - hist->start_of_downtime);
502 return total;
505 /** Helper: Return the weighted percent-of-time-online of the router with
506 * history <b>hist</b>. */
507 static double
508 get_weighted_fractional_uptime(or_history_t *hist, time_t when)
510 long total = hist->total_weighted_time;
511 long up = hist->weighted_uptime;
513 if (hist->start_of_run) {
514 long run_length = (when - hist->start_of_run);
515 up += run_length;
516 total += run_length;
517 } else if (hist->start_of_downtime) {
518 total += (when - hist->start_of_downtime);
521 if (!total) {
522 /* Avoid calling anybody's uptime infinity (which should be impossible if
523 * the code is working), or NaN (which can happen for any router we haven't
524 * observed up or down yet). */
525 return 0.0;
528 return ((double) up) / total;
531 /** Return an estimated MTBF for the router whose identity digest is
532 * <b>id</b>. Return 0 if the router is unknown. */
533 double
534 rep_hist_get_stability(const char *id, time_t when)
536 or_history_t *hist = get_or_history(id);
537 if (!hist)
538 return 0.0;
540 return get_stability(hist, when);
543 /** Return an estimated percent-of-time-online for the router whose identity
544 * digest is <b>id</b>. Return 0 if the router is unknown. */
545 double
546 rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
548 or_history_t *hist = get_or_history(id);
549 if (!hist)
550 return 0.0;
552 return get_weighted_fractional_uptime(hist, when);
555 /** Return a number representing how long we've known about the router whose
556 * digest is <b>id</b>. Return 0 if the router is unknown.
558 * Be careful: this measure increases monotonically as we know the router for
559 * longer and longer, but it doesn't increase linearly.
561 long
562 rep_hist_get_weighted_time_known(const char *id, time_t when)
564 or_history_t *hist = get_or_history(id);
565 if (!hist)
566 return 0;
568 return get_total_weighted_time(hist, when);
571 /** Return true if we've been measuring MTBFs for long enough to
572 * pronounce on Stability. */
574 rep_hist_have_measured_enough_stability(void)
576 /* XXXX021 This doesn't do so well when we change our opinion
577 * as to whether we're tracking router stability. */
578 return started_tracking_stability < time(NULL) - 4*60*60;
581 /** Remember that we successfully extended from the OR with identity
582 * digest <b>from_id</b> to the OR with identity digest
583 * <b>to_name</b>.
585 void
586 rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
588 link_history_t *hist;
589 /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
590 hist = get_link_history(from_id, to_id);
591 if (!hist)
592 return;
593 ++hist->n_extend_ok;
594 hist->changed = time(NULL);
597 /** Remember that we tried to extend from the OR with identity digest
598 * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
599 * failed.
601 void
602 rep_hist_note_extend_failed(const char *from_id, const char *to_id)
604 link_history_t *hist;
605 /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
606 hist = get_link_history(from_id, to_id);
607 if (!hist)
608 return;
609 ++hist->n_extend_fail;
610 hist->changed = time(NULL);
613 /** Log all the reliability data we have remembered, with the chosen
614 * severity.
616 void
617 rep_hist_dump_stats(time_t now, int severity)
619 digestmap_iter_t *lhist_it;
620 digestmap_iter_t *orhist_it;
621 const char *name1, *name2, *digest1, *digest2;
622 char hexdigest1[HEX_DIGEST_LEN+1];
623 or_history_t *or_history;
624 link_history_t *link_history;
625 void *or_history_p, *link_history_p;
626 double uptime;
627 char buffer[2048];
628 size_t len;
629 int ret;
630 unsigned long upt, downt;
631 routerinfo_t *r;
633 rep_history_clean(now - get_options()->RephistTrackTime);
635 log(severity, LD_HIST, "--------------- Dumping history information:");
637 for (orhist_it = digestmap_iter_init(history_map);
638 !digestmap_iter_done(orhist_it);
639 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
640 double s;
641 long stability;
642 digestmap_iter_get(orhist_it, &digest1, &or_history_p);
643 or_history = (or_history_t*) or_history_p;
645 if ((r = router_get_by_digest(digest1)))
646 name1 = r->nickname;
647 else
648 name1 = "(unknown)";
649 base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
650 update_or_history(or_history, now);
651 upt = or_history->uptime;
652 downt = or_history->downtime;
653 s = get_stability(or_history, now);
654 stability = (long)s;
655 if (upt+downt) {
656 uptime = ((double)upt) / (upt+downt);
657 } else {
658 uptime=1.0;
660 log(severity, LD_HIST,
661 "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
662 "wmtbf %lu:%02lu:%02lu",
663 name1, hexdigest1,
664 or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
665 upt, upt+downt, uptime*100.0,
666 stability/3600, (stability/60)%60, stability%60);
668 if (!digestmap_isempty(or_history->link_history_map)) {
669 strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
670 len = strlen(buffer);
671 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
672 !digestmap_iter_done(lhist_it);
673 lhist_it = digestmap_iter_next(or_history->link_history_map,
674 lhist_it)) {
675 digestmap_iter_get(lhist_it, &digest2, &link_history_p);
676 if ((r = router_get_by_digest(digest2)))
677 name2 = r->nickname;
678 else
679 name2 = "(unknown)";
681 link_history = (link_history_t*) link_history_p;
683 ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
684 link_history->n_extend_ok,
685 link_history->n_extend_ok+link_history->n_extend_fail);
686 if (ret<0)
687 break;
688 else
689 len += ret;
691 log(severity, LD_HIST, "%s", buffer);
696 /** Remove history info for routers/links that haven't changed since
697 * <b>before</b>.
699 void
700 rep_history_clean(time_t before)
702 int authority = authdir_mode(get_options());
703 or_history_t *or_history;
704 link_history_t *link_history;
705 void *or_history_p, *link_history_p;
706 digestmap_iter_t *orhist_it, *lhist_it;
707 const char *d1, *d2;
709 orhist_it = digestmap_iter_init(history_map);
710 while (!digestmap_iter_done(orhist_it)) {
711 int remove;
712 digestmap_iter_get(orhist_it, &d1, &or_history_p);
713 or_history = or_history_p;
715 remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
716 !or_history->start_of_run)
717 : (or_history->changed < before);
718 if (remove) {
719 orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
720 free_or_history(or_history);
721 continue;
723 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
724 !digestmap_iter_done(lhist_it); ) {
725 digestmap_iter_get(lhist_it, &d2, &link_history_p);
726 link_history = link_history_p;
727 if (link_history->changed < before) {
728 lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
729 lhist_it);
730 rephist_total_alloc -= sizeof(link_history_t);
731 tor_free(link_history);
732 continue;
734 lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
736 orhist_it = digestmap_iter_next(history_map, orhist_it);
740 /** Write MTBF data to disk. Return 0 on success, negative on failure.
742 * If <b>missing_means_down</b>, then if we're about to write an entry
743 * that is still considered up but isn't in our routerlist, consider it
744 * to be down. */
746 rep_hist_record_mtbf_data(time_t now, int missing_means_down)
748 char time_buf[ISO_TIME_LEN+1];
750 digestmap_iter_t *orhist_it;
751 const char *digest;
752 void *or_history_p;
753 or_history_t *hist;
754 open_file_t *open_file = NULL;
755 FILE *f;
758 char *filename = get_datadir_fname("router-stability");
759 f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
760 &open_file);
761 tor_free(filename);
762 if (!f)
763 return -1;
766 /* File format is:
767 * FormatLine *KeywordLine Data
769 * FormatLine = "format 1" NL
770 * KeywordLine = Keyword SP Arguments NL
771 * Data = "data" NL *RouterMTBFLine "." NL
772 * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
773 * TotalRunWeights [SP S=StartRunTime] NL
775 #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
776 #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
778 PUT("format 2\n");
780 format_iso_time(time_buf, time(NULL));
781 PRINTF((f, "stored-at %s\n", time_buf));
783 if (started_tracking_stability) {
784 format_iso_time(time_buf, started_tracking_stability);
785 PRINTF((f, "tracked-since %s\n", time_buf));
787 if (stability_last_downrated) {
788 format_iso_time(time_buf, stability_last_downrated);
789 PRINTF((f, "last-downrated %s\n", time_buf));
792 PUT("data\n");
794 /* XXX Nick: now bridge auths record this for all routers too.
795 * Should we make them record it only for bridge routers? -RD
796 * Not for 0.2.0. -NM */
797 for (orhist_it = digestmap_iter_init(history_map);
798 !digestmap_iter_done(orhist_it);
799 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
800 char dbuf[HEX_DIGEST_LEN+1];
801 const char *t = NULL;
802 digestmap_iter_get(orhist_it, &digest, &or_history_p);
803 hist = (or_history_t*) or_history_p;
805 base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
807 if (missing_means_down && hist->start_of_run &&
808 !router_get_by_digest(digest)) {
809 /* We think this relay is running, but it's not listed in our
810 * routerlist. Somehow it fell out without telling us it went
811 * down. Complain and also correct it. */
812 log_info(LD_HIST,
813 "Relay '%s' is listed as up in rephist, but it's not in "
814 "our routerlist. Correcting.", dbuf);
815 rep_hist_note_router_unreachable(digest, now);
818 PRINTF((f, "R %s\n", dbuf));
819 if (hist->start_of_run > 0) {
820 format_iso_time(time_buf, hist->start_of_run);
821 t = time_buf;
823 PRINTF((f, "+MTBF %lu %.5lf%s%s\n",
824 hist->weighted_run_length, hist->total_run_weights,
825 t ? " S=" : "", t ? t : ""));
826 t = NULL;
827 if (hist->start_of_downtime > 0) {
828 format_iso_time(time_buf, hist->start_of_downtime);
829 t = time_buf;
831 PRINTF((f, "+WFU %lu %lu%s%s\n",
832 hist->weighted_uptime, hist->total_weighted_time,
833 t ? " S=" : "", t ? t : ""));
836 PUT(".\n");
838 #undef PUT
839 #undef PRINTF
841 return finish_writing_to_file(open_file);
842 err:
843 abort_writing_to_file(open_file);
844 return -1;
847 /** Format the current tracked status of the router in <b>hist</b> at time
848 * <b>now</b> for analysis; return it in a newly allocated string. */
849 static char *
850 rep_hist_format_router_status(or_history_t *hist, time_t now)
852 char sor_buf[ISO_TIME_LEN+1];
853 char sod_buf[ISO_TIME_LEN+1];
854 double wfu;
855 double mtbf;
856 int up = 0, down = 0;
857 char *cp = NULL;
859 if (hist->start_of_run) {
860 format_iso_time(sor_buf, hist->start_of_run);
861 up = 1;
863 if (hist->start_of_downtime) {
864 format_iso_time(sod_buf, hist->start_of_downtime);
865 down = 1;
868 wfu = get_weighted_fractional_uptime(hist, now);
869 mtbf = get_stability(hist, now);
870 tor_asprintf(&cp,
871 "%s%s%s"
872 "%s%s%s"
873 "wfu %0.3lf\n"
874 " weighted-time %lu\n"
875 " weighted-uptime %lu\n"
876 "mtbf %0.1lf\n"
877 " weighted-run-length %lu\n"
878 " total-run-weights %lf\n",
879 up?"uptime-started ":"", up?sor_buf:"", up?" UTC\n":"",
880 down?"downtime-started ":"", down?sod_buf:"", down?" UTC\n":"",
881 wfu,
882 hist->total_weighted_time,
883 hist->weighted_uptime,
884 mtbf,
885 hist->weighted_run_length,
886 hist->total_run_weights
888 return cp;
891 /** The last stability analysis document that we created, or NULL if we never
892 * have created one. */
893 static char *last_stability_doc = NULL;
894 /** The last time we created a stability analysis document, or 0 if we never
895 * have created one. */
896 static time_t built_last_stability_doc_at = 0;
897 /** Shortest allowable time between building two stability documents. */
898 #define MAX_STABILITY_DOC_BUILD_RATE (3*60)
900 /** Return a pointer to a NUL-terminated document describing our view of the
901 * stability of the routers we've been tracking. Return NULL on failure. */
902 const char *
903 rep_hist_get_router_stability_doc(time_t now)
905 char *result;
906 smartlist_t *chunks;
907 if (built_last_stability_doc_at + MAX_STABILITY_DOC_BUILD_RATE > now)
908 return last_stability_doc;
910 if (!history_map)
911 return NULL;
913 tor_free(last_stability_doc);
914 chunks = smartlist_create();
916 if (rep_hist_have_measured_enough_stability()) {
917 smartlist_add(chunks, tor_strdup("we-have-enough-measurements\n"));
918 } else {
919 smartlist_add(chunks, tor_strdup("we-do-not-have-enough-measurements\n"));
922 DIGESTMAP_FOREACH(history_map, id, or_history_t *, hist) {
923 routerinfo_t *ri;
924 char dbuf[BASE64_DIGEST_LEN+1];
925 char header_buf[512];
926 char *info;
927 digest_to_base64(dbuf, id);
928 ri = router_get_by_digest(id);
929 if (ri) {
930 char *ip = tor_dup_ip(ri->addr);
931 char tbuf[ISO_TIME_LEN+1];
932 format_iso_time(tbuf, ri->cache_info.published_on);
933 tor_snprintf(header_buf, sizeof(header_buf),
934 "router %s %s %s\n"
935 "published %s\n"
936 "relevant-flags %s%s%s\n"
937 "declared-uptime %ld\n",
938 dbuf, ri->nickname, ip,
939 tbuf,
940 ri->is_running ? "Running " : "",
941 ri->is_valid ? "Valid " : "",
942 ri->is_hibernating ? "Hibernating " : "",
943 ri->uptime);
944 tor_free(ip);
945 } else {
946 tor_snprintf(header_buf, sizeof(header_buf),
947 "router %s {no descriptor}\n", dbuf);
949 smartlist_add(chunks, tor_strdup(header_buf));
950 info = rep_hist_format_router_status(hist, now);
951 if (info)
952 smartlist_add(chunks, info);
954 } DIGESTMAP_FOREACH_END;
956 result = smartlist_join_strings(chunks, "", 0, NULL);
957 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
958 smartlist_free(chunks);
960 last_stability_doc = result;
961 built_last_stability_doc_at = time(NULL);
962 return result;
965 /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
966 * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
967 * such line exists. */
968 static int
969 find_next_with(smartlist_t *sl, int i, const char *prefix)
971 for ( ; i < smartlist_len(sl); ++i) {
972 const char *line = smartlist_get(sl, i);
973 if (!strcmpstart(line, prefix))
974 return i;
975 if (!strcmpstart(line, "R "))
976 return -1;
978 return -1;
981 /** How many bad times has parse_possibly_bad_iso_time parsed? */
982 static int n_bogus_times = 0;
983 /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
984 * rounds any pre-1970 date to Jan 1, 1970. */
985 static int
986 parse_possibly_bad_iso_time(const char *s, time_t *time_out)
988 int year;
989 char b[5];
990 strlcpy(b, s, sizeof(b));
991 b[4] = '\0';
992 year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
993 if (year < 1970) {
994 *time_out = 0;
995 ++n_bogus_times;
996 return 0;
997 } else
998 return parse_iso_time(s, time_out);
1001 /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
1002 * says we started measuring at <b>started_measuring</b>. Return a new number
1003 * that's about as much before <b>now</b> as <b>t</b> was before
1004 * <b>stored_at</b>.
1006 static INLINE time_t
1007 correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
1009 if (t < started_measuring - 24*60*60*365)
1010 return 0;
1011 else if (t < started_measuring)
1012 return started_measuring;
1013 else if (t > stored_at)
1014 return 0;
1015 else {
1016 long run_length = stored_at - t;
1017 t = now - run_length;
1018 if (t < started_measuring)
1019 t = started_measuring;
1020 return t;
1024 /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
1025 * on failure. */
1027 rep_hist_load_mtbf_data(time_t now)
1029 /* XXXX won't handle being called while history is already populated. */
1030 smartlist_t *lines;
1031 const char *line = NULL;
1032 int r=0, i;
1033 time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
1034 time_t latest_possible_start = now;
1035 long format = -1;
1038 char *filename = get_datadir_fname("router-stability");
1039 char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1040 tor_free(filename);
1041 if (!d)
1042 return -1;
1043 lines = smartlist_create();
1044 smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
1045 tor_free(d);
1049 const char *firstline;
1050 if (smartlist_len(lines)>4) {
1051 firstline = smartlist_get(lines, 0);
1052 if (!strcmpstart(firstline, "format "))
1053 format = tor_parse_long(firstline+strlen("format "),
1054 10, -1, LONG_MAX, NULL, NULL);
1057 if (format != 1 && format != 2) {
1058 log_warn(LD_HIST,
1059 "Unrecognized format in mtbf history file. Skipping.");
1060 goto err;
1062 for (i = 1; i < smartlist_len(lines); ++i) {
1063 line = smartlist_get(lines, i);
1064 if (!strcmp(line, "data"))
1065 break;
1066 if (!strcmpstart(line, "last-downrated ")) {
1067 if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
1068 log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
1069 "history file.");
1071 if (!strcmpstart(line, "stored-at ")) {
1072 if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
1073 log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
1074 "history file.");
1076 if (!strcmpstart(line, "tracked-since ")) {
1077 if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
1078 log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
1079 "history file.");
1082 if (last_downrated > now)
1083 last_downrated = now;
1084 if (tracked_since > now)
1085 tracked_since = now;
1087 if (!stored_at) {
1088 log_warn(LD_HIST, "No stored time recorded.");
1089 goto err;
1092 if (line && !strcmp(line, "data"))
1093 ++i;
1095 n_bogus_times = 0;
1097 for (; i < smartlist_len(lines); ++i) {
1098 char digest[DIGEST_LEN];
1099 char hexbuf[HEX_DIGEST_LEN+1];
1100 char mtbf_timebuf[ISO_TIME_LEN+1];
1101 char wfu_timebuf[ISO_TIME_LEN+1];
1102 time_t start_of_run = 0;
1103 time_t start_of_downtime = 0;
1104 int have_mtbf = 0, have_wfu = 0;
1105 long wrl = 0;
1106 double trw = 0;
1107 long wt_uptime = 0, total_wt_time = 0;
1108 int n;
1109 or_history_t *hist;
1110 line = smartlist_get(lines, i);
1111 if (!strcmp(line, "."))
1112 break;
1114 mtbf_timebuf[0] = '\0';
1115 wfu_timebuf[0] = '\0';
1117 if (format == 1) {
1118 n = sscanf(line, "%40s %ld %lf S=%10s %8s",
1119 hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1120 if (n != 3 && n != 5) {
1121 log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
1122 continue;
1124 have_mtbf = 1;
1125 } else {
1126 // format == 2.
1127 int mtbf_idx, wfu_idx;
1128 if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
1129 continue;
1130 strlcpy(hexbuf, line+2, sizeof(hexbuf));
1131 mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
1132 wfu_idx = find_next_with(lines, i+1, "+WFU ");
1133 if (mtbf_idx >= 0) {
1134 const char *mtbfline = smartlist_get(lines, mtbf_idx);
1135 n = sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
1136 &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1137 if (n == 2 || n == 4) {
1138 have_mtbf = 1;
1139 } else {
1140 log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
1141 escaped(mtbfline));
1144 if (wfu_idx >= 0) {
1145 const char *wfuline = smartlist_get(lines, wfu_idx);
1146 n = sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
1147 &wt_uptime, &total_wt_time,
1148 wfu_timebuf, wfu_timebuf+11);
1149 if (n == 2 || n == 4) {
1150 have_wfu = 1;
1151 } else {
1152 log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
1155 if (wfu_idx > i)
1156 i = wfu_idx;
1157 if (mtbf_idx > i)
1158 i = mtbf_idx;
1160 if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
1161 log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
1162 continue;
1164 hist = get_or_history(digest);
1165 if (!hist)
1166 continue;
1168 if (have_mtbf) {
1169 if (mtbf_timebuf[0]) {
1170 mtbf_timebuf[10] = ' ';
1171 if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
1172 log_warn(LD_HIST, "Couldn't parse time %s",
1173 escaped(mtbf_timebuf));
1175 hist->start_of_run = correct_time(start_of_run, now, stored_at,
1176 tracked_since);
1177 if (hist->start_of_run < latest_possible_start + wrl)
1178 latest_possible_start = hist->start_of_run - wrl;
1180 hist->weighted_run_length = wrl;
1181 hist->total_run_weights = trw;
1183 if (have_wfu) {
1184 if (wfu_timebuf[0]) {
1185 wfu_timebuf[10] = ' ';
1186 if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
1187 log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
1190 hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
1191 tracked_since);
1192 hist->weighted_uptime = wt_uptime;
1193 hist->total_weighted_time = total_wt_time;
1195 if (strcmp(line, "."))
1196 log_warn(LD_HIST, "Truncated MTBF file.");
1198 if (tracked_since < 86400*365) /* Recover from insanely early value. */
1199 tracked_since = latest_possible_start;
1201 stability_last_downrated = last_downrated;
1202 started_tracking_stability = tracked_since;
1204 goto done;
1205 err:
1206 r = -1;
1207 done:
1208 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1209 smartlist_free(lines);
1210 return r;
1213 /** For how many seconds do we keep track of individual per-second bandwidth
1214 * totals? */
1215 #define NUM_SECS_ROLLING_MEASURE 10
1216 /** How large are the intervals for which we track and report bandwidth use? */
1217 /* XXXX Watch out! Before Tor 0.2.2.21-alpha, using any other value here would
1218 * generate an unparseable state file. */
1219 #define NUM_SECS_BW_SUM_INTERVAL (15*60)
1220 /** How far in the past do we remember and publish bandwidth use? */
1221 #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
1222 /** How many bandwidth usage intervals do we remember? (derived) */
1223 #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
1225 /** Structure to track bandwidth use, and remember the maxima for a given
1226 * time period.
1228 typedef struct bw_array_t {
1229 /** Observation array: Total number of bytes transferred in each of the last
1230 * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
1231 uint64_t obs[NUM_SECS_ROLLING_MEASURE];
1232 int cur_obs_idx; /**< Current position in obs. */
1233 time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
1234 uint64_t total_obs; /**< Total for all members of obs except
1235 * obs[cur_obs_idx] */
1236 uint64_t max_total; /**< Largest value that total_obs has taken on in the
1237 * current period. */
1238 uint64_t total_in_period; /**< Total bytes transferred in the current
1239 * period. */
1241 /** When does the next period begin? */
1242 time_t next_period;
1243 /** Where in 'maxima' should the maximum bandwidth usage for the current
1244 * period be stored? */
1245 int next_max_idx;
1246 /** How many values in maxima/totals have been set ever? */
1247 int num_maxes_set;
1248 /** Circular array of the maximum
1249 * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
1250 * NUM_TOTALS periods */
1251 uint64_t maxima[NUM_TOTALS];
1252 /** Circular array of the total bandwidth usage for the last NUM_TOTALS
1253 * periods */
1254 uint64_t totals[NUM_TOTALS];
1255 } bw_array_t;
1257 /** Shift the current period of b forward by one. */
1258 static void
1259 commit_max(bw_array_t *b)
1261 /* Store total from current period. */
1262 b->totals[b->next_max_idx] = b->total_in_period;
1263 /* Store maximum from current period. */
1264 b->maxima[b->next_max_idx++] = b->max_total;
1265 /* Advance next_period and next_max_idx */
1266 b->next_period += NUM_SECS_BW_SUM_INTERVAL;
1267 if (b->next_max_idx == NUM_TOTALS)
1268 b->next_max_idx = 0;
1269 if (b->num_maxes_set < NUM_TOTALS)
1270 ++b->num_maxes_set;
1271 /* Reset max_total. */
1272 b->max_total = 0;
1273 /* Reset total_in_period. */
1274 b->total_in_period = 0;
1277 /** Shift the current observation time of 'b' forward by one second. */
1278 static INLINE void
1279 advance_obs(bw_array_t *b)
1281 int nextidx;
1282 uint64_t total;
1284 /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
1285 * seconds; adjust max_total as needed.*/
1286 total = b->total_obs + b->obs[b->cur_obs_idx];
1287 if (total > b->max_total)
1288 b->max_total = total;
1290 nextidx = b->cur_obs_idx+1;
1291 if (nextidx == NUM_SECS_ROLLING_MEASURE)
1292 nextidx = 0;
1294 b->total_obs = total - b->obs[nextidx];
1295 b->obs[nextidx]=0;
1296 b->cur_obs_idx = nextidx;
1298 if (++b->cur_obs_time >= b->next_period)
1299 commit_max(b);
1302 /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
1303 * <b>when</b>. */
1304 static INLINE void
1305 add_obs(bw_array_t *b, time_t when, uint64_t n)
1307 /* Don't record data in the past. */
1308 if (when<b->cur_obs_time)
1309 return;
1310 /* If we're currently adding observations for an earlier second than
1311 * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
1312 * appropriate number of seconds, and do all the other housekeeping */
1313 while (when>b->cur_obs_time) {
1314 /* Doing this one second at a time is potentially inefficient, if we start
1315 with a state file that is very old. Fortunately, it doesn't seem to
1316 show up in profiles, so we can just ignore it for now. */
1317 advance_obs(b);
1320 b->obs[b->cur_obs_idx] += n;
1321 b->total_in_period += n;
1324 /** Allocate, initialize, and return a new bw_array. */
1325 static bw_array_t *
1326 bw_array_new(void)
1328 bw_array_t *b;
1329 time_t start;
1330 b = tor_malloc_zero(sizeof(bw_array_t));
1331 rephist_total_alloc += sizeof(bw_array_t);
1332 start = time(NULL);
1333 b->cur_obs_time = start;
1334 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1335 return b;
1338 /** Recent history of bandwidth observations for read operations. */
1339 static bw_array_t *read_array = NULL;
1340 /** Recent history of bandwidth observations for write operations. */
1341 static bw_array_t *write_array = NULL;
1342 /** Recent history of bandwidth observations for read operations for the
1343 directory protocol. */
1344 static bw_array_t *dir_read_array = NULL;
1345 /** Recent history of bandwidth observations for write operations for the
1346 directory protocol. */
1347 static bw_array_t *dir_write_array = NULL;
1349 /** Set up [dir-]read_array and [dir-]write_array, freeing them if they
1350 * already exist. */
1351 static void
1352 bw_arrays_init(void)
1354 tor_free(read_array);
1355 tor_free(write_array);
1356 tor_free(dir_read_array);
1357 tor_free(dir_write_array);
1358 read_array = bw_array_new();
1359 write_array = bw_array_new();
1360 dir_read_array = bw_array_new();
1361 dir_write_array = bw_array_new();
1364 /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
1366 * Add num_bytes to the current running total for <b>when</b>.
1368 * <b>when</b> can go back to time, but it's safe to ignore calls
1369 * earlier than the latest <b>when</b> you've heard of.
1371 void
1372 rep_hist_note_bytes_written(size_t num_bytes, time_t when)
1374 /* Maybe a circular array for recent seconds, and step to a new point
1375 * every time a new second shows up. Or simpler is to just to have
1376 * a normal array and push down each item every second; it's short.
1378 /* When a new second has rolled over, compute the sum of the bytes we've
1379 * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
1380 * somewhere. See rep_hist_bandwidth_assess() below.
1382 add_obs(write_array, when, num_bytes);
1385 /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
1386 * (like rep_hist_note_bytes_written() above)
1388 void
1389 rep_hist_note_bytes_read(size_t num_bytes, time_t when)
1391 /* if we're smart, we can make this func and the one above share code */
1392 add_obs(read_array, when, num_bytes);
1395 /** We wrote <b>num_bytes</b> more directory bytes in second <b>when</b>.
1396 * (like rep_hist_note_bytes_written() above)
1398 void
1399 rep_hist_note_dir_bytes_written(size_t num_bytes, time_t when)
1401 add_obs(dir_write_array, when, num_bytes);
1404 /** We read <b>num_bytes</b> more directory bytes in second <b>when</b>.
1405 * (like rep_hist_note_bytes_written() above)
1407 void
1408 rep_hist_note_dir_bytes_read(size_t num_bytes, time_t when)
1410 add_obs(dir_read_array, when, num_bytes);
1413 /** Helper: Return the largest value in b->maxima. (This is equal to the
1414 * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
1415 * NUM_SECS_BW_SUM_IS_VALID seconds.)
1417 static uint64_t
1418 find_largest_max(bw_array_t *b)
1420 int i;
1421 uint64_t max;
1422 max=0;
1423 for (i=0; i<NUM_TOTALS; ++i) {
1424 if (b->maxima[i]>max)
1425 max = b->maxima[i];
1427 return max;
1430 /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
1431 * seconds. Find one sum for reading and one for writing. They don't have
1432 * to be at the same time.
1434 * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
1437 rep_hist_bandwidth_assess(void)
1439 uint64_t w,r;
1440 r = find_largest_max(read_array);
1441 w = find_largest_max(write_array);
1442 if (r>w)
1443 return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
1444 else
1445 return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
1448 /** Print the bandwidth history of b (either [dir-]read_array or
1449 * [dir-]write_array) into the buffer pointed to by buf. The format is
1450 * simply comma separated numbers, from oldest to newest.
1452 * It returns the number of bytes written.
1454 static size_t
1455 rep_hist_fill_bandwidth_history(char *buf, size_t len, const bw_array_t *b)
1457 char *cp = buf;
1458 int i, n;
1459 or_options_t *options = get_options();
1460 uint64_t cutoff;
1462 if (b->num_maxes_set <= b->next_max_idx) {
1463 /* We haven't been through the circular array yet; time starts at i=0.*/
1464 i = 0;
1465 } else {
1466 /* We've been around the array at least once. The next i to be
1467 overwritten is the oldest. */
1468 i = b->next_max_idx;
1471 if (options->RelayBandwidthRate) {
1472 /* We don't want to report that we used more bandwidth than the max we're
1473 * willing to relay; otherwise everybody will know how much traffic
1474 * we used ourself. */
1475 cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
1476 } else {
1477 cutoff = UINT64_MAX;
1480 for (n=0; n<b->num_maxes_set; ++n,++i) {
1481 uint64_t total;
1482 if (i >= NUM_TOTALS)
1483 i -= NUM_TOTALS;
1484 tor_assert(i < NUM_TOTALS);
1485 /* Round the bandwidth used down to the nearest 1k. */
1486 total = b->totals[i] & ~0x3ff;
1487 if (total > cutoff)
1488 total = cutoff;
1490 if (n==(b->num_maxes_set-1))
1491 tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
1492 else
1493 tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
1494 cp += strlen(cp);
1496 return cp-buf;
1499 /** Allocate and return lines for representing this server's bandwidth
1500 * history in its descriptor.
1502 char *
1503 rep_hist_get_bandwidth_lines(void)
1505 char *buf, *cp;
1506 char t[ISO_TIME_LEN+1];
1507 int r;
1508 bw_array_t *b = NULL;
1509 const char *desc = NULL;
1510 size_t len;
1512 /* opt [dirreq-](read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n... */
1513 len = (67+21*NUM_TOTALS)*4;
1514 buf = tor_malloc_zero(len);
1515 cp = buf;
1516 for (r=0;r<4;++r) {
1517 switch (r) {
1518 case 0:
1519 b = write_array;
1520 desc = "write-history";
1521 break;
1522 case 1:
1523 b = read_array;
1524 desc = "read-history";
1525 break;
1526 case 2:
1527 b = dir_write_array;
1528 desc = "dirreq-write-history";
1529 break;
1530 case 3:
1531 b = dir_read_array;
1532 desc = "dirreq-read-history";
1533 break;
1535 tor_assert(b);
1536 format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
1537 tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ",
1538 desc, t, NUM_SECS_BW_SUM_INTERVAL);
1539 cp += strlen(cp);
1540 cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
1541 strlcat(cp, "\n", len-(cp-buf));
1542 ++cp;
1544 return buf;
1547 /** Write a single bw_array_t into the Values, Ends, Interval, and Maximum
1548 * entries of an or_state_t. */
1549 static void
1550 rep_hist_update_bwhist_state_section(or_state_t *state,
1551 const bw_array_t *b,
1552 smartlist_t **s_values,
1553 smartlist_t **s_maxima,
1554 time_t *s_begins,
1555 int *s_interval)
1557 char *cp;
1558 int i,j;
1560 if (*s_values) {
1561 SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
1562 smartlist_free(*s_values);
1564 if (*s_maxima) {
1565 SMARTLIST_FOREACH(*s_maxima, char *, val, tor_free(val));
1566 smartlist_free(*s_maxima);
1568 if (! server_mode(get_options())) {
1569 /* Clients don't need to store bandwidth history persistently;
1570 * force these values to the defaults. */
1571 /* FFFF we should pull the default out of config.c's state table,
1572 * so we don't have two defaults. */
1573 if (*s_begins != 0 || *s_interval != 900) {
1574 time_t now = time(NULL);
1575 time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
1576 or_state_mark_dirty(state, save_at);
1578 *s_begins = 0;
1579 *s_interval = 900;
1580 *s_values = smartlist_create();
1581 *s_maxima = smartlist_create();
1582 return;
1584 *s_begins = b->next_period;
1585 *s_interval = NUM_SECS_BW_SUM_INTERVAL;
1587 *s_values = smartlist_create();
1588 *s_maxima = smartlist_create();
1589 /* Set i to first position in circular array */
1590 i = (b->num_maxes_set <= b->next_max_idx) ? 0 : b->next_max_idx;
1591 for (j=0; j < b->num_maxes_set; ++j,++i) {
1592 uint64_t maxval;
1593 if (i >= NUM_TOTALS)
1594 i = 0;
1595 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(b->totals[i] & ~0x3ff));
1596 smartlist_add(*s_values, cp);
1597 maxval = b->maxima[i] / NUM_SECS_ROLLING_MEASURE;
1598 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(maxval & ~0x3ff));
1599 smartlist_add(*s_maxima, cp);
1601 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(b->total_in_period & ~0x3ff));
1602 smartlist_add(*s_values, cp);
1603 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(b->max_total & ~0x3ff));
1604 smartlist_add(*s_maxima, cp);
1607 /** Update <b>state</b> with the newest bandwidth history. */
1608 void
1609 rep_hist_update_state(or_state_t *state)
1611 #define UPDATE(arrname,st) \
1612 rep_hist_update_bwhist_state_section(state,\
1613 (arrname),\
1614 &state->BWHistory ## st ## Values, \
1615 &state->BWHistory ## st ## Maxima, \
1616 &state->BWHistory ## st ## Ends, \
1617 &state->BWHistory ## st ## Interval)
1619 UPDATE(write_array, Write);
1620 UPDATE(read_array, Read);
1621 UPDATE(dir_write_array, DirWrite);
1622 UPDATE(dir_read_array, DirRead);
1624 if (server_mode(get_options())) {
1625 or_state_mark_dirty(state, time(NULL)+(2*3600));
1627 #undef UPDATE
1630 /** Load a single bw_array_t from its Values, Ends, Maxima, and Interval
1631 * entries in an or_state_t. */
1632 static int
1633 rep_hist_load_bwhist_state_section(bw_array_t *b,
1634 const smartlist_t *s_values,
1635 const smartlist_t *s_maxima,
1636 const time_t s_begins,
1637 const int s_interval)
1639 time_t now = time(NULL);
1640 int retval = 0;
1641 time_t start;
1643 uint64_t v, mv;
1644 int i,ok,ok_m;
1645 int have_maxima = (smartlist_len(s_values) == smartlist_len(s_maxima));
1647 if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
1648 start = s_begins - s_interval*(smartlist_len(s_values));
1649 if (start > now)
1650 return 0;
1651 b->cur_obs_time = start;
1652 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1653 SMARTLIST_FOREACH_BEGIN(s_values, const char *, cp) {
1654 const char *maxstr = NULL;
1655 v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
1656 if (have_maxima) {
1657 maxstr = smartlist_get(s_maxima, cp_sl_idx);
1658 mv = tor_parse_uint64(maxstr, 10, 0, UINT64_MAX, &ok_m, NULL);
1659 mv *= NUM_SECS_ROLLING_MEASURE;
1660 } else {
1661 /* No maxima known; guess average rate to be conservative. */
1662 mv = v / s_interval;
1664 if (!ok) {
1665 retval = -1;
1666 log_notice(LD_HIST, "Could not parse value '%s' into a number.'",cp);
1668 if (maxstr && !ok_m) {
1669 retval = -1;
1670 log_notice(LD_HIST, "Could not parse maximum '%s' into a number.'",
1671 maxstr);
1674 if (start < now) {
1675 add_obs(b, start, v);
1676 b->max_total = mv;
1677 /* This will result in some fairly choppy history if s_interval
1678 * is notthe same as NUM_SECS_BW_SUM_INTERVAL. XXXX */
1679 start += s_interval;
1681 } SMARTLIST_FOREACH_END(cp);
1684 /* Clean up maxima and observed */
1685 for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
1686 b->obs[i] = 0;
1688 b->total_obs = 0;
1690 return retval;
1693 /** Set bandwidth history from our saved state. */
1695 rep_hist_load_state(or_state_t *state, char **err)
1697 int all_ok = 1;
1699 /* Assert they already have been malloced */
1700 tor_assert(read_array && write_array);
1701 tor_assert(dir_read_array && dir_write_array);
1703 #define LOAD(arrname,st) \
1704 if (rep_hist_load_bwhist_state_section( \
1705 (arrname), \
1706 state->BWHistory ## st ## Values, \
1707 state->BWHistory ## st ## Maxima, \
1708 state->BWHistory ## st ## Ends, \
1709 state->BWHistory ## st ## Interval)<0) \
1710 all_ok = 0
1712 LOAD(write_array, Write);
1713 LOAD(read_array, Read);
1714 LOAD(dir_write_array, DirWrite);
1715 LOAD(dir_read_array, DirRead);
1717 #undef LOAD
1718 if (!all_ok) {
1719 *err = tor_strdup("Parsing of bandwidth history values failed");
1720 /* and create fresh arrays */
1721 bw_arrays_init();
1722 return -1;
1724 return 0;
1727 /*********************************************************************/
1729 /** A list of port numbers that have been used recently. */
1730 static smartlist_t *predicted_ports_list=NULL;
1731 /** The corresponding most recently used time for each port. */
1732 static smartlist_t *predicted_ports_times=NULL;
1734 /** We just got an application request for a connection with
1735 * port <b>port</b>. Remember it for the future, so we can keep
1736 * some circuits open that will exit to this port.
1738 static void
1739 add_predicted_port(time_t now, uint16_t port)
1741 /* XXXX we could just use uintptr_t here, I think. */
1742 uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
1743 time_t *tmp_time = tor_malloc(sizeof(time_t));
1744 *tmp_port = port;
1745 *tmp_time = now;
1746 rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
1747 smartlist_add(predicted_ports_list, tmp_port);
1748 smartlist_add(predicted_ports_times, tmp_time);
1751 /** Initialize whatever memory and structs are needed for predicting
1752 * which ports will be used. Also seed it with port 80, so we'll build
1753 * circuits on start-up.
1755 static void
1756 predicted_ports_init(void)
1758 predicted_ports_list = smartlist_create();
1759 predicted_ports_times = smartlist_create();
1760 add_predicted_port(time(NULL), 80); /* add one to kickstart us */
1763 /** Free whatever memory is needed for predicting which ports will
1764 * be used.
1766 static void
1767 predicted_ports_free(void)
1769 rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
1770 SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
1771 smartlist_free(predicted_ports_list);
1772 rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
1773 SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
1774 smartlist_free(predicted_ports_times);
1777 /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
1778 * This is used for predicting what sorts of streams we'll make in the
1779 * future and making exit circuits to anticipate that.
1781 void
1782 rep_hist_note_used_port(time_t now, uint16_t port)
1784 int i;
1785 uint16_t *tmp_port;
1786 time_t *tmp_time;
1788 tor_assert(predicted_ports_list);
1789 tor_assert(predicted_ports_times);
1791 if (!port) /* record nothing */
1792 return;
1794 for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
1795 tmp_port = smartlist_get(predicted_ports_list, i);
1796 tmp_time = smartlist_get(predicted_ports_times, i);
1797 if (*tmp_port == port) {
1798 *tmp_time = now;
1799 return;
1802 /* it's not there yet; we need to add it */
1803 add_predicted_port(now, port);
1806 /** For this long after we've seen a request for a given port, assume that
1807 * we'll want to make connections to the same port in the future. */
1808 #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
1810 /** Return a pointer to the list of port numbers that
1811 * are likely to be asked for in the near future.
1813 * The caller promises not to mess with it.
1815 smartlist_t *
1816 rep_hist_get_predicted_ports(time_t now)
1818 int i;
1819 uint16_t *tmp_port;
1820 time_t *tmp_time;
1822 tor_assert(predicted_ports_list);
1823 tor_assert(predicted_ports_times);
1825 /* clean out obsolete entries */
1826 for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
1827 tmp_time = smartlist_get(predicted_ports_times, i);
1828 if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
1829 tmp_port = smartlist_get(predicted_ports_list, i);
1830 log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
1831 smartlist_del(predicted_ports_list, i);
1832 smartlist_del(predicted_ports_times, i);
1833 rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
1834 tor_free(tmp_port);
1835 tor_free(tmp_time);
1836 i--;
1839 return predicted_ports_list;
1842 /** The user asked us to do a resolve. Rather than keeping track of
1843 * timings and such of resolves, we fake it for now by treating
1844 * it the same way as a connection to port 80. This way we will continue
1845 * to have circuits lying around if the user only uses Tor for resolves.
1847 void
1848 rep_hist_note_used_resolve(time_t now)
1850 rep_hist_note_used_port(now, 80);
1853 /** The last time at which we needed an internal circ. */
1854 static time_t predicted_internal_time = 0;
1855 /** The last time we needed an internal circ with good uptime. */
1856 static time_t predicted_internal_uptime_time = 0;
1857 /** The last time we needed an internal circ with good capacity. */
1858 static time_t predicted_internal_capacity_time = 0;
1860 /** Remember that we used an internal circ at time <b>now</b>. */
1861 void
1862 rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
1864 predicted_internal_time = now;
1865 if (need_uptime)
1866 predicted_internal_uptime_time = now;
1867 if (need_capacity)
1868 predicted_internal_capacity_time = now;
1871 /** Return 1 if we've used an internal circ recently; else return 0. */
1873 rep_hist_get_predicted_internal(time_t now, int *need_uptime,
1874 int *need_capacity)
1876 if (!predicted_internal_time) { /* initialize it */
1877 predicted_internal_time = now;
1878 predicted_internal_uptime_time = now;
1879 predicted_internal_capacity_time = now;
1881 if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
1882 return 0; /* too long ago */
1883 if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
1884 *need_uptime = 1;
1885 // Always predict that we need capacity.
1886 *need_capacity = 1;
1887 return 1;
1890 /** Any ports used lately? These are pre-seeded if we just started
1891 * up or if we're running a hidden service. */
1893 any_predicted_circuits(time_t now)
1895 return smartlist_len(predicted_ports_list) ||
1896 predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now;
1899 /** Return 1 if we have no need for circuits currently, else return 0. */
1901 rep_hist_circbuilding_dormant(time_t now)
1903 if (any_predicted_circuits(now))
1904 return 0;
1906 /* see if we'll still need to build testing circuits */
1907 if (server_mode(get_options()) &&
1908 (!check_whether_orport_reachable() || !circuit_enough_testing_circs()))
1909 return 0;
1910 if (!check_whether_dirport_reachable())
1911 return 0;
1913 return 1;
1916 /** Structure to track how many times we've done each public key operation. */
1917 static struct {
1918 /** How many directory objects have we signed? */
1919 unsigned long n_signed_dir_objs;
1920 /** How many routerdescs have we signed? */
1921 unsigned long n_signed_routerdescs;
1922 /** How many directory objects have we verified? */
1923 unsigned long n_verified_dir_objs;
1924 /** How many routerdescs have we verified */
1925 unsigned long n_verified_routerdescs;
1926 /** How many onionskins have we encrypted to build circuits? */
1927 unsigned long n_onionskins_encrypted;
1928 /** How many onionskins have we decrypted to do circuit build requests? */
1929 unsigned long n_onionskins_decrypted;
1930 /** How many times have we done the TLS handshake as a client? */
1931 unsigned long n_tls_client_handshakes;
1932 /** How many times have we done the TLS handshake as a server? */
1933 unsigned long n_tls_server_handshakes;
1934 /** How many PK operations have we done as a hidden service client? */
1935 unsigned long n_rend_client_ops;
1936 /** How many PK operations have we done as a hidden service midpoint? */
1937 unsigned long n_rend_mid_ops;
1938 /** How many PK operations have we done as a hidden service provider? */
1939 unsigned long n_rend_server_ops;
1940 } pk_op_counts = {0,0,0,0,0,0,0,0,0,0,0};
1942 /** Increment the count of the number of times we've done <b>operation</b>. */
1943 void
1944 note_crypto_pk_op(pk_op_t operation)
1946 switch (operation)
1948 case SIGN_DIR:
1949 pk_op_counts.n_signed_dir_objs++;
1950 break;
1951 case SIGN_RTR:
1952 pk_op_counts.n_signed_routerdescs++;
1953 break;
1954 case VERIFY_DIR:
1955 pk_op_counts.n_verified_dir_objs++;
1956 break;
1957 case VERIFY_RTR:
1958 pk_op_counts.n_verified_routerdescs++;
1959 break;
1960 case ENC_ONIONSKIN:
1961 pk_op_counts.n_onionskins_encrypted++;
1962 break;
1963 case DEC_ONIONSKIN:
1964 pk_op_counts.n_onionskins_decrypted++;
1965 break;
1966 case TLS_HANDSHAKE_C:
1967 pk_op_counts.n_tls_client_handshakes++;
1968 break;
1969 case TLS_HANDSHAKE_S:
1970 pk_op_counts.n_tls_server_handshakes++;
1971 break;
1972 case REND_CLIENT:
1973 pk_op_counts.n_rend_client_ops++;
1974 break;
1975 case REND_MID:
1976 pk_op_counts.n_rend_mid_ops++;
1977 break;
1978 case REND_SERVER:
1979 pk_op_counts.n_rend_server_ops++;
1980 break;
1981 default:
1982 log_warn(LD_BUG, "Unknown pk operation %d", operation);
1986 /** Log the number of times we've done each public/private-key operation. */
1987 void
1988 dump_pk_ops(int severity)
1990 log(severity, LD_HIST,
1991 "PK operations: %lu directory objects signed, "
1992 "%lu directory objects verified, "
1993 "%lu routerdescs signed, "
1994 "%lu routerdescs verified, "
1995 "%lu onionskins encrypted, "
1996 "%lu onionskins decrypted, "
1997 "%lu client-side TLS handshakes, "
1998 "%lu server-side TLS handshakes, "
1999 "%lu rendezvous client operations, "
2000 "%lu rendezvous middle operations, "
2001 "%lu rendezvous server operations.",
2002 pk_op_counts.n_signed_dir_objs,
2003 pk_op_counts.n_verified_dir_objs,
2004 pk_op_counts.n_signed_routerdescs,
2005 pk_op_counts.n_verified_routerdescs,
2006 pk_op_counts.n_onionskins_encrypted,
2007 pk_op_counts.n_onionskins_decrypted,
2008 pk_op_counts.n_tls_client_handshakes,
2009 pk_op_counts.n_tls_server_handshakes,
2010 pk_op_counts.n_rend_client_ops,
2011 pk_op_counts.n_rend_mid_ops,
2012 pk_op_counts.n_rend_server_ops);
2015 /*** Exit port statistics ***/
2017 /* Some constants */
2018 /** To what multiple should byte numbers be rounded up? */
2019 #define EXIT_STATS_ROUND_UP_BYTES 1024
2020 /** To what multiple should stream counts be rounded up? */
2021 #define EXIT_STATS_ROUND_UP_STREAMS 4
2022 /** Number of TCP ports */
2023 #define EXIT_STATS_NUM_PORTS 65536
2024 /** Top n ports that will be included in exit stats. */
2025 #define EXIT_STATS_TOP_N_PORTS 10
2027 /* The following data structures are arrays and no fancy smartlists or maps,
2028 * so that all write operations can be done in constant time. This comes at
2029 * the price of some memory (1.25 MB) and linear complexity when writing
2030 * stats for measuring relays. */
2031 /** Number of bytes read in current period by exit port */
2032 static uint64_t *exit_bytes_read = NULL;
2033 /** Number of bytes written in current period by exit port */
2034 static uint64_t *exit_bytes_written = NULL;
2035 /** Number of streams opened in current period by exit port */
2036 static uint32_t *exit_streams = NULL;
2038 /** Start time of exit stats or 0 if we're not collecting exit stats. */
2039 static time_t start_of_exit_stats_interval;
2041 /** Initialize exit port stats. */
2042 void
2043 rep_hist_exit_stats_init(time_t now)
2045 start_of_exit_stats_interval = now;
2046 exit_bytes_read = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2047 sizeof(uint64_t));
2048 exit_bytes_written = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2049 sizeof(uint64_t));
2050 exit_streams = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2051 sizeof(uint32_t));
2054 /** Reset counters for exit port statistics. */
2055 void
2056 rep_hist_reset_exit_stats(time_t now)
2058 start_of_exit_stats_interval = now;
2059 memset(exit_bytes_read, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2060 memset(exit_bytes_written, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2061 memset(exit_streams, 0, EXIT_STATS_NUM_PORTS * sizeof(uint32_t));
2064 /** Stop collecting exit port stats in a way that we can re-start doing
2065 * so in rep_hist_exit_stats_init(). */
2066 void
2067 rep_hist_exit_stats_term(void)
2069 start_of_exit_stats_interval = 0;
2070 tor_free(exit_bytes_read);
2071 tor_free(exit_bytes_written);
2072 tor_free(exit_streams);
2075 /** Helper for qsort: compare two ints. */
2076 static int
2077 _compare_int(const void *x, const void *y)
2079 return (*(int*)x - *(int*)y);
2082 /** Return a newly allocated string containing the exit port statistics
2083 * until <b>now</b>, or NULL if we're not collecting exit stats. */
2084 char *
2085 rep_hist_format_exit_stats(time_t now)
2087 int i, j, top_elements = 0, cur_min_idx = 0, cur_port;
2088 uint64_t top_bytes[EXIT_STATS_TOP_N_PORTS];
2089 int top_ports[EXIT_STATS_TOP_N_PORTS];
2090 uint64_t cur_bytes = 0, other_read = 0, other_written = 0,
2091 total_read = 0, total_written = 0;
2092 uint32_t total_streams = 0, other_streams = 0;
2093 char *buf;
2094 smartlist_t *written_strings, *read_strings, *streams_strings;
2095 char *written_string, *read_string, *streams_string;
2096 char t[ISO_TIME_LEN+1];
2097 char *result;
2099 if (!start_of_exit_stats_interval)
2100 return NULL; /* Not initialized. */
2102 /* Go through all ports to find the n ports that saw most written and
2103 * read bytes.
2105 * Invariant: at the end of the loop for iteration i,
2106 * total_read is the sum of all exit_bytes_read[0..i]
2107 * total_written is the sum of all exit_bytes_written[0..i]
2108 * total_stream is the sum of all exit_streams[0..i]
2110 * top_elements = MAX(EXIT_STATS_TOP_N_PORTS,
2111 * #{j | 0 <= j <= i && volume(i) > 0})
2113 * For all 0 <= j < top_elements,
2114 * top_bytes[j] > 0
2115 * 0 <= top_ports[j] <= 65535
2116 * top_bytes[j] = volume(top_ports[j])
2118 * There is no j in 0..i and k in 0..top_elements such that:
2119 * volume(j) > top_bytes[k] AND j is not in top_ports[0..top_elements]
2121 * There is no j!=cur_min_idx in 0..top_elements such that:
2122 * top_bytes[j] < top_bytes[cur_min_idx]
2124 * where volume(x) == exit_bytes_read[x]+exit_bytes_written[x]
2126 * Worst case: O(EXIT_STATS_NUM_PORTS * EXIT_STATS_TOP_N_PORTS)
2128 for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
2129 total_read += exit_bytes_read[i];
2130 total_written += exit_bytes_written[i];
2131 total_streams += exit_streams[i];
2132 cur_bytes = exit_bytes_read[i] + exit_bytes_written[i];
2133 if (cur_bytes == 0) {
2134 continue;
2136 if (top_elements < EXIT_STATS_TOP_N_PORTS) {
2137 top_bytes[top_elements] = cur_bytes;
2138 top_ports[top_elements++] = i;
2139 } else if (cur_bytes > top_bytes[cur_min_idx]) {
2140 top_bytes[cur_min_idx] = cur_bytes;
2141 top_ports[cur_min_idx] = i;
2142 } else {
2143 continue;
2145 cur_min_idx = 0;
2146 for (j = 1; j < top_elements; j++) {
2147 if (top_bytes[j] < top_bytes[cur_min_idx]) {
2148 cur_min_idx = j;
2153 /* Add observations of top ports to smartlists. */
2154 written_strings = smartlist_create();
2155 read_strings = smartlist_create();
2156 streams_strings = smartlist_create();
2157 other_read = total_read;
2158 other_written = total_written;
2159 other_streams = total_streams;
2160 /* Sort the ports; this puts them out of sync with top_bytes, but we
2161 * won't be using top_bytes again anyway */
2162 qsort(top_ports, top_elements, sizeof(int), _compare_int);
2163 for (j = 0; j < top_elements; j++) {
2164 cur_port = top_ports[j];
2165 if (exit_bytes_written[cur_port] > 0) {
2166 uint64_t num = round_uint64_to_next_multiple_of(
2167 exit_bytes_written[cur_port],
2168 EXIT_STATS_ROUND_UP_BYTES);
2169 num /= 1024;
2170 buf = NULL;
2171 tor_asprintf(&buf, "%d="U64_FORMAT, cur_port, U64_PRINTF_ARG(num));
2172 smartlist_add(written_strings, buf);
2173 other_written -= exit_bytes_written[cur_port];
2175 if (exit_bytes_read[cur_port] > 0) {
2176 uint64_t num = round_uint64_to_next_multiple_of(
2177 exit_bytes_read[cur_port],
2178 EXIT_STATS_ROUND_UP_BYTES);
2179 num /= 1024;
2180 buf = NULL;
2181 tor_asprintf(&buf, "%d="U64_FORMAT, cur_port, U64_PRINTF_ARG(num));
2182 smartlist_add(read_strings, buf);
2183 other_read -= exit_bytes_read[cur_port];
2185 if (exit_streams[cur_port] > 0) {
2186 uint32_t num = round_uint32_to_next_multiple_of(
2187 exit_streams[cur_port],
2188 EXIT_STATS_ROUND_UP_STREAMS);
2189 buf = NULL;
2190 tor_asprintf(&buf, "%d=%u", cur_port, num);
2191 smartlist_add(streams_strings, buf);
2192 other_streams -= exit_streams[cur_port];
2196 /* Add observations of other ports in a single element. */
2197 other_written = round_uint64_to_next_multiple_of(other_written,
2198 EXIT_STATS_ROUND_UP_BYTES);
2199 other_written /= 1024;
2200 buf = NULL;
2201 tor_asprintf(&buf, "other="U64_FORMAT, U64_PRINTF_ARG(other_written));
2202 smartlist_add(written_strings, buf);
2203 other_read = round_uint64_to_next_multiple_of(other_read,
2204 EXIT_STATS_ROUND_UP_BYTES);
2205 other_read /= 1024;
2206 buf = NULL;
2207 tor_asprintf(&buf, "other="U64_FORMAT, U64_PRINTF_ARG(other_read));
2208 smartlist_add(read_strings, buf);
2209 other_streams = round_uint32_to_next_multiple_of(other_streams,
2210 EXIT_STATS_ROUND_UP_STREAMS);
2211 buf = NULL;
2212 tor_asprintf(&buf, "other=%u", other_streams);
2213 smartlist_add(streams_strings, buf);
2215 /* Join all observations in single strings. */
2216 written_string = smartlist_join_strings(written_strings, ",", 0, NULL);
2217 read_string = smartlist_join_strings(read_strings, ",", 0, NULL);
2218 streams_string = smartlist_join_strings(streams_strings, ",", 0, NULL);
2219 SMARTLIST_FOREACH(written_strings, char *, cp, tor_free(cp));
2220 SMARTLIST_FOREACH(read_strings, char *, cp, tor_free(cp));
2221 SMARTLIST_FOREACH(streams_strings, char *, cp, tor_free(cp));
2222 smartlist_free(written_strings);
2223 smartlist_free(read_strings);
2224 smartlist_free(streams_strings);
2226 /* Put everything together. */
2227 format_iso_time(t, now);
2228 tor_asprintf(&result, "exit-stats-end %s (%d s)\n"
2229 "exit-kibibytes-written %s\n"
2230 "exit-kibibytes-read %s\n"
2231 "exit-streams-opened %s\n",
2232 t, (unsigned) (now - start_of_exit_stats_interval),
2233 written_string,
2234 read_string,
2235 streams_string);
2236 tor_free(written_string);
2237 tor_free(read_string);
2238 tor_free(streams_string);
2239 return result;
2242 /** If 24 hours have passed since the beginning of the current exit port
2243 * stats period, write exit stats to $DATADIR/stats/exit-stats (possibly
2244 * overwriting an existing file) and reset counters. Return when we would
2245 * next want to write exit stats or 0 if we never want to write. */
2246 time_t
2247 rep_hist_exit_stats_write(time_t now)
2249 char *statsdir = NULL, *filename = NULL, *str = NULL;
2251 if (!start_of_exit_stats_interval)
2252 return 0; /* Not initialized. */
2253 if (start_of_exit_stats_interval + WRITE_STATS_INTERVAL > now)
2254 goto done; /* Not ready to write. */
2256 log_info(LD_HIST, "Writing exit port statistics to disk.");
2258 /* Generate history string. */
2259 str = rep_hist_format_exit_stats(now);
2261 /* Reset counters. */
2262 rep_hist_reset_exit_stats(now);
2264 /* Try to write to disk. */
2265 statsdir = get_datadir_fname("stats");
2266 if (check_private_dir(statsdir, CPD_CREATE) < 0) {
2267 log_warn(LD_HIST, "Unable to create stats/ directory!");
2268 goto done;
2270 filename = get_datadir_fname2("stats", "exit-stats");
2271 if (write_str_to_file(filename, str, 0) < 0)
2272 log_warn(LD_HIST, "Unable to write exit port statistics to disk!");
2274 done:
2275 tor_free(str);
2276 tor_free(statsdir);
2277 tor_free(filename);
2278 return start_of_exit_stats_interval + WRITE_STATS_INTERVAL;
2281 /** Note that we wrote <b>num_written</b> bytes and read <b>num_read</b>
2282 * bytes to/from an exit connection to <b>port</b>. */
2283 void
2284 rep_hist_note_exit_bytes(uint16_t port, size_t num_written,
2285 size_t num_read)
2287 if (!start_of_exit_stats_interval)
2288 return; /* Not initialized. */
2289 exit_bytes_written[port] += num_written;
2290 exit_bytes_read[port] += num_read;
2291 log_debug(LD_HIST, "Written %lu bytes and read %lu bytes to/from an "
2292 "exit connection to port %d.",
2293 (unsigned long)num_written, (unsigned long)num_read, port);
2296 /** Note that we opened an exit stream to <b>port</b>. */
2297 void
2298 rep_hist_note_exit_stream_opened(uint16_t port)
2300 if (!start_of_exit_stats_interval)
2301 return; /* Not initialized. */
2302 exit_streams[port]++;
2303 log_debug(LD_HIST, "Opened exit stream to port %d", port);
2306 /*** cell statistics ***/
2308 /** Start of the current buffer stats interval or 0 if we're not
2309 * collecting buffer statistics. */
2310 static time_t start_of_buffer_stats_interval;
2312 /** Initialize buffer stats. */
2313 void
2314 rep_hist_buffer_stats_init(time_t now)
2316 start_of_buffer_stats_interval = now;
2319 typedef struct circ_buffer_stats_t {
2320 uint32_t processed_cells;
2321 double mean_num_cells_in_queue;
2322 double mean_time_cells_in_queue;
2323 uint32_t local_circ_id;
2324 } circ_buffer_stats_t;
2326 /** Holds stats. */
2327 smartlist_t *circuits_for_buffer_stats = NULL;
2329 /** Remember cell statistics for circuit <b>circ</b> at time
2330 * <b>end_of_interval</b> and reset cell counters in case the circuit
2331 * remains open in the next measurement interval. */
2332 void
2333 rep_hist_buffer_stats_add_circ(circuit_t *circ, time_t end_of_interval)
2335 circ_buffer_stats_t *stat;
2336 time_t start_of_interval;
2337 int interval_length;
2338 or_circuit_t *orcirc;
2339 if (CIRCUIT_IS_ORIGIN(circ))
2340 return;
2341 orcirc = TO_OR_CIRCUIT(circ);
2342 if (!orcirc->processed_cells)
2343 return;
2344 if (!circuits_for_buffer_stats)
2345 circuits_for_buffer_stats = smartlist_create();
2346 start_of_interval = circ->timestamp_created >
2347 start_of_buffer_stats_interval ?
2348 circ->timestamp_created :
2349 start_of_buffer_stats_interval;
2350 interval_length = (int) (end_of_interval - start_of_interval);
2351 stat = tor_malloc_zero(sizeof(circ_buffer_stats_t));
2352 stat->processed_cells = orcirc->processed_cells;
2353 /* 1000.0 for s -> ms; 2.0 because of app-ward and exit-ward queues */
2354 stat->mean_num_cells_in_queue = interval_length == 0 ? 0.0 :
2355 (double) orcirc->total_cell_waiting_time /
2356 (double) interval_length / 1000.0 / 2.0;
2357 stat->mean_time_cells_in_queue =
2358 (double) orcirc->total_cell_waiting_time /
2359 (double) orcirc->processed_cells;
2360 smartlist_add(circuits_for_buffer_stats, stat);
2361 orcirc->total_cell_waiting_time = 0;
2362 orcirc->processed_cells = 0;
2365 /** Sorting helper: return -1, 1, or 0 based on comparison of two
2366 * circ_buffer_stats_t */
2367 static int
2368 _buffer_stats_compare_entries(const void **_a, const void **_b)
2370 const circ_buffer_stats_t *a = *_a, *b = *_b;
2371 if (a->processed_cells < b->processed_cells)
2372 return 1;
2373 else if (a->processed_cells > b->processed_cells)
2374 return -1;
2375 else
2376 return 0;
2379 /** Stop collecting cell stats in a way that we can re-start doing so in
2380 * rep_hist_buffer_stats_init(). */
2381 void
2382 rep_hist_buffer_stats_term(void)
2384 start_of_buffer_stats_interval = 0;
2385 if (!circuits_for_buffer_stats)
2386 circuits_for_buffer_stats = smartlist_create();
2387 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
2388 stat, tor_free(stat));
2389 smartlist_clear(circuits_for_buffer_stats);
2392 /** Write buffer statistics to $DATADIR/stats/buffer-stats and return when
2393 * we would next want to write exit stats. */
2394 time_t
2395 rep_hist_buffer_stats_write(time_t now)
2397 char *statsdir = NULL, *filename = NULL;
2398 char written[ISO_TIME_LEN+1];
2399 open_file_t *open_file = NULL;
2400 FILE *out;
2401 #define SHARES 10
2402 int processed_cells[SHARES], circs_in_share[SHARES],
2403 number_of_circuits, i;
2404 double queued_cells[SHARES], time_in_queue[SHARES];
2405 smartlist_t *str_build = smartlist_create();
2406 char *str = NULL, *buf=NULL;
2407 circuit_t *circ;
2409 if (!start_of_buffer_stats_interval)
2410 return 0; /* Not initialized. */
2411 if (start_of_buffer_stats_interval + WRITE_STATS_INTERVAL > now)
2412 goto done; /* Not ready to write */
2414 /* add current circuits to stats */
2415 for (circ = _circuit_get_global_list(); circ; circ = circ->next)
2416 rep_hist_buffer_stats_add_circ(circ, now);
2417 /* calculate deciles */
2418 memset(processed_cells, 0, SHARES * sizeof(int));
2419 memset(circs_in_share, 0, SHARES * sizeof(int));
2420 memset(queued_cells, 0, SHARES * sizeof(double));
2421 memset(time_in_queue, 0, SHARES * sizeof(double));
2422 if (!circuits_for_buffer_stats)
2423 circuits_for_buffer_stats = smartlist_create();
2424 smartlist_sort(circuits_for_buffer_stats,
2425 _buffer_stats_compare_entries);
2426 number_of_circuits = smartlist_len(circuits_for_buffer_stats);
2427 if (number_of_circuits < 1) {
2428 log_info(LD_HIST, "Attempt to write cell statistics to disk failed. "
2429 "We haven't seen a single circuit to report about.");
2430 goto done;
2432 i = 0;
2433 SMARTLIST_FOREACH_BEGIN(circuits_for_buffer_stats,
2434 circ_buffer_stats_t *, stat)
2436 int share = i++ * SHARES / number_of_circuits;
2437 processed_cells[share] += stat->processed_cells;
2438 queued_cells[share] += stat->mean_num_cells_in_queue;
2439 time_in_queue[share] += stat->mean_time_cells_in_queue;
2440 circs_in_share[share]++;
2442 SMARTLIST_FOREACH_END(stat);
2443 /* clear buffer stats history */
2444 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
2445 stat, tor_free(stat));
2446 smartlist_clear(circuits_for_buffer_stats);
2447 /* write to file */
2448 statsdir = get_datadir_fname("stats");
2449 if (check_private_dir(statsdir, CPD_CREATE) < 0)
2450 goto done;
2451 filename = get_datadir_fname2("stats", "buffer-stats");
2452 out = start_writing_to_stdio_file(filename, OPEN_FLAGS_APPEND,
2453 0600, &open_file);
2454 if (!out)
2455 goto done;
2456 format_iso_time(written, now);
2457 if (fprintf(out, "cell-stats-end %s (%d s)\n", written,
2458 (unsigned) (now - start_of_buffer_stats_interval)) < 0)
2459 goto done;
2460 for (i = 0; i < SHARES; i++) {
2461 tor_asprintf(&buf,"%d", !circs_in_share[i] ? 0 :
2462 processed_cells[i] / circs_in_share[i]);
2463 smartlist_add(str_build, buf);
2465 str = smartlist_join_strings(str_build, ",", 0, NULL);
2466 if (fprintf(out, "cell-processed-cells %s\n", str) < 0)
2467 goto done;
2468 tor_free(str);
2469 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2470 smartlist_clear(str_build);
2471 for (i = 0; i < SHARES; i++) {
2472 tor_asprintf(&buf, "%.2f", circs_in_share[i] == 0 ? 0.0 :
2473 queued_cells[i] / (double) circs_in_share[i]);
2474 smartlist_add(str_build, buf);
2476 str = smartlist_join_strings(str_build, ",", 0, NULL);
2477 if (fprintf(out, "cell-queued-cells %s\n", str) < 0)
2478 goto done;
2479 tor_free(str);
2480 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2481 smartlist_clear(str_build);
2482 for (i = 0; i < SHARES; i++) {
2483 tor_asprintf(&buf, "%.0f", circs_in_share[i] == 0 ? 0.0 :
2484 time_in_queue[i] / (double) circs_in_share[i]);
2485 smartlist_add(str_build, buf);
2487 str = smartlist_join_strings(str_build, ",", 0, NULL);
2488 if (fprintf(out, "cell-time-in-queue %s\n", str) < 0)
2489 goto done;
2490 tor_free(str);
2491 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2492 smartlist_free(str_build);
2493 str_build = NULL;
2494 if (fprintf(out, "cell-circuits-per-decile %d\n",
2495 (number_of_circuits + SHARES - 1) / SHARES) < 0)
2496 goto done;
2497 finish_writing_to_file(open_file);
2498 open_file = NULL;
2499 start_of_buffer_stats_interval = now;
2500 done:
2501 if (open_file)
2502 abort_writing_to_file(open_file);
2503 tor_free(filename);
2504 tor_free(statsdir);
2505 if (str_build) {
2506 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2507 smartlist_free(str_build);
2509 tor_free(str);
2510 #undef SHARES
2511 return start_of_buffer_stats_interval + WRITE_STATS_INTERVAL;
2514 /** Free all storage held by the OR/link history caches, by the
2515 * bandwidth history arrays, by the port history, or by statistics . */
2516 void
2517 rep_hist_free_all(void)
2519 digestmap_free(history_map, free_or_history);
2520 tor_free(read_array);
2521 tor_free(write_array);
2522 tor_free(last_stability_doc);
2523 tor_free(exit_bytes_read);
2524 tor_free(exit_bytes_written);
2525 tor_free(exit_streams);
2526 built_last_stability_doc_at = 0;
2527 predicted_ports_free();