Coveralls logob
Coveralls logo
  • Home
  • Features
  • Pricing
  • Docs
  • Sign In

tlyu / tor / 1092

24 Apr 2018 - 18:55 coverage decreased (-0.01%) to 58.863%
1092

Pull #1

travis-ci

9181eb84f9c35729a3bad740fb7f9d93?size=18&default=identiconweb-flow
mention 19429 in changes file
Pull Request #1: Ticket19429 rebased

40442 of 68705 relevant lines covered (58.86%)

27196.08 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.35
/src/or/circuitstats.c
1
/* Copyright (c) 2001 Matej Pfajfar.
2
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4
 * Copyright (c) 2007-2017, The Tor Project, Inc. */
5
/* See LICENSE for licensing information */
6

7
/**
8
 * \file circuitstats.c
9
 *
10
 * \brief Maintains and analyzes statistics about circuit built times, so we
11
 * can tell how long we may need to wait for a fast circuit to be constructed.
12
 *
13
 * By keeping these statistics, a client learns when it should time out a slow
14
 * circuit for being too slow, and when it should keep a circuit open in order
15
 * to wait for it to complete.
16
 *
17
 * The information here is kept in a circuit_built_times_t structure, which is
18
 * currently a singleton, but doesn't need to be.  It's updated by calls to
19
 * circuit_build_times_count_timeout() from circuituse.c,
20
 * circuit_build_times_count_close() from circuituse.c, and
21
 * circuit_build_times_add_time() from circuitbuild.c, and inspected by other
22
 * calls into this module, mostly from circuitlist.c.  Observations are
23
 * persisted to disk via the or_state_t-related calls.
24
 */
25

26
#define CIRCUITSTATS_PRIVATE
27

28
#include "or.h"
29
#include "circuitbuild.h"
30
#include "circuitstats.h"
31
#include "config.h"
32
#include "confparse.h"
33
#include "control.h"
34
#include "main.h"
35
#include "networkstatus.h"
36
#include "rendclient.h"
37
#include "rendservice.h"
38
#include "statefile.h"
39
#include "circuitlist.h"
40
#include "circuituse.h"
41

42
#undef log
43
#include <math.h>
44

45
static void cbt_control_event_buildtimeout_set(
46
                                  const circuit_build_times_t *cbt,
47
                                  buildtimeout_set_event_t type);
48
static void circuit_build_times_scale_circ_counts(circuit_build_times_t *cbt);
49

50
#define CBT_BIN_TO_MS(bin) ((bin)*CBT_BIN_WIDTH + (CBT_BIN_WIDTH/2))
51

52
/** Global list of circuit build times */
53
// XXXX: Add this as a member for entry_guard_t instead of global?
54
// Then we could do per-guard statistics, as guards are likely to
55
// vary in their own latency. The downside of this is that guards
56
// can change frequently, so we'd be building a lot more circuits
57
// most likely.
58
static circuit_build_times_t circ_times;
59

60
#ifdef TOR_UNIT_TESTS
61
/** If set, we're running the unit tests: we should avoid clobbering
62
 * our state file or accessing get_options() or get_or_state() */
63
static int unit_tests = 0;
64
#else
65
#define unit_tests 0
66
#endif /* defined(TOR_UNIT_TESTS) */
67

68
/** Return a pointer to the data structure describing our current circuit
69
 * build time history and computations. */
70
const circuit_build_times_t *
71
get_circuit_build_times(void)
69×
72
{
73
  return &circ_times;
69×
74
}
75

76
/** As get_circuit_build_times, but return a mutable pointer. */
77
circuit_build_times_t *
78
get_circuit_build_times_mutable(void)
108×
79
{
80
  return &circ_times;
108×
81
}
82

83
/** Return the time to wait before actually closing an under-construction, in
84
 * milliseconds. */
85
double
86
get_circuit_build_close_time_ms(void)
28×
87
{
88
  return circ_times.close_ms;
28×
89
}
90

91
/** Return the time to wait before giving up on an under-construction circuit,
92
 * in milliseconds. */
93
double
94
get_circuit_build_timeout_ms(void)
29×
95
{
96
  return circ_times.timeout_ms;
29×
97
}
98

99
/**
100
 * This function decides if CBT learning should be disabled. It returns
101
 * true if one or more of the following conditions are met:
102
 *
103
 *  1. If the cbtdisabled consensus parameter is set.
104
 *  2. If the torrc option LearnCircuitBuildTimeout is false.
105
 *  3. If we are a directory authority
106
 *  4. If we fail to write circuit build time history to our state file.
107
 *  5. If we are compiled or configured in Tor2web mode
108
 *  6. If we are configured in Single Onion mode
109
 */
110
int
111
circuit_build_times_disabled(const or_options_t *options)
1,983×
112
{
113
  return circuit_build_times_disabled_(options, 0);
1,983×
114
}
115

116
/** As circuit_build_times_disabled, but take options as an argument. */
117
int
118
circuit_build_times_disabled_(const or_options_t *options,
2,219×
119
                              int ignore_consensus)
120
{
121
  if (unit_tests) {
2,219×
122
    return 0;
123
  } else {
124
    int consensus_disabled =
314×
125
      ignore_consensus ? 0 : networkstatus_get_param(NULL, "cbtdisabled",
314×
126
                                                     0, 0, 1);
127
    int config_disabled = !options->LearnCircuitBuildTimeout;
314×
128
    int dirauth_disabled = options->AuthoritativeDir;
314×
129
    int state_disabled = did_last_state_file_write_fail() ? 1 : 0;
314×
130
    /* LearnCircuitBuildTimeout and Tor2web/Single Onion Services are
131
     * incompatible in two ways:
132
     *
133
     * - LearnCircuitBuildTimeout results in a low CBT, which
134
     *   Single Onion use of one-hop intro and rendezvous circuits lowers
135
     *   much further, producing *far* too many timeouts.
136
     *
137
     * - The adaptive CBT code does not update its timeout estimate
138
     *   using build times for single-hop circuits.
139
     *
140
     * If we fix both of these issues someday, we should test
141
     * these modes with LearnCircuitBuildTimeout on again. */
142
    int tor2web_disabled = rend_client_allow_non_anonymous_connection(options);
314×
143
    int single_onion_disabled = rend_service_allow_non_anonymous_connection(
314×
144
                                                                      options);
145

146
    if (consensus_disabled || config_disabled || dirauth_disabled ||
314×
147
        state_disabled || tor2web_disabled || single_onion_disabled) {
314×
148
#if 0
149
      log_debug(LD_CIRC,
150
               "CircuitBuildTime learning is disabled. "
151
               "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
152
               consensus_disabled, config_disabled, dirauth_disabled,
153
               state_disabled);
154
#endif /* 0 */
155
      return 1;
156
    } else {
157
#if 0
158
      log_debug(LD_CIRC,
159
                "CircuitBuildTime learning is not disabled. "
160
                "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
161
                consensus_disabled, config_disabled, dirauth_disabled,
162
                state_disabled);
163
#endif /* 0 */
164
      return 0;
78×
165
    }
166
  }
167
}
168

169
/**
170
 * Retrieve and bounds-check the cbtmaxtimeouts consensus parameter.
171
 *
172
 * Effect: When this many timeouts happen in the last 'cbtrecentcount'
173
 * circuit attempts, the client should discard all of its history and
174
 * begin learning a fresh timeout value.
175
 */
176
static int32_t
177
circuit_build_times_max_timeouts(void)
1,902×
178
{
179
  int32_t cbt_maxtimeouts;
180

181
  cbt_maxtimeouts = networkstatus_get_param(NULL, "cbtmaxtimeouts",
1,902×
182
                                 CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT,
183
                                 CBT_MIN_MAX_RECENT_TIMEOUT_COUNT,
184
                                 CBT_MAX_MAX_RECENT_TIMEOUT_COUNT);
185

186
  if (!(get_options()->LearnCircuitBuildTimeout)) {
1,902×
187
    log_debug(LD_BUG,
!
188
              "circuit_build_times_max_timeouts() called, cbtmaxtimeouts is"
189
              " %d",
190
              cbt_maxtimeouts);
191
  }
192

193
  return cbt_maxtimeouts;
1,902×
194
}
195

196
/**
197
 * Retrieve and bounds-check the cbtnummodes consensus parameter.
198
 *
199
 * Effect: This value governs how many modes to use in the weighted
200
 * average calculation of Pareto parameter Xm. A value of 3 introduces
201
 * some bias (2-5% of CDF) under ideal conditions, but allows for better
202
 * performance in the event that a client chooses guard nodes of radically
203
 * different performance characteristics.
204
 */
205
static int32_t
206
circuit_build_times_default_num_xm_modes(void)
5×
207
{
208
  int32_t num = networkstatus_get_param(NULL, "cbtnummodes",
5×
209
                                        CBT_DEFAULT_NUM_XM_MODES,
210
                                        CBT_MIN_NUM_XM_MODES,
211
                                        CBT_MAX_NUM_XM_MODES);
212

213
  if (!(get_options()->LearnCircuitBuildTimeout)) {
5×
214
    log_debug(LD_BUG,
!
215
              "circuit_build_times_default_num_xm_modes() called, cbtnummodes"
216
              " is %d",
217
              num);
218
  }
219

220
  return num;
5×
221
}
222

