channeltls.c 81.4 KB
Newer Older
Nick Mathewson's avatar
Nick Mathewson committed
1
/* * Copyright (c) 2012-2019, The Tor Project, Inc. */
2
3
4
5
/* See LICENSE for licensing information */

/**
 * \file channeltls.c
6
7
8
 *
 * \brief A concrete subclass of channel_t using or_connection_t to transfer
 * cells between Tor instances.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 *
 * This module fills in the various function pointers in channel_t, to
 * implement the channel_tls_t channels as used in Tor today.  These channels
 * are created from channel_tls_connect() and
 * channel_tls_handle_incoming(). Each corresponds 1:1 to or_connection_t
 * object, as implemented in connection_or.c.  These channels transmit cells
 * to the underlying or_connection_t by calling
 * connection_or_write_*_cell_to_buf(), and receive cells from the underlying
 * or_connection_t when connection_or_process_cells_from_inbuf() calls
 * channel_tls_handle_*_cell().
 *
 * Here we also implement the server (responder) side of the v3+ Tor link
 * handshake, which uses CERTS and AUTHENTICATE cell to negotiate versions,
 * exchange expected and observed IP and time information, and bootstrap a
 * level of authentication higher than we have gotten on the raw TLS
 * handshake.
 *
 * NOTE: Since there is currently only one type of channel, there are probably
 * more than a few cases where functionality that is currently in
 * channeltls.c, connection_or.c, and channel.c ought to be divided up
 * differently.  The right time to do this is probably whenever we introduce
 * our next channel type.
31
32
33
34
35
36
 **/

/*
 * Define this so channel.h gives us things only channel_t subclasses
 * should touch.
 */
37
#define TOR_CHANNEL_INTERNAL_
38

39
40
#define CHANNELTLS_PRIVATE

41
42
43
44
45
46
47
48
49
50
51
#include "core/or/or.h"
#include "core/or/channel.h"
#include "core/or/channeltls.h"
#include "core/or/circuitmux.h"
#include "core/or/circuitmux_ewma.h"
#include "core/or/command.h"
#include "app/config/config.h"
#include "core/mainloop/connection.h"
#include "core/or/connection_or.h"
#include "feature/control/control.h"
#include "feature/client/entrynodes.h"
Nick Mathewson's avatar
Nick Mathewson committed
52
#include "trunnel/link_handshake.h"
53
54
55
#include "core/or/relay.h"
#include "feature/stats/rephist.h"
#include "feature/relay/router.h"
56
#include "feature/relay/routermode.h"
57
#include "feature/nodelist/dirlist.h"
58
59
60
#include "core/or/scheduler.h"
#include "feature/nodelist/torcert.h"
#include "feature/nodelist/networkstatus.h"
Nick Mathewson's avatar
Nick Mathewson committed
61
#include "trunnel/channelpadding_negotiation.h"
62
#include "core/or/channelpadding.h"
63

64
65
66
67
68
69
70
71
#include "core/or/cell_st.h"
#include "core/or/cell_queue_st.h"
#include "core/or/extend_info_st.h"
#include "core/or/or_connection_st.h"
#include "core/or/or_handshake_certs_st.h"
#include "core/or/or_handshake_state_st.h"
#include "feature/nodelist/routerinfo_st.h"
#include "core/or/var_cell_st.h"
72

73
#include "lib/tls/tortls.h"
74
#include "lib/tls/x509.h"
75

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/** How many CELL_PADDING cells have we received, ever? */
uint64_t stats_n_padding_cells_processed = 0;
/** How many CELL_VERSIONS cells have we received, ever? */
uint64_t stats_n_versions_cells_processed = 0;
/** How many CELL_NETINFO cells have we received, ever? */
uint64_t stats_n_netinfo_cells_processed = 0;
/** How many CELL_VPADDING cells have we received, ever? */
uint64_t stats_n_vpadding_cells_processed = 0;
/** How many CELL_CERTS cells have we received, ever? */
uint64_t stats_n_certs_cells_processed = 0;
/** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
uint64_t stats_n_auth_challenge_cells_processed = 0;
/** How many CELL_AUTHENTICATE cells have we received, ever? */
uint64_t stats_n_authenticate_cells_processed = 0;
/** How many CELL_AUTHORIZE cells have we received, ever? */
uint64_t stats_n_authorize_cells_processed = 0;

