Use observed instead of declared uptime for HSDir
[tor/rransom.git] / src / or / rephist.c
blob69001de8397f51da4c500586ad280c5f2ec8d62e
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 how long the router whose identity digest is <b>id</b> has
532 * been reachable. Return 0 if the router is unknown or currently deemed
533 * unreachable. */
534 long
535 rep_hist_get_uptime(const char *id, time_t when)
537 or_history_t *hist = get_or_history(id);
538 if (!hist)
539 return 0;
540 if (!hist->start_of_run)
541 return 0;
542 return when - hist->start_of_run;
545 /** Return an estimated MTBF for the router whose identity digest is
546 * <b>id</b>. Return 0 if the router is unknown. */
547 double
548 rep_hist_get_stability(const char *id, time_t when)
550 or_history_t *hist = get_or_history(id);
551 if (!hist)
552 return 0.0;
554 return get_stability(hist, when);
557 /** Return an estimated percent-of-time-online for the router whose identity
558 * digest is <b>id</b>. Return 0 if the router is unknown. */
559 double
560 rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
562 or_history_t *hist = get_or_history(id);
563 if (!hist)
564 return 0.0;
566 return get_weighted_fractional_uptime(hist, when);
569 /** Return a number representing how long we've known about the router whose
570 * digest is <b>id</b>. Return 0 if the router is unknown.
572 * Be careful: this measure increases monotonically as we know the router for
573 * longer and longer, but it doesn't increase linearly.
575 long
576 rep_hist_get_weighted_time_known(const char *id, time_t when)
578 or_history_t *hist = get_or_history(id);
579 if (!hist)
580 return 0;
582 return get_total_weighted_time(hist, when);
585 /** Return true if we've been measuring MTBFs for long enough to
586 * pronounce on Stability. */
588 rep_hist_have_measured_enough_stability(void)
590 /* XXXX021 This doesn't do so well when we change our opinion
591 * as to whether we're tracking router stability. */
592 return started_tracking_stability < time(NULL) - 4*60*60;
595 /** Remember that we successfully extended from the OR with identity
596 * digest <b>from_id</b> to the OR with identity digest
597 * <b>to_name</b>.
599 void
600 rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
602 link_history_t *hist;
603 /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
604 hist = get_link_history(from_id, to_id);
605 if (!hist)
606 return;
607 ++hist->n_extend_ok;
608 hist->changed = time(NULL);
611 /** Remember that we tried to extend from the OR with identity digest
612 * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
613 * failed.
615 void
616 rep_hist_note_extend_failed(const char *from_id, const char *to_id)
618 link_history_t *hist;
619 /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
620 hist = get_link_history(from_id, to_id);
621 if (!hist)
622 return;
623 ++hist->n_extend_fail;
624 hist->changed = time(NULL);
627 /** Log all the reliability data we have remembered, with the chosen
628 * severity.
630 void
631 rep_hist_dump_stats(time_t now, int severity)
633 digestmap_iter_t *lhist_it;
634 digestmap_iter_t *orhist_it;
635 const char *name1, *name2, *digest1, *digest2;
636 char hexdigest1[HEX_DIGEST_LEN+1];
637 or_history_t *or_history;
638 link_history_t *link_history;
639 void *or_history_p, *link_history_p;
640 double uptime;
641 char buffer[2048];
642 size_t len;
643 int ret;
644 unsigned long upt, downt;
645 routerinfo_t *r;
647 rep_history_clean(now - get_options()->RephistTrackTime);
649 log(severity, LD_HIST, "--------------- Dumping history information:");
651 for (orhist_it = digestmap_iter_init(history_map);
652 !digestmap_iter_done(orhist_it);
653 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
654 double s;
655 long stability;
656 digestmap_iter_get(orhist_it, &digest1, &or_history_p);
657 or_history = (or_history_t*) or_history_p;
659 if ((r = router_get_by_digest(digest1)))
660 name1 = r->nickname;
661 else
662 name1 = "(unknown)";
663 base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
664 update_or_history(or_history, now);
665 upt = or_history->uptime;
666 downt = or_history->downtime;
667 s = get_stability(or_history, now);
668 stability = (long)s;
669 if (upt+downt) {
670 uptime = ((double)upt) / (upt+downt);
671 } else {
672 uptime=1.0;
674 log(severity, LD_HIST,
675 "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
676 "wmtbf %lu:%02lu:%02lu",
677 name1, hexdigest1,
678 or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
679 upt, upt+downt, uptime*100.0,
680 stability/3600, (stability/60)%60, stability%60);
682 if (!digestmap_isempty(or_history->link_history_map)) {
683 strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
684 len = strlen(buffer);
685 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
686 !digestmap_iter_done(lhist_it);
687 lhist_it = digestmap_iter_next(or_history->link_history_map,
688 lhist_it)) {
689 digestmap_iter_get(lhist_it, &digest2, &link_history_p);
690 if ((r = router_get_by_digest(digest2)))
691 name2 = r->nickname;
692 else
693 name2 = "(unknown)";
695 link_history = (link_history_t*) link_history_p;
697 ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
698 link_history->n_extend_ok,
699 link_history->n_extend_ok+link_history->n_extend_fail);
700 if (ret<0)
701 break;
702 else
703 len += ret;
705 log(severity, LD_HIST, "%s", buffer);
710 /** Remove history info for routers/links that haven't changed since
711 * <b>before</b>.
713 void
714 rep_history_clean(time_t before)
716 int authority = authdir_mode(get_options());
717 or_history_t *or_history;
718 link_history_t *link_history;
719 void *or_history_p, *link_history_p;
720 digestmap_iter_t *orhist_it, *lhist_it;
721 const char *d1, *d2;
723 orhist_it = digestmap_iter_init(history_map);
724 while (!digestmap_iter_done(orhist_it)) {
725 int remove;
726 digestmap_iter_get(orhist_it, &d1, &or_history_p);
727 or_history = or_history_p;
729 remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
730 !or_history->start_of_run)
731 : (or_history->changed < before);
732 if (remove) {
733 orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
734 free_or_history(or_history);
735 continue;
737 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
738 !digestmap_iter_done(lhist_it); ) {
739 digestmap_iter_get(lhist_it, &d2, &link_history_p);
740 link_history = link_history_p;
741 if (link_history->changed < before) {
742 lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
743 lhist_it);
744 rephist_total_alloc -= sizeof(link_history_t);
745 tor_free(link_history);
746 continue;
748 lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
750 orhist_it = digestmap_iter_next(history_map, orhist_it);
754 /** Write MTBF data to disk. Return 0 on success, negative on failure.
756 * If <b>missing_means_down</b>, then if we're about to write an entry
757 * that is still considered up but isn't in our routerlist, consider it
758 * to be down. */
760 rep_hist_record_mtbf_data(time_t now, int missing_means_down)
762 char time_buf[ISO_TIME_LEN+1];
764 digestmap_iter_t *orhist_it;
765 const char *digest;
766 void *or_history_p;
767 or_history_t *hist;
768 open_file_t *open_file = NULL;
769 FILE *f;
772 char *filename = get_datadir_fname("router-stability");
773 f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
774 &open_file);
775 tor_free(filename);
776 if (!f)
777 return -1;
780 /* File format is:
781 * FormatLine *KeywordLine Data
783 * FormatLine = "format 1" NL
784 * KeywordLine = Keyword SP Arguments NL
785 * Data = "data" NL *RouterMTBFLine "." NL
786 * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
787 * TotalRunWeights [SP S=StartRunTime] NL
789 #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
790 #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
792 PUT("format 2\n");
794 format_iso_time(time_buf, time(NULL));
795 PRINTF((f, "stored-at %s\n", time_buf));
797 if (started_tracking_stability) {
798 format_iso_time(time_buf, started_tracking_stability);
799 PRINTF((f, "tracked-since %s\n", time_buf));
801 if (stability_last_downrated) {
802 format_iso_time(time_buf, stability_last_downrated);
803 PRINTF((f, "last-downrated %s\n", time_buf));
806 PUT("data\n");
808 /* XXX Nick: now bridge auths record this for all routers too.
809 * Should we make them record it only for bridge routers? -RD
810 * Not for 0.2.0. -NM */
811 for (orhist_it = digestmap_iter_init(history_map);
812 !digestmap_iter_done(orhist_it);
813 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
814 char dbuf[HEX_DIGEST_LEN+1];
815 const char *t = NULL;
816 digestmap_iter_get(orhist_it, &digest, &or_history_p);
817 hist = (or_history_t*) or_history_p;
819 base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
821 if (missing_means_down && hist->start_of_run &&
822 !router_get_by_digest(digest)) {
823 /* We think this relay is running, but it's not listed in our
824 * routerlist. Somehow it fell out without telling us it went
825 * down. Complain and also correct it. */
826 log_info(LD_HIST,
827 "Relay '%s' is listed as up in rephist, but it's not in "
828 "our routerlist. Correcting.", dbuf);
829 rep_hist_note_router_unreachable(digest, now);
832 PRINTF((f, "R %s\n", dbuf));
833 if (hist->start_of_run > 0) {
834 format_iso_time(time_buf, hist->start_of_run);
835 t = time_buf;
837 PRINTF((f, "+MTBF %lu %.5lf%s%s\n",
838 hist->weighted_run_length, hist->total_run_weights,
839 t ? " S=" : "", t ? t : ""));
840 t = NULL;
841 if (hist->start_of_downtime > 0) {
842 format_iso_time(time_buf, hist->start_of_downtime);
843 t = time_buf;
845 PRINTF((f, "+WFU %lu %lu%s%s\n",
846 hist->weighted_uptime, hist->total_weighted_time,
847 t ? " S=" : "", t ? t : ""));
850 PUT(".\n");
852 #undef PUT
853 #undef PRINTF
855 return finish_writing_to_file(open_file);
856 err:
857 abort_writing_to_file(open_file);
858 return -1;
861 /** Format the current tracked status of the router in <b>hist</b> at time
862 * <b>now</b> for analysis; return it in a newly allocated string. */
863 static char *
864 rep_hist_format_router_status(or_history_t *hist, time_t now)
866 char sor_buf[ISO_TIME_LEN+1];
867 char sod_buf[ISO_TIME_LEN+1];
868 double wfu;
869 double mtbf;
870 int up = 0, down = 0;
871 char *cp = NULL;
873 if (hist->start_of_run) {
874 format_iso_time(sor_buf, hist->start_of_run);
875 up = 1;
877 if (hist->start_of_downtime) {
878 format_iso_time(sod_buf, hist->start_of_downtime);
879 down = 1;
882 wfu = get_weighted_fractional_uptime(hist, now);
883 mtbf = get_stability(hist, now);
884 tor_asprintf(&cp,
885 "%s%s%s"
886 "%s%s%s"
887 "wfu %0.3lf\n"
888 " weighted-time %lu\n"
889 " weighted-uptime %lu\n"
890 "mtbf %0.1lf\n"
891 " weighted-run-length %lu\n"
892 " total-run-weights %lf\n",
893 up?"uptime-started ":"", up?sor_buf:"", up?" UTC\n":"",
894 down?"downtime-started ":"", down?sod_buf:"", down?" UTC\n":"",
895 wfu,
896 hist->total_weighted_time,
897 hist->weighted_uptime,
898 mtbf,
899 hist->weighted_run_length,
900 hist->total_run_weights
902 return cp;
905 /** The last stability analysis document that we created, or NULL if we never
906 * have created one. */
907 static char *last_stability_doc = NULL;
908 /** The last time we created a stability analysis document, or 0 if we never
909 * have created one. */
910 static time_t built_last_stability_doc_at = 0;
911 /** Shortest allowable time between building two stability documents. */
912 #define MAX_STABILITY_DOC_BUILD_RATE (3*60)
914 /** Return a pointer to a NUL-terminated document describing our view of the
915 * stability of the routers we've been tracking. Return NULL on failure. */
916 const char *
917 rep_hist_get_router_stability_doc(time_t now)
919 char *result;
920 smartlist_t *chunks;
921 if (built_last_stability_doc_at + MAX_STABILITY_DOC_BUILD_RATE > now)
922 return last_stability_doc;
924 if (!history_map)
925 return NULL;
927 tor_free(last_stability_doc);
928 chunks = smartlist_create();
930 if (rep_hist_have_measured_enough_stability()) {
931 smartlist_add(chunks, tor_strdup("we-have-enough-measurements\n"));
932 } else {
933 smartlist_add(chunks, tor_strdup("we-do-not-have-enough-measurements\n"));
936 DIGESTMAP_FOREACH(history_map, id, or_history_t *, hist) {
937 routerinfo_t *ri;
938 char dbuf[BASE64_DIGEST_LEN+1];
939 char header_buf[512];
940 char *info;
941 digest_to_base64(dbuf, id);
942 ri = router_get_by_digest(id);
943 if (ri) {
944 char *ip = tor_dup_ip(ri->addr);
945 char tbuf[ISO_TIME_LEN+1];
946 format_iso_time(tbuf, ri->cache_info.published_on);
947 tor_snprintf(header_buf, sizeof(header_buf),
948 "router %s %s %s\n"
949 "published %s\n"
950 "relevant-flags %s%s%s\n"
951 "declared-uptime %ld\n",
952 dbuf, ri->nickname, ip,
953 tbuf,
954 ri->is_running ? "Running " : "",
955 ri->is_valid ? "Valid " : "",
956 ri->is_hibernating ? "Hibernating " : "",
957 ri->uptime);
958 tor_free(ip);
959 } else {
960 tor_snprintf(header_buf, sizeof(header_buf),
961 "router %s {no descriptor}\n", dbuf);
963 smartlist_add(chunks, tor_strdup(header_buf));
964 info = rep_hist_format_router_status(hist, now);
965 if (info)
966 smartlist_add(chunks, info);
968 } DIGESTMAP_FOREACH_END;
970 result = smartlist_join_strings(chunks, "", 0, NULL);
971 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
972 smartlist_free(chunks);
974 last_stability_doc = result;
975 built_last_stability_doc_at = time(NULL);
976 return result;
979 /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
980 * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
981 * such line exists. */
982 static int
983 find_next_with(smartlist_t *sl, int i, const char *prefix)
985 for ( ; i < smartlist_len(sl); ++i) {
986 const char *line = smartlist_get(sl, i);
987 if (!strcmpstart(line, prefix))
988 return i;
989 if (!strcmpstart(line, "R "))
990 return -1;
992 return -1;
995 /** How many bad times has parse_possibly_bad_iso_time parsed? */
996 static int n_bogus_times = 0;
997 /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
998 * rounds any pre-1970 date to Jan 1, 1970. */
999 static int
1000 parse_possibly_bad_iso_time(const char *s, time_t *time_out)
1002 int year;
1003 char b[5];
1004 strlcpy(b, s, sizeof(b));
1005 b[4] = '\0';
1006 year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
1007 if (year < 1970) {
1008 *time_out = 0;
1009 ++n_bogus_times;
1010 return 0;
1011 } else
1012 return parse_iso_time(s, time_out);
1015 /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
1016 * says we started measuring at <b>started_measuring</b>. Return a new number
1017 * that's about as much before <b>now</b> as <b>t</b> was before
1018 * <b>stored_at</b>.
1020 static INLINE time_t
1021 correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
1023 if (t < started_measuring - 24*60*60*365)
1024 return 0;
1025 else if (t < started_measuring)
1026 return started_measuring;
1027 else if (t > stored_at)
1028 return 0;
1029 else {
1030 long run_length = stored_at - t;
1031 t = now - run_length;
1032 if (t < started_measuring)
1033 t = started_measuring;
1034 return t;
1038 /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
1039 * on failure. */
1041 rep_hist_load_mtbf_data(time_t now)
1043 /* XXXX won't handle being called while history is already populated. */
1044 smartlist_t *lines;
1045 const char *line = NULL;
1046 int r=0, i;
1047 time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
1048 time_t latest_possible_start = now;
1049 long format = -1;
1052 char *filename = get_datadir_fname("router-stability");
1053 char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1054 tor_free(filename);
1055 if (!d)
1056 return -1;
1057 lines = smartlist_create();
1058 smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
1059 tor_free(d);
1063 const char *firstline;
1064 if (smartlist_len(lines)>4) {
1065 firstline = smartlist_get(lines, 0);
1066 if (!strcmpstart(firstline, "format "))
1067 format = tor_parse_long(firstline+strlen("format "),
1068 10, -1, LONG_MAX, NULL, NULL);
1071 if (format != 1 && format != 2) {
1072 log_warn(LD_HIST,
1073 "Unrecognized format in mtbf history file. Skipping.");
1074 goto err;
1076 for (i = 1; i < smartlist_len(lines); ++i) {
1077 line = smartlist_get(lines, i);
1078 if (!strcmp(line, "data"))
1079 break;
1080 if (!strcmpstart(line, "last-downrated ")) {
1081 if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
1082 log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
1083 "history file.");
1085 if (!strcmpstart(line, "stored-at ")) {
1086 if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
1087 log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
1088 "history file.");
1090 if (!strcmpstart(line, "tracked-since ")) {
1091 if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
1092 log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
1093 "history file.");
1096 if (last_downrated > now)
1097 last_downrated = now;
1098 if (tracked_since > now)
1099 tracked_since = now;
1101 if (!stored_at) {
1102 log_warn(LD_HIST, "No stored time recorded.");
1103 goto err;
1106 if (line && !strcmp(line, "data"))
1107 ++i;
1109 n_bogus_times = 0;
1111 for (; i < smartlist_len(lines); ++i) {
1112 char digest[DIGEST_LEN];
1113 char hexbuf[HEX_DIGEST_LEN+1];
1114 char mtbf_timebuf[ISO_TIME_LEN+1];
1115 char wfu_timebuf[ISO_TIME_LEN+1];
1116 time_t start_of_run = 0;
1117 time_t start_of_downtime = 0;
1118 int have_mtbf = 0, have_wfu = 0;
1119 long wrl = 0;
1120 double trw = 0;
1121 long wt_uptime = 0, total_wt_time = 0;
1122 int n;
1123 or_history_t *hist;
1124 line = smartlist_get(lines, i);
1125 if (!strcmp(line, "."))
1126 break;
1128 mtbf_timebuf[0] = '\0';
1129 wfu_timebuf[0] = '\0';
1131 if (format == 1) {
1132 n = sscanf(line, "%40s %ld %lf S=%10s %8s",
1133 hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1134 if (n != 3 && n != 5) {
1135 log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
1136 continue;
1138 have_mtbf = 1;
1139 } else {
1140 // format == 2.
1141 int mtbf_idx, wfu_idx;
1142 if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
1143 continue;
1144 strlcpy(hexbuf, line+2, sizeof(hexbuf));
1145 mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
1146 wfu_idx = find_next_with(lines, i+1, "+WFU ");
1147 if (mtbf_idx >= 0) {
1148 const char *mtbfline = smartlist_get(lines, mtbf_idx);
1149 n = sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
1150 &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1151 if (n == 2 || n == 4) {
1152 have_mtbf = 1;
1153 } else {
1154 log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
1155 escaped(mtbfline));
1158 if (wfu_idx >= 0) {
1159 const char *wfuline = smartlist_get(lines, wfu_idx);
1160 n = sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
1161 &wt_uptime, &total_wt_time,
1162 wfu_timebuf, wfu_timebuf+11);
1163 if (n == 2 || n == 4) {
1164 have_wfu = 1;
1165 } else {
1166 log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
1169 if (wfu_idx > i)
1170 i = wfu_idx;
1171 if (mtbf_idx > i)
1172 i = mtbf_idx;
1174 if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
1175 log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
1176 continue;
1178 hist = get_or_history(digest);
1179 if (!hist)
1180 continue;
1182 if (have_mtbf) {
1183 if (mtbf_timebuf[0]) {
1184 mtbf_timebuf[10] = ' ';
1185 if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
1186 log_warn(LD_HIST, "Couldn't parse time %s",
1187 escaped(mtbf_timebuf));
1189 hist->start_of_run = correct_time(start_of_run, now, stored_at,
1190 tracked_since);
1191 if (hist->start_of_run < latest_possible_start + wrl)
1192 latest_possible_start = hist->start_of_run - wrl;
1194 hist->weighted_run_length = wrl;
1195 hist->total_run_weights = trw;
1197 if (have_wfu) {
1198 if (wfu_timebuf[0]) {
1199 wfu_timebuf[10] = ' ';
1200 if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
1201 log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
1204 hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
1205 tracked_since);
1206 hist->weighted_uptime = wt_uptime;
1207 hist->total_weighted_time = total_wt_time;
1209 if (strcmp(line, "."))
1210 log_warn(LD_HIST, "Truncated MTBF file.");
1212 if (tracked_since < 86400*365) /* Recover from insanely early value. */
1213 tracked_since = latest_possible_start;
1215 stability_last_downrated = last_downrated;
1216 started_tracking_stability = tracked_since;
1218 goto done;
1219 err:
1220 r = -1;
1221 done:
1222 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1223 smartlist_free(lines);
1224 return r;
1227 /** For how many seconds do we keep track of individual per-second bandwidth
1228 * totals? */
1229 #define NUM_SECS_ROLLING_MEASURE 10
1230 /** How large are the intervals for which we track and report bandwidth use? */
1231 /* XXXX Watch out! Before Tor 0.2.2.21-alpha, using any other value here would
1232 * generate an unparseable state file. */
1233 #define NUM_SECS_BW_SUM_INTERVAL (15*60)
1234 /** How far in the past do we remember and publish bandwidth use? */
1235 #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
1236 /** How many bandwidth usage intervals do we remember? (derived) */
1237 #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
1239 /** Structure to track bandwidth use, and remember the maxima for a given
1240 * time period.
1242 typedef struct bw_array_t {
1243 /** Observation array: Total number of bytes transferred in each of the last
1244 * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
1245 uint64_t obs[NUM_SECS_ROLLING_MEASURE];
1246 int cur_obs_idx; /**< Current position in obs. */
1247 time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
1248 uint64_t total_obs; /**< Total for all members of obs except
1249 * obs[cur_obs_idx] */
1250 uint64_t max_total; /**< Largest value that total_obs has taken on in the
1251 * current period. */
1252 uint64_t total_in_period; /**< Total bytes transferred in the current
1253 * period. */
1255 /** When does the next period begin? */
1256 time_t next_period;
1257 /** Where in 'maxima' should the maximum bandwidth usage for the current
1258 * period be stored? */
1259 int next_max_idx;
1260 /** How many values in maxima/totals have been set ever? */
1261 int num_maxes_set;
1262 /** Circular array of the maximum
1263 * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
1264 * NUM_TOTALS periods */
1265 uint64_t maxima[NUM_TOTALS];
1266 /** Circular array of the total bandwidth usage for the last NUM_TOTALS
1267 * periods */
1268 uint64_t totals[NUM_TOTALS];
1269 } bw_array_t;
1271 /** Shift the current period of b forward by one. */
1272 static void
1273 commit_max(bw_array_t *b)
1275 /* Store total from current period. */
1276 b->totals[b->next_max_idx] = b->total_in_period;
1277 /* Store maximum from current period. */
1278 b->maxima[b->next_max_idx++] = b->max_total;
1279 /* Advance next_period and next_max_idx */
1280 b->next_period += NUM_SECS_BW_SUM_INTERVAL;
1281 if (b->next_max_idx == NUM_TOTALS)
1282 b->next_max_idx = 0;
1283 if (b->num_maxes_set < NUM_TOTALS)
1284 ++b->num_maxes_set;
1285 /* Reset max_total. */
1286 b->max_total = 0;
1287 /* Reset total_in_period. */
1288 b->total_in_period = 0;
1291 /** Shift the current observation time of 'b' forward by one second. */
1292 static INLINE void
1293 advance_obs(bw_array_t *b)
1295 int nextidx;
1296 uint64_t total;
1298 /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
1299 * seconds; adjust max_total as needed.*/
1300 total = b->total_obs + b->obs[b->cur_obs_idx];
1301 if (total > b->max_total)
1302 b->max_total = total;
1304 nextidx = b->cur_obs_idx+1;
1305 if (nextidx == NUM_SECS_ROLLING_MEASURE)
1306 nextidx = 0;
1308 b->total_obs = total - b->obs[nextidx];
1309 b->obs[nextidx]=0;
1310 b->cur_obs_idx = nextidx;
1312 if (++b->cur_obs_time >= b->next_period)
1313 commit_max(b);
1316 /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
1317 * <b>when</b>. */
1318 static INLINE void
1319 add_obs(bw_array_t *b, time_t when, uint64_t n)
1321 /* Don't record data in the past. */
1322 if (when<b->cur_obs_time)
1323 return;
1324 /* If we're currently adding observations for an earlier second than
1325 * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
1326 * appropriate number of seconds, and do all the other housekeeping */
1327 while (when>b->cur_obs_time) {
1328 /* Doing this one second at a time is potentially inefficient, if we start
1329 with a state file that is very old. Fortunately, it doesn't seem to
1330 show up in profiles, so we can just ignore it for now. */
1331 advance_obs(b);
1334 b->obs[b->cur_obs_idx] += n;
1335 b->total_in_period += n;
1338 /** Allocate, initialize, and return a new bw_array. */
1339 static bw_array_t *
1340 bw_array_new(void)
1342 bw_array_t *b;
1343 time_t start;
1344 b = tor_malloc_zero(sizeof(bw_array_t));
1345 rephist_total_alloc += sizeof(bw_array_t);
1346 start = time(NULL);
1347 b->cur_obs_time = start;
1348 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1349 return b;
1352 /** Recent history of bandwidth observations for read operations. */
1353 static bw_array_t *read_array = NULL;
1354 /** Recent history of bandwidth observations for write operations. */
1355 static bw_array_t *write_array = NULL;
1356 /** Recent history of bandwidth observations for read operations for the
1357 directory protocol. */
1358 static bw_array_t *dir_read_array = NULL;
1359 /** Recent history of bandwidth observations for write operations for the
1360 directory protocol. */
1361 static bw_array_t *dir_write_array = NULL;
1363 /** Set up [dir-]read_array and [dir-]write_array, freeing them if they
1364 * already exist. */
1365 static void
1366 bw_arrays_init(void)
1368 tor_free(read_array);
1369 tor_free(write_array);
1370 tor_free(dir_read_array);
1371 tor_free(dir_write_array);
1372 read_array = bw_array_new();
1373 write_array = bw_array_new();
1374 dir_read_array = bw_array_new();
1375 dir_write_array = bw_array_new();
1378 /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
1380 * Add num_bytes to the current running total for <b>when</b>.
1382 * <b>when</b> can go back to time, but it's safe to ignore calls
1383 * earlier than the latest <b>when</b> you've heard of.
1385 void
1386 rep_hist_note_bytes_written(size_t num_bytes, time_t when)
1388 /* Maybe a circular array for recent seconds, and step to a new point
1389 * every time a new second shows up. Or simpler is to just to have
1390 * a normal array and push down each item every second; it's short.
1392 /* When a new second has rolled over, compute the sum of the bytes we've
1393 * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
1394 * somewhere. See rep_hist_bandwidth_assess() below.
1396 add_obs(write_array, when, num_bytes);
1399 /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
1400 * (like rep_hist_note_bytes_written() above)
1402 void
1403 rep_hist_note_bytes_read(size_t num_bytes, time_t when)
1405 /* if we're smart, we can make this func and the one above share code */
1406 add_obs(read_array, when, num_bytes);
1409 /** We wrote <b>num_bytes</b> more directory bytes in second <b>when</b>.
1410 * (like rep_hist_note_bytes_written() above)
1412 void
1413 rep_hist_note_dir_bytes_written(size_t num_bytes, time_t when)
1415 add_obs(dir_write_array, when, num_bytes);
1418 /** We read <b>num_bytes</b> more directory bytes in second <b>when</b>.
1419 * (like rep_hist_note_bytes_written() above)
1421 void
1422 rep_hist_note_dir_bytes_read(size_t num_bytes, time_t when)
1424 add_obs(dir_read_array, when, num_bytes);
1427 /** Helper: Return the largest value in b->maxima. (This is equal to the
1428 * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
1429 * NUM_SECS_BW_SUM_IS_VALID seconds.)
1431 static uint64_t
1432 find_largest_max(bw_array_t *b)
1434 int i;
1435 uint64_t max;
1436 max=0;
1437 for (i=0; i<NUM_TOTALS; ++i) {
1438 if (b->maxima[i]>max)
1439 max = b->maxima[i];
1441 return max;
1444 /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
1445 * seconds. Find one sum for reading and one for writing. They don't have
1446 * to be at the same time.
1448 * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
1451 rep_hist_bandwidth_assess(void)
1453 uint64_t w,r;
1454 r = find_largest_max(read_array);
1455 w = find_largest_max(write_array);
1456 if (r>w)
1457 return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
1458 else
1459 return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
1462 /** Print the bandwidth history of b (either [dir-]read_array or
1463 * [dir-]write_array) into the buffer pointed to by buf. The format is
1464 * simply comma separated numbers, from oldest to newest.
1466 * It returns the number of bytes written.
1468 static size_t
1469 rep_hist_fill_bandwidth_history(char *buf, size_t len, const bw_array_t *b)
1471 char *cp = buf;
1472 int i, n;
1473 or_options_t *options = get_options();
1474 uint64_t cutoff;
1476 if (b->num_maxes_set <= b->next_max_idx) {
1477 /* We haven't been through the circular array yet; time starts at i=0.*/
1478 i = 0;
1479 } else {
1480 /* We've been around the array at least once. The next i to be
1481 overwritten is the oldest. */
1482 i = b->next_max_idx;
1485 if (options->RelayBandwidthRate) {
1486 /* We don't want to report that we used more bandwidth than the max we're
1487 * willing to relay; otherwise everybody will know how much traffic
1488 * we used ourself. */
1489 cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
1490 } else {
1491 cutoff = UINT64_MAX;
1494 for (n=0; n<b->num_maxes_set; ++n,++i) {
1495 uint64_t total;
1496 if (i >= NUM_TOTALS)
1497 i -= NUM_TOTALS;
1498 tor_assert(i < NUM_TOTALS);
1499 /* Round the bandwidth used down to the nearest 1k. */
1500 total = b->totals[i] & ~0x3ff;
1501 if (total > cutoff)
1502 total = cutoff;
1504 if (n==(b->num_maxes_set-1))
1505 tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
1506 else
1507 tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
1508 cp += strlen(cp);
1510 return cp-buf;
1513 /** Allocate and return lines for representing this server's bandwidth
1514 * history in its descriptor.
1516 char *
1517 rep_hist_get_bandwidth_lines(void)
1519 char *buf, *cp;
1520 char t[ISO_TIME_LEN+1];
1521 int r;
1522 bw_array_t *b = NULL;
1523 const char *desc = NULL;
1524 size_t len;
1526 /* opt [dirreq-](read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n... */
1527 len = (67+21*NUM_TOTALS)*4;
1528 buf = tor_malloc_zero(len);
1529 cp = buf;
1530 for (r=0;r<4;++r) {
1531 switch (r) {
1532 case 0:
1533 b = write_array;
1534 desc = "write-history";
1535 break;
1536 case 1:
1537 b = read_array;
1538 desc = "read-history";
1539 break;
1540 case 2:
1541 b = dir_write_array;
1542 desc = "dirreq-write-history";
1543 break;
1544 case 3:
1545 b = dir_read_array;
1546 desc = "dirreq-read-history";
1547 break;
1549 tor_assert(b);
1550 format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
1551 tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ",
1552 desc, t, NUM_SECS_BW_SUM_INTERVAL);
1553 cp += strlen(cp);
1554 cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
1555 strlcat(cp, "\n", len-(cp-buf));
1556 ++cp;
1558 return buf;
1561 /** Write a single bw_array_t into the Values, Ends, Interval, and Maximum
1562 * entries of an or_state_t. */
1563 static void
1564 rep_hist_update_bwhist_state_section(or_state_t *state,
1565 const bw_array_t *b,
1566 smartlist_t **s_values,
1567 smartlist_t **s_maxima,
1568 time_t *s_begins,
1569 int *s_interval)
1571 char *cp;
1572 int i,j;
1574 if (*s_values) {
1575 SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
1576 smartlist_free(*s_values);
1578 if (*s_maxima) {
1579 SMARTLIST_FOREACH(*s_maxima, char *, val, tor_free(val));
1580 smartlist_free(*s_maxima);
1582 if (! server_mode(get_options())) {
1583 /* Clients don't need to store bandwidth history persistently;
1584 * force these values to the defaults. */
1585 /* FFFF we should pull the default out of config.c's state table,
1586 * so we don't have two defaults. */
1587 if (*s_begins != 0 || *s_interval != 900) {
1588 time_t now = time(NULL);
1589 time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
1590 or_state_mark_dirty(state, save_at);
1592 *s_begins = 0;
1593 *s_interval = 900;
1594 *s_values = smartlist_create();
1595 *s_maxima = smartlist_create();
1596 return;
1598 *s_begins = b->next_period;
1599 *s_interval = NUM_SECS_BW_SUM_INTERVAL;
1601 *s_values = smartlist_create();
1602 *s_maxima = smartlist_create();
1603 /* Set i to first position in circular array */
1604 i = (b->num_maxes_set <= b->next_max_idx) ? 0 : b->next_max_idx;
1605 for (j=0; j < b->num_maxes_set; ++j,++i) {
1606 uint64_t maxval;
1607 if (i >= NUM_TOTALS)
1608 i = 0;
1609 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(b->totals[i] & ~0x3ff));
1610 smartlist_add(*s_values, cp);
1611 maxval = b->maxima[i] / NUM_SECS_ROLLING_MEASURE;
1612 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(maxval & ~0x3ff));
1613 smartlist_add(*s_maxima, cp);
1615 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(b->total_in_period & ~0x3ff));
1616 smartlist_add(*s_values, cp);
1617 tor_asprintf(&cp, U64_FORMAT, U64_PRINTF_ARG(b->max_total & ~0x3ff));
1618 smartlist_add(*s_maxima, cp);
1621 /** Update <b>state</b> with the newest bandwidth history. */
1622 void
1623 rep_hist_update_state(or_state_t *state)
1625 #define UPDATE(arrname,st) \
1626 rep_hist_update_bwhist_state_section(state,\
1627 (arrname),\
1628 &state->BWHistory ## st ## Values, \
1629 &state->BWHistory ## st ## Maxima, \
1630 &state->BWHistory ## st ## Ends, \
1631 &state->BWHistory ## st ## Interval)
1633 UPDATE(write_array, Write);
1634 UPDATE(read_array, Read);
1635 UPDATE(dir_write_array, DirWrite);
1636 UPDATE(dir_read_array, DirRead);
1638 if (server_mode(get_options())) {
1639 or_state_mark_dirty(state, time(NULL)+(2*3600));
1641 #undef UPDATE
1644 /** Load a single bw_array_t from its Values, Ends, Maxima, and Interval
1645 * entries in an or_state_t. */
1646 static int
1647 rep_hist_load_bwhist_state_section(bw_array_t *b,
1648 const smartlist_t *s_values,
1649 const smartlist_t *s_maxima,
1650 const time_t s_begins,
1651 const int s_interval)
1653 time_t now = time(NULL);
1654 int retval = 0;
1655 time_t start;
1657 uint64_t v, mv;
1658 int i,ok,ok_m;
1659 int have_maxima = (smartlist_len(s_values) == smartlist_len(s_maxima));
1661 if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
1662 start = s_begins - s_interval*(smartlist_len(s_values));
1663 if (start > now)
1664 return 0;
1665 b->cur_obs_time = start;
1666 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1667 SMARTLIST_FOREACH_BEGIN(s_values, const char *, cp) {
1668 const char *maxstr = NULL;
1669 v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
1670 if (have_maxima) {
1671 maxstr = smartlist_get(s_maxima, cp_sl_idx);
1672 mv = tor_parse_uint64(maxstr, 10, 0, UINT64_MAX, &ok_m, NULL);
1673 mv *= NUM_SECS_ROLLING_MEASURE;
1674 } else {
1675 /* No maxima known; guess average rate to be conservative. */
1676 mv = v / s_interval;
1678 if (!ok) {
1679 retval = -1;
1680 log_notice(LD_HIST, "Could not parse value '%s' into a number.'",cp);
1682 if (maxstr && !ok_m) {
1683 retval = -1;
1684 log_notice(LD_HIST, "Could not parse maximum '%s' into a number.'",
1685 maxstr);
1688 if (start < now) {
1689 add_obs(b, start, v);
1690 b->max_total = mv;
1691 /* This will result in some fairly choppy history if s_interval
1692 * is notthe same as NUM_SECS_BW_SUM_INTERVAL. XXXX */
1693 start += s_interval;
1695 } SMARTLIST_FOREACH_END(cp);
1698 /* Clean up maxima and observed */
1699 for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
1700 b->obs[i] = 0;
1702 b->total_obs = 0;
1704 return retval;
1707 /** Set bandwidth history from our saved state. */
1709 rep_hist_load_state(or_state_t *state, char **err)
1711 int all_ok = 1;
1713 /* Assert they already have been malloced */
1714 tor_assert(read_array && write_array);
1715 tor_assert(dir_read_array && dir_write_array);
1717 #define LOAD(arrname,st) \
1718 if (rep_hist_load_bwhist_state_section( \
1719 (arrname), \
1720 state->BWHistory ## st ## Values, \
1721 state->BWHistory ## st ## Maxima, \
1722 state->BWHistory ## st ## Ends, \
1723 state->BWHistory ## st ## Interval)<0) \
1724 all_ok = 0
1726 LOAD(write_array, Write);
1727 LOAD(read_array, Read);
1728 LOAD(dir_write_array, DirWrite);
1729 LOAD(dir_read_array, DirRead);
1731 #undef LOAD
1732 if (!all_ok) {
1733 *err = tor_strdup("Parsing of bandwidth history values failed");
1734 /* and create fresh arrays */
1735 bw_arrays_init();
1736 return -1;
1738 return 0;
1741 /*********************************************************************/
1743 /** A list of port numbers that have been used recently. */
1744 static smartlist_t *predicted_ports_list=NULL;
1745 /** The corresponding most recently used time for each port. */
1746 static smartlist_t *predicted_ports_times=NULL;
1748 /** We just got an application request for a connection with
1749 * port <b>port</b>. Remember it for the future, so we can keep
1750 * some circuits open that will exit to this port.
1752 static void
1753 add_predicted_port(time_t now, uint16_t port)
1755 /* XXXX we could just use uintptr_t here, I think. */
1756 uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
1757 time_t *tmp_time = tor_malloc(sizeof(time_t));
1758 *tmp_port = port;
1759 *tmp_time = now;
1760 rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
1761 smartlist_add(predicted_ports_list, tmp_port);
1762 smartlist_add(predicted_ports_times, tmp_time);
1765 /** Initialize whatever memory and structs are needed for predicting
1766 * which ports will be used. Also seed it with port 80, so we'll build
1767 * circuits on start-up.
1769 static void
1770 predicted_ports_init(void)
1772 predicted_ports_list = smartlist_create();
1773 predicted_ports_times = smartlist_create();
1774 add_predicted_port(time(NULL), 80); /* add one to kickstart us */
1777 /** Free whatever memory is needed for predicting which ports will
1778 * be used.
1780 static void
1781 predicted_ports_free(void)
1783 rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
1784 SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
1785 smartlist_free(predicted_ports_list);
1786 rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
1787 SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
1788 smartlist_free(predicted_ports_times);
1791 /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
1792 * This is used for predicting what sorts of streams we'll make in the
1793 * future and making exit circuits to anticipate that.
1795 void
1796 rep_hist_note_used_port(time_t now, uint16_t port)
1798 int i;
1799 uint16_t *tmp_port;
1800 time_t *tmp_time;
1802 tor_assert(predicted_ports_list);
1803 tor_assert(predicted_ports_times);
1805 if (!port) /* record nothing */
1806 return;
1808 for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
1809 tmp_port = smartlist_get(predicted_ports_list, i);
1810 tmp_time = smartlist_get(predicted_ports_times, i);
1811 if (*tmp_port == port) {
1812 *tmp_time = now;
1813 return;
1816 /* it's not there yet; we need to add it */
1817 add_predicted_port(now, port);
1820 /** For this long after we've seen a request for a given port, assume that
1821 * we'll want to make connections to the same port in the future. */
1822 #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
1824 /** Return a pointer to the list of port numbers that
1825 * are likely to be asked for in the near future.
1827 * The caller promises not to mess with it.
1829 smartlist_t *
1830 rep_hist_get_predicted_ports(time_t now)
1832 int i;
1833 uint16_t *tmp_port;
1834 time_t *tmp_time;
1836 tor_assert(predicted_ports_list);
1837 tor_assert(predicted_ports_times);
1839 /* clean out obsolete entries */
1840 for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
1841 tmp_time = smartlist_get(predicted_ports_times, i);
1842 if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
1843 tmp_port = smartlist_get(predicted_ports_list, i);
1844 log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
1845 smartlist_del(predicted_ports_list, i);
1846 smartlist_del(predicted_ports_times, i);
1847 rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
1848 tor_free(tmp_port);
1849 tor_free(tmp_time);
1850 i--;
1853 return predicted_ports_list;
1856 /** The user asked us to do a resolve. Rather than keeping track of
1857 * timings and such of resolves, we fake it for now by treating
1858 * it the same way as a connection to port 80. This way we will continue
1859 * to have circuits lying around if the user only uses Tor for resolves.
1861 void
1862 rep_hist_note_used_resolve(time_t now)
1864 rep_hist_note_used_port(now, 80);
1867 /** The last time at which we needed an internal circ. */
1868 static time_t predicted_internal_time = 0;
1869 /** The last time we needed an internal circ with good uptime. */
1870 static time_t predicted_internal_uptime_time = 0;
1871 /** The last time we needed an internal circ with good capacity. */
1872 static time_t predicted_internal_capacity_time = 0;
1874 /** Remember that we used an internal circ at time <b>now</b>. */
1875 void
1876 rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
1878 predicted_internal_time = now;
1879 if (need_uptime)
1880 predicted_internal_uptime_time = now;
1881 if (need_capacity)
1882 predicted_internal_capacity_time = now;
1885 /** Return 1 if we've used an internal circ recently; else return 0. */
1887 rep_hist_get_predicted_internal(time_t now, int *need_uptime,
1888 int *need_capacity)
1890 if (!predicted_internal_time) { /* initialize it */
1891 predicted_internal_time = now;
1892 predicted_internal_uptime_time = now;
1893 predicted_internal_capacity_time = now;
1895 if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
1896 return 0; /* too long ago */
1897 if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
1898 *need_uptime = 1;
1899 // Always predict that we need capacity.
1900 *need_capacity = 1;
1901 return 1;
1904 /** Any ports used lately? These are pre-seeded if we just started
1905 * up or if we're running a hidden service. */
1907 any_predicted_circuits(time_t now)
1909 return smartlist_len(predicted_ports_list) ||
1910 predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now;
1913 /** Return 1 if we have no need for circuits currently, else return 0. */
1915 rep_hist_circbuilding_dormant(time_t now)
1917 if (any_predicted_circuits(now))
1918 return 0;
1920 /* see if we'll still need to build testing circuits */
1921 if (server_mode(get_options()) &&
1922 (!check_whether_orport_reachable() || !circuit_enough_testing_circs()))
1923 return 0;
1924 if (!check_whether_dirport_reachable())
1925 return 0;
1927 return 1;
1930 /** Structure to track how many times we've done each public key operation. */
1931 static struct {
1932 /** How many directory objects have we signed? */
1933 unsigned long n_signed_dir_objs;
1934 /** How many routerdescs have we signed? */
1935 unsigned long n_signed_routerdescs;
1936 /** How many directory objects have we verified? */
1937 unsigned long n_verified_dir_objs;
1938 /** How many routerdescs have we verified */
1939 unsigned long n_verified_routerdescs;
1940 /** How many onionskins have we encrypted to build circuits? */
1941 unsigned long n_onionskins_encrypted;
1942 /** How many onionskins have we decrypted to do circuit build requests? */
1943 unsigned long n_onionskins_decrypted;
1944 /** How many times have we done the TLS handshake as a client? */
1945 unsigned long n_tls_client_handshakes;
1946 /** How many times have we done the TLS handshake as a server? */
1947 unsigned long n_tls_server_handshakes;
1948 /** How many PK operations have we done as a hidden service client? */
1949 unsigned long n_rend_client_ops;
1950 /** How many PK operations have we done as a hidden service midpoint? */
1951 unsigned long n_rend_mid_ops;
1952 /** How many PK operations have we done as a hidden service provider? */
1953 unsigned long n_rend_server_ops;
1954 } pk_op_counts = {0,0,0,0,0,0,0,0,0,0,0};
1956 /** Increment the count of the number of times we've done <b>operation</b>. */
1957 void
1958 note_crypto_pk_op(pk_op_t operation)
1960 switch (operation)
1962 case SIGN_DIR:
1963 pk_op_counts.n_signed_dir_objs++;
1964 break;
1965 case SIGN_RTR:
1966 pk_op_counts.n_signed_routerdescs++;
1967 break;
1968 case VERIFY_DIR:
1969 pk_op_counts.n_verified_dir_objs++;
1970 break;
1971 case VERIFY_RTR:
1972 pk_op_counts.n_verified_routerdescs++;
1973 break;
1974 case ENC_ONIONSKIN:
1975 pk_op_counts.n_onionskins_encrypted++;
1976 break;
1977 case DEC_ONIONSKIN:
1978 pk_op_counts.n_onionskins_decrypted++;
1979 break;
1980 case TLS_HANDSHAKE_C:
1981 pk_op_counts.n_tls_client_handshakes++;
1982 break;
1983 case TLS_HANDSHAKE_S:
1984 pk_op_counts.n_tls_server_handshakes++;
1985 break;
1986 case REND_CLIENT:
1987 pk_op_counts.n_rend_client_ops++;
1988 break;
1989 case REND_MID:
1990 pk_op_counts.n_rend_mid_ops++;
1991 break;
1992 case REND_SERVER:
1993 pk_op_counts.n_rend_server_ops++;
1994 break;
1995 default:
1996 log_warn(LD_BUG, "Unknown pk operation %d", operation);
2000 /** Log the number of times we've done each public/private-key operation. */
2001 void
2002 dump_pk_ops(int severity)
2004 log(severity, LD_HIST,
2005 "PK operations: %lu directory objects signed, "
2006 "%lu directory objects verified, "
2007 "%lu routerdescs signed, "
2008 "%lu routerdescs verified, "
2009 "%lu onionskins encrypted, "
2010 "%lu onionskins decrypted, "
2011 "%lu client-side TLS handshakes, "
2012 "%lu server-side TLS handshakes, "
2013 "%lu rendezvous client operations, "
2014 "%lu rendezvous middle operations, "
2015 "%lu rendezvous server operations.",
2016 pk_op_counts.n_signed_dir_objs,
2017 pk_op_counts.n_verified_dir_objs,
2018 pk_op_counts.n_signed_routerdescs,
2019 pk_op_counts.n_verified_routerdescs,
2020 pk_op_counts.n_onionskins_encrypted,
2021 pk_op_counts.n_onionskins_decrypted,
2022 pk_op_counts.n_tls_client_handshakes,
2023 pk_op_counts.n_tls_server_handshakes,
2024 pk_op_counts.n_rend_client_ops,
2025 pk_op_counts.n_rend_mid_ops,
2026 pk_op_counts.n_rend_server_ops);
2029 /*** Exit port statistics ***/
2031 /* Some constants */
2032 /** To what multiple should byte numbers be rounded up? */
2033 #define EXIT_STATS_ROUND_UP_BYTES 1024
2034 /** To what multiple should stream counts be rounded up? */
2035 #define EXIT_STATS_ROUND_UP_STREAMS 4
2036 /** Number of TCP ports */
2037 #define EXIT_STATS_NUM_PORTS 65536
2038 /** Top n ports that will be included in exit stats. */
2039 #define EXIT_STATS_TOP_N_PORTS 10
2041 /* The following data structures are arrays and no fancy smartlists or maps,
2042 * so that all write operations can be done in constant time. This comes at
2043 * the price of some memory (1.25 MB) and linear complexity when writing
2044 * stats for measuring relays. */
2045 /** Number of bytes read in current period by exit port */
2046 static uint64_t *exit_bytes_read = NULL;
2047 /** Number of bytes written in current period by exit port */
2048 static uint64_t *exit_bytes_written = NULL;
2049 /** Number of streams opened in current period by exit port */
2050 static uint32_t *exit_streams = NULL;
2052 /** Start time of exit stats or 0 if we're not collecting exit stats. */
2053 static time_t start_of_exit_stats_interval;
2055 /** Initialize exit port stats. */
2056 void
2057 rep_hist_exit_stats_init(time_t now)
2059 start_of_exit_stats_interval = now;
2060 exit_bytes_read = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2061 sizeof(uint64_t));
2062 exit_bytes_written = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2063 sizeof(uint64_t));
2064 exit_streams = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2065 sizeof(uint32_t));
2068 /** Reset counters for exit port statistics. */
2069 void
2070 rep_hist_reset_exit_stats(time_t now)
2072 start_of_exit_stats_interval = now;
2073 memset(exit_bytes_read, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2074 memset(exit_bytes_written, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2075 memset(exit_streams, 0, EXIT_STATS_NUM_PORTS * sizeof(uint32_t));
2078 /** Stop collecting exit port stats in a way that we can re-start doing
2079 * so in rep_hist_exit_stats_init(). */
2080 void
2081 rep_hist_exit_stats_term(void)
2083 start_of_exit_stats_interval = 0;
2084 tor_free(exit_bytes_read);
2085 tor_free(exit_bytes_written);
2086 tor_free(exit_streams);
2089 /** Helper for qsort: compare two ints. */
2090 static int
2091 _compare_int(const void *x, const void *y)
2093 return (*(int*)x - *(int*)y);
2096 /** Return a newly allocated string containing the exit port statistics
2097 * until <b>now</b>, or NULL if we're not collecting exit stats. */
2098 char *
2099 rep_hist_format_exit_stats(time_t now)
2101 int i, j, top_elements = 0, cur_min_idx = 0, cur_port;
2102 uint64_t top_bytes[EXIT_STATS_TOP_N_PORTS];
2103 int top_ports[EXIT_STATS_TOP_N_PORTS];
2104 uint64_t cur_bytes = 0, other_read = 0, other_written = 0,
2105 total_read = 0, total_written = 0;
2106 uint32_t total_streams = 0, other_streams = 0;
2107 char *buf;
2108 smartlist_t *written_strings, *read_strings, *streams_strings;
2109 char *written_string, *read_string, *streams_string;
2110 char t[ISO_TIME_LEN+1];
2111 char *result;
2113 if (!start_of_exit_stats_interval)
2114 return NULL; /* Not initialized. */
2116 /* Go through all ports to find the n ports that saw most written and
2117 * read bytes.
2119 * Invariant: at the end of the loop for iteration i,
2120 * total_read is the sum of all exit_bytes_read[0..i]
2121 * total_written is the sum of all exit_bytes_written[0..i]
2122 * total_stream is the sum of all exit_streams[0..i]
2124 * top_elements = MAX(EXIT_STATS_TOP_N_PORTS,
2125 * #{j | 0 <= j <= i && volume(i) > 0})
2127 * For all 0 <= j < top_elements,
2128 * top_bytes[j] > 0
2129 * 0 <= top_ports[j] <= 65535
2130 * top_bytes[j] = volume(top_ports[j])
2132 * There is no j in 0..i and k in 0..top_elements such that:
2133 * volume(j) > top_bytes[k] AND j is not in top_ports[0..top_elements]
2135 * There is no j!=cur_min_idx in 0..top_elements such that:
2136 * top_bytes[j] < top_bytes[cur_min_idx]
2138 * where volume(x) == exit_bytes_read[x]+exit_bytes_written[x]
2140 * Worst case: O(EXIT_STATS_NUM_PORTS * EXIT_STATS_TOP_N_PORTS)
2142 for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
2143 total_read += exit_bytes_read[i];
2144 total_written += exit_bytes_written[i];
2145 total_streams += exit_streams[i];
2146 cur_bytes = exit_bytes_read[i] + exit_bytes_written[i];
2147 if (cur_bytes == 0) {
2148 continue;
2150 if (top_elements < EXIT_STATS_TOP_N_PORTS) {
2151 top_bytes[top_elements] = cur_bytes;
2152 top_ports[top_elements++] = i;
2153 } else if (cur_bytes > top_bytes[cur_min_idx]) {
2154 top_bytes[cur_min_idx] = cur_bytes;
2155 top_ports[cur_min_idx] = i;
2156 } else {
2157 continue;
2159 cur_min_idx = 0;
2160 for (j = 1; j < top_elements; j++) {
2161 if (top_bytes[j] < top_bytes[cur_min_idx]) {
2162 cur_min_idx = j;
2167 /* Add observations of top ports to smartlists. */
2168 written_strings = smartlist_create();
2169 read_strings = smartlist_create();
2170 streams_strings = smartlist_create();
2171 other_read = total_read;
2172 other_written = total_written;
2173 other_streams = total_streams;
2174 /* Sort the ports; this puts them out of sync with top_bytes, but we
2175 * won't be using top_bytes again anyway */
2176 qsort(top_ports, top_elements, sizeof(int), _compare_int);
2177 for (j = 0; j < top_elements; j++) {
2178 cur_port = top_ports[j];
2179 if (exit_bytes_written[cur_port] > 0) {
2180 uint64_t num = round_uint64_to_next_multiple_of(
2181 exit_bytes_written[cur_port],
2182 EXIT_STATS_ROUND_UP_BYTES);
2183 num /= 1024;
2184 buf = NULL;
2185 tor_asprintf(&buf, "%d="U64_FORMAT, cur_port, U64_PRINTF_ARG(num));
2186 smartlist_add(written_strings, buf);
2187 other_written -= exit_bytes_written[cur_port];
2189 if (exit_bytes_read[cur_port] > 0) {
2190 uint64_t num = round_uint64_to_next_multiple_of(
2191 exit_bytes_read[cur_port],
2192 EXIT_STATS_ROUND_UP_BYTES);
2193 num /= 1024;
2194 buf = NULL;
2195 tor_asprintf(&buf, "%d="U64_FORMAT, cur_port, U64_PRINTF_ARG(num));
2196 smartlist_add(read_strings, buf);
2197 other_read -= exit_bytes_read[cur_port];
2199 if (exit_streams[cur_port] > 0) {
2200 uint32_t num = round_uint32_to_next_multiple_of(
2201 exit_streams[cur_port],
2202 EXIT_STATS_ROUND_UP_STREAMS);
2203 buf = NULL;
2204 tor_asprintf(&buf, "%d=%u", cur_port, num);
2205 smartlist_add(streams_strings, buf);
2206 other_streams -= exit_streams[cur_port];
2210 /* Add observations of other ports in a single element. */
2211 other_written = round_uint64_to_next_multiple_of(other_written,
2212 EXIT_STATS_ROUND_UP_BYTES);
2213 other_written /= 1024;
2214 buf = NULL;
2215 tor_asprintf(&buf, "other="U64_FORMAT, U64_PRINTF_ARG(other_written));
2216 smartlist_add(written_strings, buf);
2217 other_read = round_uint64_to_next_multiple_of(other_read,
2218 EXIT_STATS_ROUND_UP_BYTES);
2219 other_read /= 1024;
2220 buf = NULL;
2221 tor_asprintf(&buf, "other="U64_FORMAT, U64_PRINTF_ARG(other_read));
2222 smartlist_add(read_strings, buf);
2223 other_streams = round_uint32_to_next_multiple_of(other_streams,
2224 EXIT_STATS_ROUND_UP_STREAMS);
2225 buf = NULL;
2226 tor_asprintf(&buf, "other=%u", other_streams);
2227 smartlist_add(streams_strings, buf);
2229 /* Join all observations in single strings. */
2230 written_string = smartlist_join_strings(written_strings, ",", 0, NULL);
2231 read_string = smartlist_join_strings(read_strings, ",", 0, NULL);
2232 streams_string = smartlist_join_strings(streams_strings, ",", 0, NULL);
2233 SMARTLIST_FOREACH(written_strings, char *, cp, tor_free(cp));
2234 SMARTLIST_FOREACH(read_strings, char *, cp, tor_free(cp));
2235 SMARTLIST_FOREACH(streams_strings, char *, cp, tor_free(cp));
2236 smartlist_free(written_strings);
2237 smartlist_free(read_strings);
2238 smartlist_free(streams_strings);
2240 /* Put everything together. */
2241 format_iso_time(t, now);
2242 tor_asprintf(&result, "exit-stats-end %s (%d s)\n"
2243 "exit-kibibytes-written %s\n"
2244 "exit-kibibytes-read %s\n"
2245 "exit-streams-opened %s\n",
2246 t, (unsigned) (now - start_of_exit_stats_interval),
2247 written_string,
2248 read_string,
2249 streams_string);
2250 tor_free(written_string);
2251 tor_free(read_string);
2252 tor_free(streams_string);
2253 return result;
2256 /** If 24 hours have passed since the beginning of the current exit port
2257 * stats period, write exit stats to $DATADIR/stats/exit-stats (possibly
2258 * overwriting an existing file) and reset counters. Return when we would
2259 * next want to write exit stats or 0 if we never want to write. */
2260 time_t
2261 rep_hist_exit_stats_write(time_t now)
2263 char *statsdir = NULL, *filename = NULL, *str = NULL;
2265 if (!start_of_exit_stats_interval)
2266 return 0; /* Not initialized. */
2267 if (start_of_exit_stats_interval + WRITE_STATS_INTERVAL > now)
2268 goto done; /* Not ready to write. */
2270 log_info(LD_HIST, "Writing exit port statistics to disk.");
2272 /* Generate history string. */
2273 str = rep_hist_format_exit_stats(now);
2275 /* Reset counters. */
2276 rep_hist_reset_exit_stats(now);
2278 /* Try to write to disk. */
2279 statsdir = get_datadir_fname("stats");
2280 if (check_private_dir(statsdir, CPD_CREATE) < 0) {
2281 log_warn(LD_HIST, "Unable to create stats/ directory!");
2282 goto done;
2284 filename = get_datadir_fname2("stats", "exit-stats");
2285 if (write_str_to_file(filename, str, 0) < 0)
2286 log_warn(LD_HIST, "Unable to write exit port statistics to disk!");
2288 done:
2289 tor_free(str);
2290 tor_free(statsdir);
2291 tor_free(filename);
2292 return start_of_exit_stats_interval + WRITE_STATS_INTERVAL;
2295 /** Note that we wrote <b>num_written</b> bytes and read <b>num_read</b>
2296 * bytes to/from an exit connection to <b>port</b>. */
2297 void
2298 rep_hist_note_exit_bytes(uint16_t port, size_t num_written,
2299 size_t num_read)
2301 if (!start_of_exit_stats_interval)
2302 return; /* Not initialized. */
2303 exit_bytes_written[port] += num_written;
2304 exit_bytes_read[port] += num_read;
2305 log_debug(LD_HIST, "Written %lu bytes and read %lu bytes to/from an "
2306 "exit connection to port %d.",
2307 (unsigned long)num_written, (unsigned long)num_read, port);
2310 /** Note that we opened an exit stream to <b>port</b>. */
2311 void
2312 rep_hist_note_exit_stream_opened(uint16_t port)
2314 if (!start_of_exit_stats_interval)
2315 return; /* Not initialized. */
2316 exit_streams[port]++;
2317 log_debug(LD_HIST, "Opened exit stream to port %d", port);
2320 /*** cell statistics ***/
2322 /** Start of the current buffer stats interval or 0 if we're not
2323 * collecting buffer statistics. */
2324 static time_t start_of_buffer_stats_interval;
2326 /** Initialize buffer stats. */
2327 void
2328 rep_hist_buffer_stats_init(time_t now)
2330 start_of_buffer_stats_interval = now;
2333 typedef struct circ_buffer_stats_t {
2334 uint32_t processed_cells;
2335 double mean_num_cells_in_queue;
2336 double mean_time_cells_in_queue;
2337 uint32_t local_circ_id;
2338 } circ_buffer_stats_t;
2340 /** Holds stats. */
2341 smartlist_t *circuits_for_buffer_stats = NULL;
2343 /** Remember cell statistics for circuit <b>circ</b> at time
2344 * <b>end_of_interval</b> and reset cell counters in case the circuit
2345 * remains open in the next measurement interval. */
2346 void
2347 rep_hist_buffer_stats_add_circ(circuit_t *circ, time_t end_of_interval)
2349 circ_buffer_stats_t *stat;
2350 time_t start_of_interval;
2351 int interval_length;
2352 or_circuit_t *orcirc;
2353 if (CIRCUIT_IS_ORIGIN(circ))
2354 return;
2355 orcirc = TO_OR_CIRCUIT(circ);
2356 if (!orcirc->processed_cells)
2357 return;
2358 if (!circuits_for_buffer_stats)
2359 circuits_for_buffer_stats = smartlist_create();
2360 start_of_interval = circ->timestamp_created >
2361 start_of_buffer_stats_interval ?
2362 circ->timestamp_created :
2363 start_of_buffer_stats_interval;
2364 interval_length = (int) (end_of_interval - start_of_interval);
2365 stat = tor_malloc_zero(sizeof(circ_buffer_stats_t));
2366 stat->processed_cells = orcirc->processed_cells;
2367 /* 1000.0 for s -> ms; 2.0 because of app-ward and exit-ward queues */
2368 stat->mean_num_cells_in_queue = interval_length == 0 ? 0.0 :
2369 (double) orcirc->total_cell_waiting_time /
2370 (double) interval_length / 1000.0 / 2.0;
2371 stat->mean_time_cells_in_queue =
2372 (double) orcirc->total_cell_waiting_time /
2373 (double) orcirc->processed_cells;
2374 smartlist_add(circuits_for_buffer_stats, stat);
2375 orcirc->total_cell_waiting_time = 0;
2376 orcirc->processed_cells = 0;
2379 /** Sorting helper: return -1, 1, or 0 based on comparison of two
2380 * circ_buffer_stats_t */
2381 static int
2382 _buffer_stats_compare_entries(const void **_a, const void **_b)
2384 const circ_buffer_stats_t *a = *_a, *b = *_b;
2385 if (a->processed_cells < b->processed_cells)
2386 return 1;
2387 else if (a->processed_cells > b->processed_cells)
2388 return -1;
2389 else
2390 return 0;
2393 /** Stop collecting cell stats in a way that we can re-start doing so in
2394 * rep_hist_buffer_stats_init(). */
2395 void
2396 rep_hist_buffer_stats_term(void)
2398 start_of_buffer_stats_interval = 0;
2399 if (!circuits_for_buffer_stats)
2400 circuits_for_buffer_stats = smartlist_create();
2401 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
2402 stat, tor_free(stat));
2403 smartlist_clear(circuits_for_buffer_stats);
2406 /** Write buffer statistics to $DATADIR/stats/buffer-stats and return when
2407 * we would next want to write exit stats. */
2408 time_t
2409 rep_hist_buffer_stats_write(time_t now)
2411 char *statsdir = NULL, *filename = NULL;
2412 char written[ISO_TIME_LEN+1];
2413 open_file_t *open_file = NULL;
2414 FILE *out;
2415 #define SHARES 10
2416 int processed_cells[SHARES], circs_in_share[SHARES],
2417 number_of_circuits, i;
2418 double queued_cells[SHARES], time_in_queue[SHARES];
2419 smartlist_t *str_build = smartlist_create();
2420 char *str = NULL, *buf=NULL;
2421 circuit_t *circ;
2423 if (!start_of_buffer_stats_interval)
2424 return 0; /* Not initialized. */
2425 if (start_of_buffer_stats_interval + WRITE_STATS_INTERVAL > now)
2426 goto done; /* Not ready to write */
2428 /* add current circuits to stats */
2429 for (circ = _circuit_get_global_list(); circ; circ = circ->next)
2430 rep_hist_buffer_stats_add_circ(circ, now);
2431 /* calculate deciles */
2432 memset(processed_cells, 0, SHARES * sizeof(int));
2433 memset(circs_in_share, 0, SHARES * sizeof(int));
2434 memset(queued_cells, 0, SHARES * sizeof(double));
2435 memset(time_in_queue, 0, SHARES * sizeof(double));
2436 if (!circuits_for_buffer_stats)
2437 circuits_for_buffer_stats = smartlist_create();
2438 smartlist_sort(circuits_for_buffer_stats,
2439 _buffer_stats_compare_entries);
2440 number_of_circuits = smartlist_len(circuits_for_buffer_stats);
2441 if (number_of_circuits < 1) {
2442 log_info(LD_HIST, "Attempt to write cell statistics to disk failed. "
2443 "We haven't seen a single circuit to report about.");
2444 goto done;
2446 i = 0;
2447 SMARTLIST_FOREACH_BEGIN(circuits_for_buffer_stats,
2448 circ_buffer_stats_t *, stat)
2450 int share = i++ * SHARES / number_of_circuits;
2451 processed_cells[share] += stat->processed_cells;
2452 queued_cells[share] += stat->mean_num_cells_in_queue;
2453 time_in_queue[share] += stat->mean_time_cells_in_queue;
2454 circs_in_share[share]++;
2456 SMARTLIST_FOREACH_END(stat);
2457 /* clear buffer stats history */
2458 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
2459 stat, tor_free(stat));
2460 smartlist_clear(circuits_for_buffer_stats);
2461 /* write to file */
2462 statsdir = get_datadir_fname("stats");
2463 if (check_private_dir(statsdir, CPD_CREATE) < 0)
2464 goto done;
2465 filename = get_datadir_fname2("stats", "buffer-stats");
2466 out = start_writing_to_stdio_file(filename, OPEN_FLAGS_APPEND,
2467 0600, &open_file);
2468 if (!out)
2469 goto done;
2470 format_iso_time(written, now);
2471 if (fprintf(out, "cell-stats-end %s (%d s)\n", written,
2472 (unsigned) (now - start_of_buffer_stats_interval)) < 0)
2473 goto done;
2474 for (i = 0; i < SHARES; i++) {
2475 tor_asprintf(&buf,"%d", !circs_in_share[i] ? 0 :
2476 processed_cells[i] / circs_in_share[i]);
2477 smartlist_add(str_build, buf);
2479 str = smartlist_join_strings(str_build, ",", 0, NULL);
2480 if (fprintf(out, "cell-processed-cells %s\n", str) < 0)
2481 goto done;
2482 tor_free(str);
2483 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2484 smartlist_clear(str_build);
2485 for (i = 0; i < SHARES; i++) {
2486 tor_asprintf(&buf, "%.2f", circs_in_share[i] == 0 ? 0.0 :
2487 queued_cells[i] / (double) circs_in_share[i]);
2488 smartlist_add(str_build, buf);
2490 str = smartlist_join_strings(str_build, ",", 0, NULL);
2491 if (fprintf(out, "cell-queued-cells %s\n", str) < 0)
2492 goto done;
2493 tor_free(str);
2494 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2495 smartlist_clear(str_build);
2496 for (i = 0; i < SHARES; i++) {
2497 tor_asprintf(&buf, "%.0f", circs_in_share[i] == 0 ? 0.0 :
2498 time_in_queue[i] / (double) circs_in_share[i]);
2499 smartlist_add(str_build, buf);
2501 str = smartlist_join_strings(str_build, ",", 0, NULL);
2502 if (fprintf(out, "cell-time-in-queue %s\n", str) < 0)
2503 goto done;
2504 tor_free(str);
2505 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2506 smartlist_free(str_build);
2507 str_build = NULL;
2508 if (fprintf(out, "cell-circuits-per-decile %d\n",
2509 (number_of_circuits + SHARES - 1) / SHARES) < 0)
2510 goto done;
2511 finish_writing_to_file(open_file);
2512 open_file = NULL;
2513 start_of_buffer_stats_interval = now;
2514 done:
2515 if (open_file)
2516 abort_writing_to_file(open_file);
2517 tor_free(filename);
2518 tor_free(statsdir);
2519 if (str_build) {
2520 SMARTLIST_FOREACH(str_build, char *, c, tor_free(c));
2521 smartlist_free(str_build);
2523 tor_free(str);
2524 #undef SHARES
2525 return start_of_buffer_stats_interval + WRITE_STATS_INTERVAL;
2528 /** Free all storage held by the OR/link history caches, by the
2529 * bandwidth history arrays, by the port history, or by statistics . */
2530 void
2531 rep_hist_free_all(void)
2533 digestmap_free(history_map, free_or_history);
2534 tor_free(read_array);
2535 tor_free(write_array);
2536 tor_free(last_stability_doc);
2537 tor_free(exit_bytes_read);
2538 tor_free(exit_bytes_written);
2539 tor_free(exit_streams);
2540 built_last_stability_doc_at = 0;
2541 predicted_ports_free();