223
/**
224
 * Retrieve and bounds-check the cbtmincircs consensus parameter.
225
 *
226
 * Effect: This is the minimum number of circuits to build before
227
 * computing a timeout.
228
 */
229
static int32_t
230
circuit_build_times_min_circs_to_observe(void)
56×
231
{
232
  int32_t num = networkstatus_get_param(NULL, "cbtmincircs",
56×
233
                                        CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE,
234
                                        CBT_MIN_MIN_CIRCUITS_TO_OBSERVE,
235
                                        CBT_MAX_MIN_CIRCUITS_TO_OBSERVE);
236

237
  if (!(get_options()->LearnCircuitBuildTimeout)) {
56×
238
    log_debug(LD_BUG,
!
239
              "circuit_build_times_min_circs_to_observe() called, cbtmincircs"
240
              " is %d",
241
              num);
242
  }
243

244
  return num;
56×
245
}
246

247
/** Return true iff <b>cbt</b> has recorded enough build times that we
248
 * want to start acting on the timeout it implies. */
249
int
250
circuit_build_times_enough_to_compute(const circuit_build_times_t *cbt)
56×
251
{
252
  return cbt->total_build_times >= circuit_build_times_min_circs_to_observe();
56×
253
}
254

255
/**
256
 * Retrieve and bounds-check the cbtquantile consensus parameter.
257
 *
258
 * Effect: This is the position on the quantile curve to use to set the
259
 * timeout value. It is a percent (10-99).
260
 */
261
double
262
circuit_build_times_quantile_cutoff(void)
9×
263
{
264
  int32_t num = networkstatus_get_param(NULL, "cbtquantile",
9×
265
                                        CBT_DEFAULT_QUANTILE_CUTOFF,
266
                                        CBT_MIN_QUANTILE_CUTOFF,
267
                                        CBT_MAX_QUANTILE_CUTOFF);
268

269
  if (!(get_options()->LearnCircuitBuildTimeout)) {
9×
270
    log_debug(LD_BUG,
!
271
              "circuit_build_times_quantile_cutoff() called, cbtquantile"
272
              " is %d",
273
              num);
274
  }
275

276
  return num/100.0;
9×
277
}
278

279
/**
280
 * Retrieve and bounds-check the cbtclosequantile consensus parameter.
281
 *
282
 * Effect: This is the position on the quantile curve to use to set the
283
 * timeout value to use to actually close circuits. It is a percent
284
 * (0-99).
285
 */
286
static double
287
circuit_build_times_close_quantile(void)
3×
288
{
289
  int32_t param;
290
  /* Cast is safe - circuit_build_times_quantile_cutoff() is capped */
291
  int32_t min = (int)tor_lround(100*circuit_build_times_quantile_cutoff());
3×
292
  param = networkstatus_get_param(NULL, "cbtclosequantile",
3×
293
             CBT_DEFAULT_CLOSE_QUANTILE,
294
             CBT_MIN_CLOSE_QUANTILE,
295
             CBT_MAX_CLOSE_QUANTILE);
296

297
  if (!(get_options()->LearnCircuitBuildTimeout)) {
3×
298
    log_debug(LD_BUG,
!
299
              "circuit_build_times_close_quantile() called, cbtclosequantile"
300
              " is %d", param);
301
  }
302

303
  if (param < min) {
3×
304
    log_warn(LD_DIR, "Consensus parameter cbtclosequantile is "
!
305
             "too small, raising to %d", min);
306
    param = min;
!
307
  }
308
  return param / 100.0;
3×
309
}
310

311
/**
312
 * Retrieve and bounds-check the cbttestfreq consensus parameter.
313
 *
314
 * Effect: Describes how often in seconds to build a test circuit to
315
 * gather timeout values. Only applies if less than 'cbtmincircs'
316
 * have been recorded.
317
 */
318
static int32_t
319
circuit_build_times_test_frequency(void)
1×
320
{
321
  int32_t num = networkstatus_get_param(NULL, "cbttestfreq",
1×
322
                                        CBT_DEFAULT_TEST_FREQUENCY,
323
                                        CBT_MIN_TEST_FREQUENCY,
324
                                        CBT_MAX_TEST_FREQUENCY);
325

326
  if (!(get_options()->LearnCircuitBuildTimeout)) {
1×
327
    log_debug(LD_BUG,
!
328
              "circuit_build_times_test_frequency() called, cbttestfreq is %d",
329
              num);
330
  }
331

332
  return num;
1×
333
}
334

335
/**
336
 * Retrieve and bounds-check the cbtmintimeout consensus parameter.
337
 *
338
 * Effect: This is the minimum allowed timeout value in milliseconds.
339
 * The minimum is to prevent rounding to 0 (we only check once
340
 * per second).
341
 */
342
static int32_t
343
circuit_build_times_min_timeout(void)
114×
344
{
345
  int32_t num = networkstatus_get_param(NULL, "cbtmintimeout",
114×
346
                                        CBT_DEFAULT_TIMEOUT_MIN_VALUE,
347
                                        CBT_MIN_TIMEOUT_MIN_VALUE,
348
                                        CBT_MAX_TIMEOUT_MIN_VALUE);
349

350
  if (!(get_options()->LearnCircuitBuildTimeout)) {
114×
351
    log_debug(LD_BUG,
!
352
              "circuit_build_times_min_timeout() called, cbtmintimeout is %d",
353
              num);
354
  }
355
  return num;
114×
356
}
357

358
/**
359
 * Retrieve and bounds-check the cbtinitialtimeout consensus parameter.
360
 *
361
 * Effect: This is the timeout value to use before computing a timeout,
362
 * in milliseconds.
363
 */
364
int32_t
365
circuit_build_times_initial_timeout(void)
111×
366
{
367
  int32_t min = circuit_build_times_min_timeout();
111×
368
  int32_t param = networkstatus_get_param(NULL, "cbtinitialtimeout",
111×
369
                                          CBT_DEFAULT_TIMEOUT_INITIAL_VALUE,
370
                                          CBT_MIN_TIMEOUT_INITIAL_VALUE,
371
                                          CBT_MAX_TIMEOUT_INITIAL_VALUE);
372

373
  if (!(get_options()->LearnCircuitBuildTimeout)) {
111×
374
    log_debug(LD_BUG,
!
375
              "circuit_build_times_initial_timeout() called, "
376
              "cbtinitialtimeout is %d",
377
              param);
378
  }
379

380
  if (param < min) {
111×
381
    log_warn(LD_DIR, "Consensus parameter cbtinitialtimeout is too small, "
!
382
             "raising to %d", min);
383
    param = min;
!
384
  }
385
  return param;
111×
386
}
387

388
/**
389
 * Retrieve and bounds-check the cbtrecentcount consensus parameter.
390
 *
391
 * Effect: This is the number of circuit build times to keep track of
392
 * for deciding if we hit cbtmaxtimeouts and need to reset our state
393
 * and learn a new timeout.
394
 */
395
static int32_t
396
circuit_build_times_recent_circuit_count(networkstatus_t *ns)
9×
397
{
398
  int32_t num;
399
  num = networkstatus_get_param(ns, "cbtrecentcount",
9×
400
                                CBT_DEFAULT_RECENT_CIRCUITS,
401
                                CBT_MIN_RECENT_CIRCUITS,
402
                                CBT_MAX_RECENT_CIRCUITS);
403

404
  if (!(get_options()->LearnCircuitBuildTimeout)) {
9×
405
    log_debug(LD_BUG,
!
406
              "circuit_build_times_recent_circuit_count() called, "
407
              "cbtrecentcount is %d",
408
              num);
409
  }
410

411
  return num;
9×
412
}
413

414
/**
415
 * This function is called when we get a consensus update.
416
 *
417
 * It checks to see if we have changed any consensus parameters
418
 * that require reallocation or discard of previous stats.
419
 */
420
void
421
circuit_build_times_new_consensus_params(circuit_build_times_t *cbt,
1×
422
                                         networkstatus_t *ns)