/** Active listener, if any */
94
static channel_listener_t *channel_tls_listener = NULL;
95
96
97
98

/* channel_tls_t method declarations */

static void channel_tls_close_method(channel_t *chan);
99
static const char * channel_tls_describe_transport_method(channel_t *chan);
100
static void channel_tls_free_method(channel_t *chan);
101
static double channel_tls_get_overhead_estimate_method(channel_t *chan);
102
103
static int
channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out);
104
105
static int
channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
106
static const char *
107
channel_tls_get_remote_descr_method(channel_t *chan, int flags);
108
109
110
111
112
113
114
static int channel_tls_has_queued_writes_method(channel_t *chan);
static int channel_tls_is_canonical_method(channel_t *chan, int req);
static int
channel_tls_matches_extend_info_method(channel_t *chan,
                                       extend_info_t *extend_info);
static int channel_tls_matches_target_method(channel_t *chan,
                                             const tor_addr_t *target);
115
static int channel_tls_num_cells_writeable_method(channel_t *chan);
116
static size_t channel_tls_num_bytes_queued_method(channel_t *chan);
117
118
119
120
121
122
123
static int channel_tls_write_cell_method(channel_t *chan,
                                         cell_t *cell);
static int channel_tls_write_packed_cell_method(channel_t *chan,
                                                packed_cell_t *packed_cell);
static int channel_tls_write_var_cell_method(channel_t *chan,
                                             var_cell_t *var_cell);

124
125
126
127
128
129
/* channel_listener_tls_t method declarations */

static void channel_tls_listener_close_method(channel_listener_t *chan_l);
static const char *
channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);

130
131
132
133
134
135
136
137
138
139
/** Handle incoming cells for the handshake stuff here rather than
 * passing them on up. */

static void channel_tls_process_versions_cell(var_cell_t *cell,
                                              channel_tls_t *tlschan);
static void channel_tls_process_netinfo_cell(cell_t *cell,
                                             channel_tls_t *tlschan);
static int command_allowed_before_handshake(uint8_t command);
static int enter_v3_handshake_with_cell(var_cell_t *cell,
                                        channel_tls_t *tlschan);
140
141
static void channel_tls_process_padding_negotiate_cell(cell_t *cell,
                                                       channel_tls_t *chan);
142
143

/**
144
145
 * Do parts of channel_tls_t initialization common to channel_tls_connect()
 * and channel_tls_handle_incoming().
146
 */
147
STATIC void
148
channel_tls_common_init(channel_tls_t *tlschan)
149
{
150
151
152
153
154
  channel_t *chan;

  tor_assert(tlschan);

  chan = &(tlschan->base_);
155
  channel_init(chan);
156
  chan->magic = TLS_CHAN_MAGIC;
157
158
  chan->state = CHANNEL_STATE_OPENING;
  chan->close = channel_tls_close_method;
159
  chan->describe_transport = channel_tls_describe_transport_method;
160
  chan->free_fn = channel_tls_free_method;
161
  chan->get_overhead_estimate = channel_tls_get_overhead_estimate_method;
162
163
  chan->get_remote_addr = channel_tls_get_remote_addr_method;
  chan->get_remote_descr = channel_tls_get_remote_descr_method;
164
  chan->get_transport_name = channel_tls_get_transport_name_method;
165
166
167
168
  chan->has_queued_writes = channel_tls_has_queued_writes_method;
  chan->is_canonical = channel_tls_is_canonical_method;
  chan->matches_extend_info = channel_tls_matches_extend_info_method;
  chan->matches_target = channel_tls_matches_target_method;
169
  chan->num_bytes_queued = channel_tls_num_bytes_queued_method;
170
  chan->num_cells_writeable = channel_tls_num_cells_writeable_method;
171
172
173
  chan->write_cell = channel_tls_write_cell_method;
  chan->write_packed_cell = channel_tls_write_packed_cell_method;
  chan->write_var_cell = channel_tls_write_var_cell_method;
174

175
  chan->cmux = circuitmux_alloc();
176
177
  /* We only have one policy for now so always set it to EWMA. */
  circuitmux_set_policy(chan->cmux, &ewma_policy);
178
179
180
}

