tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

circuitpadding.h (33016B)


      1 /*
      2 * Copyright (c) 2017-2021, The Tor Project, Inc. */
      3 /* See LICENSE for licensing information */
      4 
      5 /**
      6 * \file circuitpadding.h
      7 * \brief Header file for circuitpadding.c.
      8 **/
      9 
     10 #ifndef TOR_CIRCUITPADDING_H
     11 #define TOR_CIRCUITPADDING_H
     12 
     13 #include "trunnel/circpad_negotiation.h"
     14 #include "lib/evloop/timers.h"
     15 #include "core/or/relay_msg_st.h"
     16 
     17 struct circuit_t;
     18 struct origin_circuit_t;
     19 struct cell_t;
     20 
     21 /**
     22 * Signed error return with the specific property that negative
     23 * values mean error codes of various semantics, 0 means success,
     24 * and positive values are unused.
     25 *
     26 * XXX: Tor uses this concept a lot but just calls it int. Should we move
     27 * this somewhere centralized? Where?
     28 */
     29 typedef int signed_error_t;
     30 
     31 /**
     32 * These constants specify the types of events that can cause
     33 * transitions between state machine states.
     34 *
     35 * Note that SENT and RECV are relative to this endpoint. For
     36 * relays, SENT means packets destined towards the client and
     37 * RECV means packets destined towards the relay. On the client,
     38 * SENT means packets destined towards the relay, where as RECV
     39 * means packets destined towards the client.
     40 */
     41 typedef enum {
     42  /* A non-padding cell was received. */
     43  CIRCPAD_EVENT_NONPADDING_RECV = 0,
     44  /* A non-padding cell was sent. */
     45  CIRCPAD_EVENT_NONPADDING_SENT = 1,
     46  /* A padding cell (RELAY_COMMAND_DROP) was sent. */
     47  CIRCPAD_EVENT_PADDING_SENT = 2,
     48  /* A padding cell was received. */
     49  CIRCPAD_EVENT_PADDING_RECV = 3,
     50  /* We tried to schedule padding but we ended up picking the infinity bin
     51   * which means that padding was delayed infinitely */
     52  CIRCPAD_EVENT_INFINITY = 4,
     53  /* All histogram bins are empty (we are out of tokens) */
     54  CIRCPAD_EVENT_BINS_EMPTY = 5,
     55  /* This state has used up its cell count */
     56  CIRCPAD_EVENT_LENGTH_COUNT = 6
     57 } circpad_event_t;
     58 #define CIRCPAD_NUM_EVENTS ((int)CIRCPAD_EVENT_LENGTH_COUNT+1)
     59 
     60 /** Boolean type that says if we decided to transition states or not */
     61 typedef enum {
     62  CIRCPAD_STATE_UNCHANGED = 0,
     63  CIRCPAD_STATE_CHANGED = 1
     64 } circpad_decision_t;
     65 
     66 /** The type for the things in histogram bins (aka tokens) */
     67 typedef uint32_t circpad_hist_token_t;
     68 
     69 /** The type for histogram indexes (needs to be negative for errors) */
     70 typedef int8_t circpad_hist_index_t;
     71 
     72 /** The type for absolute time, from monotime_absolute_usec() */
     73 typedef uint64_t circpad_time_t;
     74 
     75 /** The type for timer delays, in microseconds */
     76 typedef uint32_t circpad_delay_t;
     77 #define CIRCPAD_DELAY_UNITS_PER_SECOND  (1000*1000)
     78 
     79 /**
     80 * An infinite padding cell delay means don't schedule any padding --
     81 * simply wait until a different event triggers a transition.
     82 *
     83 * This means that the maximum delay we can schedule is UINT32_MAX-1
     84 * microseconds, or about 4300 seconds (1.25 hours).
     85 * XXX: Is this enough if we want to simulate light, intermittent
     86 * activity on an onion service?
     87 */
     88 #define CIRCPAD_DELAY_INFINITE  (UINT32_MAX)
     89 
     90 /**
     91 * This is the maximum delay that the circuit padding system can have, in
     92 * seconds.
     93 */
     94 #define CIRCPAD_DELAY_MAX_SECS   \
     95    ((CIRCPAD_DELAY_INFINITE/CIRCPAD_DELAY_UNITS_PER_SECOND)+1)
     96 
     97 /**
     98 * Macro to clarify when we're checking the infinity bin.
     99 *
    100 * Works with either circpad_state_t or circpad_machine_runtime_t
    101 */
    102 #define CIRCPAD_INFINITY_BIN(mi)  ((mi)->histogram_len-1)
    103 
    104 /**
    105 * These constants form a bitfield that specifies when a state machine
    106 * should be applied to a circuit.
    107 *
    108 * If any of these elements is set, then the circuit will be tested against
    109 * that specific condition. If an element is unset, then we don't test it.
    110 * (E.g., if neither NO_STREAMS or STREAMS are set, then we will not care
    111 * whether a circuit has streams attached when we apply a state machine.)
    112 *
    113 * The helper function circpad_circuit_state() converts circuit state
    114 * flags into this more compact representation.
    115 */
    116 typedef enum {
    117  /* Only apply machine if the circuit is still building */
    118  CIRCPAD_CIRC_BUILDING = 1<<0,
    119  /* Only apply machine if the circuit is open */
    120  CIRCPAD_CIRC_OPENED = 1<<1,
    121  /* Only apply machine if the circuit has no attached streams */
    122  CIRCPAD_CIRC_NO_STREAMS = 1<<2,
    123  /* Only apply machine if the circuit has attached streams */
    124  CIRCPAD_CIRC_STREAMS = 1<<3,
    125  /* Only apply machine if the circuit still allows RELAY_EARLY cells */
    126  CIRCPAD_CIRC_HAS_RELAY_EARLY = 1<<4,
    127  /* Only apply machine if the circuit has depleted its RELAY_EARLY cells
    128   * allowance. */
    129  CIRCPAD_CIRC_HAS_NO_RELAY_EARLY = 1<<5
    130 } circpad_circuit_state_t;
    131 
    132 /** Bitmask that says "apply this machine to all states" */
    133 #define CIRCPAD_STATE_ALL   \
    134    (CIRCPAD_CIRC_BUILDING|CIRCPAD_CIRC_OPENED| \
    135     CIRCPAD_CIRC_STREAMS|CIRCPAD_CIRC_NO_STREAMS| \
    136     CIRCPAD_CIRC_HAS_RELAY_EARLY|CIRCPAD_CIRC_HAS_NO_RELAY_EARLY)
    137 
    138 /**
    139 * A compact circuit purpose bitfield mask that allows us to compactly
    140 * specify which circuit purposes a machine should apply to.
    141 *
    142 * The helper function circpad_circ_purpose_to_mask() converts circuit
    143 * purposes into bit positions in this bitmask.
    144 */
    145 typedef uint32_t circpad_purpose_mask_t;
    146 
    147 /** Bitmask that says "apply this machine to all purposes". */
    148 #define CIRCPAD_PURPOSE_ALL (0xFFFFFFFF)
    149 
    150 /**
    151 * This type specifies all of the conditions that must be met before
    152 * a client decides to initiate padding on a circuit.
    153 *
    154 * A circuit must satisfy every sub-field in this type in order
    155 * to be considered to match the conditions.
    156 */
    157 typedef struct circpad_machine_conditions_t {
    158  /** Only apply the machine *if* the circuit has at least this many hops */
    159  unsigned min_hops : 3;
    160 
    161  /** Only apply the machine *if* vanguards are enabled */
    162  unsigned requires_vanguards : 1;
    163 
    164  /**
    165   * This machine is ok to use if reduced padding is set in consensus
    166   * or torrc. This machine will still be applied even if reduced padding
    167   * is not set; this flag only acts to exclude machines that don't have
    168   * it set when reduced padding is requested. Therefore, reduced padding
    169   * machines should appear at the lowest priority in the padding machine
    170   * lists (aka first in the list), so that non-reduced padding machines
    171   * for the same purpose are given a chance to apply when reduced padding
    172   * is not requested. */
    173  unsigned reduced_padding_ok : 1;
    174 
    175  /** Only apply the machine *if* the circuit's state matches any of
    176   *  the bits set in this bitmask. */
    177  circpad_circuit_state_t apply_state_mask;
    178 
    179  /** Only apply a machine *if* the circuit's purpose matches one
    180   *  of the bits set in this bitmask */
    181  circpad_purpose_mask_t apply_purpose_mask;
    182 
    183  /** Keep a machine if any of the circuits's state machine's match
    184   *  the bits set in this bitmask, but don't apply new machines if
    185   *  they match this mask. */
    186  circpad_circuit_state_t keep_state_mask;
    187 
    188  /** Keep a machine if any of the circuits's state machine's match
    189   *  the bits set in this bitmask, but don't apply new machines if
    190   *  they match this mask. */
    191  circpad_purpose_mask_t keep_purpose_mask;
    192 
    193 } circpad_machine_conditions_t;
    194 
    195 /**
    196 * Token removal strategy options.
    197 *
    198 * The WTF-PAD histograms are meant to specify a target distribution to shape
    199 * traffic towards. This is accomplished by removing tokens from the histogram
    200 * when either padding or non-padding cells are sent.
    201 *
    202 * When we see a non-padding cell at a particular time since the last cell, you
    203 * remove a token from the corresponding delay bin. These flags specify
    204 * which bin to choose if that bin is already empty.
    205 */
    206 typedef enum {
    207  /** Don't remove any tokens */
    208  CIRCPAD_TOKEN_REMOVAL_NONE = 0,
    209  /**
    210   * Remove from the first non-zero higher bin index when current is zero.
    211   * This is the recommended strategy from the Adaptive Padding paper. */
    212  CIRCPAD_TOKEN_REMOVAL_HIGHER = 1,
    213  /** Remove from the first non-zero lower bin index when current is empty. */
    214  CIRCPAD_TOKEN_REMOVAL_LOWER = 2,
    215  /** Remove from the closest non-zero bin index when current is empty. */
    216  CIRCPAD_TOKEN_REMOVAL_CLOSEST = 3,
    217  /** Remove from the closest bin by time value (since bins are
    218   *  exponentially spaced). */
    219  CIRCPAD_TOKEN_REMOVAL_CLOSEST_USEC = 4,
    220  /** Only remove from the exact bin corresponding to this delay. If
    221   *  the bin is 0, simply do nothing. Don't pick another bin. */
    222  CIRCPAD_TOKEN_REMOVAL_EXACT = 5
    223 } circpad_removal_t;
    224 
    225 /**
    226 * Distribution types supported by circpad_distribution_sample().
    227 *
    228 * These can be used instead of histograms for the inter-packet
    229 * timing distribution, or to specify a distribution on the number
    230 * of cells that can be sent while in a specific state of the state
    231 * machine.
    232 *
    233 * Each distribution takes up to two parameters which are described below. */
    234 typedef enum {
    235  /* No probability distribution is used */
    236  CIRCPAD_DIST_NONE = 0,
    237  /* Uniform distribution: param1 is lower bound and param2 is upper bound */
    238  CIRCPAD_DIST_UNIFORM = 1,
    239  /* Logistic distribution: param1 is Mu, param2 is sigma. */
    240  CIRCPAD_DIST_LOGISTIC = 2,
    241  /* Log-logistic distribution: param1 is Alpha, param2 is 1.0/Beta */
    242  CIRCPAD_DIST_LOG_LOGISTIC = 3,
    243  /* Geometric distribution: param1 is 'p' (success probability) */
    244  CIRCPAD_DIST_GEOMETRIC = 4,
    245  /* Weibull distribution: param1 is k, param2 is Lambda */
    246  CIRCPAD_DIST_WEIBULL = 5,
    247  /* Generalized Pareto distribution: param1 is sigma, param2 is xi */
    248  CIRCPAD_DIST_PARETO = 6
    249 } circpad_distribution_type_t;
    250 
    251 /**
    252 * Distribution information.
    253 *
    254 * This type specifies a specific distribution above, as well as
    255 * up to two parameters for that distribution. The specific
    256 * per-distribution meaning of these parameters is specified
    257 * in circpad_distribution_sample().
    258 */
    259 typedef struct circpad_distribution_t {
    260  circpad_distribution_type_t type;
    261  double param1;
    262  double param2;
    263 } circpad_distribution_t;
    264 
    265 /** State number type. Represents current state of state machine. */
    266 typedef uint16_t circpad_statenum_t;
    267 #define  CIRCPAD_STATENUM_MAX   (UINT16_MAX)
    268 
    269 /** A histogram can be used to sample padding delays given a machine state.
    270 * This constant defines the maximum histogram width (i.e. the max number of
    271 * bins).
    272 *
    273 * The current limit is arbitrary and could be raised if there is a need,
    274 * however too many bins will be hard to serialize in the future.
    275 *
    276 * Memory concerns are not so great here since the corresponding histogram and
    277 * histogram_edges arrays are global and not per-circuit.
    278 *
    279 * If we ever upgrade this to a value that can't be represented by 8-bits we
    280 * also need to upgrade circpad_hist_index_t.
    281 */
    282 #define CIRCPAD_MAX_HISTOGRAM_LEN (100)
    283 
    284 /**
    285 * A state of a padding state machine. The information here are immutable and
    286 * represent the initial form of the state; it does not get updated as things
    287 * happen. The mutable information that gets updated in runtime are carried in
    288 * a circpad_machine_runtime_t.
    289 *
    290 * This struct describes the histograms and/or probability distributions, as
    291 * well as parameters of a single state in the adaptive padding machine.
    292 * Instances of this struct exist in global circpad machine definitions that
    293 * come from torrc or the consensus.
    294 */
    295 typedef struct circpad_state_t {
    296  /**
    297   * If a histogram is used for this state, this specifies the number of bins
    298   * of this histogram. Histograms must have at least 2 bins.
    299   *
    300   * In particular, the following histogram:
    301   *
    302   * Tokens
    303   *         +
    304   *      10 |    +----+
    305   *       9 |    |    |           +---------+
    306   *       8 |    |    |           |         |
    307   *       7 |    |    |     +-----+         |
    308   *       6 +----+ Bin+-----+     |         +---------------+
    309   *       5 |    | #1 |     |     |         |               |
    310   *         | Bin|    | Bin | Bin |  Bin #4 |    Bin #5     |
    311   *         | #0 |    | #2  | #3  |         | (infinity bin)|
    312   *         |    |    |     |     |         |               |
    313   *         |    |    |     |     |         |               |
    314   *       0 +----+----+-----+-----+---------+---------------+
    315   *         0   100  200   350   500      1000             inf  microseconds
    316   *
    317   * would be specified the following way:
    318   *    histogram_len = 6;
    319   *    histogram[] =        {   6,  10,   6,  7,    9,     6 }
    320   *    histogram_edges[] =  { 0, 100, 200, 350, 500, 1000 }
    321   *
    322   * The final bin is called the "infinity bin" and if it's chosen we don't
    323   * schedule any padding. The infinity bin is strange because its lower edge
    324   * is the max value of possible non-infinite delay allowed by this histogram,
    325   * and its upper edge is CIRCPAD_DELAY_INFINITE. You can tell if the infinity
    326   * bin is chosen by inspecting its bin index or inspecting its upper edge.
    327   *
    328   * If a delay probability distribution is used for this state, this is set
    329   * to 0. */
    330  circpad_hist_index_t histogram_len;
    331  /** The histogram itself: an array of uint16s of tokens, whose
    332   *  widths are exponentially spaced, in microseconds.
    333   *
    334   *  This array must have histogram_len elements that are strictly
    335   *  monotonically increasing. */
    336  circpad_hist_token_t histogram[CIRCPAD_MAX_HISTOGRAM_LEN];
    337  /* The histogram bin edges in usec.
    338   *
    339   * Each element of this array specifies the left edge of the corresponding
    340   * bin. The rightmost edge is always infinity and is not specified in this
    341   * array.
    342   *
    343   * This array must have histogram_len elements. */
    344  circpad_delay_t histogram_edges[CIRCPAD_MAX_HISTOGRAM_LEN+1];
    345  /** Total number of tokens in this histogram. This is a constant and is *not*
    346   *  decremented every time we spend a token. It's used for initializing and
    347   *  refilling the histogram. */
    348  uint32_t histogram_total_tokens;
    349 
    350  /**
    351   * Represents a delay probability distribution (aka IAT distribution). It's a
    352   * parametrized way of encoding inter-packet delay information in
    353   * microseconds. It can be used instead of histograms.
    354   *
    355   * If it is used, token_removal below must be set to
    356   * CIRCPAD_TOKEN_REMOVAL_NONE.
    357   *
    358   * Start_usec, range_sec, and rtt_estimates are still applied to the
    359   * results of sampling from this distribution (range_sec is used as a max).
    360   */
    361  circpad_distribution_t iat_dist;
    362  /*  If a delay probability distribution is used, this is used as the max
    363   *  value we can sample from the distribution. However, RTT measurements and
    364   *  dist_added_shift gets applied on top of this value to derive the final
    365   *  padding delay. */
    366  circpad_delay_t dist_max_sample_usec;
    367  /*  If a delay probability distribution is used and this is set, we will add
    368   *  this value on top of the value sampled from the IAT distribution to
    369   *  derive the final padding delay (We also add the RTT measurement if it's
    370   *  enabled.). */
    371  circpad_delay_t dist_added_shift_usec;
    372 
    373  /**
    374   * The length dist is a parameterized way of encoding how long this
    375   * state machine runs in terms of sent padding cells or all
    376   * sent cells. Values are sampled from this distribution, clamped
    377   * to max_len, and then start_len is added to that value.
    378   *
    379   * It may be specified instead of or in addition to
    380   * the infinity bins and bins empty conditions. */
    381  circpad_distribution_t length_dist;
    382  /** A minimum length value, added to the output of length_dist */
    383  uint16_t start_length;
    384  /** A cap on the length value that can be sampled from the length_dist */
    385  uint64_t max_length;
    386 
    387  /** Should we decrement length when we see a nonpadding packet?
    388   * XXX: Are there any machines that actually want to set this to 0? There may
    389   * not be. OTOH, it's only a bit.. */
    390  unsigned length_includes_nonpadding : 1;
    391 
    392  /**
    393   * This is an array that specifies the next state to transition to upon
    394   * receipt an event matching the indicated array index.
    395   *
    396   * This aborts our scheduled packet and switches to the state
    397   * corresponding to the index of the array. Tokens are filled upon
    398   * this transition.
    399   *
    400   * States are allowed to transition to themselves, which means re-schedule
    401   * a new padding timer. They are also allowed to temporarily "transition"
    402   * to the "IGNORE" and "CANCEL" pseudo-states. See defines below
    403   * for details on state behavior and meaning.
    404   */
    405  circpad_statenum_t next_state[CIRCPAD_NUM_EVENTS];
    406 
    407  /**
    408   * If true, estimate the RTT from this relay to the exit/website and add that
    409   * to start_usec for use as the histogram bin 0 start delay.
    410   *
    411   * Right now this is only supported for relay-side state machines.
    412   */
    413  unsigned use_rtt_estimate : 1;
    414 
    415  /** This specifies the token removal strategy to use upon padding and
    416   *  non-padding activity. */
    417  circpad_removal_t token_removal;
    418 } circpad_state_t;
    419 
    420 /**
    421 * The start state for this machine.
    422 *
    423 * In the original WTF-PAD, this is only used for transition to/from
    424 * the burst state. All other fields are not used. But to simplify the
    425 * code we've made it a first-class state. This has no performance
    426 * consequences, but may make naive serialization of the state machine
    427 * large, if we're not careful about how we represent empty fields.
    428 */
    429 #define  CIRCPAD_STATE_START       0
    430 
    431 /**
    432 * The burst state for this machine.
    433 *
    434 * In the original Adaptive Padding algorithm and in WTF-PAD
    435 * (https://www.freehaven.net/anonbib/cache/ShWa-Timing06.pdf and
    436 * https://www.cs.kau.se/pulls/hot/thebasketcase-wtfpad/), the burst
    437 * state serves to detect bursts in traffic. This is done by using longer
    438 * delays in its histogram, which represent the expected delays between
    439 * bursts of packets in the target stream. If this delay expires without a
    440 * real packet being sent, the burst state sends a padding packet and then
    441 * immediately transitions to the gap state, which is used to generate
    442 * a synthetic padding packet train. In this implementation, this transition
    443 * needs to be explicitly specified in the burst state's transition events.
    444 *
    445 * Because of this flexibility, other padding mechanisms can transition
    446 * between these two states arbitrarily, to encode other dynamics of
    447 * target traffic.
    448 */
    449 #define  CIRCPAD_STATE_BURST       1
    450 
    451 /**
    452 * The gap state for this machine.
    453 *
    454 * In the original Adaptive Padding algorithm and in WTF-PAD, the gap
    455 * state serves to simulate an artificial packet train composed of padding
    456 * packets. It does this by specifying much lower inter-packet delays than
    457 * the burst state, and transitioning back to itself after padding is sent
    458 * if these timers expire before real traffic is sent. If real traffic is
    459 * sent, it transitions back to the burst state.
    460 *
    461 * Again, in this implementation, these transitions must be specified
    462 * explicitly, and other transitions are also permitted.
    463 */
    464 #define  CIRCPAD_STATE_GAP         2
    465 
    466 /**
    467 * End is a pseudo-state that causes the machine to go completely
    468 * idle, and optionally get torn down (depending on the
    469 * value of circpad_machine_spec_t.should_negotiate_end)
    470 *
    471 * End MUST NOT occupy a slot in the machine state array.
    472 */
    473 #define  CIRCPAD_STATE_END         CIRCPAD_STATENUM_MAX
    474 
    475 /**
    476 * "Ignore" is a pseudo-state that means "do not react to this
    477 * event".
    478 *
    479 * "Ignore" MUST NOT occupy a slot in the machine state array.
    480 */
    481 #define  CIRCPAD_STATE_IGNORE         (CIRCPAD_STATENUM_MAX-1)
    482 
    483 /**
    484 * "Cancel" is a pseudo-state that means "cancel pending timers,
    485 * but remain in your current state".
    486 *
    487 * Cancel MUST NOT occupy a slot in the machine state array.
    488 */
    489 #define  CIRCPAD_STATE_CANCEL         (CIRCPAD_STATENUM_MAX-2)
    490 
    491 /**
    492 * Since we have 3 pseudo-states, the max state array length is
    493 * up to one less than cancel's statenum.
    494 */
    495 #define CIRCPAD_MAX_MACHINE_STATES  (CIRCPAD_STATE_CANCEL-1)
    496 
    497 /**
    498 * Mutable padding machine info.
    499 *
    500 * This structure contains mutable information about a padding
    501 * machine. The mutable information must be kept separate because
    502 * it exists per-circuit, where as the machines themselves are global.
    503 * This separation is done to conserve space in the circuit structure.
    504 *
    505 * This is the per-circuit state that changes regarding the global state
    506 * machine. Some parts of it are optional (ie NULL).
    507 *
    508 * XXX: Play with layout to minimize space on x64 Linux (most common relay).
    509 */
    510 typedef struct circpad_machine_runtime_t {
    511  /** The callback pointer for the padding callbacks.
    512   *
    513   *  These timers stick around the machineinfo until the machineinfo's circuit
    514   *  is closed, at which point the timer is cancelled. For this reason it's
    515   *  safe to assume that the machineinfo exists if this timer gets
    516   *  triggered. */
    517  tor_timer_t *padding_timer;
    518 
    519  /** The circuit for this machine */
    520  struct circuit_t *on_circ;
    521 
    522  /** A mutable copy of the histogram for the current state.
    523   *  NULL if remove_tokens is false for that state */
    524  circpad_hist_token_t *histogram;
    525  /** Length of the above histogram.
    526   * XXX: This field *could* be removed at the expense of added
    527   * complexity+overhead for reaching back into the immutable machine
    528   * state every time we need to inspect the histogram. It's only a byte,
    529   * though, so it seemed worth it.
    530   */
    531  circpad_hist_index_t histogram_len;
    532  /** Remove token from this index upon sending padding */
    533  circpad_hist_index_t chosen_bin;
    534 
    535  /** Stop padding/transition if this many cells sent */
    536  uint64_t state_length;
    537 #define CIRCPAD_STATE_LENGTH_INFINITE UINT64_MAX
    538 
    539  /** A scaled count of padding packets sent, used to limit padding overhead.
    540   * When this reaches UINT16_MAX, we cut it and nonpadding_sent in half. */
    541  uint16_t padding_sent;
    542  /** A scaled count of non-padding packets sent, used to limit padding
    543   *  overhead. When this reaches UINT16_MAX, we cut it and padding_sent in
    544   *  half. */
    545  uint16_t nonpadding_sent;
    546 
    547  /**
    548   * Timestamp of the most recent cell event (sent, received, padding,
    549   * non-padding), in seconds from approx_time().
    550   *
    551   * Used as an emergency break to stop holding padding circuits open.
    552   */
    553  time_t last_cell_time_sec;
    554 
    555  /**
    556   * EWMA estimate of the RTT of the circuit from this hop
    557   * to the exit end, in microseconds. */
    558  circpad_delay_t rtt_estimate_usec;
    559 
    560  /**
    561   * The last time we got an event relevant to estimating
    562   * the RTT. Monotonic time in microseconds since system
    563   * start.
    564   */
    565  circpad_time_t last_received_time_usec;
    566 
    567  /**
    568   * The time at which we scheduled a non-padding packet,
    569   * or selected an infinite delay.
    570   *
    571   * Monotonic time in microseconds since system start.
    572   * This is 0 if we haven't chosen a padding delay.
    573   */
    574  circpad_time_t padding_scheduled_at_usec;
    575 
    576  /** What state is this machine in? */
    577  circpad_statenum_t current_state;
    578 
    579  /** Machine counter, for shutdown sync.
    580   *
    581   *  Set from circuit_t.padding_machine_ctr, which is incremented each
    582   *  padding machine instantiation.
    583   */
    584  uint32_t machine_ctr;
    585 
    586  /**
    587   * True if we have scheduled a timer for padding.
    588   *
    589   * This is 1 if a timer is pending. It is 0 if
    590   * no timer is scheduled. (It can be 0 even when
    591   * padding_was_scheduled_at_usec is non-zero).
    592   */
    593  unsigned is_padding_timer_scheduled : 1;
    594 
    595  /**
    596   * If this is true, we have seen full duplex behavior.
    597   * Stop updating the RTT.
    598   */
    599  unsigned stop_rtt_update : 1;
    600 
    601 /** Max number of padding machines on each circuit. If changed,
    602 * also ensure the machine_index bitwith supports the new size. */
    603 #define CIRCPAD_MAX_MACHINES    (2)
    604  /** Which padding machine index was this for.
    605   * (make sure changes to the bitwidth can support the
    606   * CIRCPAD_MAX_MACHINES define). */
    607  unsigned machine_index : 1;
    608 
    609 } circpad_machine_runtime_t;
    610 
    611 /** Helper macro to get an actual state machine from a machineinfo */
    612 #define CIRCPAD_GET_MACHINE(machineinfo) \
    613    ((machineinfo)->on_circ->padding_machine[(machineinfo)->machine_index])
    614 
    615 /**
    616 * This specifies a particular padding machine to use after negotiation.
    617 *
    618 * The constants for machine_num_t are in trunnel.
    619 * We want to be able to define extra numbers in the consensus/torrc, though.
    620 */
    621 typedef uint8_t circpad_machine_num_t;
    622 
    623 /** Global state machine structure from the consensus */
    624 typedef struct circpad_machine_spec_t {
    625  /* Just a user-friendly machine name for logs */
    626  const char *name;
    627 
    628  /** Global machine number */
    629  circpad_machine_num_t machine_num;
    630 
    631  /** Which machine index slot should this machine go into in
    632   *  the array on the circuit_t */
    633  unsigned machine_index : 1;
    634 
    635  /** Send a padding negotiate to shut down machine at end state? */
    636  unsigned should_negotiate_end : 1;
    637 
    638  // These next three fields are origin machine-only...
    639  /** Origin side or relay side */
    640  unsigned is_origin_side : 1;
    641 
    642  /** Which hop in the circuit should we send padding to/from?
    643   *  1-indexed (ie: hop #1 is guard, #2 middle, #3 exit). */
    644  unsigned target_hopnum : 3;
    645 
    646  /** If this flag is enabled, don't close circuits that use this machine even
    647   *  if another part of Tor wants to close this circuit.
    648   *
    649   *  If this flag is set, the circuitpadding subsystem will close circuits the
    650   *  moment the machine transitions to the END state, and only if the circuit
    651   *  has already been asked to be closed by another part of Tor.
    652   *
    653   *  Circuits that should have been closed but were kept open by a padding
    654   *  machine are re-purposed to CIRCUIT_PURPOSE_C_CIRCUIT_PADDING, hence
    655   *  machines should take that purpose into account if they are filtering
    656   *  circuits by purpose. */
    657  unsigned manage_circ_lifetime : 1;
    658 
    659  /** This machine only kills fascists if the following conditions are met. */
    660  circpad_machine_conditions_t conditions;
    661 
    662  /** How many padding cells can be sent before we apply overhead limits?
    663   * XXX: Note that we can only allow up to 64k of padding cells on an
    664   * otherwise quiet circuit. Is this enough? It's 33MB. */
    665  uint16_t allowed_padding_count;
    666 
    667  /** Padding percent cap: Stop padding if we exceed this percent overhead.
    668   * 0 means no limit. Overhead is defined as percent of total traffic, so
    669   * that we can use 0..100 here. This is the same definition as used in
    670   * Prop#265. */
    671  uint8_t max_padding_percent;
    672 
    673  /** State array: indexed by circpad_statenum_t */
    674  circpad_state_t *states;
    675 
    676  /**
    677   * Number of states this machine has (ie: length of the states array).
    678   * XXX: This field is not needed other than for safety. */
    679  circpad_statenum_t num_states;
    680 } circpad_machine_spec_t;
    681 
    682 void circpad_new_consensus_params(const networkstatus_t *ns);
    683 
    684 int circpad_marked_circuit_for_padding(circuit_t *circ, int reason);
    685 
    686 /**
    687 * The following are event call-in points that are of interest to
    688 * the state machines. They are called during cell processing. */
    689 void circpad_deliver_unrecognized_cell_events(struct circuit_t *circ,
    690                                              cell_direction_t dir);
    691 void circpad_deliver_sent_relay_cell_events(struct circuit_t *circ,
    692                                            uint8_t relay_command);
    693 void circpad_deliver_recognized_relay_cell_events(struct circuit_t *circ,
    694                                                  uint8_t relay_command,
    695                                                  crypt_path_t *layer_hint);
    696 
    697 /** Cell events are delivered by the above delivery functions */
    698 void circpad_cell_event_nonpadding_sent(struct circuit_t *on_circ);
    699 void circpad_cell_event_nonpadding_received(struct circuit_t *on_circ);
    700 void circpad_cell_event_padding_sent(struct circuit_t *on_circ);
    701 void circpad_cell_event_padding_received(struct circuit_t *on_circ);
    702 
    703 /** Internal events are events the machines send to themselves */
    704 circpad_decision_t
    705 circpad_internal_event_infinity(circpad_machine_runtime_t *mi);
    706 circpad_decision_t
    707 circpad_internal_event_bins_empty(circpad_machine_runtime_t *);
    708 circpad_decision_t circpad_internal_event_state_length_up(
    709                                  circpad_machine_runtime_t *);
    710 
    711 /** Machine creation events are events that cause us to set up or
    712 *  tear down padding state machines. */
    713 void circpad_machine_event_circ_added_hop(struct origin_circuit_t *on_circ);
    714 void circpad_machine_event_circ_built(struct origin_circuit_t *circ);
    715 void circpad_machine_event_circ_purpose_changed(struct origin_circuit_t *circ);
    716 void circpad_machine_event_circ_has_streams(struct origin_circuit_t *circ);
    717 void circpad_machine_event_circ_has_no_streams(struct origin_circuit_t *circ);
    718 void
    719 circpad_machine_event_circ_has_no_relay_early(struct origin_circuit_t *circ);
    720 
    721 void circpad_machines_init(void);
    722 void circpad_machines_free(void);
    723 void circpad_register_padding_machine(circpad_machine_spec_t *machine,
    724                                      smartlist_t *machine_list);
    725 
    726 void circpad_machine_states_init(circpad_machine_spec_t *machine,
    727                                 circpad_statenum_t num_states);
    728 
    729 void circpad_circuit_free_all_machineinfos(struct circuit_t *circ);
    730 
    731 bool circpad_padding_is_from_expected_hop(struct circuit_t *circ,
    732                                         crypt_path_t *from_hop);
    733 
    734 /** Serializaton functions for writing to/from torrc and consensus */
    735 char *circpad_machine_spec_to_string(const circpad_machine_spec_t *machine);
    736 const circpad_machine_spec_t *circpad_string_to_machine(const char *str);
    737 
    738 /* Padding negotiation between client and middle */
    739 signed_error_t circpad_handle_padding_negotiate(struct circuit_t *circ,
    740                                                const relay_msg_t *msg);
    741 signed_error_t circpad_handle_padding_negotiated(struct circuit_t *circ,
    742                                      const relay_msg_t *msg,
    743                                      crypt_path_t *layer_hint);
    744 signed_error_t circpad_negotiate_padding(struct origin_circuit_t *circ,
    745                          circpad_machine_num_t machine,
    746                          uint8_t target_hopnum,
    747                          uint8_t command,
    748                          uint32_t machine_ctr);
    749 bool circpad_padding_negotiated(struct circuit_t *circ,
    750                           circpad_machine_num_t machine,
    751                           uint8_t command,
    752                           uint8_t response,
    753                           uint32_t machine_ctr);
    754 
    755 circpad_purpose_mask_t circpad_circ_purpose_to_mask(uint8_t circ_purpose);
    756 
    757 int circpad_check_received_cell(const relay_msg_t *msg, circuit_t *circ,
    758                                crypt_path_t *layer_hint);
    759 
    760 MOCK_DECL(circpad_decision_t,
    761 circpad_machine_schedule_padding,(circpad_machine_runtime_t *));
    762 
    763 MOCK_DECL(circpad_decision_t,
    764 circpad_machine_spec_transition, (circpad_machine_runtime_t *mi,
    765                             circpad_event_t event));
    766 
    767 circpad_decision_t circpad_send_padding_cell_for_callback(
    768                                 circpad_machine_runtime_t *mi);
    769 
    770 void circpad_free_all(void);
    771 
    772 #ifdef CIRCUITPADDING_PRIVATE
    773 STATIC void  machine_spec_free_(circpad_machine_spec_t *m);
    774 #define machine_spec_free(chan) \
    775  FREE_AND_NULL(circpad_machine_spec_t,machine_spec_free_, (m))
    776 
    777 STATIC circpad_delay_t
    778 circpad_machine_sample_delay(circpad_machine_runtime_t *mi);
    779 
    780 STATIC bool
    781 circpad_machine_reached_padding_limit(circpad_machine_runtime_t *mi);
    782 
    783 STATIC circpad_delay_t
    784 circpad_histogram_bin_to_usec(const circpad_machine_runtime_t *mi,
    785                              circpad_hist_index_t bin);
    786 
    787 STATIC const circpad_state_t *
    788 circpad_machine_current_state(const circpad_machine_runtime_t *mi);
    789 
    790 STATIC void circpad_machine_remove_token(circpad_machine_runtime_t *mi);
    791 
    792 STATIC circpad_hist_index_t circpad_histogram_usec_to_bin(
    793                                       const circpad_machine_runtime_t *mi,
    794                                       circpad_delay_t us);
    795 
    796 STATIC circpad_machine_runtime_t *circpad_circuit_machineinfo_new(
    797                                               struct circuit_t *on_circ,
    798                                               int machine_index);
    799 STATIC void circpad_machine_remove_higher_token(circpad_machine_runtime_t *mi,
    800                                         circpad_delay_t target_bin_us);
    801 STATIC void circpad_machine_remove_lower_token(circpad_machine_runtime_t *mi,
    802                                         circpad_delay_t target_bin_us);
    803 STATIC void circpad_machine_remove_closest_token(circpad_machine_runtime_t *mi,
    804                                         circpad_delay_t target_bin_us,
    805                                         bool use_usec);
    806 STATIC void circpad_machine_setup_tokens(circpad_machine_runtime_t *mi);
    807 
    808 MOCK_DECL(STATIC signed_error_t,
    809 circpad_send_command_to_hop,(struct origin_circuit_t *circ, uint8_t hopnum,
    810                             uint8_t relay_command, const uint8_t *payload,
    811                             ssize_t payload_len));
    812 
    813 MOCK_DECL(STATIC const node_t *,
    814 circuit_get_nth_node,(origin_circuit_t *circ, int hop));
    815 
    816 STATIC circpad_delay_t
    817 histogram_get_bin_upper_bound(const circpad_machine_runtime_t *mi,
    818                              circpad_hist_index_t bin);
    819 
    820 STATIC void
    821 circpad_add_matching_machines(origin_circuit_t *on_circ,
    822                              smartlist_t *machines_sl);
    823 
    824 #ifdef TOR_UNIT_TESTS
    825 extern smartlist_t *origin_padding_machines;
    826 extern smartlist_t *relay_padding_machines;
    827 
    828 #endif
    829 
    830 #endif /* defined(CIRCUITPADDING_PRIVATE) */
    831 
    832 #endif /* !defined(TOR_CIRCUITPADDING_H) */