423
{
424
  int32_t num;
425

426
  /*
427
   * First check if we're doing adaptive timeouts at all; nothing to
428
   * update if we aren't.
429
   */
430

431
  if (!circuit_build_times_disabled(get_options())) {
1×
432
    num = circuit_build_times_recent_circuit_count(ns);
1×
433

434
    if (num > 0) {
1×
435
      if (num != cbt->liveness.num_recent_circs) {
1×
436
        int8_t *recent_circs;
437
        if (cbt->liveness.num_recent_circs > 0) {
1×
438
          log_notice(LD_CIRC, "The Tor Directory Consensus has changed how "
!
439
                     "many circuits we must track to detect network failures "
440
                     "from %d to %d.", cbt->liveness.num_recent_circs, num);
441
        } else {
442
          log_notice(LD_CIRC, "Upon receiving a consensus directory, "
1×
443
                     "re-enabling circuit-based network failure detection.");
444
        }
445

446
        tor_assert(cbt->liveness.timeouts_after_firsthop ||
1×
447
                   cbt->liveness.num_recent_circs == 0);
448

449
        /*
450
         * Technically this is a circular array that we are reallocating
451
         * and memcopying. However, since it only consists of either 1s
452
         * or 0s, and is only used in a statistical test to determine when
453
         * we should discard our history after a sufficient number of 1's
454
         * have been reached, it is fine if order is not preserved or
455
         * elements are lost.
456
         *
457
         * cbtrecentcount should only be changing in cases of severe network
458
         * distress anyway, so memory correctness here is paramount over
459
         * doing acrobatics to preserve the array.
460
         */
461
        recent_circs = tor_calloc(num, sizeof(int8_t));
1×
462
        if (cbt->liveness.timeouts_after_firsthop &&
1×
463
            cbt->liveness.num_recent_circs > 0) {
!
464
          memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
!
465
                 sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
466
        }
467

468
        // Adjust the index if it needs it.
469
        if (num < cbt->liveness.num_recent_circs) {
1×
470
          cbt->liveness.after_firsthop_idx = MIN(num-1,
!
471
                  cbt->liveness.after_firsthop_idx);
472
        }
473

474
        tor_free(cbt->liveness.timeouts_after_firsthop);
1×
475
        cbt->liveness.timeouts_after_firsthop = recent_circs;
1×
476
        cbt->liveness.num_recent_circs = num;
1×
477
      }
478
      /* else no change, nothing to do */
479
    } else { /* num == 0 */
480
      /*
481
       * Weird.  This probably shouldn't happen, so log a warning, but try
482
       * to do something sensible anyway.
483
       */
484

485
      log_warn(LD_CIRC,
!
486
               "The cbtrecentcircs consensus parameter came back zero!  "
487
               "This disables adaptive timeouts since we can't keep track of "
488
               "any recent circuits.");
489

490
      circuit_build_times_free_timeouts(cbt);
!
491
    }
492
  } else {
493
    /*
494
     * Adaptive timeouts are disabled; this might be because of the
495
     * LearnCircuitBuildTimes config parameter, and hence permanent, or
496
     * the cbtdisabled consensus parameter, so it may be a new condition.
497
     * Treat it like getting num == 0 above and free the circuit history
498
     * if we have any.
499
     */
500

501
    circuit_build_times_free_timeouts(cbt);
!
502
  }
503
}
1×
504

505
/**
506
 * Return the initial default or configured timeout in milliseconds
507
 */
508
static double
509
circuit_build_times_get_initial_timeout(void)
108×
510
{
511
  double timeout;
512
  const or_options_t *options = get_options();
108×
513

514
  /*
515
   * Check if we have LearnCircuitBuildTimeout, and if we don't,
516
   * always use CircuitBuildTimeout, no questions asked.
517
   */
518
  if (!unit_tests && options->CircuitBuildTimeout) {
108×
519
    timeout = options->CircuitBuildTimeout*1000;
!
520
    if (!circuit_build_times_disabled(options) &&
!
521
        timeout < circuit_build_times_min_timeout()) {
!
522
      log_warn(LD_CIRC, "Config CircuitBuildTimeout too low. Setting to %ds",
!
523
               circuit_build_times_min_timeout()/1000);
524
      timeout = circuit_build_times_min_timeout();
!
525
    }
526
  } else {
527
    timeout = circuit_build_times_initial_timeout();
108×
528
  }
529

530
  return timeout;
108×
531
}
532

533
/**
534
 * Reset the build time state.
535
 *
536
 * Leave estimated parameters, timeout and network liveness intact
537
 * for future use.
538
 */
539
STATIC void
540
circuit_build_times_reset(circuit_build_times_t *cbt)
102×
541
{
542
  memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
102×
543
  cbt->total_build_times = 0;
102×
544
  cbt->build_times_idx = 0;
102×
545
  cbt->have_computed_timeout = 0;
102×
546

547
  // Reset timeout and close counts
548
  cbt->num_circ_succeeded = 0;
102×
549
  cbt->num_circ_closed = 0;
102×
550
  cbt->num_circ_timeouts = 0;
102×
551
}
102×
552

553
/**
554
 * Initialize the buildtimes structure for first use.
555
 *
556
 * Sets the initial timeout values based on either the config setting,
557
 * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
558
 */
559
void
560
circuit_build_times_init(circuit_build_times_t *cbt)
8×
561
{
562
  memset(cbt, 0, sizeof(*cbt));
563
  /*
564
   * Check if we really are using adaptive timeouts, and don't keep
565
   * track of this stuff if not.
566
   */
567
  if (!circuit_build_times_disabled(get_options())) {
8×
568
    cbt->liveness.num_recent_circs =
8×
569
      circuit_build_times_recent_circuit_count(NULL);
8×
570
    cbt->liveness.timeouts_after_firsthop =
8×
571
      tor_calloc(cbt->liveness.num_recent_circs, sizeof(int8_t));
8×
572
  } else {
573
    cbt->liveness.num_recent_circs = 0;
!
574
    cbt->liveness.timeouts_after_firsthop = NULL;
!
575
  }
576
  cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
8×
577
  cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
8×
578
}
8×
579

580
/**
581
 * Free the saved timeouts, if the cbtdisabled consensus parameter got turned
582
 * on or something.
583
 */
584

585
void
586
circuit_build_times_free_timeouts(circuit_build_times_t *cbt)
30×
587
{
588
  if (!cbt) return;
60×
589

590
  if (cbt->liveness.timeouts_after_firsthop) {
30×
591
    tor_free(cbt->liveness.timeouts_after_firsthop);
6×
592
  }
593

594
  cbt->liveness.num_recent_circs = 0;
30×
595
}
596

597
#if 0
598
/**
599
 * Rewind our build time history by n positions.
600
 */
601
static void
602
circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
603
{
604
  int i = 0;
605

606
  cbt->build_times_idx -= n;
607
  cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
608

609
  for (i = 0; i < n; i++) {
610
    cbt->circuit_build_times[(i+cbt->build_times_idx)
611
                             %CBT_NCIRCUITS_TO_OBSERVE]=0;
612
  }
613

614
  if (cbt->total_build_times > n) {
615
    cbt->total_build_times -= n;
616
  } else {
617
    cbt->total_build_times = 0;
618
  }
619

620
  log_info(LD_CIRC,
621
          "Rewound history by %d places. Current index: %d. "
622
          "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
623
}
624
#endif /* 0 */
625

626
/**
627
 * Mark this circuit as timed out, but change its purpose
628
 * so that it continues to build, allowing us to measure
629
 * its full build time.
630
 */
631
void
632
circuit_build_times_mark_circ_as_measurement_only(origin_circuit_t *circ)
1×
633
{
634
  control_event_circuit_status(circ,
1×
635
                               CIRC_EVENT_FAILED,
636
                               END_CIRC_REASON_TIMEOUT);
637
  circuit_change_purpose(TO_CIRCUIT(circ),
1×
638
                         CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT);
639
  /* Record this event to check for too many timeouts
640
   * in a row. This function does not record a time value yet
641
   * (we do that later); it only counts the fact that we did
642
   * have a timeout. We also want to avoid double-counting
643
   * already "relaxed" circuits, which are counted in
644
   * circuit_expire_building(). */
645
  if (!circ->relaxed_timeout) {
1×
646
    int first_hop_succeeded = circ->cpath &&
2×
647
          circ->cpath->state == CPATH_STATE_OPEN;
1×
648

649
    circuit_build_times_count_timeout(
1×
650
                                 get_circuit_build_times_mutable(),
651
                                 first_hop_succeeded);
652
  }
653
}
1×
654

655
/**
656
 * Perform the build time work that needs to be done when a circuit
657
 * completes a hop.
658
 *
659
 * This function decides if we should record a circuit's build time
660
 * in our histogram data and other statistics, and if so, records it.
661
 * It also will mark circuits that have already timed out as
662
 * measurement-only circuits, so they can continue to build but
663
 * not get used.
664
 *
665
 * For this, we want to consider circuits that will eventually make
666
 * it to the third hop. For circuits longer than 3 hops, we want to
667
 * record their build time when they reach the third hop, but let
668
 * them continue (and not count them later). For circuits that are
669
 * exactly 3 hops, this will count them when they are completed. We
670
 * do this so that CBT is always gathering statistics on circuits
671
 * of the same length, regardless of their type.
672
 */
673
void
674
circuit_build_times_handle_completed_hop(origin_circuit_t *circ)
12×
675
{
676
  struct timeval end;
677
  long timediff;
678

679
  /* If circuit build times are disabled, let circuit_expire_building()
680
   * handle it.. */
681
  if (circuit_build_times_disabled(get_options())) {
12×
682
    return;
3×
683
  }
684

685
  /* Is this a circuit for which the timeout applies in a straight-forward
686
   * way? If so, handle it below. If not, just return (and let
687
   * circuit_expire_building() eventually take care of it).
688
   */
689
  if (!circuit_timeout_want_to_count_circ(circ)) {
12×
690
    return;
691
  }
692

693
  tor_gettimeofday(&end);
9×
694
  timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
9×
695

696
  /* Check if we would have timed out already. If so, change the
697
   * purpose here. But don't do any timeout handling here if there
698
   * are no circuits opened yet. Save it for circuit_expire_building()
699
   * (to allow it to handle timeout "relaxing" over there). */
700
  if (timediff > get_circuit_build_timeout_ms() &&
15×
701
      circuit_any_opened_circuits_cached()) {
6×
702

703
    /* Circuits are allowed to last longer for measurement.
704
     * Switch their purpose and wait. */
705
    if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
3×
706
      log_info(LD_CIRC,
1×
707
               "Deciding to timeout circuit "U64_FORMAT"\n",
708
               U64_PRINTF_ARG(circ->global_identifier));
709
      circuit_build_times_mark_circ_as_measurement_only(circ);
1×
710
    }
711
  }
712

713
  /* If the circuit is built to exactly the DEFAULT_ROUTE_LEN,
714
   * add it to our buildtimes. */
715
  if (circuit_get_cpath_opened_len(circ) == DEFAULT_ROUTE_LEN) {
9×
716
    /* If the circuit build time is much greater than we would have cut
717
     * it off at, we probably had a suspend event along this codepath,
718
     * and we should discard the value.
719
     */
720
    if (timediff < 0 ||
6×
721
        timediff > 2*get_circuit_build_close_time_ms()+1000) {
3×
722
      log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
!
723
                 "Assuming clock jump. Purpose %d (%s)", timediff,
724
                 circ->base_.purpose,
725
                 circuit_purpose_to_string(circ->base_.purpose));
726
    } else {
727
      /* Only count circuit times if the network is live */
728
      if (circuit_build_times_network_check_live(
3×
729
                            get_circuit_build_times())) {
730
        circuit_build_times_add_time(get_circuit_build_times_mutable(),
3×
731
                                     (build_time_t)timediff);
732
        circuit_build_times_set_timeout(get_circuit_build_times_mutable());
3×
733
      }
734

735
      if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
3×
736
        circuit_build_times_network_circ_success(
2×
737
                                      get_circuit_build_times_mutable());
738
      }
739
    }