/**
181
 * Start a new TLS channel.
182
183
184
185
186
187
188
 *
 * Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
 * handshake with an OR with identity digest <b>id_digest</b>, and wrap
 * it in a channel_tls_t.
 */
channel_t *
channel_tls_connect(const tor_addr_t *addr, uint16_t port,
189
190
                    const char *id_digest,
                    const ed25519_public_key_t *ed_id)
191
192
193
194
195
196
{
  channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
  channel_t *chan = &(tlschan->base_);

  channel_tls_common_init(tlschan);

197
  log_debug(LD_CHANNEL,
198
            "In channel_tls_connect() for channel %p "
199
            "(global id %"PRIu64 ")",
200
            tlschan,
201
            (chan->global_identifier));
202

203
204
  if (is_local_addr(addr)) {
    log_debug(LD_CHANNEL,
205
206
              "Marking new outgoing channel %"PRIu64 " at %p as local",
              (chan->global_identifier), chan);
207
208
209
    channel_mark_local(chan);
  } else {
    log_debug(LD_CHANNEL,
210
211
              "Marking new outgoing channel %"PRIu64 " at %p as remote",
              (chan->global_identifier), chan);
212
213
214
    channel_mark_remote(chan);
  }

215
216
217
  channel_mark_outgoing(chan);

  /* Set up or_connection stuff */
218
  tlschan->conn = connection_or_connect(addr, port, id_digest, ed_id, tlschan);
219
220
  /* connection_or_connect() will fill in tlschan->conn */
  if (!(tlschan->conn)) {
221
    chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
222
223
224
225
226
    channel_change_state(chan, CHANNEL_STATE_ERROR);
    goto err;
  }

  log_debug(LD_CHANNEL,
227
228
            "Got orconn %p for channel with global id %"PRIu64,
            tlschan->conn, (chan->global_identifier));
229
230
231
232

  goto done;

 err:
233
  circuitmux_free(chan->cmux);
234
235
236
237
238
239
240
241
242
243
244
  tor_free(tlschan);
  chan = NULL;

 done:
  /* If we got one, we should register it */
  if (chan) channel_register(chan);

  return chan;
}

/**
245
 * Return the current channel_tls_t listener.
246
 *
247
 * Returns the current channel listener for incoming TLS connections, or
248
249
 * NULL if none has been established
 */
250
channel_listener_t *
251
252
channel_tls_get_listener(void)
{
253
  return channel_tls_listener;
254
255
256
}

/**
257
 * Start a channel_tls_t listener if necessary.
258
259
260
261
 *
 * Return the current channel_tls_t listener, or start one if we haven't yet,
 * and return that.
 */
262
channel_listener_t *
263
264
channel_tls_start_listener(void)
{
265
  channel_listener_t *listener;
266
267
268

  if (!channel_tls_listener) {
    listener = tor_malloc_zero(sizeof(*listener));
269
270
271
272
273
    channel_init_listener(listener);
    listener->state = CHANNEL_LISTENER_STATE_LISTENING;
    listener->close = channel_tls_listener_close_method;
    listener->describe_transport =
      channel_tls_listener_describe_transport_method;
274
275
276
277

    channel_tls_listener = listener;

    log_debug(LD_CHANNEL,
278
279
              "Starting TLS channel listener %p with global id %"PRIu64,
              listener, (listener->global_identifier));
280

281
282
    channel_listener_register(listener);
  } else listener = channel_tls_listener;
283

284
  return listener;
285
286
287
}

/**
288
 * Free everything on shutdown.
289
290
291
292
293
294
295
 *
 * Not much to do here, since channel_free_all() takes care of a lot, but let's
 * get rid of the listener.
 */
