Avoid crashing if we call num_usable_bridges() when bridges are not enabled
[tor/appveyor.git] / src / or / channelpadding.c
blob435436c45c54772d285f795ecde035ab27e80222
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-2015, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /* TOR_CHANNEL_INTERNAL_ define needed for an O(1) implementation of
8 * channelpadding_channel_to_channelinfo() */
9 #define TOR_CHANNEL_INTERNAL_
11 #include "or.h"
12 #include "channel.h"
13 #include "channelpadding.h"
14 #include "channeltls.h"
15 #include "config.h"
16 #include "networkstatus.h"
17 #include "connection.h"
18 #include "connection_or.h"
19 #include "main.h"
20 #include "rephist.h"
21 #include "router.h"
22 #include "compat_time.h"
23 #include <event2/event.h>
24 #include "rendservice.h"
26 STATIC int channelpadding_get_netflow_inactive_timeout_ms(const channel_t *);
27 STATIC int channelpadding_send_disable_command(channel_t *);
28 STATIC int64_t channelpadding_compute_time_until_pad_for_netflow(channel_t *);
30 /** The total number of pending channelpadding timers */
31 static uint64_t total_timers_pending;
33 /** These are cached consensus parameters for netflow */
34 /** The timeout lower bound that is allowed before sending padding */
35 static int consensus_nf_ito_low;
36 /** The timeout upper bound that is allowed before sending padding */
37 static int consensus_nf_ito_high;
38 /** The timeout lower bound that is allowed before sending reduced padding */
39 static int consensus_nf_ito_low_reduced;
40 /** The timeout upper bound that is allowed before sending reduced padding */
41 static int consensus_nf_ito_high_reduced;
42 /** The connection timeout between relays */
43 static int consensus_nf_conntimeout_relays;
44 /** The connection timeout for client connections */
45 static int consensus_nf_conntimeout_clients;
46 /** Should we pad before circuits are actually used for client data? */
47 static int consensus_nf_pad_before_usage;
48 /** Should we pad relay-to-relay connections? */
49 static int consensus_nf_pad_relays;
50 /** Should we pad tor2web connections? */
51 static int consensus_nf_pad_tor2web;
52 /** Should we pad rosos connections? */
53 static int consensus_nf_pad_single_onion;
55 #define TOR_MSEC_PER_SEC 1000
56 #define TOR_USEC_PER_MSEC 1000
58 /**
59 * How often do we get called by the connection housekeeping (ie: once
60 * per second) */
61 #define TOR_HOUSEKEEPING_CALLBACK_MSEC 1000
62 /**
63 * Additional extra time buffer on the housekeeping callback, since
64 * it can be delayed. This extra slack is used to decide if we should
65 * schedule a timer or wait for the next callback. */
66 #define TOR_HOUSEKEEPING_CALLBACK_SLACK_MSEC 100
68 /**
69 * This macro tells us if either end of the channel is connected to a client.
70 * (If we're not a server, we're definitely a client. If the channel thinks
71 * its a client, use that. Then finally verify in the consensus).
73 #define CHANNEL_IS_CLIENT(chan, options) \
74 (!public_server_mode((options)) || channel_is_client(chan) || \
75 !connection_or_digest_is_known_relay((chan)->identity_digest))
77 /**
78 * This function is called to update cached consensus parameters every time
79 * there is a consensus update. This allows us to move the consensus param
80 * search off of the critical path, so it does not need to be evaluated
81 * for every single connection, every second.
83 void
84 channelpadding_new_consensus_params(networkstatus_t *ns)
86 #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_LOW 1500
87 #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_HIGH 9500
88 #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_MIN 0
89 #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX 60000
90 consensus_nf_ito_low = networkstatus_get_param(ns, "nf_ito_low",
91 DFLT_NETFLOW_INACTIVE_KEEPALIVE_LOW,
92 DFLT_NETFLOW_INACTIVE_KEEPALIVE_MIN,
93 DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX);
94 consensus_nf_ito_high = networkstatus_get_param(ns, "nf_ito_high",
95 DFLT_NETFLOW_INACTIVE_KEEPALIVE_HIGH,
96 consensus_nf_ito_low,
97 DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX);
99 #define DFLT_NETFLOW_REDUCED_KEEPALIVE_LOW 9000
100 #define DFLT_NETFLOW_REDUCED_KEEPALIVE_HIGH 14000
101 #define DFLT_NETFLOW_REDUCED_KEEPALIVE_MIN 0
102 #define DFLT_NETFLOW_REDUCED_KEEPALIVE_MAX 60000
103 consensus_nf_ito_low_reduced =
104 networkstatus_get_param(ns, "nf_ito_low_reduced",
105 DFLT_NETFLOW_REDUCED_KEEPALIVE_LOW,
106 DFLT_NETFLOW_REDUCED_KEEPALIVE_MIN,
107 DFLT_NETFLOW_REDUCED_KEEPALIVE_MAX);
109 consensus_nf_ito_high_reduced =
110 networkstatus_get_param(ns, "nf_ito_high_reduced",
111 DFLT_NETFLOW_REDUCED_KEEPALIVE_HIGH,
112 consensus_nf_ito_low_reduced,
113 DFLT_NETFLOW_REDUCED_KEEPALIVE_MAX);
115 #define CONNTIMEOUT_RELAYS_DFLT (60*60) // 1 hour
116 #define CONNTIMEOUT_RELAYS_MIN 60
117 #define CONNTIMEOUT_RELAYS_MAX (7*24*60*60) // 1 week
118 consensus_nf_conntimeout_relays =
119 networkstatus_get_param(ns, "nf_conntimeout_relays",
120 CONNTIMEOUT_RELAYS_DFLT,
121 CONNTIMEOUT_RELAYS_MIN,
122 CONNTIMEOUT_RELAYS_MAX);
124 #define CIRCTIMEOUT_CLIENTS_DFLT (30*60) // 30 minutes
125 #define CIRCTIMEOUT_CLIENTS_MIN 60
126 #define CIRCTIMEOUT_CLIENTS_MAX (24*60*60) // 24 hours
127 consensus_nf_conntimeout_clients =
128 networkstatus_get_param(ns, "nf_conntimeout_clients",
129 CIRCTIMEOUT_CLIENTS_DFLT,
130 CIRCTIMEOUT_CLIENTS_MIN,
131 CIRCTIMEOUT_CLIENTS_MAX);
133 consensus_nf_pad_before_usage =
134 networkstatus_get_param(ns, "nf_pad_before_usage", 1, 0, 1);
136 consensus_nf_pad_relays =
137 networkstatus_get_param(ns, "nf_pad_relays", 0, 0, 1);
139 consensus_nf_pad_tor2web =
140 networkstatus_get_param(ns,
141 CHANNELPADDING_TOR2WEB_PARAM,
142 CHANNELPADDING_TOR2WEB_DEFAULT, 0, 1);
144 consensus_nf_pad_single_onion =
145 networkstatus_get_param(ns,
146 CHANNELPADDING_SOS_PARAM,
147 CHANNELPADDING_SOS_DEFAULT, 0, 1);
151 * Get a random netflow inactive timeout keepalive period in milliseconds,
152 * the range for which is determined by consensus parameters, negotiation,
153 * configuration, or default values. The consensus parameters enforce the
154 * minimum possible value, to avoid excessively frequent padding.
156 * The ranges for this value were chosen to be low enough to ensure that
157 * routers do not emit a new netflow record for a connection due to it
158 * being idle.
160 * Specific timeout values for major routers are listed in Proposal 251.
161 * No major router appeared capable of setting an inactive timeout below 10
162 * seconds, so we set the defaults below that value, since we can always
163 * scale back if it ends up being too much padding.
165 * Returns the next timeout period (in milliseconds) after which we should
166 * send a padding packet, or 0 if padding is disabled.
168 STATIC int
169 channelpadding_get_netflow_inactive_timeout_ms(const channel_t *chan)
171 int low_timeout = consensus_nf_ito_low;
172 int high_timeout = consensus_nf_ito_high;
173 int X1, X2;
175 if (low_timeout == 0 && low_timeout == high_timeout)
176 return 0; // No padding
178 /* If we have negotiated different timeout values, use those, but
179 * don't allow them to be lower than the consensus ones */
180 if (chan->padding_timeout_low_ms && chan->padding_timeout_high_ms) {
181 low_timeout = MAX(low_timeout, chan->padding_timeout_low_ms);
182 high_timeout = MAX(high_timeout, chan->padding_timeout_high_ms);
185 if (low_timeout == high_timeout)
186 return low_timeout; // No randomization
189 * This MAX() hack is here because we apply the timeout on both the client
190 * and the server. This creates the situation where the total time before
191 * sending a packet in either direction is actually
192 * min(client_timeout,server_timeout).
194 * If X is a random variable uniform from 0..R-1 (where R=high-low),
195 * then Y=max(X,X) has Prob(Y == i) = (2.0*i + 1)/(R*R).
197 * If we create a third random variable Z=min(Y,Y), then it turns out that
198 * Exp[Z] ~= Exp[X]. Here's a table:
200 * R Exp[X] Exp[Z] Exp[min(X,X)] Exp[max(X,X)]
201 * 2000 999.5 1066 666.2 1332.8
202 * 3000 1499.5 1599.5 999.5 1999.5
203 * 5000 2499.5 2666 1666.2 3332.8
204 * 6000 2999.5 3199.5 1999.5 3999.5
205 * 7000 3499.5 3732.8 2332.8 4666.2
206 * 8000 3999.5 4266.2 2666.2 5332.8
207 * 10000 4999.5 5328 3332.8 6666.2
208 * 15000 7499.5 7995 4999.5 9999.5
209 * 20000 9900.5 10661 6666.2 13332.8
211 * In other words, this hack makes it so that when both the client and
212 * the guard are sending this padding, then the averages work out closer
213 * to the midpoint of the range, making the overhead easier to tune.
214 * If only one endpoint is padding (for example: if the relay does not
215 * support padding, but the client has set ConnectionPadding 1; or
216 * if the relay does support padding, but the client has set
217 * ReducedConnectionPadding 1), then the defense will still prevent
218 * record splitting, but with less overhead than the midpoint
219 * (as seen by the Exp[max(X,X)] column).
221 * To calculate average padding packet frequency (and thus overhead),
222 * index into the table by picking a row based on R = high-low. Then,
223 * use the appropriate column (Exp[Z] for two-sided padding, and
224 * Exp[max(X,X)] for one-sided padding). Finally, take this value
225 * and add it to the low timeout value. This value is the average
226 * frequency which padding packets will be sent.
229 X1 = crypto_rand_int(high_timeout - low_timeout);
230 X2 = crypto_rand_int(high_timeout - low_timeout);
231 return low_timeout + MAX(X1, X2);
235 * Update this channel's padding settings based on the PADDING_NEGOTIATE
236 * contents.
238 * Returns -1 on error; 1 on success.
241 channelpadding_update_padding_for_channel(channel_t *chan,
242 const channelpadding_negotiate_t *pad_vars)
244 if (pad_vars->version != 0) {
245 static ratelim_t version_limit = RATELIM_INIT(600);
247 log_fn_ratelim(&version_limit,LOG_PROTOCOL_WARN,LD_PROTOCOL,
248 "Got a PADDING_NEGOTIATE cell with an unknown version. Ignoring.");
249 return -1;
252 // We should not allow malicious relays to disable or reduce padding for
253 // us as clients. In fact, we should only accept this cell at all if we're
254 // operating as a relay. Bridges should not accept it from relays, either
255 // (only from their clients).
256 if ((get_options()->BridgeRelay &&
257 connection_or_digest_is_known_relay(chan->identity_digest)) ||
258 !get_options()->ORPort_set) {
259 static ratelim_t relay_limit = RATELIM_INIT(600);
261 log_fn_ratelim(&relay_limit,LOG_PROTOCOL_WARN,LD_PROTOCOL,
262 "Got a PADDING_NEGOTIATE from relay at %s (%s). "
263 "This should not happen.",
264 chan->get_remote_descr(chan, 0),
265 hex_str(chan->identity_digest, DIGEST_LEN));
266 return -1;
269 chan->padding_enabled = (pad_vars->command == CHANNELPADDING_COMMAND_START);
271 /* Min must not be lower than the current consensus parameter
272 nf_ito_low. */
273 chan->padding_timeout_low_ms = MAX(consensus_nf_ito_low,
274 pad_vars->ito_low_ms);
276 /* Max must not be lower than ito_low_ms */
277 chan->padding_timeout_high_ms = MAX(chan->padding_timeout_low_ms,
278 pad_vars->ito_high_ms);
280 log_fn(LOG_INFO,LD_OR,
281 "Negotiated padding=%d, lo=%d, hi=%d on "U64_FORMAT,
282 chan->padding_enabled, chan->padding_timeout_low_ms,
283 chan->padding_timeout_high_ms,
284 U64_PRINTF_ARG(chan->global_identifier));
286 return 1;
290 * Sends a CELL_PADDING_NEGOTIATE on the channel to tell the other side not
291 * to send padding.
293 * Returns -1 on error, 0 on success.
295 STATIC int
296 channelpadding_send_disable_command(channel_t *chan)
298 channelpadding_negotiate_t disable;
299 cell_t cell;
301 tor_assert(BASE_CHAN_TO_TLS(chan)->conn->link_proto >=
302 MIN_LINK_PROTO_FOR_CHANNEL_PADDING);
304 memset(&cell, 0, sizeof(cell_t));
305 memset(&disable, 0, sizeof(channelpadding_negotiate_t));
306 cell.command = CELL_PADDING_NEGOTIATE;
308 channelpadding_negotiate_set_command(&disable, CHANNELPADDING_COMMAND_STOP);
310 if (channelpadding_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
311 &disable) < 0)
312 return -1;
314 if (chan->write_cell(chan, &cell) == 1)
315 return 0;
316 else
317 return -1;
321 * Sends a CELL_PADDING_NEGOTIATE on the channel to tell the other side to
322 * resume sending padding at some rate.
324 * Returns -1 on error, 0 on success.
327 channelpadding_send_enable_command(channel_t *chan, uint16_t low_timeout,
328 uint16_t high_timeout)
330 channelpadding_negotiate_t enable;
331 cell_t cell;
333 tor_assert(BASE_CHAN_TO_TLS(chan)->conn->link_proto >=
334 MIN_LINK_PROTO_FOR_CHANNEL_PADDING);
336 memset(&cell, 0, sizeof(cell_t));
337 memset(&enable, 0, sizeof(channelpadding_negotiate_t));
338 cell.command = CELL_PADDING_NEGOTIATE;
340 channelpadding_negotiate_set_command(&enable, CHANNELPADDING_COMMAND_START);
341 channelpadding_negotiate_set_ito_low_ms(&enable, low_timeout);
342 channelpadding_negotiate_set_ito_high_ms(&enable, high_timeout);
344 if (channelpadding_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
345 &enable) < 0)
346 return -1;
348 if (chan->write_cell(chan, &cell) == 1)
349 return 0;
350 else
351 return -1;
355 * Sends a CELL_PADDING cell on a channel if it has been idle since
356 * our callback was scheduled.
358 * This function also clears the pending padding timer and the callback
359 * flags.
361 static void
362 channelpadding_send_padding_cell_for_callback(channel_t *chan)
364 cell_t cell;
366 /* Check that the channel is still valid and open */
367 if (!chan || chan->state != CHANNEL_STATE_OPEN) {
368 if (chan) chan->pending_padding_callback = 0;
369 log_fn(LOG_INFO,LD_OR,
370 "Scheduled a netflow padding cell, but connection already closed.");
371 return;
374 /* We should have a pending callback flag set. */
375 if (BUG(chan->pending_padding_callback == 0))
376 return;
378 chan->pending_padding_callback = 0;
380 if (!chan->next_padding_time_ms ||
381 chan->has_queued_writes(chan)) {
382 /* We must have been active before the timer fired */
383 chan->next_padding_time_ms = 0;
384 return;
388 uint64_t now = monotime_coarse_absolute_msec();
390 log_fn(LOG_INFO,LD_OR,
391 "Sending netflow keepalive on "U64_FORMAT" to %s (%s) after "
392 I64_FORMAT" ms. Delta "I64_FORMAT"ms",
393 U64_PRINTF_ARG(chan->global_identifier),
394 safe_str_client(chan->get_remote_descr(chan, 0)),
395 safe_str_client(hex_str(chan->identity_digest, DIGEST_LEN)),
396 U64_PRINTF_ARG(now - chan->timestamp_xfer_ms),
397 U64_PRINTF_ARG(now - chan->next_padding_time_ms));
400 /* Clear the timer */
401 chan->next_padding_time_ms = 0;
403 /* Send the padding cell. This will cause the channel to get a
404 * fresh timestamp_active */
405 memset(&cell, 0, sizeof(cell));
406 cell.command = CELL_PADDING;
407 chan->write_cell(chan, &cell);
411 * tor_timer callback function for us to send padding on an idle channel.
413 * This function just obtains the channel from the callback handle, ensures
414 * it is still valid, and then hands it off to
415 * channelpadding_send_padding_cell_for_callback(), which checks if
416 * the channel is still idle before sending padding.
418 static void
419 channelpadding_send_padding_callback(tor_timer_t *timer, void *args,
420 const struct monotime_t *when)
422 channel_t *chan = channel_handle_get((struct channel_handle_t*)args);
423 (void)timer; (void)when;
425 if (chan && CHANNEL_CAN_HANDLE_CELLS(chan)) {
426 /* Hrmm.. It might be nice to have an equivalent to assert_connection_ok
427 * for channels. Then we could get rid of the channeltls dependency */
428 tor_assert(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn)->magic ==
429 OR_CONNECTION_MAGIC);
430 assert_connection_ok(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), approx_time());
432 channelpadding_send_padding_cell_for_callback(chan);
433 } else {
434 log_fn(LOG_INFO,LD_OR,
435 "Channel closed while waiting for timer.");
438 total_timers_pending--;
442 * Schedules a callback to send padding on a channel in_ms milliseconds from
443 * now.
445 * Returns CHANNELPADDING_WONTPAD on error, CHANNELPADDING_PADDING_SENT if we
446 * sent the packet immediately without a timer, and
447 * CHANNELPADDING_PADDING_SCHEDULED if we decided to schedule a timer.
449 static channelpadding_decision_t
450 channelpadding_schedule_padding(channel_t *chan, int in_ms)
452 struct timeval timeout;
453 tor_assert(!chan->pending_padding_callback);
455 if (in_ms <= 0) {
456 chan->pending_padding_callback = 1;
457 channelpadding_send_padding_cell_for_callback(chan);
458 return CHANNELPADDING_PADDING_SENT;
461 timeout.tv_sec = in_ms/TOR_MSEC_PER_SEC;
462 timeout.tv_usec = (in_ms%TOR_USEC_PER_MSEC)*TOR_USEC_PER_MSEC;
464 if (!chan->timer_handle) {
465 chan->timer_handle = channel_handle_new(chan);
468 if (chan->padding_timer) {
469 timer_set_cb(chan->padding_timer,
470 channelpadding_send_padding_callback,
471 chan->timer_handle);
472 } else {
473 chan->padding_timer = timer_new(channelpadding_send_padding_callback,
474 chan->timer_handle);
476 timer_schedule(chan->padding_timer, &timeout);
478 rep_hist_padding_count_timers(++total_timers_pending);
480 chan->pending_padding_callback = 1;
481 return CHANNELPADDING_PADDING_SCHEDULED;
485 * Calculates the number of milliseconds from now to schedule a padding cell.
487 * Returns the number of milliseconds from now (relative) to schedule the
488 * padding callback. If the padding timer is more than 1.1 seconds in the
489 * future, we return -1, to avoid scheduling excessive callbacks. If padding
490 * is disabled in the consensus, we return -2.
492 * Side-effects: Updates chan->next_padding_time_ms, storing an (absolute, not
493 * relative) millisecond representation of when we should send padding, unless
494 * other activity happens first. This side-effect allows us to avoid
495 * scheduling a libevent callback until we're within 1.1 seconds of the padding
496 * time.
498 #define CHANNELPADDING_TIME_LATER -1
499 #define CHANNELPADDING_TIME_DISABLED -2
500 STATIC int64_t
501 channelpadding_compute_time_until_pad_for_netflow(channel_t *chan)
503 uint64_t long_now = monotime_coarse_absolute_msec();
505 if (!chan->next_padding_time_ms) {
506 /* If the below line or crypto_rand_int() shows up on a profile,
507 * we can avoid getting a timeout until we're at least nf_ito_lo
508 * from a timeout window. That will prevent us from setting timers
509 * on connections that were active up to 1.5 seconds ago.
510 * Idle connections should only call this once every 5.5s on average
511 * though, so that might be a micro-optimization for little gain. */
512 int64_t padding_timeout =
513 channelpadding_get_netflow_inactive_timeout_ms(chan);
515 if (!padding_timeout)
516 return CHANNELPADDING_TIME_DISABLED;
518 chan->next_padding_time_ms = padding_timeout
519 + chan->timestamp_xfer_ms;
522 /* If the next padding time is beyond the maximum possible consensus value,
523 * then this indicates a clock jump, so just send padding now. This is
524 * better than using monotonic time because we want to avoid the situation
525 * where we wait around forever for monotonic time to move forward after
526 * a clock jump far into the past.
528 if (chan->next_padding_time_ms > long_now +
529 DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX) {
530 tor_fragile_assert();
531 log_warn(LD_BUG,
532 "Channel padding timeout scheduled "I64_FORMAT"ms in the future. "
533 "Did the monotonic clock just jump?",
534 I64_PRINTF_ARG(chan->next_padding_time_ms - long_now));
535 return 0; /* Clock jumped: Send padding now */
538 /* If the timeout will expire before the next time we're called (1000ms
539 from now, plus some slack), then calculate the number of milliseconds
540 from now which we should send padding, so we can schedule a callback
541 then.
543 if (long_now +
544 (TOR_HOUSEKEEPING_CALLBACK_MSEC + TOR_HOUSEKEEPING_CALLBACK_SLACK_MSEC)
545 >= chan->next_padding_time_ms) {
546 int64_t ms_until_pad_for_netflow = chan->next_padding_time_ms -
547 long_now;
548 /* If the padding time is in the past, that means that libevent delayed
549 * calling the once-per-second callback due to other work taking too long.
550 * See https://bugs.torproject.org/22212 and
551 * https://bugs.torproject.org/16585. This is a systemic problem
552 * with being single-threaded, but let's emit a notice if this
553 * is long enough in the past that we might have missed a netflow window,
554 * and allowed a router to emit a netflow frame, just so we don't forget
555 * about it entirely.. */
556 #define NETFLOW_MISSED_WINDOW (150000 - DFLT_NETFLOW_INACTIVE_KEEPALIVE_HIGH)
557 if (ms_until_pad_for_netflow < 0) {
558 int severity = (ms_until_pad_for_netflow < -NETFLOW_MISSED_WINDOW)
559 ? LOG_NOTICE : LOG_INFO;
560 log_fn(severity, LD_OR,
561 "Channel padding timeout scheduled "I64_FORMAT"ms in the past. ",
562 I64_PRINTF_ARG(-ms_until_pad_for_netflow));
563 return 0; /* Clock jumped: Send padding now */
566 return ms_until_pad_for_netflow;
568 return CHANNELPADDING_TIME_LATER;
572 * Returns a randomized value for channel idle timeout in seconds.
573 * The channel idle timeout governs how quickly we close a channel
574 * after its last circuit has disappeared.
576 * There are three classes of channels:
577 * 1. Client+non-canonical. These live for 3-4.5 minutes
578 * 2. relay to relay. These live for 45-75 min by default
579 * 3. Reduced padding clients. These live for 1.5-2.25 minutes.
581 * Also allows the default relay-to-relay value to be controlled by the
582 * consensus.
584 unsigned int
585 channelpadding_get_channel_idle_timeout(const channel_t *chan,
586 int is_canonical)
588 const or_options_t *options = get_options();
589 unsigned int timeout;
591 /* Non-canonical and client channels only last for 3-4.5 min when idle */
592 if (!is_canonical || CHANNEL_IS_CLIENT(chan, options)) {
593 #define CONNTIMEOUT_CLIENTS_BASE 180 // 3 to 4.5 min
594 timeout = CONNTIMEOUT_CLIENTS_BASE
595 + crypto_rand_int(CONNTIMEOUT_CLIENTS_BASE/2);
596 } else { // Canonical relay-to-relay channels
597 // 45..75min or consensus +/- 25%
598 timeout = consensus_nf_conntimeout_relays;
599 timeout = 3*timeout/4 + crypto_rand_int(timeout/2);
602 /* If ReducedConnectionPadding is set, we want to halve the duration of
603 * the channel idle timeout, since reducing the additional time that
604 * a channel stays open will reduce the total overhead for making
605 * new channels. This reduction in overhead/channel expense
606 * is important for mobile users. The option cannot be set by relays.
608 * We also don't reduce any values for timeout that the user explicitly
609 * set.
611 if (options->ReducedConnectionPadding
612 && !options->CircuitsAvailableTimeout) {
613 timeout /= 2;
616 return timeout;
620 * This function controls how long we keep idle circuits open,
621 * and how long we build predicted circuits. This behavior is under
622 * the control of channelpadding because circuit availability is the
623 * dominant factor in channel lifespan, which influences total padding
624 * overhead.
626 * Returns a randomized number of seconds in a range from
627 * CircuitsAvailableTimeout to 2*CircuitsAvailableTimeout. This value is halved
628 * if ReducedConnectionPadding is set. The default value of
629 * CircuitsAvailableTimeout can be controlled by the consensus.
632 channelpadding_get_circuits_available_timeout(void)
634 const or_options_t *options = get_options();
635 int timeout = options->CircuitsAvailableTimeout;
637 if (!timeout) {
638 timeout = consensus_nf_conntimeout_clients;
640 /* If ReducedConnectionPadding is set, we want to halve the duration of
641 * the channel idle timeout, since reducing the additional time that
642 * a channel stays open will reduce the total overhead for making
643 * new connections. This reduction in overhead/connection expense
644 * is important for mobile users. The option cannot be set by relays.
646 * We also don't reduce any values for timeout that the user explicitly
647 * set.
649 if (options->ReducedConnectionPadding) {
650 // half the value to 15..30min by default
651 timeout /= 2;
655 // 30..60min by default
656 timeout = timeout + crypto_rand_int(timeout);
658 return timeout;
662 * Calling this function on a channel causes it to tell the other side
663 * not to send padding, and disables sending padding from this side as well.
665 void
666 channelpadding_disable_padding_on_channel(channel_t *chan)
668 chan->padding_enabled = 0;
670 // Send cell to disable padding on the other end
671 channelpadding_send_disable_command(chan);
675 * Calling this function on a channel causes it to tell the other side
676 * not to send padding, and reduces the rate that padding is sent from
677 * this side.
679 void
680 channelpadding_reduce_padding_on_channel(channel_t *chan)
682 /* Padding can be forced and reduced by clients, regardless of if
683 * the channel supports it. So we check for support here before
684 * sending any commands. */
685 if (chan->padding_enabled) {
686 channelpadding_send_disable_command(chan);
689 chan->padding_timeout_low_ms = consensus_nf_ito_low_reduced;
690 chan->padding_timeout_high_ms = consensus_nf_ito_high_reduced;
692 log_fn(LOG_INFO,LD_OR,
693 "Reduced padding on channel "U64_FORMAT": lo=%d, hi=%d",
694 U64_PRINTF_ARG(chan->global_identifier),
695 chan->padding_timeout_low_ms, chan->padding_timeout_high_ms);
699 * This function is called once per second by run_connection_housekeeping(),
700 * but only if the channel is still open, valid, and non-wedged.
702 * It decides if and when we should send a padding cell, and if needed,
703 * schedules a callback to send that cell at the appropriate time.
705 * Returns an enum that represents the current padding decision state.
706 * Return value is currently used only by unit tests.
708 channelpadding_decision_t
709 channelpadding_decide_to_pad_channel(channel_t *chan)
711 const or_options_t *options = get_options();
713 /* Only pad open channels */
714 if (chan->state != CHANNEL_STATE_OPEN)
715 return CHANNELPADDING_WONTPAD;
717 if (chan->channel_usage == CHANNEL_USED_FOR_FULL_CIRCS) {
718 if (!consensus_nf_pad_before_usage)
719 return CHANNELPADDING_WONTPAD;
720 } else if (chan->channel_usage != CHANNEL_USED_FOR_USER_TRAFFIC) {
721 return CHANNELPADDING_WONTPAD;
724 if (chan->pending_padding_callback)
725 return CHANNELPADDING_PADDING_ALREADY_SCHEDULED;
727 /* Don't pad the channel if we didn't negotiate it, but still
728 * allow clients to force padding if options->ChannelPadding is
729 * explicitly set to 1.
731 if (!chan->padding_enabled && options->ConnectionPadding != 1) {
732 return CHANNELPADDING_WONTPAD;
735 if (options->Tor2webMode && !consensus_nf_pad_tor2web) {
736 /* If the consensus just changed values, this channel may still
737 * think padding is enabled. Negotiate it off. */
738 if (chan->padding_enabled)
739 channelpadding_disable_padding_on_channel(chan);
741 return CHANNELPADDING_WONTPAD;
744 if (rend_service_allow_non_anonymous_connection(options) &&
745 !consensus_nf_pad_single_onion) {
746 /* If the consensus just changed values, this channel may still
747 * think padding is enabled. Negotiate it off. */
748 if (chan->padding_enabled)
749 channelpadding_disable_padding_on_channel(chan);
751 return CHANNELPADDING_WONTPAD;
754 if (!chan->has_queued_writes(chan)) {
755 int is_client_channel = 0;
757 if (CHANNEL_IS_CLIENT(chan, options)) {
758 is_client_channel = 1;
761 /* If nf_pad_relays=1 is set in the consensus, we pad
762 * on *all* idle connections, relay-relay or relay-client.
763 * Otherwise pad only for client+bridge cons */
764 if (is_client_channel || consensus_nf_pad_relays) {
765 int64_t pad_time_ms =
766 channelpadding_compute_time_until_pad_for_netflow(chan);
768 if (pad_time_ms == CHANNELPADDING_TIME_DISABLED) {
769 return CHANNELPADDING_WONTPAD;
770 } else if (pad_time_ms == CHANNELPADDING_TIME_LATER) {
771 chan->currently_padding = 1;
772 return CHANNELPADDING_PADLATER;
773 } else {
774 if (BUG(pad_time_ms > INT_MAX)) {
775 pad_time_ms = INT_MAX;
777 /* We have to schedule a callback because we're called exactly once per
778 * second, but we don't want padding packets to go out exactly on an
779 * integer multiple of seconds. This callback will only be scheduled
780 * if we're within 1.1 seconds of the padding time.
782 chan->currently_padding = 1;
783 return channelpadding_schedule_padding(chan, (int)pad_time_ms);
785 } else {
786 chan->currently_padding = 0;
787 return CHANNELPADDING_WONTPAD;
789 } else {
790 return CHANNELPADDING_PADLATER;