740
  }
741
}
742

743
/**
744
 * Add a new build time value <b>time</b> to the set of build times. Time
745
 * units are milliseconds.
746
 *
747
 * circuit_build_times <b>cbt</b> is a circular array, so loop around when
748
 * array is full.
749
 */
750
int
751
circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t btime)
4,203×
752
{
753
  if (btime <= 0 || btime > CBT_BUILD_TIME_MAX) {
4,203×
754
    log_warn(LD_BUG, "Circuit build time is too large (%u)."
!
755
                      "This is probably a bug.", btime);
756
    tor_fragile_assert();
!
757
    return -1;
758
  }
759

760
  log_debug(LD_CIRC, "Adding circuit build time %u", btime);
4,203×
761

762
  cbt->circuit_build_times[cbt->build_times_idx] = btime;
4,203×
763
  cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
4,203×
764
  if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
4,203×
765
    cbt->total_build_times++;
4,203×
766

767
  if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
4,203×
768
    /* Save state every n circuit builds */
769
    if (!unit_tests && !get_options()->AvoidDiskWrites)
420×
770
      or_state_mark_dirty(get_or_state(), 0);
!
771
  }
772

773
  return 0;
774
}
775

776
/**
777
 * Return maximum circuit build time
778
 */
779
static build_time_t
780
circuit_build_times_max(const circuit_build_times_t *cbt)
12×
781
{
782
  int i = 0;
12×
783
  build_time_t max_build_time = 0;
12×
784
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
12,012×
785
    if (cbt->circuit_build_times[i] > max_build_time
12,000×
786
            && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
108×
787
      max_build_time = cbt->circuit_build_times[i];
63×
788
  }
789
  return max_build_time;
12×
790
}
791

792
#if 0
793
/** Return minimum circuit build time */
794
build_time_t
795
circuit_build_times_min(circuit_build_times_t *cbt)
796
{
797
  int i = 0;
798
  build_time_t min_build_time = CBT_BUILD_TIME_MAX;
799
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
800
    if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
801
        cbt->circuit_build_times[i] < min_build_time)
802
      min_build_time = cbt->circuit_build_times[i];
803
  }
804
  if (min_build_time == CBT_BUILD_TIME_MAX) {
805
    log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
806
  }
807
  return min_build_time;
808
}
809
#endif /* 0 */
810

811
/**
812
 * Calculate and return a histogram for the set of build times.
813
 *
814
 * Returns an allocated array of histrogram bins representing
815
 * the frequency of index*CBT_BIN_WIDTH millisecond
816
 * build times. Also outputs the number of bins in nbins.
817
 *
818
 * The return value must be freed by the caller.
819
 */
820
static uint32_t *
821
circuit_build_times_create_histogram(const circuit_build_times_t *cbt,
9×
822
                                     build_time_t *nbins)
823
{
824
  uint32_t *histogram;
825
  build_time_t max_build_time = circuit_build_times_max(cbt);
9×
826
  int i, c;
827

828
  *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
9×
829
  histogram = tor_calloc(*nbins, sizeof(build_time_t));
9×
830

831
  // calculate histogram
832
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
9,009×
833
    if (cbt->circuit_build_times[i] == 0
18,000×
834
            || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
9,000×
835
      continue; /* 0 <-> uninitialized */
8,430×
836

837
    c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
570×
838
    histogram[c]++;
570×
839
  }
840

841
  return histogram;
9×
842
}
843

844
/**
845
 * Return the Pareto start-of-curve parameter Xm.
846
 *
847
 * Because we are not a true Pareto curve, we compute this as the
848
 * weighted average of the N most frequent build time bins. N is either
849
 * 1 if we don't have enough circuit build time data collected, or
850
 * determined by the consensus parameter cbtnummodes (default 3).
851
 */
852
static build_time_t
853
circuit_build_times_get_xm(circuit_build_times_t *cbt)
5×
854
{
855
  build_time_t i, nbins;
856
  build_time_t *nth_max_bin;
857
  int32_t bin_counts=0;
5×
858
  build_time_t ret = 0;
5×
859
  uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
5×
860
  int n=0;
5×
861
  int num_modes = circuit_build_times_default_num_xm_modes();
5×
862

863
  tor_assert(nbins > 0);
5×
864
  tor_assert(num_modes > 0);
5×
865

866
  // Only use one mode if < 1000 buildtimes. Not enough data
867
  // for multiple.
868
  if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
5×
869
    num_modes = 1;
5×
870

871
  nth_max_bin = tor_calloc(num_modes, sizeof(build_time_t));
5×
872

873
  /* Determine the N most common build times */
874
  for (i = 0; i < nbins; i++) {
20,665×
875
    if (histogram[i] >= histogram[nth_max_bin[0]]) {
20,660×
876
      nth_max_bin[0] = i;
320×
877
    }
878

UNCOV
879
    for (n = 1; n < num_modes; n++) {
!
UNCOV
880
      if (histogram[i] >= histogram[nth_max_bin[n]] &&
!
UNCOV
881
           (!histogram[nth_max_bin[n-1]]
!
UNCOV
882
               || histogram[i] < histogram[nth_max_bin[n-1]])) {
!
UNCOV
883
        nth_max_bin[n] = i;
!
884
      }
885
    }
886
  }
887

888
  for (n = 0; n < num_modes; n++) {
5×
889
    bin_counts += histogram[nth_max_bin[n]];
5×
890
    ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
5×
891
    log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
5×
892
             histogram[nth_max_bin[n]]);
893
  }
894

895
  /* The following assert is safe, because we don't get called when we
896
   * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
897
  tor_assert(bin_counts > 0);
5×
898

899
  ret /= bin_counts;
5×
900
  tor_free(histogram);
5×
901
  tor_free(nth_max_bin);
5×
902

903
  return ret;
5×
904
}
905

906
/**
907
 * Output a histogram of current circuit build times to
908
 * the or_state_t state structure.
909
 */
910
void
911
circuit_build_times_update_state(const circuit_build_times_t *cbt,
4×
912
                                 or_state_t *state)
913
{
914
  uint32_t *histogram;
915
  build_time_t i = 0;
4×
916
  build_time_t nbins = 0;
4×
917
  config_line_t **next, *line;
918

919
  histogram = circuit_build_times_create_histogram(cbt, &nbins);
4×
920
  // write to state
921
  config_free_lines(state->BuildtimeHistogram);
4×
922
  next = &state->BuildtimeHistogram;
4×
923
  *next = NULL;
924

925
  state->TotalBuildTimes = cbt->total_build_times;
4×
926
  state->CircuitBuildAbandonedCount = 0;
4×
927

928
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
4,004×
929
    if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
4,000×
930
      state->CircuitBuildAbandonedCount++;
5×
931
  }
932

933
  for (i = 0; i < nbins; i++) {
4,135×
934
    // compress the histogram by skipping the blanks
935
    if (histogram[i] == 0) continue;
4,135×
936
    *next = line = tor_malloc_zero(sizeof(config_line_t));
82×
937
    line->key = tor_strdup("CircuitBuildTimeBin");
82×
938
    tor_asprintf(&line->value, "%d %d",
164×
939
            CBT_BIN_TO_MS(i), histogram[i]);
82×
940
    next = &(line->next);
82×
941
  }
942

943
  if (!unit_tests) {
4×
944
    if (!get_options()->AvoidDiskWrites)
3×
945
      or_state_mark_dirty(get_or_state(), 0);
3×
946
  }
947

948
  tor_free(histogram);
4×
949
}
4×
950

951
/**
952
 * Shuffle the build times array.
953
 *
954
 * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
955
 */
956
static void
957
circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
4×
958
                                            build_time_t *raw_times,
959
                                            uint32_t num_times)
960
{
961
  uint32_t n = num_times;
4×
962
  if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
4×
963
    log_notice(LD_CIRC, "The number of circuit times that this Tor version "
!
964
               "uses to calculate build times is less than the number stored "
965
               "in your state file. Decreasing the circuit time history from "
966
               "%lu to %d.", (unsigned long)num_times,
967
               CBT_NCIRCUITS_TO_OBSERVE);
968
  }