void
channel_tls_free_all(void)
{
296
297
  channel_listener_t *old_listener = NULL;

298
299
300
301
  log_debug(LD_CHANNEL,
            "Shutting down TLS channels...");

  if (channel_tls_listener) {
302
303
304
305
306
307
    /*
     * When we close it, channel_tls_listener will get nulled out, so save
     * a pointer so we can free it.
     */
    old_listener = channel_tls_listener;
    log_debug(LD_CHANNEL,
308
              "Closing channel_tls_listener with ID %"PRIu64
309
              " at %p.",
310
              (old_listener->global_identifier),
311
312
313
314
315
              old_listener);
    channel_listener_unregister(old_listener);
    channel_listener_mark_for_close(old_listener);
    channel_listener_free(old_listener);
    tor_assert(channel_tls_listener == NULL);
316
317
318
319
320
321
322
  }

  log_debug(LD_CHANNEL,
            "Done shutting down TLS channels");
}

/**
323
 * Create a new channel around an incoming or_connection_t.
324
325
326
327
328
 */
channel_t *
channel_tls_handle_incoming(or_connection_t *orconn)
{
  channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
329
  channel_t *chan = &(tlschan->base_);
330
331
332
333

  tor_assert(orconn);
  tor_assert(!(orconn->chan));

334
  channel_tls_common_init(tlschan);
335
336
337
338
339

  /* Link the channel and orconn to each other */
  tlschan->conn = orconn;
  orconn->chan = tlschan;

340
341
  if (is_local_addr(&(TO_CONN(orconn)->addr))) {
    log_debug(LD_CHANNEL,
342
343
              "Marking new incoming channel %"PRIu64 " at %p as local",
              (chan->global_identifier), chan);
344
345
346
    channel_mark_local(chan);
  } else {
    log_debug(LD_CHANNEL,
347
348
              "Marking new incoming channel %"PRIu64 " at %p as remote",
              (chan->global_identifier), chan);
349
350
351
    channel_mark_remote(chan);
  }

352
353
  channel_mark_incoming(chan);

354
355
  /* Register it */
  channel_register(chan);
356
357
358
359

  return chan;
}

360
361
362
363
364
365
366
367
368
369
370
371
/*********
 * Casts *
 ********/

/**
 * Cast a channel_tls_t to a channel_t.
 */
channel_t *
channel_tls_to_base(channel_tls_t *tlschan)
{
  if (!tlschan) return NULL;

372
  return &(tlschan->base_);
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
}

/**
 * Cast a channel_t to a channel_tls_t, with appropriate type-checking
 * asserts.
 */
channel_tls_t *
channel_tls_from_base(channel_t *chan)
{
  if (!chan) return NULL;

  tor_assert(chan->magic == TLS_CHAN_MAGIC);

  return (channel_tls_t *)(chan);
}

389
390
391
392
393
/********************************************
 * Method implementations for channel_tls_t *
 *******************************************/

/**
394
 * Close a channel_tls_t.
395
 *
396
 * This implements the close method for channel_tls_t.
397
398
399
400
401
402
403
404
 */
static void
channel_tls_close_method(channel_t *chan)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);

405
406
407
408
409
410
411
  if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
  else {
    /* Weird - we'll have to change the state ourselves, I guess */
    log_info(LD_CHANNEL,
             "Tried to close channel_tls_t %p with NULL conn",
             tlschan);
    channel_change_state(chan, CHANNEL_STATE_ERROR);
412
413
414
  }
}

415
/**
416
 * Describe the transport for a channel_tls_t.
417
418
419
420
421
422
423
424
425
426
427
428
429
430
 *
 * This returns the string "TLS channel on connection <id>" to the upper
 * layer.
 */
static const char *
channel_tls_describe_transport_method(channel_t *chan)
{
  static char *buf = NULL;
  uint64_t id;
  channel_tls_t *tlschan;
  const char *rv = NULL;

  tor_assert(chan);

431
  tlschan = BASE_CHAN_TO_TLS(chan);
432

433
434
  if (tlschan->conn) {
    id = TO_CONN(tlschan->conn)->global_identifier;
435

436
437
    if (buf) tor_free(buf);
    tor_asprintf(&buf,
438
439
                 "TLS channel (connection %"PRIu64 ")",
                 (id));
440

441
442
443
    rv = buf;
  } else {
    rv = "TLS channel (no connection)";
444
445
446
447
448
  }

  return rv;
}

