Fix valgrind error when marking a descriptor as never-downloadable.
[tor/rransom.git] / src / or / rephist.c
blob7bacd3abb677bac0273fec04cb7593843812c138
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2009, 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.
10 **/
12 #include "or.h"
13 #include "ht.h"
15 static void bw_arrays_init(void);
16 static void predicted_ports_init(void);
17 static void hs_usage_init(void);
19 /** Total number of bytes currently allocated in fields used by rephist.c. */
20 uint64_t rephist_total_alloc=0;
21 /** Number of or_history_t objects currently allocated. */
22 uint32_t rephist_total_num=0;
24 /** If the total weighted run count of all runs for a router ever falls
25 * below this amount, the router can be treated as having 0 MTBF. */
26 #define STABILITY_EPSILON 0.0001
27 /** Value by which to discount all old intervals for MTBF purposses. This
28 * is compounded every STABILITY_INTERVAL. */
29 #define STABILITY_ALPHA 0.95
30 /** Interval at which to discount all old intervals for MTBF purposes. */
31 #define STABILITY_INTERVAL (12*60*60)
32 /* (This combination of ALPHA, INTERVAL, and EPSILON makes it so that an
33 * interval that just ended counts twice as much as one that ended a week ago,
34 * 20X as much as one that ended a month ago, and routers that have had no
35 * uptime data for about half a year will get forgotten.) */
37 /** History of an OR-\>OR link. */
38 typedef struct link_history_t {
39 /** When did we start tracking this list? */
40 time_t since;
41 /** When did we most recently note a change to this link */
42 time_t changed;
43 /** How many times did extending from OR1 to OR2 succeed? */
44 unsigned long n_extend_ok;
45 /** How many times did extending from OR1 to OR2 fail? */
46 unsigned long n_extend_fail;
47 } link_history_t;
49 /** History of an OR. */
50 typedef struct or_history_t {
51 /** When did we start tracking this OR? */
52 time_t since;
53 /** When did we most recently note a change to this OR? */
54 time_t changed;
55 /** How many times did we successfully connect? */
56 unsigned long n_conn_ok;
57 /** How many times did we try to connect and fail?*/
58 unsigned long n_conn_fail;
59 /** How many seconds have we been connected to this OR before
60 * 'up_since'? */
61 unsigned long uptime;
62 /** How many seconds have we been unable to connect to this OR before
63 * 'down_since'? */
64 unsigned long downtime;
65 /** If nonzero, we have been connected since this time. */
66 time_t up_since;
67 /** If nonzero, we have been unable to connect since this time. */
68 time_t down_since;
70 /* === For MTBF tracking: */
71 /** Weighted sum total of all times that this router has been online.
73 unsigned long weighted_run_length;
74 /** If the router is now online (according to stability-checking rules),
75 * when did it come online? */
76 time_t start_of_run;
77 /** Sum of weights for runs in weighted_run_length. */
78 double total_run_weights;
79 /* === For fractional uptime tracking: */
80 time_t start_of_downtime;
81 unsigned long weighted_uptime;
82 unsigned long total_weighted_time;
84 /** Map from hex OR2 identity digest to a link_history_t for the link
85 * from this OR to OR2. */
86 digestmap_t *link_history_map;
87 } or_history_t;
89 /** When did we last multiply all routers' weighted_run_length and
90 * total_run_weights by STABILITY_ALPHA? */
91 static time_t stability_last_downrated = 0;
93 /** */
94 static time_t started_tracking_stability = 0;
96 /** Map from hex OR identity digest to or_history_t. */
97 static digestmap_t *history_map = NULL;
99 /** Return the or_history_t for the OR with identity digest <b>id</b>,
100 * creating it if necessary. */
101 static or_history_t *
102 get_or_history(const char* id)
104 or_history_t *hist;
106 if (tor_mem_is_zero(id, DIGEST_LEN))
107 return NULL;
109 hist = digestmap_get(history_map, id);
110 if (!hist) {
111 hist = tor_malloc_zero(sizeof(or_history_t));
112 rephist_total_alloc += sizeof(or_history_t);
113 rephist_total_num++;
114 hist->link_history_map = digestmap_new();
115 hist->since = hist->changed = time(NULL);
116 digestmap_set(history_map, id, hist);
118 return hist;
121 /** Return the link_history_t for the link from the first named OR to
122 * the second, creating it if necessary. (ORs are identified by
123 * identity digest.)
125 static link_history_t *
126 get_link_history(const char *from_id, const char *to_id)
128 or_history_t *orhist;
129 link_history_t *lhist;
130 orhist = get_or_history(from_id);
131 if (!orhist)
132 return NULL;
133 if (tor_mem_is_zero(to_id, DIGEST_LEN))
134 return NULL;
135 lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
136 if (!lhist) {
137 lhist = tor_malloc_zero(sizeof(link_history_t));
138 rephist_total_alloc += sizeof(link_history_t);
139 lhist->since = lhist->changed = time(NULL);
140 digestmap_set(orhist->link_history_map, to_id, lhist);
142 return lhist;
145 /** Helper: free storage held by a single link history entry. */
146 static void
147 _free_link_history(void *val)
149 rephist_total_alloc -= sizeof(link_history_t);
150 tor_free(val);
153 /** Helper: free storage held by a single OR history entry. */
154 static void
155 free_or_history(void *_hist)
157 or_history_t *hist = _hist;
158 digestmap_free(hist->link_history_map, _free_link_history);
159 rephist_total_alloc -= sizeof(or_history_t);
160 rephist_total_num--;
161 tor_free(hist);
164 /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
165 * count is up-to-date as of <b>when</b>.
167 static void
168 update_or_history(or_history_t *hist, time_t when)
170 tor_assert(hist);
171 if (hist->up_since) {
172 tor_assert(!hist->down_since);
173 hist->uptime += (when - hist->up_since);
174 hist->up_since = when;
175 } else if (hist->down_since) {
176 hist->downtime += (when - hist->down_since);
177 hist->down_since = when;
181 /** Initialize the static data structures for tracking history. */
182 void
183 rep_hist_init(void)
185 history_map = digestmap_new();
186 bw_arrays_init();
187 predicted_ports_init();
188 hs_usage_init();
191 /** Helper: note that we are no longer connected to the router with history
192 * <b>hist</b>. If <b>failed</b>, the connection failed; otherwise, it was
193 * closed correctly. */
194 static void
195 mark_or_down(or_history_t *hist, time_t when, int failed)
197 if (hist->up_since) {
198 hist->uptime += (when - hist->up_since);
199 hist->up_since = 0;
201 if (failed && !hist->down_since) {
202 hist->down_since = when;
206 /** Helper: note that we are connected to the router with history
207 * <b>hist</b>. */
208 static void
209 mark_or_up(or_history_t *hist, time_t when)
211 if (hist->down_since) {
212 hist->downtime += (when - hist->down_since);
213 hist->down_since = 0;
215 if (!hist->up_since) {
216 hist->up_since = when;
220 /** Remember that an attempt to connect to the OR with identity digest
221 * <b>id</b> failed at <b>when</b>.
223 void
224 rep_hist_note_connect_failed(const char* id, time_t when)
226 or_history_t *hist;
227 hist = get_or_history(id);
228 if (!hist)
229 return;
230 ++hist->n_conn_fail;
231 mark_or_down(hist, when, 1);
232 hist->changed = when;
235 /** Remember that an attempt to connect to the OR with identity digest
236 * <b>id</b> succeeded at <b>when</b>.
238 void
239 rep_hist_note_connect_succeeded(const char* id, time_t when)
241 or_history_t *hist;
242 hist = get_or_history(id);
243 if (!hist)
244 return;
245 ++hist->n_conn_ok;
246 mark_or_up(hist, when);
247 hist->changed = when;
250 /** Remember that we intentionally closed our connection to the OR
251 * with identity digest <b>id</b> at <b>when</b>.
253 void
254 rep_hist_note_disconnect(const char* id, time_t when)
256 or_history_t *hist;
257 hist = get_or_history(id);
258 if (!hist)
259 return;
260 mark_or_down(hist, when, 0);
261 hist->changed = when;
264 /** Remember that our connection to the OR with identity digest
265 * <b>id</b> had an error and stopped working at <b>when</b>.
267 void
268 rep_hist_note_connection_died(const char* id, time_t when)
270 or_history_t *hist;
271 if (!id) {
272 /* If conn has no identity, it didn't complete its handshake, or something
273 * went wrong. Ignore it.
275 return;
277 hist = get_or_history(id);
278 if (!hist)
279 return;
280 mark_or_down(hist, when, 1);
281 hist->changed = when;
284 /** We have just decided that this router with identity digest <b>id</b> is
285 * reachable, meaning we will give it a "Running" flag for the next while. */
286 void
287 rep_hist_note_router_reachable(const char *id, time_t when)
289 or_history_t *hist = get_or_history(id);
290 int was_in_run = 1;
291 char tbuf[ISO_TIME_LEN+1];
293 tor_assert(hist);
295 if (!started_tracking_stability)
296 started_tracking_stability = time(NULL);
297 if (!hist->start_of_run) {
298 hist->start_of_run = when;
299 was_in_run = 0;
301 if (hist->start_of_downtime) {
302 long down_length;
304 format_local_iso_time(tbuf, hist->start_of_downtime);
305 log_info(LD_HIST, "Router %s is now Running; it had been down since %s.",
306 hex_str(id, DIGEST_LEN), tbuf);
307 if (was_in_run)
308 log_info(LD_HIST, " (Paradoxically, it was already Running too.)");
310 down_length = when - hist->start_of_downtime;
311 hist->total_weighted_time += down_length;
312 hist->start_of_downtime = 0;
313 } else {
314 format_local_iso_time(tbuf, hist->start_of_run);
315 if (was_in_run)
316 log_debug(LD_HIST, "Router %s is still Running; it has been Running "
317 "since %s", hex_str(id, DIGEST_LEN), tbuf);
318 else
319 log_info(LD_HIST,"Router %s is now Running; it was previously untracked",
320 hex_str(id, DIGEST_LEN));
324 /** We have just decided that this router is unreachable, meaning
325 * we are taking away its "Running" flag. */
326 void
327 rep_hist_note_router_unreachable(const char *id, time_t when)
329 or_history_t *hist = get_or_history(id);
330 char tbuf[ISO_TIME_LEN+1];
331 int was_running = 0;
332 if (!started_tracking_stability)
333 started_tracking_stability = time(NULL);
335 tor_assert(hist);
336 if (hist->start_of_run) {
337 /*XXXX We could treat failed connections differently from failed
338 * connect attempts. */
339 long run_length = when - hist->start_of_run;
340 format_local_iso_time(tbuf, hist->start_of_run);
342 hist->weighted_run_length += run_length;
343 hist->total_run_weights += 1.0;
344 hist->start_of_run = 0;
345 hist->weighted_uptime += run_length;
346 hist->total_weighted_time += run_length;
348 was_running = 1;
349 log_info(LD_HIST, "Router %s is now non-Running: it had previously been "
350 "Running since %s. Its total weighted uptime is %lu/%lu.",
351 hex_str(id, DIGEST_LEN), tbuf, hist->weighted_uptime,
352 hist->total_weighted_time);
354 if (!hist->start_of_downtime) {
355 hist->start_of_downtime = when;
357 if (!was_running)
358 log_info(LD_HIST, "Router %s is now non-Running; it was previously "
359 "untracked.", hex_str(id, DIGEST_LEN));
360 } else {
361 if (!was_running) {
362 format_local_iso_time(tbuf, hist->start_of_downtime);
364 log_info(LD_HIST, "Router %s is still non-Running; it has been "
365 "non-Running since %s.", hex_str(id, DIGEST_LEN), tbuf);
370 /** Helper: Discount all old MTBF data, if it is time to do so. Return
371 * the time at which we should next discount MTBF data. */
372 time_t
373 rep_hist_downrate_old_runs(time_t now)
375 digestmap_iter_t *orhist_it;
376 const char *digest1;
377 or_history_t *hist;
378 void *hist_p;
379 double alpha = 1.0;
381 if (!history_map)
382 history_map = digestmap_new();
383 if (!stability_last_downrated)
384 stability_last_downrated = now;
385 if (stability_last_downrated + STABILITY_INTERVAL > now)
386 return stability_last_downrated + STABILITY_INTERVAL;
388 /* Okay, we should downrate the data. By how much? */
389 while (stability_last_downrated + STABILITY_INTERVAL < now) {
390 stability_last_downrated += STABILITY_INTERVAL;
391 alpha *= STABILITY_ALPHA;
394 log_info(LD_HIST, "Discounting all old stability info by a factor of %lf",
395 alpha);
397 /* Multiply every w_r_l, t_r_w pair by alpha. */
398 for (orhist_it = digestmap_iter_init(history_map);
399 !digestmap_iter_done(orhist_it);
400 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
401 digestmap_iter_get(orhist_it, &digest1, &hist_p);
402 hist = hist_p;
404 hist->weighted_run_length =
405 (unsigned long)(hist->weighted_run_length * alpha);
406 hist->total_run_weights *= alpha;
408 hist->weighted_uptime = (unsigned long)(hist->weighted_uptime * alpha);
409 hist->total_weighted_time = (unsigned long)
410 (hist->total_weighted_time * alpha);
413 return stability_last_downrated + STABILITY_INTERVAL;
416 /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
417 static double
418 get_stability(or_history_t *hist, time_t when)
420 unsigned long total = hist->weighted_run_length;
421 double total_weights = hist->total_run_weights;
423 if (hist->start_of_run) {
424 /* We're currently in a run. Let total and total_weights hold the values
425 * they would hold if the current run were to end now. */
426 total += (when-hist->start_of_run);
427 total_weights += 1.0;
429 if (total_weights < STABILITY_EPSILON) {
430 /* Round down to zero, and avoid divide-by-zero. */
431 return 0.0;
434 return total / total_weights;
437 /** Return the total amount of time we've been observing, with each run of
438 * time downrated by the appropriate factor. */
439 static long
440 get_total_weighted_time(or_history_t *hist, time_t when)
442 long total = hist->total_weighted_time;
443 if (hist->start_of_run) {
444 total += (when - hist->start_of_run);
445 } else if (hist->start_of_downtime) {
446 total += (when - hist->start_of_downtime);
448 return total;
451 /** Helper: Return the weighted percent-of-time-online of the router with
452 * history <b>hist</b>. */
453 static double
454 get_weighted_fractional_uptime(or_history_t *hist, time_t when)
456 unsigned long total = hist->total_weighted_time;
457 unsigned long up = hist->weighted_uptime;
459 if (hist->start_of_run) {
460 long run_length = (when - hist->start_of_run);
461 up += run_length;
462 total += run_length;
463 } else if (hist->start_of_downtime) {
464 total += (when - hist->start_of_downtime);
467 if (!total) {
468 /* Avoid calling anybody's uptime infinity (which should be impossible if
469 * the code is working), or NaN (which can happen for any router we haven't
470 * observed up or down yet). */
471 return 0.0;
474 return ((double) up) / total;
477 /** Return an estimated MTBF for the router whose identity digest is
478 * <b>id</b>. Return 0 if the router is unknown. */
479 double
480 rep_hist_get_stability(const char *id, time_t when)
482 or_history_t *hist = get_or_history(id);
483 if (!hist)
484 return 0.0;
486 return get_stability(hist, when);
489 /** Return an estimated percent-of-time-online for the router whose identity
490 * digest is <b>id</b>. Return 0 if the router is unknown. */
491 double
492 rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
494 or_history_t *hist = get_or_history(id);
495 if (!hist)
496 return 0.0;
498 return get_weighted_fractional_uptime(hist, when);
501 /** Return a number representing how long we've known about the router whose
502 * digest is <b>id</b>. Return 0 if the router is unknown.
504 * Be careful: this measure incresases monotonically as we know the router for
505 * longer and longer, but it doesn't increase linearly.
507 long
508 rep_hist_get_weighted_time_known(const char *id, time_t when)
510 or_history_t *hist = get_or_history(id);
511 if (!hist)
512 return 0;
514 return get_total_weighted_time(hist, when);
517 /** Return true if we've been measuring MTBFs for long enough to
518 * pronounce on Stability. */
520 rep_hist_have_measured_enough_stability(void)
522 /* XXXX021 This doesn't do so well when we change our opinion
523 * as to whether we're tracking router stability. */
524 return started_tracking_stability < time(NULL) - 4*60*60;
527 /** Remember that we successfully extended from the OR with identity
528 * digest <b>from_id</b> to the OR with identity digest
529 * <b>to_name</b>.
531 void
532 rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
534 link_history_t *hist;
535 /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
536 hist = get_link_history(from_id, to_id);
537 if (!hist)
538 return;
539 ++hist->n_extend_ok;
540 hist->changed = time(NULL);
543 /** Remember that we tried to extend from the OR with identity digest
544 * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
545 * failed.
547 void
548 rep_hist_note_extend_failed(const char *from_id, const char *to_id)
550 link_history_t *hist;
551 /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
552 hist = get_link_history(from_id, to_id);
553 if (!hist)
554 return;
555 ++hist->n_extend_fail;
556 hist->changed = time(NULL);
559 /** Log all the reliability data we have remembered, with the chosen
560 * severity.
562 void
563 rep_hist_dump_stats(time_t now, int severity)
565 digestmap_iter_t *lhist_it;
566 digestmap_iter_t *orhist_it;
567 const char *name1, *name2, *digest1, *digest2;
568 char hexdigest1[HEX_DIGEST_LEN+1];
569 or_history_t *or_history;
570 link_history_t *link_history;
571 void *or_history_p, *link_history_p;
572 double uptime;
573 char buffer[2048];
574 size_t len;
575 int ret;
576 unsigned long upt, downt;
577 routerinfo_t *r;
579 rep_history_clean(now - get_options()->RephistTrackTime);
581 log(severity, LD_HIST, "--------------- Dumping history information:");
583 for (orhist_it = digestmap_iter_init(history_map);
584 !digestmap_iter_done(orhist_it);
585 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
586 double s;
587 long stability;
588 digestmap_iter_get(orhist_it, &digest1, &or_history_p);
589 or_history = (or_history_t*) or_history_p;
591 if ((r = router_get_by_digest(digest1)))
592 name1 = r->nickname;
593 else
594 name1 = "(unknown)";
595 base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
596 update_or_history(or_history, now);
597 upt = or_history->uptime;
598 downt = or_history->downtime;
599 s = get_stability(or_history, now);
600 stability = (long)s;
601 if (upt+downt) {
602 uptime = ((double)upt) / (upt+downt);
603 } else {
604 uptime=1.0;
606 log(severity, LD_HIST,
607 "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
608 "wmtbf %lu:%02lu:%02lu",
609 name1, hexdigest1,
610 or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
611 upt, upt+downt, uptime*100.0,
612 stability/3600, (stability/60)%60, stability%60);
614 if (!digestmap_isempty(or_history->link_history_map)) {
615 strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
616 len = strlen(buffer);
617 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
618 !digestmap_iter_done(lhist_it);
619 lhist_it = digestmap_iter_next(or_history->link_history_map,
620 lhist_it)) {
621 digestmap_iter_get(lhist_it, &digest2, &link_history_p);
622 if ((r = router_get_by_digest(digest2)))
623 name2 = r->nickname;
624 else
625 name2 = "(unknown)";
627 link_history = (link_history_t*) link_history_p;
629 ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
630 link_history->n_extend_ok,
631 link_history->n_extend_ok+link_history->n_extend_fail);
632 if (ret<0)
633 break;
634 else
635 len += ret;
637 log(severity, LD_HIST, "%s", buffer);
642 /** Remove history info for routers/links that haven't changed since
643 * <b>before</b>.
645 void
646 rep_history_clean(time_t before)
648 int authority = authdir_mode(get_options());
649 or_history_t *or_history;
650 link_history_t *link_history;
651 void *or_history_p, *link_history_p;
652 digestmap_iter_t *orhist_it, *lhist_it;
653 const char *d1, *d2;
655 orhist_it = digestmap_iter_init(history_map);
656 while (!digestmap_iter_done(orhist_it)) {
657 int remove;
658 digestmap_iter_get(orhist_it, &d1, &or_history_p);
659 or_history = or_history_p;
661 remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
662 !or_history->start_of_run)
663 : (or_history->changed < before);
664 if (remove) {
665 orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
666 free_or_history(or_history);
667 continue;
669 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
670 !digestmap_iter_done(lhist_it); ) {
671 digestmap_iter_get(lhist_it, &d2, &link_history_p);
672 link_history = link_history_p;
673 if (link_history->changed < before) {
674 lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
675 lhist_it);
676 rephist_total_alloc -= sizeof(link_history_t);
677 tor_free(link_history);
678 continue;
680 lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
682 orhist_it = digestmap_iter_next(history_map, orhist_it);
686 /** Write MTBF data to disk. Returns 0 on success, negative on failure. */
688 rep_hist_record_mtbf_data(void)
690 char time_buf[ISO_TIME_LEN+1];
692 digestmap_iter_t *orhist_it;
693 const char *digest;
694 void *or_history_p;
695 or_history_t *hist;
696 open_file_t *open_file = NULL;
697 FILE *f;
700 char *filename = get_datadir_fname("router-stability");
701 f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
702 &open_file);
703 tor_free(filename);
704 if (!f)
705 return -1;
708 /* File format is:
709 * FormatLine *KeywordLine Data
711 * FormatLine = "format 1" NL
712 * KeywordLine = Keyword SP Arguments NL
713 * Data = "data" NL *RouterMTBFLine "." NL
714 * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
715 * TotalRunWeights [SP S=StartRunTime] NL
717 #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
718 #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
720 PUT("format 2\n");
722 format_iso_time(time_buf, time(NULL));
723 PRINTF((f, "stored-at %s\n", time_buf));
725 if (started_tracking_stability) {
726 format_iso_time(time_buf, started_tracking_stability);
727 PRINTF((f, "tracked-since %s\n", time_buf));
729 if (stability_last_downrated) {
730 format_iso_time(time_buf, stability_last_downrated);
731 PRINTF((f, "last-downrated %s\n", time_buf));
734 PUT("data\n");
736 /* XXX Nick: now bridge auths record this for all routers too.
737 * Should we make them record it only for bridge routers? -RD
738 * Not for 0.2.0. -NM */
739 for (orhist_it = digestmap_iter_init(history_map);
740 !digestmap_iter_done(orhist_it);
741 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
742 char dbuf[HEX_DIGEST_LEN+1];
743 const char *t = NULL;
744 digestmap_iter_get(orhist_it, &digest, &or_history_p);
745 hist = (or_history_t*) or_history_p;
747 base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
748 PRINTF((f, "R %s\n", dbuf));
749 if (hist->start_of_run > 0) {
750 format_iso_time(time_buf, hist->start_of_run);
751 t = time_buf;
753 PRINTF((f, "+MTBF %lu %.5lf%s%s\n",
754 hist->weighted_run_length, hist->total_run_weights,
755 t ? " S=" : "", t ? t : ""));
756 t = NULL;
757 if (hist->start_of_downtime > 0) {
758 format_iso_time(time_buf, hist->start_of_downtime);
759 t = time_buf;
761 PRINTF((f, "+WFU %lu %lu%s%s\n",
762 hist->weighted_uptime, hist->total_weighted_time,
763 t ? " S=" : "", t ? t : ""));
766 PUT(".\n");
768 #undef PUT
769 #undef PRINTF
771 return finish_writing_to_file(open_file);
772 err:
773 abort_writing_to_file(open_file);
774 return -1;
777 /** Format the current tracked status of the router in <b>hist</b> at time
778 * <b>now</b> for analysis; return it in a newly allocated string. */
779 static char *
780 rep_hist_format_router_status(or_history_t *hist, time_t now)
782 char buf[1024];
783 char sor_buf[ISO_TIME_LEN+1];
784 char sod_buf[ISO_TIME_LEN+1];
785 double wfu;
786 double mtbf;
787 int up = 0, down = 0;
789 if (hist->start_of_run) {
790 format_iso_time(sor_buf, hist->start_of_run);
791 up = 1;
793 if (hist->start_of_downtime) {
794 format_iso_time(sod_buf, hist->start_of_downtime);
795 down = 1;
798 wfu = get_weighted_fractional_uptime(hist, now);
799 mtbf = get_stability(hist, now);
800 tor_snprintf(buf, sizeof(buf),
801 "%s%s%s"
802 "%s%s%s"
803 "wfu %0.3lf\n"
804 " weighted-time %lu\n"
805 " weighted-uptime %lu\n"
806 "mtbf %0.1lf\n"
807 " weighted-run-length %lu\n"
808 " total-run-weights %lf\n",
809 up?"uptime-started ":"", up?sor_buf:"", up?" UTC\n":"",
810 down?"downtime-started ":"", down?sod_buf:"", down?" UTC\n":"",
811 wfu,
812 hist->total_weighted_time,
813 hist->weighted_uptime,
814 mtbf,
815 hist->weighted_run_length,
816 hist->total_run_weights
819 return tor_strdup(buf);
822 /** The last stability analysis document that we created, or NULL if we never
823 * have created one. */
824 static char *last_stability_doc = NULL;
825 /** The last time we created a stability analysis document, or 0 if we never
826 * have created one. */
827 static time_t built_last_stability_doc_at = 0;
828 /** Shortest allowable time between building two stability documents. */
829 #define MAX_STABILITY_DOC_BUILD_RATE (3*60)
831 /** Return a pointer to a NUL-terminated document describing our view of the
832 * stability of the routers we've been tracking. Return NULL on failure. */
833 const char *
834 rep_hist_get_router_stability_doc(time_t now)
836 char *result;
837 smartlist_t *chunks;
838 if (built_last_stability_doc_at + MAX_STABILITY_DOC_BUILD_RATE > now)
839 return last_stability_doc;
841 if (!history_map)
842 return NULL;
844 tor_free(last_stability_doc);
845 chunks = smartlist_create();
847 if (rep_hist_have_measured_enough_stability()) {
848 smartlist_add(chunks, tor_strdup("we-have-enough-measurements\n"));
849 } else {
850 smartlist_add(chunks, tor_strdup("we-do-not-have-enough-measurements\n"));
853 DIGESTMAP_FOREACH(history_map, id, or_history_t *, hist) {
854 routerinfo_t *ri;
855 char dbuf[BASE64_DIGEST_LEN+1];
856 char header_buf[512];
857 char *info;
858 digest_to_base64(dbuf, id);
859 ri = router_get_by_digest(id);
860 if (ri) {
861 char *ip = tor_dup_ip(ri->addr);
862 char tbuf[ISO_TIME_LEN+1];
863 format_iso_time(tbuf, ri->cache_info.published_on);
864 tor_snprintf(header_buf, sizeof(header_buf),
865 "router %s %s %s\n"
866 "published %s\n"
867 "relevant-flags %s%s%s\n"
868 "declared-uptime %ld\n",
869 dbuf, ri->nickname, ip,
870 tbuf,
871 ri->is_running ? "Running " : "",
872 ri->is_valid ? "Valid " : "",
873 ri->is_hibernating ? "Hibernating " : "",
874 ri->uptime);
875 tor_free(ip);
876 } else {
877 tor_snprintf(header_buf, sizeof(header_buf),
878 "router %s {no descriptor}\n", dbuf);
880 smartlist_add(chunks, tor_strdup(header_buf));
881 info = rep_hist_format_router_status(hist, now);
882 if (info)
883 smartlist_add(chunks, info);
885 } DIGESTMAP_FOREACH_END;
887 result = smartlist_join_strings(chunks, "", 0, NULL);
888 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
889 smartlist_free(chunks);
891 last_stability_doc = result;
892 built_last_stability_doc_at = time(NULL);
893 return result;
896 /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
897 * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
898 * such line exists. */
899 static int
900 find_next_with(smartlist_t *sl, int i, const char *prefix)
902 for ( ; i < smartlist_len(sl); ++i) {
903 const char *line = smartlist_get(sl, i);
904 if (!strcmpstart(line, prefix))
905 return i;
906 if (!strcmpstart(line, "R "))
907 return -1;
909 return -1;
912 /** How many bad times has parse_possibly_bad_iso_time parsed? */
913 static int n_bogus_times = 0;
914 /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
915 * rounds any pre-1970 date to Jan 1, 1970. */
916 static int
917 parse_possibly_bad_iso_time(const char *s, time_t *time_out)
919 int year;
920 char b[5];
921 strlcpy(b, s, sizeof(b));
922 b[4] = '\0';
923 year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
924 if (year < 1970) {
925 *time_out = 0;
926 ++n_bogus_times;
927 return 0;
928 } else
929 return parse_iso_time(s, time_out);
932 /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
933 * says we started measuring at <b>started_measuring</b>. Return a new number
934 * that's about as much before <b>now</b> as <b>t</b> was before
935 * <b>stored_at</b>.
937 static INLINE time_t
938 correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
940 if (t < started_measuring - 24*60*60*365)
941 return 0;
942 else if (t < started_measuring)
943 return started_measuring;
944 else if (t > stored_at)
945 return 0;
946 else {
947 long run_length = stored_at - t;
948 t = now - run_length;
949 if (t < started_measuring)
950 t = started_measuring;
951 return t;
955 /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
956 * on failure. */
958 rep_hist_load_mtbf_data(time_t now)
960 /* XXXX won't handle being called while history is already populated. */
961 smartlist_t *lines;
962 const char *line = NULL;
963 int r=0, i;
964 time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
965 time_t latest_possible_start = now;
966 long format = -1;
969 char *filename = get_datadir_fname("router-stability");
970 char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
971 tor_free(filename);
972 if (!d)
973 return -1;
974 lines = smartlist_create();
975 smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
976 tor_free(d);
980 const char *firstline;
981 if (smartlist_len(lines)>4) {
982 firstline = smartlist_get(lines, 0);
983 if (!strcmpstart(firstline, "format "))
984 format = tor_parse_long(firstline+strlen("format "),
985 10, -1, LONG_MAX, NULL, NULL);
988 if (format != 1 && format != 2) {
989 log_warn(LD_HIST,
990 "Unrecognized format in mtbf history file. Skipping.");
991 goto err;
993 for (i = 1; i < smartlist_len(lines); ++i) {
994 line = smartlist_get(lines, i);
995 if (!strcmp(line, "data"))
996 break;
997 if (!strcmpstart(line, "last-downrated ")) {
998 if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
999 log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
1000 "history file.");
1002 if (!strcmpstart(line, "stored-at ")) {
1003 if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
1004 log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
1005 "history file.");
1007 if (!strcmpstart(line, "tracked-since ")) {
1008 if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
1009 log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
1010 "history file.");
1013 if (last_downrated > now)
1014 last_downrated = now;
1015 if (tracked_since > now)
1016 tracked_since = now;
1018 if (!stored_at) {
1019 log_warn(LD_HIST, "No stored time recorded.");
1020 goto err;
1023 if (line && !strcmp(line, "data"))
1024 ++i;
1026 n_bogus_times = 0;
1028 for (; i < smartlist_len(lines); ++i) {
1029 char digest[DIGEST_LEN];
1030 char hexbuf[HEX_DIGEST_LEN+1];
1031 char mtbf_timebuf[ISO_TIME_LEN+1];
1032 char wfu_timebuf[ISO_TIME_LEN+1];
1033 time_t start_of_run = 0;
1034 time_t start_of_downtime = 0;
1035 int have_mtbf = 0, have_wfu = 0;
1036 long wrl = 0;
1037 double trw = 0;
1038 long wt_uptime = 0, total_wt_time = 0;
1039 int n;
1040 or_history_t *hist;
1041 line = smartlist_get(lines, i);
1042 if (!strcmp(line, "."))
1043 break;
1045 mtbf_timebuf[0] = '\0';
1046 wfu_timebuf[0] = '\0';
1048 if (format == 1) {
1049 n = sscanf(line, "%40s %ld %lf S=%10s %8s",
1050 hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1051 if (n != 3 && n != 5) {
1052 log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
1053 continue;
1055 have_mtbf = 1;
1056 } else {
1057 // format == 2.
1058 int mtbf_idx, wfu_idx;
1059 if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
1060 continue;
1061 strlcpy(hexbuf, line+2, sizeof(hexbuf));
1062 mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
1063 wfu_idx = find_next_with(lines, i+1, "+WFU ");
1064 if (mtbf_idx >= 0) {
1065 const char *mtbfline = smartlist_get(lines, mtbf_idx);
1066 n = sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
1067 &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1068 if (n == 2 || n == 4) {
1069 have_mtbf = 1;
1070 } else {
1071 log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
1072 escaped(mtbfline));
1075 if (wfu_idx >= 0) {
1076 const char *wfuline = smartlist_get(lines, wfu_idx);
1077 n = sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
1078 &wt_uptime, &total_wt_time,
1079 wfu_timebuf, wfu_timebuf+11);
1080 if (n == 2 || n == 4) {
1081 have_wfu = 1;
1082 } else {
1083 log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
1086 if (wfu_idx > i)
1087 i = wfu_idx;
1088 if (mtbf_idx > i)
1089 i = mtbf_idx;
1091 if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
1092 log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
1093 continue;
1095 hist = get_or_history(digest);
1096 if (!hist)
1097 continue;
1099 if (have_mtbf) {
1100 if (mtbf_timebuf[0]) {
1101 mtbf_timebuf[10] = ' ';
1102 if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
1103 log_warn(LD_HIST, "Couldn't parse time %s",
1104 escaped(mtbf_timebuf));
1106 hist->start_of_run = correct_time(start_of_run, now, stored_at,
1107 tracked_since);
1108 if (hist->start_of_run < latest_possible_start + wrl)
1109 latest_possible_start = hist->start_of_run - wrl;
1111 hist->weighted_run_length = wrl;
1112 hist->total_run_weights = trw;
1114 if (have_wfu) {
1115 if (wfu_timebuf[0]) {
1116 wfu_timebuf[10] = ' ';
1117 if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
1118 log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
1121 hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
1122 tracked_since);
1123 hist->weighted_uptime = wt_uptime;
1124 hist->total_weighted_time = total_wt_time;
1126 if (strcmp(line, "."))
1127 log_warn(LD_HIST, "Truncated MTBF file.");
1129 if (tracked_since < 86400*365) /* Recover from insanely early value. */
1130 tracked_since = latest_possible_start;
1132 stability_last_downrated = last_downrated;
1133 started_tracking_stability = tracked_since;
1135 goto done;
1136 err:
1137 r = -1;
1138 done:
1139 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1140 smartlist_free(lines);
1141 return r;
1144 /** For how many seconds do we keep track of individual per-second bandwidth
1145 * totals? */
1146 #define NUM_SECS_ROLLING_MEASURE 10
1147 /** How large are the intervals for which we track and report bandwidth use? */
1148 #define NUM_SECS_BW_SUM_INTERVAL (15*60)
1149 /** How far in the past do we remember and publish bandwidth use? */
1150 #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
1151 /** How many bandwidth usage intervals do we remember? (derived) */
1152 #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
1154 /** Structure to track bandwidth use, and remember the maxima for a given
1155 * time period.
1157 typedef struct bw_array_t {
1158 /** Observation array: Total number of bytes transferred in each of the last
1159 * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
1160 uint64_t obs[NUM_SECS_ROLLING_MEASURE];
1161 int cur_obs_idx; /**< Current position in obs. */
1162 time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
1163 uint64_t total_obs; /**< Total for all members of obs except
1164 * obs[cur_obs_idx] */
1165 uint64_t max_total; /**< Largest value that total_obs has taken on in the
1166 * current period. */
1167 uint64_t total_in_period; /**< Total bytes transferred in the current
1168 * period. */
1170 /** When does the next period begin? */
1171 time_t next_period;
1172 /** Where in 'maxima' should the maximum bandwidth usage for the current
1173 * period be stored? */
1174 int next_max_idx;
1175 /** How many values in maxima/totals have been set ever? */
1176 int num_maxes_set;
1177 /** Circular array of the maximum
1178 * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
1179 * NUM_TOTALS periods */
1180 uint64_t maxima[NUM_TOTALS];
1181 /** Circular array of the total bandwidth usage for the last NUM_TOTALS
1182 * periods */
1183 uint64_t totals[NUM_TOTALS];
1184 } bw_array_t;
1186 /** Shift the current period of b forward by one. */
1187 static void
1188 commit_max(bw_array_t *b)
1190 /* Store total from current period. */
1191 b->totals[b->next_max_idx] = b->total_in_period;
1192 /* Store maximum from current period. */
1193 b->maxima[b->next_max_idx++] = b->max_total;
1194 /* Advance next_period and next_max_idx */
1195 b->next_period += NUM_SECS_BW_SUM_INTERVAL;
1196 if (b->next_max_idx == NUM_TOTALS)
1197 b->next_max_idx = 0;
1198 if (b->num_maxes_set < NUM_TOTALS)
1199 ++b->num_maxes_set;
1200 /* Reset max_total. */
1201 b->max_total = 0;
1202 /* Reset total_in_period. */
1203 b->total_in_period = 0;
1206 /** Shift the current observation time of 'b' forward by one second. */
1207 static INLINE void
1208 advance_obs(bw_array_t *b)
1210 int nextidx;
1211 uint64_t total;
1213 /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
1214 * seconds; adjust max_total as needed.*/
1215 total = b->total_obs + b->obs[b->cur_obs_idx];
1216 if (total > b->max_total)
1217 b->max_total = total;
1219 nextidx = b->cur_obs_idx+1;
1220 if (nextidx == NUM_SECS_ROLLING_MEASURE)
1221 nextidx = 0;
1223 b->total_obs = total - b->obs[nextidx];
1224 b->obs[nextidx]=0;
1225 b->cur_obs_idx = nextidx;
1227 if (++b->cur_obs_time >= b->next_period)
1228 commit_max(b);
1231 /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
1232 * <b>when</b>. */
1233 static INLINE void
1234 add_obs(bw_array_t *b, time_t when, uint64_t n)
1236 /* Don't record data in the past. */
1237 if (when<b->cur_obs_time)
1238 return;
1239 /* If we're currently adding observations for an earlier second than
1240 * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
1241 * appropriate number of seconds, and do all the other housekeeping */
1242 while (when>b->cur_obs_time)
1243 advance_obs(b);
1245 b->obs[b->cur_obs_idx] += n;
1246 b->total_in_period += n;
1249 /** Allocate, initialize, and return a new bw_array. */
1250 static bw_array_t *
1251 bw_array_new(void)
1253 bw_array_t *b;
1254 time_t start;
1255 b = tor_malloc_zero(sizeof(bw_array_t));
1256 rephist_total_alloc += sizeof(bw_array_t);
1257 start = time(NULL);
1258 b->cur_obs_time = start;
1259 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1260 return b;
1263 /** Recent history of bandwidth observations for read operations. */
1264 static bw_array_t *read_array = NULL;
1265 /** Recent history of bandwidth observations for write operations. */
1266 static bw_array_t *write_array = NULL;
1268 /** Set up read_array and write_array. */
1269 static void
1270 bw_arrays_init(void)
1272 read_array = bw_array_new();
1273 write_array = bw_array_new();
1276 /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
1278 * Add num_bytes to the current running total for <b>when</b>.
1280 * <b>when</b> can go back to time, but it's safe to ignore calls
1281 * earlier than the latest <b>when</b> you've heard of.
1283 void
1284 rep_hist_note_bytes_written(size_t num_bytes, time_t when)
1286 /* Maybe a circular array for recent seconds, and step to a new point
1287 * every time a new second shows up. Or simpler is to just to have
1288 * a normal array and push down each item every second; it's short.
1290 /* When a new second has rolled over, compute the sum of the bytes we've
1291 * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
1292 * somewhere. See rep_hist_bandwidth_assess() below.
1294 add_obs(write_array, when, num_bytes);
1297 /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
1298 * (like rep_hist_note_bytes_written() above)
1300 void
1301 rep_hist_note_bytes_read(size_t num_bytes, time_t when)
1303 /* if we're smart, we can make this func and the one above share code */
1304 add_obs(read_array, when, num_bytes);
1307 /** Helper: Return the largest value in b->maxima. (This is equal to the
1308 * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
1309 * NUM_SECS_BW_SUM_IS_VALID seconds.)
1311 static uint64_t
1312 find_largest_max(bw_array_t *b)
1314 int i;
1315 uint64_t max;
1316 max=0;
1317 for (i=0; i<NUM_TOTALS; ++i) {
1318 if (b->maxima[i]>max)
1319 max = b->maxima[i];
1321 return max;
1324 /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
1325 * seconds. Find one sum for reading and one for writing. They don't have
1326 * to be at the same time.
1328 * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
1331 rep_hist_bandwidth_assess(void)
1333 uint64_t w,r;
1334 r = find_largest_max(read_array);
1335 w = find_largest_max(write_array);
1336 if (r>w)
1337 return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
1338 else
1339 return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
1342 /** Print the bandwidth history of b (either read_array or write_array)
1343 * into the buffer pointed to by buf. The format is simply comma
1344 * separated numbers, from oldest to newest.
1346 * It returns the number of bytes written.
1348 static size_t
1349 rep_hist_fill_bandwidth_history(char *buf, size_t len, bw_array_t *b)
1351 char *cp = buf;
1352 int i, n;
1353 or_options_t *options = get_options();
1354 uint64_t cutoff;
1356 if (b->num_maxes_set <= b->next_max_idx) {
1357 /* We haven't been through the circular array yet; time starts at i=0.*/
1358 i = 0;
1359 } else {
1360 /* We've been around the array at least once. The next i to be
1361 overwritten is the oldest. */
1362 i = b->next_max_idx;
1365 if (options->RelayBandwidthRate) {
1366 /* We don't want to report that we used more bandwidth than the max we're
1367 * willing to relay; otherwise everybody will know how much traffic
1368 * we used ourself. */
1369 cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
1370 } else {
1371 cutoff = UINT64_MAX;
1374 for (n=0; n<b->num_maxes_set; ++n,++i) {
1375 uint64_t total;
1376 if (i >= NUM_TOTALS)
1377 i -= NUM_TOTALS;
1378 tor_assert(i < NUM_TOTALS);
1379 /* Round the bandwidth used down to the nearest 1k. */
1380 total = b->totals[i] & ~0x3ff;
1381 if (total > cutoff)
1382 total = cutoff;
1384 if (n==(b->num_maxes_set-1))
1385 tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
1386 else
1387 tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
1388 cp += strlen(cp);
1390 return cp-buf;
1393 /** Allocate and return lines for representing this server's bandwidth
1394 * history in its descriptor.
1396 char *
1397 rep_hist_get_bandwidth_lines(int for_extrainfo)
1399 char *buf, *cp;
1400 char t[ISO_TIME_LEN+1];
1401 int r;
1402 bw_array_t *b;
1403 size_t len;
1405 /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
1406 len = (60+20*NUM_TOTALS)*2;
1407 buf = tor_malloc_zero(len);
1408 cp = buf;
1409 for (r=0;r<2;++r) {
1410 b = r?read_array:write_array;
1411 tor_assert(b);
1412 format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
1413 tor_snprintf(cp, len-(cp-buf), "%s%s %s (%d s) ",
1414 for_extrainfo ? "" : "opt ",
1415 r ? "read-history" : "write-history", t,
1416 NUM_SECS_BW_SUM_INTERVAL);
1417 cp += strlen(cp);
1418 cp += rep_hist_fill_bandwidth_history(cp, len-(cp-buf), b);
1419 strlcat(cp, "\n", len-(cp-buf));
1420 ++cp;
1422 return buf;
1425 /** Update <b>state</b> with the newest bandwidth history. */
1426 void
1427 rep_hist_update_state(or_state_t *state)
1429 int len, r;
1430 char *buf, *cp;
1431 smartlist_t **s_values;
1432 time_t *s_begins;
1433 int *s_interval;
1434 bw_array_t *b;
1436 len = 20*NUM_TOTALS+1;
1437 buf = tor_malloc_zero(len);
1439 for (r=0;r<2;++r) {
1440 b = r?read_array:write_array;
1441 s_begins = r?&state->BWHistoryReadEnds :&state->BWHistoryWriteEnds;
1442 s_interval= r?&state->BWHistoryReadInterval:&state->BWHistoryWriteInterval;
1443 s_values = r?&state->BWHistoryReadValues :&state->BWHistoryWriteValues;
1445 if (*s_values) {
1446 SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
1447 smartlist_free(*s_values);
1449 if (! server_mode(get_options())) {
1450 /* Clients don't need to store bandwidth history persistently;
1451 * force these values to the defaults. */
1452 /* FFFF we should pull the default out of config.c's state table,
1453 * so we don't have two defaults. */
1454 if (*s_begins != 0 || *s_interval != 900) {
1455 time_t now = time(NULL);
1456 time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
1457 or_state_mark_dirty(state, save_at);
1459 *s_begins = 0;
1460 *s_interval = 900;
1461 *s_values = smartlist_create();
1462 continue;
1464 *s_begins = b->next_period;
1465 *s_interval = NUM_SECS_BW_SUM_INTERVAL;
1466 cp = buf;
1467 cp += rep_hist_fill_bandwidth_history(cp, len, b);
1468 tor_snprintf(cp, len-(cp-buf), cp == buf ? U64_FORMAT : ","U64_FORMAT,
1469 U64_PRINTF_ARG(b->total_in_period));
1470 *s_values = smartlist_create();
1471 if (server_mode(get_options()))
1472 smartlist_split_string(*s_values, buf, ",", SPLIT_SKIP_SPACE, 0);
1474 tor_free(buf);
1475 if (server_mode(get_options())) {
1476 or_state_mark_dirty(get_or_state(), time(NULL)+(2*3600));
1480 /** Set bandwidth history from our saved state. */
1482 rep_hist_load_state(or_state_t *state, char **err)
1484 time_t s_begins, start;
1485 time_t now = time(NULL);
1486 uint64_t v;
1487 int r,i,ok;
1488 int all_ok = 1;
1489 int s_interval;
1490 smartlist_t *s_values;
1491 bw_array_t *b;
1493 /* Assert they already have been malloced */
1494 tor_assert(read_array && write_array);
1496 for (r=0;r<2;++r) {
1497 b = r?read_array:write_array;
1498 s_begins = r?state->BWHistoryReadEnds:state->BWHistoryWriteEnds;
1499 s_interval = r?state->BWHistoryReadInterval:state->BWHistoryWriteInterval;
1500 s_values = r?state->BWHistoryReadValues:state->BWHistoryWriteValues;
1501 if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
1502 start = s_begins - s_interval*(smartlist_len(s_values));
1503 if (start > now)
1504 continue;
1505 b->cur_obs_time = start;
1506 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1507 SMARTLIST_FOREACH(s_values, char *, cp, {
1508 v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
1509 if (!ok) {
1510 all_ok=0;
1511 log_notice(LD_HIST, "Could not parse '%s' into a number.'", cp);
1513 if (start < now) {
1514 add_obs(b, start, v);
1515 start += NUM_SECS_BW_SUM_INTERVAL;
1520 /* Clean up maxima and observed */
1521 /* Do we really want to zero this for the purpose of max capacity? */
1522 for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
1523 b->obs[i] = 0;
1525 b->total_obs = 0;
1526 for (i=0; i<NUM_TOTALS; ++i) {
1527 b->maxima[i] = 0;
1529 b->max_total = 0;
1532 if (!all_ok) {
1533 *err = tor_strdup("Parsing of bandwidth history values failed");
1534 /* and create fresh arrays */
1535 tor_free(read_array);
1536 tor_free(write_array);
1537 read_array = bw_array_new();
1538 write_array = bw_array_new();
1539 return -1;
1541 return 0;
1544 /*********************************************************************/
1546 /** A list of port numbers that have been used recently. */
1547 static smartlist_t *predicted_ports_list=NULL;
1548 /** The corresponding most recently used time for each port. */
1549 static smartlist_t *predicted_ports_times=NULL;
1551 /** We just got an application request for a connection with
1552 * port <b>port</b>. Remember it for the future, so we can keep
1553 * some circuits open that will exit to this port.
1555 static void
1556 add_predicted_port(time_t now, uint16_t port)
1558 /* XXXX we could just use uintptr_t here, I think. */
1559 uint16_t *tmp_port = tor_malloc(sizeof(uint16_t));
1560 time_t *tmp_time = tor_malloc(sizeof(time_t));
1561 *tmp_port = port;
1562 *tmp_time = now;
1563 rephist_total_alloc += sizeof(uint16_t) + sizeof(time_t);
1564 smartlist_add(predicted_ports_list, tmp_port);
1565 smartlist_add(predicted_ports_times, tmp_time);
1568 /** Initialize whatever memory and structs are needed for predicting
1569 * which ports will be used. Also seed it with port 80, so we'll build
1570 * circuits on start-up.
1572 static void
1573 predicted_ports_init(void)
1575 predicted_ports_list = smartlist_create();
1576 predicted_ports_times = smartlist_create();
1577 add_predicted_port(time(NULL), 80); /* add one to kickstart us */
1580 /** Free whatever memory is needed for predicting which ports will
1581 * be used.
1583 static void
1584 predicted_ports_free(void)
1586 rephist_total_alloc -= smartlist_len(predicted_ports_list)*sizeof(uint16_t);
1587 SMARTLIST_FOREACH(predicted_ports_list, char *, cp, tor_free(cp));
1588 smartlist_free(predicted_ports_list);
1589 rephist_total_alloc -= smartlist_len(predicted_ports_times)*sizeof(time_t);
1590 SMARTLIST_FOREACH(predicted_ports_times, char *, cp, tor_free(cp));
1591 smartlist_free(predicted_ports_times);
1594 /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
1595 * This is used for predicting what sorts of streams we'll make in the
1596 * future and making exit circuits to anticipate that.
1598 void
1599 rep_hist_note_used_port(time_t now, uint16_t port)
1601 int i;
1602 uint16_t *tmp_port;
1603 time_t *tmp_time;
1605 tor_assert(predicted_ports_list);
1606 tor_assert(predicted_ports_times);
1608 if (!port) /* record nothing */
1609 return;
1611 for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
1612 tmp_port = smartlist_get(predicted_ports_list, i);
1613 tmp_time = smartlist_get(predicted_ports_times, i);
1614 if (*tmp_port == port) {
1615 *tmp_time = now;
1616 return;
1619 /* it's not there yet; we need to add it */
1620 add_predicted_port(now, port);
1623 /** For this long after we've seen a request for a given port, assume that
1624 * we'll want to make connections to the same port in the future. */
1625 #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
1627 /** Return a pointer to the list of port numbers that
1628 * are likely to be asked for in the near future.
1630 * The caller promises not to mess with it.
1632 smartlist_t *
1633 rep_hist_get_predicted_ports(time_t now)
1635 int i;
1636 uint16_t *tmp_port;
1637 time_t *tmp_time;
1639 tor_assert(predicted_ports_list);
1640 tor_assert(predicted_ports_times);
1642 /* clean out obsolete entries */
1643 for (i = 0; i < smartlist_len(predicted_ports_list); ++i) {
1644 tmp_time = smartlist_get(predicted_ports_times, i);
1645 if (*tmp_time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
1646 tmp_port = smartlist_get(predicted_ports_list, i);
1647 log_debug(LD_CIRC, "Expiring predicted port %d", *tmp_port);
1648 smartlist_del(predicted_ports_list, i);
1649 smartlist_del(predicted_ports_times, i);
1650 rephist_total_alloc -= sizeof(uint16_t)+sizeof(time_t);
1651 tor_free(tmp_port);
1652 tor_free(tmp_time);
1653 i--;
1656 return predicted_ports_list;
1659 /** The user asked us to do a resolve. Rather than keeping track of
1660 * timings and such of resolves, we fake it for now by treating
1661 * it the same way as a connection to port 80. This way we will continue
1662 * to have circuits lying around if the user only uses Tor for resolves.
1664 void
1665 rep_hist_note_used_resolve(time_t now)
1667 rep_hist_note_used_port(now, 80);
1670 /** The last time at which we needed an internal circ. */
1671 static time_t predicted_internal_time = 0;
1672 /** The last time we needed an internal circ with good uptime. */
1673 static time_t predicted_internal_uptime_time = 0;
1674 /** The last time we needed an internal circ with good capacity. */
1675 static time_t predicted_internal_capacity_time = 0;
1677 /** Remember that we used an internal circ at time <b>now</b>. */
1678 void
1679 rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
1681 predicted_internal_time = now;
1682 if (need_uptime)
1683 predicted_internal_uptime_time = now;
1684 if (need_capacity)
1685 predicted_internal_capacity_time = now;
1688 /** Return 1 if we've used an internal circ recently; else return 0. */
1690 rep_hist_get_predicted_internal(time_t now, int *need_uptime,
1691 int *need_capacity)
1693 if (!predicted_internal_time) { /* initialize it */
1694 predicted_internal_time = now;
1695 predicted_internal_uptime_time = now;
1696 predicted_internal_capacity_time = now;
1698 if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
1699 return 0; /* too long ago */
1700 if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
1701 *need_uptime = 1;
1702 if (predicted_internal_capacity_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
1703 *need_capacity = 1;
1704 return 1;
1707 /** Any ports used lately? These are pre-seeded if we just started
1708 * up or if we're running a hidden service. */
1710 any_predicted_circuits(time_t now)
1712 return smartlist_len(predicted_ports_list) ||
1713 predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now;
1716 /** Return 1 if we have no need for circuits currently, else return 0. */
1718 rep_hist_circbuilding_dormant(time_t now)
1720 if (any_predicted_circuits(now))
1721 return 0;
1723 /* see if we'll still need to build testing circuits */
1724 if (server_mode(get_options()) &&
1725 (!check_whether_orport_reachable() || !circuit_enough_testing_circs()))
1726 return 0;
1727 if (!check_whether_dirport_reachable())
1728 return 0;
1730 return 1;
1733 /** Structure to track how many times we've done each public key operation. */
1734 static struct {
1735 /** How many directory objects have we signed? */
1736 unsigned long n_signed_dir_objs;
1737 /** How many routerdescs have we signed? */
1738 unsigned long n_signed_routerdescs;
1739 /** How many directory objects have we verified? */
1740 unsigned long n_verified_dir_objs;
1741 /** How many routerdescs have we verified */
1742 unsigned long n_verified_routerdescs;
1743 /** How many onionskins have we encrypted to build circuits? */
1744 unsigned long n_onionskins_encrypted;
1745 /** How many onionskins have we decrypted to do circuit build requests? */
1746 unsigned long n_onionskins_decrypted;
1747 /** How many times have we done the TLS handshake as a client? */
1748 unsigned long n_tls_client_handshakes;
1749 /** How many times have we done the TLS handshake as a server? */
1750 unsigned long n_tls_server_handshakes;
1751 /** How many PK operations have we done as a hidden service client? */
1752 unsigned long n_rend_client_ops;
1753 /** How many PK operations have we done as a hidden service midpoint? */
1754 unsigned long n_rend_mid_ops;
1755 /** How many PK operations have we done as a hidden service provider? */
1756 unsigned long n_rend_server_ops;
1757 } pk_op_counts = {0,0,0,0,0,0,0,0,0,0,0};
1759 /** Increment the count of the number of times we've done <b>operation</b>. */
1760 void
1761 note_crypto_pk_op(pk_op_t operation)
1763 switch (operation)
1765 case SIGN_DIR:
1766 pk_op_counts.n_signed_dir_objs++;
1767 break;
1768 case SIGN_RTR:
1769 pk_op_counts.n_signed_routerdescs++;
1770 break;
1771 case VERIFY_DIR:
1772 pk_op_counts.n_verified_dir_objs++;
1773 break;
1774 case VERIFY_RTR:
1775 pk_op_counts.n_verified_routerdescs++;
1776 break;
1777 case ENC_ONIONSKIN:
1778 pk_op_counts.n_onionskins_encrypted++;
1779 break;
1780 case DEC_ONIONSKIN:
1781 pk_op_counts.n_onionskins_decrypted++;
1782 break;
1783 case TLS_HANDSHAKE_C:
1784 pk_op_counts.n_tls_client_handshakes++;
1785 break;
1786 case TLS_HANDSHAKE_S:
1787 pk_op_counts.n_tls_server_handshakes++;
1788 break;
1789 case REND_CLIENT:
1790 pk_op_counts.n_rend_client_ops++;
1791 break;
1792 case REND_MID:
1793 pk_op_counts.n_rend_mid_ops++;
1794 break;
1795 case REND_SERVER:
1796 pk_op_counts.n_rend_server_ops++;
1797 break;
1798 default:
1799 log_warn(LD_BUG, "Unknown pk operation %d", operation);
1803 /** Log the number of times we've done each public/private-key operation. */
1804 void
1805 dump_pk_ops(int severity)
1807 log(severity, LD_HIST,
1808 "PK operations: %lu directory objects signed, "
1809 "%lu directory objects verified, "
1810 "%lu routerdescs signed, "
1811 "%lu routerdescs verified, "
1812 "%lu onionskins encrypted, "
1813 "%lu onionskins decrypted, "
1814 "%lu client-side TLS handshakes, "
1815 "%lu server-side TLS handshakes, "
1816 "%lu rendezvous client operations, "
1817 "%lu rendezvous middle operations, "
1818 "%lu rendezvous server operations.",
1819 pk_op_counts.n_signed_dir_objs,
1820 pk_op_counts.n_verified_dir_objs,
1821 pk_op_counts.n_signed_routerdescs,
1822 pk_op_counts.n_verified_routerdescs,
1823 pk_op_counts.n_onionskins_encrypted,
1824 pk_op_counts.n_onionskins_decrypted,
1825 pk_op_counts.n_tls_client_handshakes,
1826 pk_op_counts.n_tls_server_handshakes,
1827 pk_op_counts.n_rend_client_ops,
1828 pk_op_counts.n_rend_mid_ops,
1829 pk_op_counts.n_rend_server_ops);
1832 /** Free all storage held by the OR/link history caches, by the
1833 * bandwidth history arrays, or by the port history. */
1834 void
1835 rep_hist_free_all(void)
1837 digestmap_free(history_map, free_or_history);
1838 tor_free(read_array);
1839 tor_free(write_array);
1840 tor_free(last_stability_doc);
1841 built_last_stability_doc_at = 0;
1842 predicted_ports_free();
1845 /****************** hidden service usage statistics ******************/
1847 /** How large are the intervals for which we track and report hidden service
1848 * use? */
1849 #define NUM_SECS_HS_USAGE_SUM_INTERVAL (15*60)
1850 /** How far in the past do we remember and publish hidden service use? */
1851 #define NUM_SECS_HS_USAGE_SUM_IS_VALID (24*60*60)
1852 /** How many hidden service usage intervals do we remember? (derived) */
1853 #define NUM_TOTALS_HS_USAGE (NUM_SECS_HS_USAGE_SUM_IS_VALID/ \
1854 NUM_SECS_HS_USAGE_SUM_INTERVAL)
1856 /** List element containing a service id and the count. */
1857 typedef struct hs_usage_list_elem_t {
1858 /** Service id of this elem. */
1859 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
1860 /** Number of occurrences for the given service id. */
1861 uint32_t count;
1862 /* Pointer to next list elem */
1863 struct hs_usage_list_elem_t *next;
1864 } hs_usage_list_elem_t;
1866 /** Ordered list that stores service ids and the number of observations. It is
1867 * ordered by the number of occurrences in descending order. Its purpose is to
1868 * calculate the frequency distribution when the period is over. */
1869 typedef struct hs_usage_list_t {
1870 /* Pointer to the first element in the list. */
1871 hs_usage_list_elem_t *start;
1872 /* Number of total occurrences for all list elements. */
1873 uint32_t total_count;
1874 /* Number of service ids, i.e. number of list elements. */
1875 uint32_t total_service_ids;
1876 } hs_usage_list_t;
1878 /** Tracks service-related observations in the current period and their
1879 * history. */
1880 typedef struct hs_usage_service_related_observation_t {
1881 /** Ordered list that stores service ids and the number of observations in
1882 * the current period. It is ordered by the number of occurrences in
1883 * descending order. Its purpose is to calculate the frequency distribution
1884 * when the period is over. */
1885 hs_usage_list_t *list;
1886 /** Circular arrays that store the history of observations. totals stores all
1887 * observations, twenty (ten, five) the number of observations related to a
1888 * service id being accounted for the top 20 (10, 5) percent of all
1889 * observations. */
1890 uint32_t totals[NUM_TOTALS_HS_USAGE];
1891 uint32_t five[NUM_TOTALS_HS_USAGE];
1892 uint32_t ten[NUM_TOTALS_HS_USAGE];
1893 uint32_t twenty[NUM_TOTALS_HS_USAGE];
1894 } hs_usage_service_related_observation_t;
1896 /** Tracks the history of general period-related observations, i.e. those that
1897 * cannot be related to a specific service id. */
1898 typedef struct hs_usage_general_period_related_observations_t {
1899 /** Circular array that stores the history of observations. */
1900 uint32_t totals[NUM_TOTALS_HS_USAGE];
1901 } hs_usage_general_period_related_observations_t;
1903 /** Keeps information about the current observation period and its relation to
1904 * the histories of observations. */
1905 typedef struct hs_usage_current_observation_period_t {
1906 /** Where do we write the next history entry? */
1907 int next_idx;
1908 /** How many values in history have been set ever? (upper bound!) */
1909 int num_set;
1910 /** When did this period begin? */
1911 time_t start_of_current_period;
1912 /** When does the next period begin? */
1913 time_t start_of_next_period;
1914 } hs_usage_current_observation_period_t;
1916 /** Usage statistics for the current observation period. */
1917 static hs_usage_current_observation_period_t *current_period = NULL;
1919 /** Total number of descriptor publish requests in the current observation
1920 * period. */
1921 static hs_usage_service_related_observation_t *publish_total = NULL;
1923 /** Number of descriptor publish requests for services that have not been
1924 * seen before in the current observation period. */
1925 static hs_usage_service_related_observation_t *publish_novel = NULL;
1927 /** Total number of descriptor fetch requests in the current observation
1928 * period. */
1929 static hs_usage_service_related_observation_t *fetch_total = NULL;
1931 /** Number of successful descriptor fetch requests in the current
1932 * observation period. */
1933 static hs_usage_service_related_observation_t *fetch_successful = NULL;
1935 /** Number of descriptors stored in the current observation period. */
1936 static hs_usage_general_period_related_observations_t *descs = NULL;
1938 /** Creates an empty ordered list element. */
1939 static hs_usage_list_elem_t *
1940 hs_usage_list_elem_new(void)
1942 hs_usage_list_elem_t *e;
1943 e = tor_malloc_zero(sizeof(hs_usage_list_elem_t));
1944 rephist_total_alloc += sizeof(hs_usage_list_elem_t);
1945 e->count = 1;
1946 e->next = NULL;
1947 return e;
1950 /** Creates an empty ordered list. */
1951 static hs_usage_list_t *
1952 hs_usage_list_new(void)
1954 hs_usage_list_t *l;
1955 l = tor_malloc_zero(sizeof(hs_usage_list_t));
1956 rephist_total_alloc += sizeof(hs_usage_list_t);
1957 l->start = NULL;
1958 l->total_count = 0;
1959 l->total_service_ids = 0;
1960 return l;
1963 /** Creates an empty structure for storing service-related observations. */
1964 static hs_usage_service_related_observation_t *
1965 hs_usage_service_related_observation_new(void)
1967 hs_usage_service_related_observation_t *h;
1968 h = tor_malloc_zero(sizeof(hs_usage_service_related_observation_t));
1969 rephist_total_alloc += sizeof(hs_usage_service_related_observation_t);
1970 h->list = hs_usage_list_new();
1971 return h;
1974 /** Creates an empty structure for storing general period-related
1975 * observations. */
1976 static hs_usage_general_period_related_observations_t *
1977 hs_usage_general_period_related_observations_new(void)
1979 hs_usage_general_period_related_observations_t *p;
1980 p = tor_malloc_zero(sizeof(hs_usage_general_period_related_observations_t));
1981 rephist_total_alloc+= sizeof(hs_usage_general_period_related_observations_t);
1982 return p;
1985 /** Creates an empty structure for storing period-specific information. */
1986 static hs_usage_current_observation_period_t *
1987 hs_usage_current_observation_period_new(void)
1989 hs_usage_current_observation_period_t *c;
1990 time_t now;
1991 c = tor_malloc_zero(sizeof(hs_usage_current_observation_period_t));
1992 rephist_total_alloc += sizeof(hs_usage_current_observation_period_t);
1993 now = time(NULL);
1994 c->start_of_current_period = now;
1995 c->start_of_next_period = now + NUM_SECS_HS_USAGE_SUM_INTERVAL;
1996 return c;
1999 /** Initializes the structures for collecting hidden service usage data. */
2000 static void
2001 hs_usage_init(void)
2003 current_period = hs_usage_current_observation_period_new();
2004 publish_total = hs_usage_service_related_observation_new();
2005 publish_novel = hs_usage_service_related_observation_new();
2006 fetch_total = hs_usage_service_related_observation_new();
2007 fetch_successful = hs_usage_service_related_observation_new();
2008 descs = hs_usage_general_period_related_observations_new();
2011 /** Clears the given ordered list by resetting its attributes and releasing
2012 * the memory allocated by its elements. */
2013 static void
2014 hs_usage_list_clear(hs_usage_list_t *lst)
2016 /* walk through elements and free memory */
2017 hs_usage_list_elem_t *current = lst->start;
2018 hs_usage_list_elem_t *tmp;
2019 while (current != NULL) {
2020 tmp = current->next;
2021 rephist_total_alloc -= sizeof(hs_usage_list_elem_t);
2022 tor_free(current);
2023 current = tmp;
2025 /* reset attributes */
2026 lst->start = NULL;
2027 lst->total_count = 0;
2028 lst->total_service_ids = 0;
2029 return;
2032 /** Frees the memory used by the given list. */
2033 static void
2034 hs_usage_list_free(hs_usage_list_t *lst)
2036 if (!lst)
2037 return;
2038 hs_usage_list_clear(lst);
2039 rephist_total_alloc -= sizeof(hs_usage_list_t);
2040 tor_free(lst);
2043 /** Frees the memory used by the given service-related observations. */
2044 static void
2045 hs_usage_service_related_observation_free(
2046 hs_usage_service_related_observation_t *s)
2048 if (!s)
2049 return;
2050 hs_usage_list_free(s->list);
2051 rephist_total_alloc -= sizeof(hs_usage_service_related_observation_t);
2052 tor_free(s);
2055 /** Frees the memory used by the given period-specific observations. */
2056 static void
2057 hs_usage_general_period_related_observations_free(
2058 hs_usage_general_period_related_observations_t *s)
2060 rephist_total_alloc-=sizeof(hs_usage_general_period_related_observations_t);
2061 tor_free(s);
2064 /** Frees the memory used by period-specific information. */
2065 static void
2066 hs_usage_current_observation_period_free(
2067 hs_usage_current_observation_period_t *s)
2069 rephist_total_alloc -= sizeof(hs_usage_current_observation_period_t);
2070 tor_free(s);
2073 /** Frees all memory that was used for collecting hidden service usage data. */
2074 void
2075 hs_usage_free_all(void)
2077 hs_usage_general_period_related_observations_free(descs);
2078 descs = NULL;
2079 hs_usage_service_related_observation_free(fetch_successful);
2080 hs_usage_service_related_observation_free(fetch_total);
2081 hs_usage_service_related_observation_free(publish_novel);
2082 hs_usage_service_related_observation_free(publish_total);
2083 fetch_successful = fetch_total = publish_novel = publish_total = NULL;
2084 hs_usage_current_observation_period_free(current_period);
2085 current_period = NULL;
2088 /** Inserts a new occurrence for the given service id to the given ordered
2089 * list. */
2090 static void
2091 hs_usage_insert_value(hs_usage_list_t *lst, const char *service_id)
2093 /* search if there is already an elem with same service_id in list */
2094 hs_usage_list_elem_t *current = lst->start;
2095 hs_usage_list_elem_t *previous = NULL;
2096 while (current != NULL && strcasecmp(current->service_id,service_id)) {
2097 previous = current;
2098 current = current->next;
2100 /* found an element with same service_id? */
2101 if (current == NULL) {
2102 /* not found! append to end (which could also be the end of a zero-length
2103 * list), don't need to sort (1 is smallest value). */
2104 /* create elem */
2105 hs_usage_list_elem_t *e = hs_usage_list_elem_new();
2106 /* update list attributes (one new elem, one new occurrence) */
2107 lst->total_count++;
2108 lst->total_service_ids++;
2109 /* copy service id to elem */
2110 strlcpy(e->service_id,service_id,sizeof(e->service_id));
2111 /* let either l->start or previously last elem point to new elem */
2112 if (lst->start == NULL) {
2113 /* this is the first elem */
2114 lst->start = e;
2115 } else {
2116 /* there were elems in the list before */
2117 previous->next = e;
2119 } else {
2120 /* found! add occurrence to elem and consider resorting */
2121 /* update list attributes (no new elem, but one new occurrence) */
2122 lst->total_count++;
2123 /* add occurrence to elem */
2124 current->count++;
2125 /* is it another than the first list elem? and has previous elem fewer
2126 * count than current? then we need to resort */
2127 if (previous != NULL && previous->count < current->count) {
2128 /* yes! we need to resort */
2129 /* remove current elem first */
2130 previous->next = current->next;
2131 /* can we prepend elem to all other elements? */
2132 if (lst->start->count <= current->count) {
2133 /* yes! prepend elem */
2134 current->next = lst->start;
2135 lst->start = current;
2136 } else {
2137 /* no! walk through list a second time and insert at correct place */
2138 hs_usage_list_elem_t *insert_current = lst->start->next;
2139 hs_usage_list_elem_t *insert_previous = lst->start;
2140 while (insert_current != NULL &&
2141 insert_current->count > current->count) {
2142 insert_previous = insert_current;
2143 insert_current = insert_current->next;
2145 /* insert here */
2146 current->next = insert_current;
2147 insert_previous->next = current;
2153 /** Writes the current service-related observations to the history array and
2154 * clears the observations of the current period. */
2155 static void
2156 hs_usage_write_service_related_observations_to_history(
2157 hs_usage_current_observation_period_t *p,
2158 hs_usage_service_related_observation_t *h)
2160 /* walk through the first 20 % of list elements and calculate frequency
2161 * distributions */
2162 /* maximum indices for the three frequencies */
2163 int five_percent_idx = h->list->total_service_ids/20;
2164 int ten_percent_idx = h->list->total_service_ids/10;
2165 int twenty_percent_idx = h->list->total_service_ids/5;
2166 /* temp values */
2167 uint32_t five_percent = 0;
2168 uint32_t ten_percent = 0;
2169 uint32_t twenty_percent = 0;
2170 /* walk through list */
2171 hs_usage_list_elem_t *current = h->list->start;
2172 int i=0;
2173 while (current != NULL && i <= twenty_percent_idx) {
2174 twenty_percent += current->count;
2175 if (i <= ten_percent_idx)
2176 ten_percent += current->count;
2177 if (i <= five_percent_idx)
2178 five_percent += current->count;
2179 current = current->next;
2180 i++;
2182 /* copy frequencies */
2183 h->twenty[p->next_idx] = twenty_percent;
2184 h->ten[p->next_idx] = ten_percent;
2185 h->five[p->next_idx] = five_percent;
2186 /* copy total number of observations */
2187 h->totals[p->next_idx] = h->list->total_count;
2188 /* free memory of old list */
2189 hs_usage_list_clear(h->list);
2192 /** Advances to next observation period. */
2193 static void
2194 hs_usage_advance_current_observation_period(void)
2196 /* aggregate observations to history, including frequency distribution
2197 * arrays */
2198 hs_usage_write_service_related_observations_to_history(
2199 current_period, publish_total);
2200 hs_usage_write_service_related_observations_to_history(
2201 current_period, publish_novel);
2202 hs_usage_write_service_related_observations_to_history(
2203 current_period, fetch_total);
2204 hs_usage_write_service_related_observations_to_history(
2205 current_period, fetch_successful);
2206 /* write current number of descriptors to descs history */
2207 descs->totals[current_period->next_idx] = rend_cache_size();
2208 /* advance to next period */
2209 current_period->next_idx++;
2210 if (current_period->next_idx == NUM_TOTALS_HS_USAGE)
2211 current_period->next_idx = 0;
2212 if (current_period->num_set < NUM_TOTALS_HS_USAGE)
2213 ++current_period->num_set;
2214 current_period->start_of_current_period=current_period->start_of_next_period;
2215 current_period->start_of_next_period += NUM_SECS_HS_USAGE_SUM_INTERVAL;
2218 /** Checks if the current period is up to date, and if not, advances it. */
2219 static void
2220 hs_usage_check_if_current_period_is_up_to_date(time_t now)
2222 while (now > current_period->start_of_next_period) {
2223 hs_usage_advance_current_observation_period();
2227 /** Adds a service-related observation, maybe after advancing to next
2228 * observation period. */
2229 static void
2230 hs_usage_add_service_related_observation(
2231 hs_usage_service_related_observation_t *h,
2232 time_t now,
2233 const char *service_id)
2235 if (now < current_period->start_of_current_period) {
2236 /* don't record old data */
2237 return;
2239 /* check if we are up-to-date */
2240 hs_usage_check_if_current_period_is_up_to_date(now);
2241 /* add observation */
2242 hs_usage_insert_value(h->list, service_id);
2245 /** Adds the observation of storing a rendezvous service descriptor to our
2246 * cache in our role as HS authoritative directory. */
2247 void
2248 hs_usage_note_publish_total(const char *service_id, time_t now)
2250 hs_usage_add_service_related_observation(publish_total, now, service_id);
2253 /** Adds the observation of storing a novel rendezvous service descriptor to
2254 * our cache in our role as HS authoritative directory. */
2255 void
2256 hs_usage_note_publish_novel(const char *service_id, time_t now)
2258 hs_usage_add_service_related_observation(publish_novel, now, service_id);
2261 /** Adds the observation of being requested for a rendezvous service descriptor
2262 * in our role as HS authoritative directory. */
2263 void
2264 hs_usage_note_fetch_total(const char *service_id, time_t now)
2266 hs_usage_add_service_related_observation(fetch_total, now, service_id);
2269 /** Adds the observation of being requested for a rendezvous service descriptor
2270 * in our role as HS authoritative directory and being able to answer that
2271 * request successfully. */
2272 void
2273 hs_usage_note_fetch_successful(const char *service_id, time_t now)
2275 hs_usage_add_service_related_observation(fetch_successful, now, service_id);
2278 /** Writes the given circular array to a string. */
2279 static size_t
2280 hs_usage_format_history(char *buf, size_t len, uint32_t *data)
2282 char *cp = buf; /* pointer where we are in the buffer */
2283 int i, n;
2284 if (current_period->num_set <= current_period->next_idx) {
2285 i = 0; /* not been through circular array */
2286 } else {
2287 i = current_period->next_idx;
2289 for (n = 0; n < current_period->num_set; ++n,++i) {
2290 if (i >= NUM_TOTALS_HS_USAGE)
2291 i -= NUM_TOTALS_HS_USAGE;
2292 tor_assert(i < NUM_TOTALS_HS_USAGE);
2293 if (n == (current_period->num_set-1))
2294 tor_snprintf(cp, len-(cp-buf), "%d", data[i]);
2295 else
2296 tor_snprintf(cp, len-(cp-buf), "%d,", data[i]);
2297 cp += strlen(cp);
2299 return cp-buf;
2302 /** Writes the complete usage history as hidden service authoritative directory
2303 * to a string. */
2304 static char *
2305 hs_usage_format_statistics(void)
2307 char *buf, *cp, *s = NULL;
2308 char t[ISO_TIME_LEN+1];
2309 int r;
2310 uint32_t *data = NULL;
2311 size_t len;
2312 len = (70+20*NUM_TOTALS_HS_USAGE)*11;
2313 buf = tor_malloc_zero(len);
2314 cp = buf;
2315 for (r = 0; r < 11; ++r) {
2316 switch (r) {
2317 case 0:
2318 s = (char*) "publish-total-history";
2319 data = publish_total->totals;
2320 break;
2321 case 1:
2322 s = (char*) "publish-novel-history";
2323 data = publish_novel->totals;
2324 break;
2325 case 2:
2326 s = (char*) "publish-top-5-percent-history";
2327 data = publish_total->five;
2328 break;
2329 case 3:
2330 s = (char*) "publish-top-10-percent-history";
2331 data = publish_total->ten;
2332 break;
2333 case 4:
2334 s = (char*) "publish-top-20-percent-history";
2335 data = publish_total->twenty;
2336 break;
2337 case 5:
2338 s = (char*) "fetch-total-history";
2339 data = fetch_total->totals;
2340 break;
2341 case 6:
2342 s = (char*) "fetch-successful-history";
2343 data = fetch_successful->totals;
2344 break;
2345 case 7:
2346 s = (char*) "fetch-top-5-percent-history";
2347 data = fetch_total->five;
2348 break;
2349 case 8:
2350 s = (char*) "fetch-top-10-percent-history";
2351 data = fetch_total->ten;
2352 break;
2353 case 9:
2354 s = (char*) "fetch-top-20-percent-history";
2355 data = fetch_total->twenty;
2356 break;
2357 case 10:
2358 s = (char*) "desc-total-history";
2359 data = descs->totals;
2360 break;
2362 format_iso_time(t, current_period->start_of_current_period);
2363 tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ", s, t,
2364 NUM_SECS_HS_USAGE_SUM_INTERVAL);
2365 cp += strlen(cp);
2366 cp += hs_usage_format_history(cp, len-(cp-buf), data);
2367 strlcat(cp, "\n", len-(cp-buf));
2368 ++cp;
2370 return buf;
2373 /** Write current statistics about hidden service usage to file. */
2374 void
2375 hs_usage_write_statistics_to_file(time_t now)
2377 char *buf;
2378 size_t len;
2379 char *fname;
2380 or_options_t *options = get_options();
2381 /* check if we are up-to-date */
2382 hs_usage_check_if_current_period_is_up_to_date(now);
2383 buf = hs_usage_format_statistics();
2384 len = strlen(options->DataDirectory) + 16;
2385 fname = tor_malloc(len);
2386 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"hsusage",
2387 options->DataDirectory);
2388 write_str_to_file(fname,buf,0);
2389 tor_free(buf);
2390 tor_free(fname);