969

970
  if (n > INT_MAX-1) {
4×
971
    log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
!
972
             "observations in your state file. That's far too many; probably "
973
             "there's a bug here.", (unsigned long)n);
974
    n = INT_MAX-1;
!
975
  }
976

977
  /* This code can only be run on a compact array */
978
  while (n-- > 1) {
103×
979
    int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
99×
980
    build_time_t tmp = raw_times[k];
99×
981
    raw_times[k] = raw_times[n];
99×
982
    raw_times[n] = tmp;
99×
983
  }
984

985
  /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
986
   * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
987
  for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
100×
988
    circuit_build_times_add_time(cbt, raw_times[n]);
100×
989
  }
990
}
4×
991

992
/**
993
 * Filter old synthetic timeouts that were created before the
994
 * new right-censored Pareto calculation was deployed.
995
 *
996
 * Once all clients before 0.2.1.13-alpha are gone, this code
997
 * will be unused.
998
 */
999
static int
1000
circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
!
1001
{
1002
  int num_filtered=0, i=0;
!
1003
  double timeout_rate = 0;
!
1004
  build_time_t max_timeout = 0;
!
1005

1006
  timeout_rate = circuit_build_times_timeout_rate(cbt);
!
1007
  max_timeout = (build_time_t)cbt->close_ms;
!
1008

1009
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
!
1010
    if (cbt->circuit_build_times[i] > max_timeout) {
!
1011
      build_time_t replaced = cbt->circuit_build_times[i];
!
1012
      num_filtered++;
!
1013
      cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
!
1014

1015
      log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
!
1016
               cbt->circuit_build_times[i]);
1017
    }
1018
  }
1019

1020
  log_info(LD_CIRC,
!
1021
           "We had %d timeouts out of %d build times, "
1022
           "and filtered %d above the max of %u",
1023
          (int)(cbt->total_build_times*timeout_rate),
1024
          cbt->total_build_times, num_filtered, max_timeout);
1025

1026
  return num_filtered;
!
1027
}
1028

1029
/**
1030
 * Load histogram from <b>state</b>, shuffling the resulting array
1031
 * after we do so. Use this result to estimate parameters and
1032
 * calculate the timeout.
1033
 *
1034
 * Return -1 on error.
1035
 */
1036
int
1037
circuit_build_times_parse_state(circuit_build_times_t *cbt,
4×
1038
                                or_state_t *state)
1039
{
1040
  int tot_values = 0;
4×
1041
  uint32_t loaded_cnt = 0, N = 0;
4×
1042
  config_line_t *line;
1043
  int i;
1044
  build_time_t *loaded_times;
1045
  int err = 0;
4×
1046
  circuit_build_times_init(cbt);
4×
1047

1048
  if (circuit_build_times_disabled(get_options())) {
4×
1049
    return 0;
1050
  }
1051

1052
  /* build_time_t 0 means uninitialized */
1053
  loaded_times = tor_calloc(state->TotalBuildTimes, sizeof(build_time_t));
4×
1054

1055
  for (line = state->BuildtimeHistogram; line; line = line->next) {
172×
1056
    smartlist_t *args = smartlist_new();
82×
1057
    smartlist_split_string(args, line->value, " ",
82×
1058
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1059
    if (smartlist_len(args) < 2) {
82×
1060
      log_warn(LD_GENERAL, "Unable to parse circuit build times: "
!
1061
                           "Too few arguments to CircuitBuildTime");
1062
      err = 1;
!
1063
      SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
!
1064
      smartlist_free(args);
!
1065
      break;
!
1066
    } else {
1067
      const char *ms_str = smartlist_get(args,0);
82×
1068
      const char *count_str = smartlist_get(args,1);
82×
1069
      uint32_t count, k;
1070
      build_time_t ms;
1071
      int ok;
1072
      ms = (build_time_t)tor_parse_ulong(ms_str, 10, 0,
82×
1073
                                         CBT_BUILD_TIME_MAX, &ok, NULL);
1074
      if (!ok) {
82×
1075
        log_warn(LD_GENERAL, "Unable to parse circuit build times: "
!
1076
                             "Unparsable bin number");
1077
        err = 1;
!
1078
        SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
!
1079
        smartlist_free(args);
!
1080
        break;
!
1081
      }
1082
      count = (uint32_t)tor_parse_ulong(count_str, 10, 0,
82×
1083
                                        UINT32_MAX, &ok, NULL);
1084
      if (!ok) {
82×
1085
        log_warn(LD_GENERAL, "Unable to parse circuit build times: "
!
1086
                             "Unparsable bin count");
1087
        err = 1;
!
1088
        SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
!
1089
        smartlist_free(args);
!
1090
        break;
!
1091
      }
1092

1093
      if (loaded_cnt+count+ (unsigned)state->CircuitBuildAbandonedCount
164×
1094
          > (unsigned) state->TotalBuildTimes) {
82×
1095
        log_warn(LD_CIRC,
!
1096
                 "Too many build times in state file. "
1097
                 "Stopping short before %d",
1098
                 loaded_cnt+count);
1099
        SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
!
1100
        smartlist_free(args);
!
1101
        break;
!
1102
      }
1103

1104
      for (k = 0; k < count; k++) {
95×
1105
        loaded_times[loaded_cnt++] = ms;
95×
1106
      }
1107
      N++;
82×
1108
      SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
82×
1109
      smartlist_free(args);
82×
1110
    }
1111
  }
1112

1113
  log_info(LD_CIRC,
4×
1114
           "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
1115
  for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
9×
1116
    loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
5×
1117
  }
1118

1119
  if (loaded_cnt != (unsigned)state->TotalBuildTimes) {
4×
1120
    log_warn(LD_CIRC,
!
1121
            "Corrupt state file? Build times count mismatch. "
1122
            "Read %d times, but file says %d", loaded_cnt,
1123
            state->TotalBuildTimes);
1124
    err = 1;
!
1125
    circuit_build_times_reset(cbt);
!
1126
    goto done;
!
1127
  }
1128

1129
  circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
4×
1130

1131
  /* Verify that we didn't overwrite any indexes */
1132
  for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
104×
1133
    if (!cbt->circuit_build_times[i])
104×
1134
      break;
1135
    tot_values++;
100×
1136
  }
1137
  log_info(LD_CIRC,
4×
1138
           "Loaded %d/%d values from %d lines in circuit time histogram",
1139
           tot_values, cbt->total_build_times, N);
1140

1141
  if (cbt->total_build_times != tot_values
4×
1142
        || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
4×
1143
    log_warn(LD_CIRC,
!
1144
            "Corrupt state file? Shuffled build times mismatch. "
1145
            "Read %d times, but file says %d", tot_values,
1146
            state->TotalBuildTimes);
1147
    err = 1;
!
1148
    circuit_build_times_reset(cbt);
!
1149
    goto done;
!
1150
  }
1151

1152
  circuit_build_times_set_timeout(cbt);
4×
1153

1154
  if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
4×
1155
    circuit_build_times_filter_timeouts(cbt);
!
1156
  }
1157

1158
 done:
1159
  tor_free(loaded_times);
4×
1160
  return err ? -1 : 0;
4×
1161
}
1162

1163
/**
1164
 * Estimates the Xm and Alpha parameters using
1165
 * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
1166
 *
1167
 * The notable difference is that we use mode instead of min to estimate Xm.
1168
 * This is because our distribution is frechet-like. We claim this is
1169
 * an acceptable approximation because we are only concerned with the
1170
 * accuracy of the CDF of the tail.
1171
 */
1172
STATIC int
1173
circuit_build_times_update_alpha(circuit_build_times_t *cbt)
5×
1174
{
1175
  build_time_t *x=cbt->circuit_build_times;
5×
1176
  double a = 0;
5×
1177
  int n=0,i=0,abandoned_count=0;
5×
1178
  build_time_t max_time=0;
5×
1179

1180
  /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
1181
  /* We sort of cheat here and make our samples slightly more pareto-like
1182
   * and less frechet-like. */
1183
  cbt->Xm = circuit_build_times_get_xm(cbt);
5×
1184

1185
  tor_assert(cbt->Xm > 0);
5×
1186

1187
  for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
5,000×
1188
    if (!x[i]) {
5,000×
1189
      continue;
4,500×
1190
    }
1191

1192
    if (x[i] < cbt->Xm) {
500×
1193
      a += tor_mathlog(cbt->Xm);
74×
1194
    } else if (x[i] == CBT_BUILD_ABANDONED) {
426×
1195
      abandoned_count++;
25×
1196
    } else {
1197
      a += tor_mathlog(x[i]);
401×
1198
      if (x[i] > max_time)
401×
1199
        max_time = x[i];
35×
1200
    }
1201
    n++;
500×
1202
  }
1203

1204
  /*
1205
   * We are erring and asserting here because this can only happen
1206
   * in codepaths other than startup. The startup state parsing code
1207
   * performs this same check, and resets state if it hits it. If we
1208
   * hit it at runtime, something serious has gone wrong.
1209
   */
1210
  if (n!=cbt->total_build_times) {
5×
1211
    log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
!
1212
            cbt->total_build_times);
1213
  }
1214
  tor_assert(n==cbt->total_build_times);
5×
1215