449
/**
450
 * Free a channel_tls_t.
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
 *
 * This is called by the generic channel layer when freeing a channel_tls_t;
 * this happens either on a channel which has already reached
 * CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
 * on shutdown from channel_free_all().  In the latter case we might still
 * have an orconn active (which connection_free_all() will get to later),
 * so we should null out its channel pointer now.
 */
static void
channel_tls_free_method(channel_t *chan)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);

  if (tlschan->conn) {
    tlschan->conn->chan = NULL;
    tlschan->conn = NULL;
  }
}

472
/**
473
 * Get an estimate of the average TLS overhead for the upper layer.
474
475
476
477
 */
static double
channel_tls_get_overhead_estimate_method(channel_t *chan)
{
478
  double overhead = 1.0;
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
  tor_assert(tlschan->conn);

  /* Just return 1.0f if we don't have sensible data */
  if (tlschan->conn->bytes_xmitted > 0 &&
      tlschan->conn->bytes_xmitted_by_tls >=
      tlschan->conn->bytes_xmitted) {
    overhead = ((double)(tlschan->conn->bytes_xmitted_by_tls)) /
      ((double)(tlschan->conn->bytes_xmitted));

    /*
     * Never estimate more than 2.0; otherwise we get silly large estimates
     * at the very start of a new TLS connection.
     */
495
496
    if (overhead > 2.0)
      overhead = 2.0;
497
498
499
  }

  log_debug(LD_CHANNEL,
500
501
            "Estimated overhead ratio for TLS chan %"PRIu64 " is %f",
            (chan->global_identifier), overhead);
502
503
504
505

  return overhead;
}

506
/**
507
 * Get the remote address of a channel_tls_t.
508
509
510
511
512
513
514
515
 *
 * This implements the get_remote_addr method for channel_tls_t; copy the
 * remote endpoint of the channel to addr_out and return 1 (always
 * succeeds for this transport).
 */
static int
channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out)
{
516
  int rv = 0;
517
518
519
520
521
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
  tor_assert(addr_out);

522
  if (tlschan->conn) {
523
    tor_addr_copy(addr_out, &(tlschan->conn->real_addr));
524
525
    rv = 1;
  } else tor_addr_make_unspec(addr_out);
526

527
  return rv;
528
529
}

530
531
532
533
534
535
/**
 * Get the name of the pluggable transport used by a channel_tls_t.
 *
 * This implements the get_transport_name for channel_tls_t. If the
 * channel uses a pluggable transport, copy its name to
 * <b>transport_out</b> and return 0. If the channel did not use a
536
537
 * pluggable transport, return -1.
 */
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
static int
channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
  tor_assert(transport_out);
  tor_assert(tlschan->conn);

  if (!tlschan->conn->ext_or_transport)
    return -1;

  *transport_out = tor_strdup(tlschan->conn->ext_or_transport);
  return 0;
}

554
/**
555
 * Get endpoint description of a channel_tls_t.
556
557
558
 *
 * This implements the get_remote_descr method for channel_tls_t; it returns
 * a text description of the remote endpoint of the channel suitable for use
559
 * in log messages. The req parameter is 0 for the canonical address or 1 for
560
561
562
 * the actual address seen.
 */