1216
  if (max_time <= 0) {
5×
1217
    /* This can happen if Xm is actually the *maximum* value in the set.
1218
     * It can also happen if we've abandoned every single circuit somehow.
1219
     * In either case, tell the caller not to compute a new build timeout. */
1220
    log_warn(LD_BUG,
!
1221
             "Could not determine largest build time (%d). "
1222
             "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
1223
             cbt->Xm, abandoned_count, n);
1224
    return 0;
!
1225
  }
1226

1227
  a += abandoned_count*tor_mathlog(max_time);
5×
1228

1229
  a -= n*tor_mathlog(cbt->Xm);
5×
1230
  // Estimator comes from Eq #4 in:
1231
  // "Bayesian estimation based on trimmed samples from Pareto populations"
1232
  // by Arturo J. Fernández. We are right-censored only.
1233
  a = (n-abandoned_count)/a;
5×
1234

1235
  cbt->alpha = a;
5×
1236

1237
  return 1;
5×
1238
}
1239

1240
/**
1241
 * This is the Pareto Quantile Function. It calculates the point x
1242
 * in the distribution such that F(x) = quantile (ie quantile*100%
1243
 * of the mass of the density function is below x on the curve).
1244
 *
1245
 * We use it to calculate the timeout and also to generate synthetic
1246
 * values of time for circuits that timeout before completion.
1247
 *
1248
 * See http://en.wikipedia.org/wiki/Quantile_function,
1249
 * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
1250
 * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
1251
 *     random_sample_from_Pareto_distribution
1252
 * That's right. I'll cite wikipedia all day long.
1253
 *
1254
 * Return value is in milliseconds, clamped to INT32_MAX.
1255
 */
1256
STATIC double
1257
circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
4,210×
1258
                                      double quantile)
1259
{
1260
  double ret;
1261
  tor_assert(quantile >= 0);
4,210×
1262
  tor_assert(1.0-quantile > 0);
4,210×
1263
  tor_assert(cbt->Xm > 0);
4,210×
1264

1265
  /* If either alpha or p are 0, we would divide by zero, yielding an
1266
   * infinite (double) result; which would be clamped to INT32_MAX.
1267
   * Instead, initialise ret to INT32_MAX, and skip over these
1268
   * potentially illegal/trapping divides by zero.
1269
   */
1270
  ret = INT32_MAX;
4,210×
1271

1272
  if (cbt->alpha > 0) {
4,210×
1273
    double p;
1274
    p = pow(1.0-quantile,1.0/cbt->alpha);
4,160×
1275
    if (p > 0) {
4,160×
1276
      ret = cbt->Xm/p;
4,160×
1277
    }
1278
  }
1279

1280
  if (ret > INT32_MAX) {
4,210×
1281
    ret = INT32_MAX;
!
1282
  }
1283
  tor_assert(ret > 0);
4,210×
1284
  return ret;
4,210×
1285
}
1286

1287
#ifdef TOR_UNIT_TESTS
1288
/** Pareto CDF */
1289
double
1290
circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
4×
1291
{
1292
  double ret;
1293
  tor_assert(cbt->Xm > 0);
4×
1294
  ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
4×
1295
  tor_assert(0 <= ret && ret <= 1.0);
4×
1296
  return ret;
4×
1297
}
1298
#endif /* defined(TOR_UNIT_TESTS) */
1299

1300
#ifdef TOR_UNIT_TESTS
1301
/**
1302
 * Generate a synthetic time using our distribution parameters.
1303
 *
1304
 * The return value will be within the [q_lo, q_hi) quantile points
1305
 * on the CDF.
1306
 */
1307
build_time_t
1308
circuit_build_times_generate_sample(circuit_build_times_t *cbt,
4,100×
1309
                                    double q_lo, double q_hi)
1310
{
1311
  double randval = crypto_rand_double();
4,100×
1312
  build_time_t ret;
1313
  double u;
1314

1315
  /* Generate between [q_lo, q_hi) */
1316
  /*XXXX This is what nextafter is supposed to be for; we should use it on the
1317
   * platforms that support it. */
1318
  q_hi -= 1.0/(INT32_MAX);
4,100×
1319

1320
  tor_assert(q_lo >= 0);
4,100×
1321
  tor_assert(q_hi < 1);
4,100×
1322
  tor_assert(q_lo < q_hi);
4,100×
1323

1324
  u = q_lo + (q_hi-q_lo)*randval;
4,100×
1325

1326
  tor_assert(0 <= u && u < 1.0);
4,100×
1327
  /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
1328
  ret = (build_time_t)
4,100×
1329
    tor_lround(circuit_build_times_calculate_timeout(cbt, u));
4,100×
1330
  tor_assert(ret > 0);
4,100×
1331
  return ret;
4,100×
1332
}
1333
#endif /* defined(TOR_UNIT_TESTS) */
1334

1335
#ifdef TOR_UNIT_TESTS
1336
/**
1337
 * Estimate an initial alpha parameter by solving the quantile
1338
 * function with a quantile point and a specific timeout value.
1339
 */
1340
void
1341
circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
1×
1342
                                  double quantile, double timeout_ms)
1343
{
1344
  // Q(u) = Xm/((1-u)^(1/a))
1345
  // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
1346
  // CircBuildTimeout = Xm/((1-0.8))^(1/a))
1347
  // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
1348
  // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
1349
  // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
1350
  tor_assert(quantile >= 0);
1×
1351
  tor_assert(cbt->Xm > 0);
1×
1352
  cbt->alpha = tor_mathlog(1.0-quantile)/
2×
1353
    (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
1×
1354
  tor_assert(cbt->alpha > 0);
1×
1355
}
1×
1356
#endif /* defined(TOR_UNIT_TESTS) */
1357

1358
/**
1359
 * Returns true if we need circuits to be built
1360
 */
1361
int
1362
circuit_build_times_needs_circuits(const circuit_build_times_t *cbt)
47×
1363
{
1364
  /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
1365
  return !circuit_build_times_enough_to_compute(cbt);
47×
1366
}
1367

1368
/**
1369
 * Returns true if we should build a timeout test circuit
1370
 * right now.
1371
 */
1372
int
1373
circuit_build_times_needs_circuits_now(const circuit_build_times_t *cbt)
1×
1374
{
1375
  return circuit_build_times_needs_circuits(cbt) &&
2×
1376
    approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
1×
1377
}
1378

1379
/**
1380
 * How long should we be unreachable before we think we need to check if
1381
 * our published IP address has changed.
1382
 */
1383
#define CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP (60*3)
1384

1385
/**
1386
 * Called to indicate that the network showed some signs of liveness,
1387
 * i.e. we received a cell.
1388
 *
1389
 * This is used by circuit_build_times_network_check_live() to decide
1390
 * if we should record the circuit build timeout or not.
1391
 *
1392
 * This function is called every time we receive a cell. Avoid
1393
 * syscalls, events, and other high-intensity work.
1394
 */
1395
void
1396
circuit_build_times_network_is_live(circuit_build_times_t *cbt)
121×
1397
{
1398
  time_t now = approx_time();
121×
1399
  if (cbt->liveness.nonlive_timeouts > 0) {
121×
1400
    time_t time_since_live = now - cbt->liveness.network_last_live;
100×
1401
    log_notice(LD_CIRC,
100×
1402
               "Tor now sees network activity. Restoring circuit build "
1403
               "timeout recording. Network was down for %d seconds "
1404
               "during %d circuit attempts.",
1405
               (int)time_since_live,
1406
               cbt->liveness.nonlive_timeouts);
1407
    if (time_since_live > CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP)
100×
1408
      reschedule_descriptor_update_check();
100×
1409
  }
1410
  cbt->liveness.network_last_live = now;
121×
1411
  cbt->liveness.nonlive_timeouts = 0;
121×
1412

1413
  /* Tell control.c */
1414
  control_event_network_liveness_update(1);
121×
1415
}
121×
1416

1417
/**
1418
 * Non-destructively scale all of our circuit success, timeout, and close
1419
 * counts down by a factor of two. Scaling in this way preserves the
1420
 * ratios between succeeded vs timed out vs closed circuits, so that
1421
 * our statistics don't change when we scale.
1422
 *
1423
 * This is used only in the rare event that we build more than
1424
 * INT32_MAX circuits.  Since the num_circ_* variables are
1425
 * uint32_t, we won't even be close to overflowing them.
1426
 */
1427
void
1428
circuit_build_times_scale_circ_counts(circuit_build_times_t *cbt)
!
1429
{
1430
  cbt->num_circ_succeeded /= 2;
!
1431
  cbt->num_circ_timeouts /= 2;
!
1432
  cbt->num_circ_closed /= 2;
!
1433
}
1434

1435
/**
1436
 * Called to indicate that we "completed" a circuit. Because this circuit
1437
 * succeeded, it doesn't count as a timeout-after-the-first-hop.
1438
 *
1439
 * (For the purposes of the cbt code, we consider a circuit "completed" if
1440
 * it has 3 hops, regardless of its final hop count. We do this because
1441
 * we're trying to answer the question, "how long should a circuit take to
1442
 * reach the 3-hop count".)
1443
 *
1444
 * This is used by circuit_build_times_network_check_changed() to determine
1445
 * if we had too many recent timeouts and need to reset our learned timeout
1446
 * to something higher.
1447
 */
1448
void
1449
circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
4,002×
1450
{
1451
  // Count circuit success
1452
  cbt->num_circ_succeeded++;
4,002×
1453

1454
  // If we're going to wrap int32, scale everything
1455
  if (cbt->num_circ_succeeded >= INT32_MAX) {
4,002×
1456
    circuit_build_times_scale_circ_counts(cbt);
!
1457
  }
1458

1459
  /* Check for NULLness because we might not be using adaptive timeouts */
1460
  if (cbt->liveness.timeouts_after_firsthop &&
8,004×
1461
      cbt->liveness.num_recent_circs > 0) {
4,002×
1462
    cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
4,002×
1463
      = 0;
4,002×
1464
    cbt->liveness.after_firsthop_idx++;
4,002×
1465
    cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
4,002×
1466
  }
1467
}
4,002×
1468

1469
/**
1470
 * A circuit just timed out. If it failed after the first hop, record it
1471
 * in our history for later deciding if the network speed has changed.
1472
 *
1473
 * This is used by circuit_build_times_network_check_changed() to determine
1474
 * if we had too many recent timeouts and need to reset our learned timeout
1475
 * to something higher.
1476
 */
1477
static void
1478
circuit_build_times_network_timeout(circuit_build_times_t *cbt,
1,802×
1479
                                    int did_onehop)
1480
{
1481
  // Count circuit timeout
1482
  cbt->num_circ_timeouts++;
1,802×
1483

1484
  // If we're going to wrap int32, scale everything
1485
  if (cbt->num_circ_timeouts >= INT32_MAX) {
1,802×
1486
    circuit_build_times_scale_circ_counts(cbt);
!
1487
  }
1488

1489
  /* Check for NULLness because we might not be using adaptive timeouts */
1490
  if (cbt->liveness.timeouts_after_firsthop &&
3,604×
1491
      cbt->liveness.num_recent_circs > 0) {
1,802×
1492
    if (did_onehop) {
1,802×
1493
      cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
1,802×
1494
        = 1;
1,802×
1495
      cbt->liveness.after_firsthop_idx++;
1,802×
1496
      cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
1,802×
1497
    }
1498
  }
1499
}
1,802×
1500

1501
/**
1502
 * A circuit was just forcibly closed. If there has been no recent network
1503
 * activity at all, but this circuit was launched back when we thought the
1504
 * network was live, increment the number of "nonlive" circuit timeouts.
1505
 *
1506
 * This is used by circuit_build_times_network_check_live() to decide
1507
 * if we should record the circuit build timeout or not.
1508
 */
1509
static void
1510
circuit_build_times_network_close(circuit_build_times_t *cbt,
100×
1511
                                    int did_onehop, time_t start_time)
1512
{
1513
  time_t now = time(NULL);
100×
1514

1515
  // Count circuit close
1516
  cbt->num_circ_closed++;
100×
1517

1518
  // If we're going to wrap int32, scale everything
1519
  if (cbt->num_circ_closed >= INT32_MAX) {
100×
1520
    circuit_build_times_scale_circ_counts(cbt);
!
1521
  }
1522

1523
  /*
1524
   * Check if this is a timeout that was for a circuit that spent its
1525
   * entire existence during a time where we have had no network activity.
1526
   */
1527
  if (cbt->liveness.network_last_live < start_time) {
100×
1528
    if (did_onehop) {
100×
1529
      char last_live_buf[ISO_TIME_LEN+1];
1530
      char start_time_buf[ISO_TIME_LEN+1];
1531
      char now_buf[ISO_TIME_LEN+1];
1532
      format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
!
1533
      format_local_iso_time(start_time_buf, start_time);
!
1534
      format_local_iso_time(now_buf, now);
!
1535
      log_notice(LD_CIRC,
!
1536
               "A circuit somehow completed a hop while the network was "
1537
               "not live. The network was last live at %s, but the circuit "
1538
               "launched at %s. It's now %s. This could mean your clock "
1539
               "changed.", last_live_buf, start_time_buf, now_buf);
1540
    }
1541
    cbt->liveness.nonlive_timeouts++;
100×
1542
    if (cbt->liveness.nonlive_timeouts == 1) {
100×
1543
      log_notice(LD_CIRC,
100×
1544
                 "Tor has not observed any network activity for the past %d "
1545
                 "seconds. Disabling circuit build timeout recording.",
1546
                 (int)(now - cbt->liveness.network_last_live));
1547

1548
      /* Tell control.c */
1549
      control_event_network_liveness_update(0);
100×
1550
    } else {
1551
      log_info(LD_CIRC,
!
1552
             "Got non-live timeout. Current count is: %d",
1553
             cbt->liveness.nonlive_timeouts);
1554
    }
1555
  }
1556
}
100×
1557

1558
/**
1559
 * When the network is not live, we do not record circuit build times.
1560
 *
1561
 * The network is considered not live if there has been at least one
1562
 * circuit build that began and ended (had its close_ms measurement
1563
 * period expire) since we last received a cell.
1564
 *
1565
 * Also has the side effect of rewinding the circuit time history
1566
 * in the case of recent liveness changes.
1567
 */
1568
int
1569
circuit_build_times_network_check_live(const circuit_build_times_t *cbt)
403×
1570
{
1571
  if (cbt->liveness.nonlive_timeouts > 0) {
403×
1572
    return 0;
1573
  }
1574

1575
  return 1;
203×
1576
}
1577

1578
/**
1579
 * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
1580
 * the past RECENT_CIRCUITS time out after the first hop. Used to detect
1581
 * if the network connection has changed significantly, and if so,
1582
 * resets our circuit build timeout to the default.
1583
 *
1584
 * Also resets the entire timeout history in this case and causes us
1585
 * to restart the process of building test circuits and estimating a
1586
 * new timeout.
1587
 */
1588
STATIC int
1589
circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
1,902×
1590
{
1591
  int total_build_times = cbt->total_build_times;
1,902×
1592
  int timeout_count=0;
1,902×
1593
  int i;
1594

1595
  if (cbt->liveness.timeouts_after_firsthop &&
3,804×
1596
      cbt->liveness.num_recent_circs > 0) {
1,902×
1597
    /* how many of our recent circuits made it to the first hop but then
1598
     * timed out? */
1599
    for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
38,040×
1600
      timeout_count += cbt->liveness.timeouts_after_firsthop[i];
38,040×
1601
    }
1602
  }
1603

1604
  /* If 80% of our recent circuits are timing out after the first hop,
1605
   * we need to re-estimate a new initial alpha and timeout. */
1606
  if (timeout_count < circuit_build_times_max_timeouts()) {
1,902×
1607
    return 0;
1608
  }
1609

1610
  circuit_build_times_reset(cbt);
100×
1611
  if (cbt->liveness.timeouts_after_firsthop &&
200×
1612
      cbt->liveness.num_recent_circs > 0) {
100×
1613
    memset(cbt->liveness.timeouts_after_firsthop, 0,
100×
1614
            sizeof(*cbt->liveness.timeouts_after_firsthop)*
1615
            cbt->liveness.num_recent_circs);
1616
  }
1617
  cbt->liveness.after_firsthop_idx = 0;
100×
1618

1619
#define MAX_TIMEOUT ((int32_t) (INT32_MAX/2))
1620
  /* Check to see if this has happened before. If so, double the timeout
1621
   * to give clients on abysmally bad network connections a shot at access */
1622
  if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
100×
1623
    if (cbt->timeout_ms > MAX_TIMEOUT || cbt->close_ms > MAX_TIMEOUT) {
100×
1624
      log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
!
1625
              "(timeout = %fmsec, close = %fmsec)",
1626
               cbt->timeout_ms, cbt->close_ms);
1627
    } else {
1628
      cbt->timeout_ms *= 2;
100×
1629
      cbt->close_ms *= 2;
100×
1630
    }
1631
  } else {
1632
    cbt->close_ms = cbt->timeout_ms
!
1633
                  = circuit_build_times_get_initial_timeout();
!
1634
  }
1635
#undef MAX_TIMEOUT
1636

1637
  cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
100×
1638

1639
  log_notice(LD_CIRC,
100×
1640
            "Your network connection speed appears to have changed. Resetting "
1641
            "timeout to %lds after %d timeouts and %d buildtimes.",
1642
            tor_lround(cbt->timeout_ms/1000), timeout_count,
1643
            total_build_times);
1644

1645
  return 1;
100×
1646
}
1647

1648
/**
1649
 * Count the number of timeouts in a set of cbt data.
1650
 */
1651
double
1652
circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
3×
1653
{
1654
  int i=0,timeouts=0;
3×
1655
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
3,003×
1656
    if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
3,000×
1657
       timeouts++;
72×
1658
    }
1659
  }
1660

1661
  if (!cbt->total_build_times)
3×
1662
    return 0;
1663

1664
  return ((double)timeouts)/cbt->total_build_times;
3×
1665
}
1666

1667
/**
1668
 * Count the number of closed circuits in a set of cbt data.
1669
 */
1670
double
1671
circuit_build_times_close_rate(const circuit_build_times_t *cbt)
!
1672
{
1673
  int i=0,closed=0;
!
1674
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
!
1675
    if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
!
1676
       closed++;
!
1677
    }
1678
  }
1679

1680
  if (!cbt->total_build_times)
!
1681
    return 0;
1682

1683
  return ((double)closed)/cbt->total_build_times;
!
1684
}
1685