static const char *
563
channel_tls_get_remote_descr_method(channel_t *chan, int flags)
564
565
566
567
568
569
570
571
572
573
574
{
#define MAX_DESCR_LEN 32

  static char buf[MAX_DESCR_LEN + 1];
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  connection_t *conn;
  const char *answer = NULL;
  char *addr_str;

  tor_assert(tlschan);

575
576
577
578
579
580
581
582
583
584
585
  if (tlschan->conn) {
    conn = TO_CONN(tlschan->conn);
    switch (flags) {
      case 0:
        /* Canonical address with port*/
        tor_snprintf(buf, MAX_DESCR_LEN + 1,
                     "%s:%u", conn->address, conn->port);
        answer = buf;
        break;
      case GRD_FLAG_ORIGINAL:
        /* Actual address with port */
586
        addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
587
588
589
590
591
592
593
594
595
596
597
598
        tor_snprintf(buf, MAX_DESCR_LEN + 1,
                     "%s:%u", addr_str, conn->port);
        tor_free(addr_str);
        answer = buf;
        break;
      case GRD_FLAG_ADDR_ONLY:
        /* Canonical address, no port */
        strlcpy(buf, conn->address, sizeof(buf));
        answer = buf;
        break;
      case GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY:
        /* Actual address, no port */
599
        addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
600
601
602
603
604
605
        strlcpy(buf, addr_str, sizeof(buf));
        tor_free(addr_str);
        answer = buf;
        break;
      default:
        /* Something's broken in channel.c */
606
        tor_assert_nonfatal_unreached_once();
607
608
609
610
    }
  } else {
    strlcpy(buf, "(No connection)", sizeof(buf));
    answer = buf;
611
612
613
614
615
616
  }

  return answer;
}

/**
617
 * Tell the upper layer if we have queued writes.
618
 *
619
 * This implements the has_queued_writes method for channel_tls t_; it returns
620
621
622
623
624
625
626
627
628
 * 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
 */
static int
channel_tls_has_queued_writes_method(channel_t *chan)
{
  size_t outbuf_len;
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
629
630
631
  if (!(tlschan->conn)) {
    log_info(LD_CHANNEL,
             "something called has_queued_writes on a tlschan "
632
633
             "(%p with ID %"PRIu64 " but no conn",
             chan, (chan->global_identifier));
634
  }
635

636
637
638
  outbuf_len = (tlschan->conn != NULL) ?
    connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
    0;
639
640
641
642
643

  return (outbuf_len > 0);
}

/**
644
 * Tell the upper layer if we're canonical.
645
646
647
648
649
650
651
652
653
654
655
656
657
 *
 * This implements the is_canonical method for channel_tls_t; if req is zero,
 * it returns whether this is a canonical channel, and if it is one it returns
 * whether that can be relied upon.
 */
static int
channel_tls_is_canonical_method(channel_t *chan, int req)
{
  int answer = 0;
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);

658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
  if (tlschan->conn) {
    switch (req) {
      case 0:
        answer = tlschan->conn->is_canonical;
        break;
      case 1:
        /*
         * Is the is_canonical bit reliable?  In protocols version 2 and up
         * we get the canonical address from a NETINFO cell, but in older
         * versions it might be based on an obsolete descriptor.
         */
        answer = (tlschan->conn->link_proto >= 2);
        break;
      default:
        /* This shouldn't happen; channel.c is broken if it does */
673
        tor_assert_nonfatal_unreached_once();
674
    }
675
  }
676
  /* else return 0 for tlschan->conn == NULL */
677
678
679
680
681

  return answer;
}

/**
682
 * Check if we match an extend_info_t.
683
684
685
686
687
688
689
690
691
692
693
694
695
 *
 * This implements the matches_extend_info method for channel_tls_t; the upper
 * layer wants to know if this channel matches an extend_info_t.
 */
static int
channel_tls_matches_extend_info_method(channel_t *chan,
                                       extend_info_t *extend_info)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
  tor_assert(extend_info);

696
697
698
699
  /* Never match if we have no conn */
  if (!(tlschan->conn)) {
    log_info(LD_CHANNEL,
             "something called matches_extend_info on a tlschan "
700
701
             "(%p with ID %"PRIu64 " but no conn",
             chan, (chan->global_identifier));
702
703
704
    return 0;
  }

705
706
707
708
709
710
  return (tor_addr_eq(&(extend_info->addr),
                      &(TO_CONN(tlschan->conn)->addr)) &&
         (extend_info->port == TO_CONN(tlschan->conn)->port));
}

/**
711
 * Check if we match a target address; return true iff we do.
712
 *
713
 * This implements the matches_target method for channel_tls t_; the upper
714
715
716
717
718
719
720
721
722
723
724
 * layer wants to know if this channel matches a target address when extending
 * a circuit.
 */
static int
channel_tls_matches_target_method(channel_t *chan,
                                  const tor_addr_t *target)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
  tor_assert(target);