1686
/**
1687
 * Store a timeout as a synthetic value.
1688
 *
1689
 * Returns true if the store was successful and we should possibly
1690
 * update our timeout estimate.
1691
 */
1692
int
1693
circuit_build_times_count_close(circuit_build_times_t *cbt,
100×
1694
                                int did_onehop,
1695
                                time_t start_time)
1696
{
1697
  if (circuit_build_times_disabled(get_options())) {
100×
1698
    cbt->close_ms = cbt->timeout_ms
!
1699
                  = circuit_build_times_get_initial_timeout();
!
1700
    return 0;
!
1701
  }
1702

1703
  /* Record this force-close to help determine if the network is dead */
1704
  circuit_build_times_network_close(cbt, did_onehop, start_time);
100×
1705

1706
  /* Only count timeouts if network is live.. */
1707
  if (!circuit_build_times_network_check_live(cbt)) {
100×
1708
    return 0;
1709
  }
1710

1711
  circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
!
1712
  return 1;
!
1713
}
1714

1715
/**
1716
 * Update timeout counts to determine if we need to expire
1717
 * our build time history due to excessive timeouts.
1718
 *
1719
 * We do not record any actual time values at this stage;
1720
 * we are only interested in recording the fact that a timeout
1721
 * happened. We record the time values via
1722
 * circuit_build_times_count_close() and circuit_build_times_add_time().
1723
 */
1724
void
1725
circuit_build_times_count_timeout(circuit_build_times_t *cbt,
1,802×
1726
                                  int did_onehop)
1727
{
1728
  if (circuit_build_times_disabled(get_options())) {
1,802×
1729
    cbt->close_ms = cbt->timeout_ms
!
1730
                  = circuit_build_times_get_initial_timeout();
!
1731
    return;
1,802×
1732
  }
1733

1734
  /* Register the fact that a timeout just occurred. */
1735
  circuit_build_times_network_timeout(cbt, did_onehop);
1,802×
1736

1737
  /* If there are a ton of timeouts, we should reset
1738
   * the circuit build timeout. */
1739
  circuit_build_times_network_check_changed(cbt);
1,802×
1740
}
1741

1742
/**
1743
 * Estimate a new timeout based on history and set our timeout
1744
 * variable accordingly.
1745
 */
1746
static int
1747
circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
9×
1748
{
1749
  build_time_t max_time;
1750
  if (!circuit_build_times_enough_to_compute(cbt))
9×
1751
    return 0;
1752

1753
  if (!circuit_build_times_update_alpha(cbt))
3×
1754
    return 0;
1755

1756
  cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
3×
1757
                                circuit_build_times_quantile_cutoff());
1758

1759
  cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
3×
1760
                                circuit_build_times_close_quantile());
1761

1762
  max_time = circuit_build_times_max(cbt);
3×
1763

1764
  if (cbt->timeout_ms > max_time) {
3×
1765
    log_info(LD_CIRC,
!
1766
               "Circuit build timeout of %dms is beyond the maximum build "
1767
               "time we have ever observed. Capping it to %dms.",
1768
               (int)cbt->timeout_ms, max_time);
1769
    cbt->timeout_ms = max_time;
!
1770
  }
1771

1772
  if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
3×
1773
    log_info(LD_CIRC,
!
1774
               "Circuit build measurement period of %dms is more than twice "
1775
               "the maximum build time we have ever observed. Capping it to "
1776
               "%dms.", (int)cbt->close_ms, 2*max_time);
1777
    cbt->close_ms = 2*max_time;
!
1778
  }
1779

1780
  /* Sometimes really fast guard nodes give us such a steep curve
1781
   * that this ends up being not that much greater than timeout_ms.
1782
   * Make it be at least 1 min to handle this case. */
1783
  cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
3×
1784

1785
  cbt->have_computed_timeout = 1;
3×
1786
  return 1;
3×
1787
}
1788

1789
/**
1790
 * Exposed function to compute a new timeout. Dispatches events and
1791
 * also filters out extremely high timeout values.
1792
 */
1793
void
1794
circuit_build_times_set_timeout(circuit_build_times_t *cbt)
9×
1795
{
1796
  long prev_timeout = tor_lround(cbt->timeout_ms/1000);
9×
1797
  double timeout_rate;
1798

1799
  /*
1800
   * Just return if we aren't using adaptive timeouts
1801
   */
1802
  if (circuit_build_times_disabled(get_options()))
9×
1803
    return;
1804

1805
  if (!circuit_build_times_set_timeout_worker(cbt))
9×
1806
    return;
1807

1808
  if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
3×
1809
    log_info(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
!
1810
             cbt->timeout_ms, circuit_build_times_min_timeout());
1811
    cbt->timeout_ms = circuit_build_times_min_timeout();
!
1812
    if (cbt->close_ms < cbt->timeout_ms) {
!
1813
      /* This shouldn't happen because of MAX() in timeout_worker above,
1814
       * but doing it just in case */
1815
      cbt->close_ms = circuit_build_times_initial_timeout();
!
1816
    }
1817
  }
1818

1819
  cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
3×
1820

1821
  timeout_rate = circuit_build_times_timeout_rate(cbt);
3×
1822

1823
  if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
3×
1824
    log_info(LD_CIRC,
2×
1825
               "Based on %d circuit times, it looks like we don't need to "
1826
               "wait so long for circuits to finish. We will now assume a "
1827
               "circuit is too slow to use after waiting %ld seconds.",
1828
               cbt->total_build_times,
1829
               tor_lround(cbt->timeout_ms/1000));
1830
    log_info(LD_CIRC,
2×
1831
             "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
1832
             cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
1833
             timeout_rate);
1834
  } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
1×
UNCOV
1835
    log_info(LD_CIRC,
!
1836
               "Based on %d circuit times, it looks like we need to wait "
1837
               "longer for circuits to finish. We will now assume a "
1838
               "circuit is too slow to use after waiting %ld seconds.",
1839
               cbt->total_build_times,
1840
               tor_lround(cbt->timeout_ms/1000));
UNCOV
1841
    log_info(LD_CIRC,
!
1842
             "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
1843
             cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
1844
             timeout_rate);
1845
  } else {
1846
    log_info(LD_CIRC,
1×
1847
             "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
1848
             " r: %f) based on %d circuit times",
1849
             tor_lround(cbt->timeout_ms/1000),
1850
             cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
1851
             cbt->total_build_times);
1852
  }
1853
}
1854

1855
#ifdef TOR_UNIT_TESTS
1856
/** Make a note that we're running unit tests (rather than running Tor
1857
 * itself), so we avoid clobbering our state file. */
1858
void
1859
circuitbuild_running_unit_tests(void)
1×
1860
{
1861
  unit_tests = 1;
1×
1862
}
1×
1863
#endif /* defined(TOR_UNIT_TESTS) */
1864

1865
void
1866
circuit_build_times_update_last_circ(circuit_build_times_t *cbt)
46×
1867
{
1868
  cbt->last_circ_at = approx_time();
46×
1869
}
46×
1870

1871
static void
1872
cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
111×
1873
                                   buildtimeout_set_event_t type)
1874
{
1875
  char *args = NULL;
111×
1876
  double qnt;
1877
  double timeout_rate = 0.0;
111×
1878
  double close_rate = 0.0;
111×
1879

1880
  switch (type) {
111×
1881
    case BUILDTIMEOUT_SET_EVENT_RESET:
1882
    case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
1883
    case BUILDTIMEOUT_SET_EVENT_DISCARD:
1884
      qnt = 1.0;
1885
      break;
1886
    case BUILDTIMEOUT_SET_EVENT_COMPUTED:
1887
    case BUILDTIMEOUT_SET_EVENT_RESUME:
1888
    default:
1889
      qnt = circuit_build_times_quantile_cutoff();
3×
1890
      break;
3×
1891
  }
1892

1893
  /* The timeout rate is the ratio of the timeout count over
1894
   * the total number of circuits attempted. The total number of
1895
   * circuits is (timeouts+succeeded+closed), since a circuit can
1896
   * either timeout, close, or succeed. We cast the denominator
1897
   * to promote it to double before the addition, to avoid int32
1898
   * overflow. */
1899
  const double total_circuits =
111×
1900
    ((double)cbt->num_circ_timeouts) + cbt->num_circ_succeeded
111×
1901
       + cbt->num_circ_closed;
111×
1902
  if (total_circuits >= 1.0) {
111×
1903
    timeout_rate = cbt->num_circ_timeouts / total_circuits;
!
1904
    close_rate = cbt->num_circ_closed / total_circuits;
!
1905
  }
1906

1907
  tor_asprintf(&args, "TOTAL_TIMES=%lu "
444×
1908
               "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
1909
               "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f",
1910
               (unsigned long)cbt->total_build_times,
111×
1911
               (unsigned long)cbt->timeout_ms,
111×
1912
               (unsigned long)cbt->Xm, cbt->alpha, qnt,
111×
1913
               timeout_rate,
1914
               (unsigned long)cbt->close_ms,
111×
1915
               close_rate);
1916

1917
  control_event_buildtimeout_set(type, args);
111×
1918

1919
  tor_free(args);
111×
1920
}
111×
1921

Troubleshooting · Open an Issue · Sales · Support · ENTERPRISE · CAREERS · STATUS
BLOG · TWITTER · Legal & Privacy · Supported CI Services · What's a CI service? · Automated Testing

© 2021 Coveralls, Inc