725
726
727
728
729

  /* Never match if we have no conn */
  if (!(tlschan->conn)) {
    log_info(LD_CHANNEL,
             "something called matches_target on a tlschan "
730
731
             "(%p with ID %"PRIu64 " but no conn",
             chan, (chan->global_identifier));
732
733
    return 0;
  }
734

735
736
737
738
739
740
741
742
743
  /* real_addr is the address this connection came from.
   * base_.addr is updated by connection_or_init_conn_from_address()
   * to be the address in the descriptor. It may be tempting to
   * allow either address to be allowed, but if we did so, it would
   * enable someone who steals a relay's keys to impersonate/MITM it
   * from anywhere on the Internet! (Because they could make long-lived
   * TLS connections from anywhere to all relays, and wait for them to
   * be used for extends).
   */
744
  return tor_addr_eq(&(tlschan->conn->real_addr), target);
745
746
}

747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/**
 * Tell the upper layer how many bytes we have queued and not yet
 * sent.
 */
static size_t
channel_tls_num_bytes_queued_method(channel_t *chan)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);

  tor_assert(tlschan);
  tor_assert(tlschan->conn);

  return connection_get_outbuf_len(TO_CONN(tlschan->conn));
}

762
/**
763
 * Tell the upper layer how many cells we can accept to write.
764
765
766
767
768
769
770
771
772
 *
 * This implements the num_cells_writeable method for channel_tls_t; it
 * returns an estimate of the number of cells we can accept with
 * channel_tls_write_*_cell().
 */
static int
channel_tls_num_cells_writeable_method(channel_t *chan)
{
  size_t outbuf_len;
Nick Mathewson's avatar
Nick Mathewson committed
773
  ssize_t n;
774
775
776
777
778
779
780
781
782
783
784
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  size_t cell_network_size;

  tor_assert(tlschan);
  tor_assert(tlschan->conn);

  cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
  outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
  /* Get the number of cells */
  n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
  if (n < 0) n = 0;
Nick Mathewson's avatar
Nick Mathewson committed
785
786
787
#if SIZEOF_SIZE_T > SIZEOF_INT
  if (n > INT_MAX) n = INT_MAX;
#endif
788

Nick Mathewson's avatar
Nick Mathewson committed
789
  return (int)n;
790
791
}

792
/**
793
 * Write a cell to a channel_tls_t.
794
795
796
797
798
799
800
801
 *
 * This implements the write_cell method for channel_tls_t; given a
 * channel_tls_t and a cell_t, transmit the cell_t.
 */
static int
channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
802
  int written = 0;
803
804
805
806

  tor_assert(tlschan);
  tor_assert(cell);

807
808
809
810
811
812
  if (tlschan->conn) {
    connection_or_write_cell_to_buf(cell, tlschan->conn);
    ++written;
  } else {
    log_info(LD_CHANNEL,
             "something called write_cell on a tlschan "
813
814
             "(%p with ID %"PRIu64 " but no conn",
             chan, (chan->global_identifier));
815
  }
816

817
  return written;
818
819
820
}

/**
821
 * Write a packed cell to a channel_tls_t.
822
823
824
 *
 * This implements the write_packed_cell method for channel_tls_t; given a
 * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
825
826
827
 *
 * Return 0 on success or negative value on error. The caller must free the
 * packed cell.
828
829
830
831
832
 */
static int
channel_tls_write_packed_cell_method(channel_t *chan,
                                     packed_cell_t *packed_cell)
{
833
  tor_assert(chan);
834
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
835
  size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
836
837
838
839

  tor_assert(tlschan);
  tor_assert(packed_cell);

840
  if (tlschan->conn) {
841
    connection_buf_add(packed_cell->body, cell_network_size,
842
843
844
845
                            TO_CONN(tlschan->conn));
  } else {
    log_info(LD_CHANNEL,
             "something called write_packed_cell on a tlschan "
846
847
             "(%p with ID %"PRIu64 " but no conn",
             chan, (chan->global_identifier));
848
    return -1;
849
  }
850

851
  return 0;
852
853
854
}

/**
855
 * Write a variable-length cell to a channel_tls_t.
856
857
858
859
860
861
862
863
 *
 * This implements the write_var_cell method for channel_tls_t; given a
 * channel_tls_t and a var_cell_t, transmit the var_cell_t.
 */
static int
channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
{
  channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
864
  int written = 0;
865
866
867
868

  tor_assert(tlschan);
  tor_assert(var_cell);

869
870
871
872
873
874
  if (tlschan->conn) {
    connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
    ++written;
  } else {
    log_info(LD_CHANNEL,
             "something called write_var_cell on a tlschan "
875
876
             "(%p with ID %"PRIu64 " but no conn",
             chan, (chan->global_identifier));
877
  }
878

879
  return written;
880
881
}

882
883
884
885
886
/*************************************************
 * Method implementations for channel_listener_t *
 ************************************************/

/**
887
 * Close a channel_listener_t.
888
 *
889
 * This implements the close method for channel_listener_t.
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
 */
static void
channel_tls_listener_close_method(channel_listener_t *chan_l)
{
  tor_assert(chan_l);

  /*
   * Listeners we just go ahead and change state through to CLOSED, but
   * make sure to check if they're channel_tls_listener to NULL it out.
   */
  if (chan_l == channel_tls_listener)
    channel_tls_listener = NULL;

  if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
        chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
        chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
    channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  }

  if (chan_l->incoming_list) {
    SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
                            channel_t *, ichan) {
      channel_mark_for_close(ichan);
    } SMARTLIST_FOREACH_END(ichan);

    smartlist_free(chan_l->incoming_list);
    chan_l->incoming_list = NULL;
  }

  if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
        chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
    channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
  }
}

/**
926
 * Describe the transport for a channel_listener_t.
927
928
929
930
931
932
933
934
935
936
937
938
 *
 * This returns the string "TLS channel (listening)" to the upper
 * layer.
 */
static const char *
channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
{
  tor_assert(chan_l);

  return "TLS channel (listening)";
}

939
940
941
942
943
/*******************************************************
 * Functions for handling events on an or_connection_t *
 ******************************************************/

/**
944
 * Handle an orconn state change.
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
 *
 * This function will be called by connection_or.c when the or_connection_t
 * associated with this channel_tls_t changes state.
 */
void
channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
                                          or_connection_t *conn,
                                          uint8_t old_state,
                                          uint8_t state)
{
  channel_t *base_chan;

  tor_assert(chan);
  tor_assert(conn);
  tor_assert(conn->chan == chan);
  tor_assert(chan->conn == conn);
teor's avatar
teor committed
961
962
  /* Shut the compiler up without triggering -Wtautological-compare */
  (void)old_state;
963
964
965

  base_chan = TLS_CHAN_TO_BASE(chan);

rl1987's avatar
rl1987 committed
966
967
  /* Make sure the base connection state makes sense - shouldn't be error
   * or closed. */
968

969
970
971
972
  tor_assert(CHANNEL_IS_OPENING(base_chan) ||
             CHANNEL_IS_OPEN(base_chan) ||
             CHANNEL_IS_MAINT(base_chan) ||
             CHANNEL_IS_CLOSING(base_chan));
973
974
975
976
977
978
979

  /* Did we just go to state open? */
  if (state == OR_CONN_STATE_OPEN) {
    /*
     * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
     * CHANNEL_STATE_MAINT on this.
     */
980
    channel_change_state_open(base_chan);
981
982
983
984
    /* We might have just become writeable; check and tell the scheduler */
    if (connection_or_num_cells_writeable(conn) > 0) {
      scheduler_channel_wants_writes(base_chan);
    }
985
986
987
988
989
  } else {
    /*
     * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
     * otherwise no change.
     */
990
    if (CHANNEL_IS_OPEN(base_chan)) {
991
992
993
994
995
996
997
998
      channel_change_state(base_chan, CHANNEL_STATE_MAINT);
    }
  }
}

#ifdef KEEP_TIMING_STATS

/**
999
 * Timing states wrapper.
1000
 *
For faster browsing, not all history is shown. View entire blame