channel.c 116 KB
Newer Older
1
/* * Copyright (c) 2012-2013, The Tor Project, Inc. */
2
3
4
5
6
7
8
9
10
11
12
13
/* See LICENSE for licensing information */

/**
 * \file channel.c
 * \brief OR-to-OR channel abstraction layer
 **/

/*
 * Define this so channel.h gives us things only channel_t subclasses
 * should touch.
 */

14
#define TOR_CHANNEL_INTERNAL_
15
16
17
18
19
20

#include "or.h"
#include "channel.h"
#include "channeltls.h"
#include "circuitbuild.h"
#include "circuitlist.h"
21
#include "circuitstats.h"
22
#include "connection_or.h" /* For var_cell_free() */
23
#include "circuitmux.h"
24
#include "entrynodes.h"
25
26
27
28
29
30
31
32
33
34
35
#include "geoip.h"
#include "nodelist.h"
#include "relay.h"
#include "rephist.h"
#include "router.h"
#include "routerlist.h"

/* Cell queue structure */

typedef struct cell_queue_entry_s cell_queue_entry_t;
struct cell_queue_entry_s {
36
  TOR_SIMPLEQ_ENTRY(cell_queue_entry_s) next;
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  enum {
    CELL_QUEUE_FIXED,
    CELL_QUEUE_VAR,
    CELL_QUEUE_PACKED
  } type;
  union {
    struct {
      cell_t *cell;
    } fixed;
    struct {
      var_cell_t *var_cell;
    } var;
    struct {
      packed_cell_t *packed_cell;
    } packed;
  } u;
};

/* Global lists of channels */

/* All channel_t instances */
static smartlist_t *all_channels = NULL;

/* All channel_t instances not in ERROR or CLOSED states */
static smartlist_t *active_channels = NULL;

/* All channel_t instances in ERROR or CLOSED states */
static smartlist_t *finished_channels = NULL;

66
67
68
69
70
71
72
73
74
/* All channel_listener_t instances */
static smartlist_t *all_listeners = NULL;

/* All channel_listener_t instances in LISTENING state */
static smartlist_t *active_listeners = NULL;

/* All channel_listener_t instances in LISTENING state */
static smartlist_t *finished_listeners = NULL;

75
76
77
78
79
80
81
82
83
84
85
/* Counter for ID numbers */
static uint64_t n_channels_allocated = 0;

/* Digest->channel map
 *
 * Similar to the one used in connection_or.c, this maps from the identity
 * digest of a remote endpoint to a channel_t to that endpoint.  Channels
 * should be placed here when registered and removed when they close or error.
 * If more than one channel exists, follow the next_with_same_id pointer
 * as a linked list.
 */
86
87
88
89
90
91
HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
  HT_INITIALIZER();

typedef struct channel_idmap_entry_s {
  HT_ENTRY(channel_idmap_entry_s) node;
  uint8_t digest[DIGEST_LEN];
92
  TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
93
94
95
96
97
} channel_idmap_entry_t;

static INLINE unsigned
channel_idmap_hash(const channel_idmap_entry_t *ent)
{
98
  return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
99
100
101
102
103
104
105
106
107
108
109
110
}

static INLINE int
channel_idmap_eq(const channel_idmap_entry_t *a,
                  const channel_idmap_entry_t *b)
{
  return tor_memeq(a->digest, b->digest, DIGEST_LEN);
}

HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
             channel_idmap_eq);
HT_GENERATE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
111
            channel_idmap_eq, 0.5, tor_malloc, tor_realloc, tor_free_);
112

113
114
static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
static void cell_queue_entry_free(cell_queue_entry_t *q, int handed_off);
Andrea Shepard's avatar
Andrea Shepard committed
115
static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
116
117
118
119
static cell_queue_entry_t *
cell_queue_entry_new_fixed(cell_t *cell);
static cell_queue_entry_t *
cell_queue_entry_new_var(var_cell_t *var_cell);
120
121
static int is_destroy_cell(channel_t *chan,
                           const cell_queue_entry_t *q, circid_t *circid_out);
Andrea Shepard's avatar
Andrea Shepard committed
122

123
124
125
126
127
128
129
130
131
132
133
/* Functions to maintain the digest map */
static void channel_add_to_digest_map(channel_t *chan);
static void channel_remove_from_digest_map(channel_t *chan);

/*
 * Flush cells from just the outgoing queue without trying to get them
 * from circuits; used internall by channel_flush_some_cells().
 */
static ssize_t
channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
                                             ssize_t num_cells);
134
static void channel_force_free(channel_t *chan);
Andrea Shepard's avatar
Andrea Shepard committed
135
static void
136
137
138
139
140
channel_free_list(smartlist_t *channels, int mark_for_close);
static void
channel_listener_free_list(smartlist_t *channels, int mark_for_close);
static void channel_listener_force_free(channel_listener_t *chan_l);
static void
Andrea Shepard's avatar
Andrea Shepard committed
141
channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q);
142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/***********************************
 * Channel state utility functions *
 **********************************/

/**
 * Indicate whether a given channel state is valid
 */

int
channel_state_is_valid(channel_state_t state)
{
  int is_valid;

  switch (state) {
    case CHANNEL_STATE_CLOSED:
    case CHANNEL_STATE_CLOSING:
    case CHANNEL_STATE_ERROR:
    case CHANNEL_STATE_MAINT:
    case CHANNEL_STATE_OPENING:
    case CHANNEL_STATE_OPEN:
      is_valid = 1;
      break;
    case CHANNEL_STATE_LAST:
    default:
      is_valid = 0;
  }

  return is_valid;
}

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/**
 * Indicate whether a given channel listener state is valid
 */

int
channel_listener_state_is_valid(channel_listener_state_t state)
{
  int is_valid;

  switch (state) {
    case CHANNEL_LISTENER_STATE_CLOSED:
    case CHANNEL_LISTENER_STATE_LISTENING:
    case CHANNEL_LISTENER_STATE_CLOSING:
    case CHANNEL_LISTENER_STATE_ERROR:
      is_valid = 1;
      break;
    case CHANNEL_LISTENER_STATE_LAST:
    default:
      is_valid = 0;
  }

  return is_valid;
}

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
 * Indicate whether a channel state transition is valid
 *
 * This function takes two channel states and indicates whether a
 * transition between them is permitted (see the state definitions and
 * transition table in or.h at the channel_state_t typedef).
 */

int
channel_state_can_transition(channel_state_t from, channel_state_t to)
{
  int is_valid;

  switch (from) {
    case CHANNEL_STATE_CLOSED:
212
      is_valid = (to == CHANNEL_STATE_OPENING);
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
      break;
    case CHANNEL_STATE_CLOSING:
      is_valid = (to == CHANNEL_STATE_CLOSED ||
                  to == CHANNEL_STATE_ERROR);
      break;
    case CHANNEL_STATE_ERROR:
      is_valid = 0;
      break;
    case CHANNEL_STATE_MAINT:
      is_valid = (to == CHANNEL_STATE_CLOSING ||
                  to == CHANNEL_STATE_ERROR ||
                  to == CHANNEL_STATE_OPEN);
      break;
    case CHANNEL_STATE_OPENING:
      is_valid = (to == CHANNEL_STATE_CLOSING ||
                  to == CHANNEL_STATE_ERROR ||
                  to == CHANNEL_STATE_OPEN);
      break;
    case CHANNEL_STATE_OPEN:
      is_valid = (to == CHANNEL_STATE_CLOSING ||
                  to == CHANNEL_STATE_ERROR ||
                  to == CHANNEL_STATE_MAINT);
      break;
    case CHANNEL_STATE_LAST:
    default:
      is_valid = 0;
  }

  return is_valid;
}

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
 * Indicate whether a channel listener state transition is valid
 *
 * This function takes two channel listener states and indicates whether a
 * transition between them is permitted (see the state definitions and
 * transition table in or.h at the channel_listener_state_t typedef).
 */

int
channel_listener_state_can_transition(channel_listener_state_t from,
                                      channel_listener_state_t to)
{
  int is_valid;

  switch (from) {
    case CHANNEL_LISTENER_STATE_CLOSED:
      is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
      break;
    case CHANNEL_LISTENER_STATE_CLOSING:
      is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
                  to == CHANNEL_LISTENER_STATE_ERROR);
      break;
    case CHANNEL_LISTENER_STATE_ERROR:
      is_valid = 0;
      break;
    case CHANNEL_LISTENER_STATE_LISTENING:
      is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
                  to == CHANNEL_LISTENER_STATE_ERROR);
      break;
    case CHANNEL_LISTENER_STATE_LAST:
    default:
      is_valid = 0;
  }

  return is_valid;
}

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
 * Return a human-readable description for a channel state
 */

const char *
channel_state_to_string(channel_state_t state)
{
  const char *descr;

  switch (state) {
    case CHANNEL_STATE_CLOSED:
      descr = "closed";
      break;
    case CHANNEL_STATE_CLOSING:
      descr = "closing";
      break;
    case CHANNEL_STATE_ERROR:
      descr = "channel error";
      break;
    case CHANNEL_STATE_MAINT:
      descr = "temporarily suspended for maintenance";
      break;
    case CHANNEL_STATE_OPENING:
      descr = "opening";
      break;
    case CHANNEL_STATE_OPEN:
      descr = "open";
      break;
    case CHANNEL_STATE_LAST:
    default:
      descr = "unknown or invalid channel state";
  }

  return descr;
}

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/**
 * Return a human-readable description for a channel listenier state
 */

const char *
channel_listener_state_to_string(channel_listener_state_t state)
{
  const char *descr;

  switch (state) {
    case CHANNEL_LISTENER_STATE_CLOSED:
      descr = "closed";
      break;
    case CHANNEL_LISTENER_STATE_CLOSING:
      descr = "closing";
      break;
    case CHANNEL_LISTENER_STATE_ERROR:
      descr = "channel listener error";
      break;
    case CHANNEL_LISTENER_STATE_LISTENING:
      descr = "listening";
      break;
    case CHANNEL_LISTENER_STATE_LAST:
    default:
      descr = "unknown or invalid channel listener state";
  }

  return descr;
}

347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/***************************************
 * Channel registration/unregistration *
 ***************************************/

/**
 * Register a channel
 *
 * This function registers a newly created channel in the global lists/maps
 * of active channels.
 */

void
channel_register(channel_t *chan)
{
  tor_assert(chan);

  /* No-op if already registered */
  if (chan->registered) return;

366
367
368
369
370
371
  log_debug(LD_CHANNEL,
            "Registering channel %p (ID " U64_FORMAT ") "
            "in state %s (%d) with digest %s",
            chan, U64_PRINTF_ARG(chan->global_identifier),
            channel_state_to_string(chan->state), chan->state,
            hex_str(chan->identity_digest, DIGEST_LEN));
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387

  /* Make sure we have all_channels, then add it */
  if (!all_channels) all_channels = smartlist_new();
  smartlist_add(all_channels, chan);

  /* Is it finished? */
  if (chan->state == CHANNEL_STATE_CLOSED ||
      chan->state == CHANNEL_STATE_ERROR) {
    /* Put it in the finished list, creating it if necessary */
    if (!finished_channels) finished_channels = smartlist_new();
    smartlist_add(finished_channels, chan);
  } else {
    /* Put it in the active list, creating it if necessary */
    if (!active_channels) active_channels = smartlist_new();
    smartlist_add(active_channels, chan);

388
389
390
391
392
393
394
395
396
397
398
    if (chan->state != CHANNEL_STATE_CLOSING) {
      /* It should have a digest set */
      if (!tor_digest_is_zero(chan->identity_digest)) {
        /* Yeah, we're good, add it to the map */
        channel_add_to_digest_map(chan);
      } else {
        log_info(LD_CHANNEL,
                "Channel %p (global ID " U64_FORMAT ") "
                "in state %s (%d) registered with no identity digest",
                chan, U64_PRINTF_ARG(chan->global_identifier),
                channel_state_to_string(chan->state), chan->state);
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
      }
    }
  }

  /* Mark it as registered */
  chan->registered = 1;
}

/**
 * Unregister a channel
 *
 * This function removes a channel from the global lists and maps and is used
 * when freeing a closed/errored channel.
 */

void
channel_unregister(channel_t *chan)
{
  tor_assert(chan);

  /* No-op if not registered */
  if (!(chan->registered)) return;

  /* Is it finished? */
  if (chan->state == CHANNEL_STATE_CLOSED ||
      chan->state == CHANNEL_STATE_ERROR) {
    /* Get it out of the finished list */
    if (finished_channels) smartlist_remove(finished_channels, chan);
  } else {
    /* Get it out of the active list */
    if (active_channels) smartlist_remove(active_channels, chan);
  }

  /* Get it out of all_channels */
 if (all_channels) smartlist_remove(all_channels, chan);

  /* Mark it as unregistered */
  chan->registered = 0;

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
  /* Should it be in the digest map? */
  if (!tor_digest_is_zero(chan->identity_digest) &&
      !(chan->state == CHANNEL_STATE_CLOSING ||
        chan->state == CHANNEL_STATE_CLOSED ||
        chan->state == CHANNEL_STATE_ERROR)) {
    /* Remove it */
    channel_remove_from_digest_map(chan);
  }
}

/**
 * Register a channel listener
 *
 * This function registers a newly created channel listner in the global
 * lists/maps of active channel listeners.
 */

void
channel_listener_register(channel_listener_t *chan_l)
{
  tor_assert(chan_l);

  /* No-op if already registered */
  if (chan_l->registered) return;

  log_debug(LD_CHANNEL,
            "Registering channel listener %p (ID " U64_FORMAT ") "
            "in state %s (%d)",
            chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
            channel_listener_state_to_string(chan_l->state),
            chan_l->state);

  /* Make sure we have all_channels, then add it */
  if (!all_listeners) all_listeners = smartlist_new();
  smartlist_add(all_listeners, chan_l);

  /* Is it finished? */
  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
      chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
    /* Put it in the finished list, creating it if necessary */
    if (!finished_listeners) finished_listeners = smartlist_new();
    smartlist_add(finished_listeners, chan_l);
  } else {
    /* Put it in the active list, creating it if necessary */
    if (!active_listeners) active_listeners = smartlist_new();
    smartlist_add(active_listeners, chan_l);
  }

  /* Mark it as registered */
  chan_l->registered = 1;
}

/**
 * Unregister a channel listener
 *
 * This function removes a channel listener from the global lists and maps
 * and is used when freeing a closed/errored channel listener.
 */

void
channel_listener_unregister(channel_listener_t *chan_l)
{
  tor_assert(chan_l);

  /* No-op if not registered */
  if (!(chan_l->registered)) return;

  /* Is it finished? */
  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
      chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
    /* Get it out of the finished list */
    if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  } else {
    /* Get it out of the active list */
    if (active_listeners) smartlist_remove(active_listeners, chan_l);
513
  }
514
515
516
517
518
519

  /* Get it out of all_channels */
 if (all_listeners) smartlist_remove(all_listeners, chan_l);

  /* Mark it as unregistered */
  chan_l->registered = 0;
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
}

/*********************************
 * Channel digest map maintenance
 *********************************/

/**
 * Add a channel to the digest map
 *
 * This function adds a channel to the digest map and inserts it into the
 * correct linked list if channels with that remote endpoint identity digest
 * already exist.
 */

static void
channel_add_to_digest_map(channel_t *chan)
{
537
  channel_idmap_entry_t *ent, search;
538
539
540
541

  tor_assert(chan);

  /* Assert that the state makes sense */
542
  tor_assert(!(chan->state == CHANNEL_STATE_CLOSING ||
543
544
545
546
               chan->state == CHANNEL_STATE_CLOSED ||
               chan->state == CHANNEL_STATE_ERROR));

  /* Assert that there is a digest */
547
  tor_assert(!tor_digest_is_zero(chan->identity_digest));
548

549
550
551
552
553
  memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  if (! ent) {
    ent = tor_malloc(sizeof(channel_idmap_entry_t));
    memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
554
    TOR_LIST_INIT(&ent->channel_list);
555
    HT_INSERT(channel_idmap, &channel_identity_map, ent);
556
  }
557
  TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
558
559

  log_debug(LD_CHANNEL,
560
561
562
            "Added channel %p (global ID " U64_FORMAT ") "
            "to identity map in state %s (%d) with digest %s",
            chan, U64_PRINTF_ARG(chan->global_identifier),
563
            channel_state_to_string(chan->state), chan->state,
564
            hex_str(chan->identity_digest, DIGEST_LEN));
565
566
567
568
569
570
571
572
573
574
575
576
}

/**
 * Remove a channel from the digest map
 *
 * This function removes a channel from the digest map and the linked list of
 * channels for that digest if more than one exists.
 */

static void
channel_remove_from_digest_map(channel_t *chan)
{
577
  channel_idmap_entry_t *ent, search;
578
579
580
581

  tor_assert(chan);

  /* Assert that there is a digest */
582
  tor_assert(!tor_digest_is_zero(chan->identity_digest));
583

584
#if 0
585
586
587
588
589
590
591
  /* Make sure we have a map */
  if (!channel_identity_map) {
    /*
     * No identity map, so we can't find it by definition.  This
     * case is similar to digestmap_get() failing below.
     */
    log_warn(LD_BUG,
592
593
594
595
             "Trying to remove channel %p (global ID " U64_FORMAT ") "
             "with digest %s from identity map, but didn't have any identity "
             "map",
             chan, U64_PRINTF_ARG(chan->global_identifier),
596
             hex_str(chan->identity_digest, DIGEST_LEN));
597
    /* Clear out its next/prev pointers */
598
599
    if (chan->next_with_same_id) {
      chan->next_with_same_id->prev_with_same_id = chan->prev_with_same_id;
600
    }
601
602
    if (chan->prev_with_same_id) {
      chan->prev_with_same_id->next_with_same_id = chan->next_with_same_id;
603
    }
604
605
    chan->next_with_same_id = NULL;
    chan->prev_with_same_id = NULL;
606
607
608

    return;
  }
609
#endif
610

611
  /* Pull it out of its list, wherever that list is */
612
  TOR_LIST_REMOVE(chan, next_with_same_id);
613

614
615
  memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
616

617
618
619
  /* Look for it in the map */
  if (ent) {
    /* Okay, it's here */
620

621
    if (TOR_LIST_EMPTY(&ent->channel_list)) {
622
623
      HT_REMOVE(channel_idmap, &channel_identity_map, ent);
      tor_free(ent);
624
    }
625
626
627
628
629
630
631

    log_debug(LD_CHANNEL,
              "Removed channel %p (global ID " U64_FORMAT ") from "
              "identity map in state %s (%d) with digest %s",
              chan, U64_PRINTF_ARG(chan->global_identifier),
              channel_state_to_string(chan->state), chan->state,
              hex_str(chan->identity_digest, DIGEST_LEN));
632
633
634
  } else {
    /* Shouldn't happen */
    log_warn(LD_BUG,
635
636
637
638
             "Trying to remove channel %p (global ID " U64_FORMAT ") with "
             "digest %s from identity map, but couldn't find any with "
             "that digest",
             chan, U64_PRINTF_ARG(chan->global_identifier),
639
             hex_str(chan->identity_digest, DIGEST_LEN));
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
  }
}

/****************************
 * Channel lookup functions *
 ***************************/

/**
 * Find channel by global ID
 *
 * This function searches for a channel by the global_identifier assigned
 * at initialization time.  This identifier is unique for the lifetime of the
 * Tor process.
 */

channel_t *
channel_find_by_global_id(uint64_t global_identifier)
{
  channel_t *rv = NULL;

  if (all_channels && smartlist_len(all_channels) > 0) {
    SMARTLIST_FOREACH_BEGIN(all_channels, channel_t *, curr) {
      if (curr->global_identifier == global_identifier) {
        rv = curr;
        break;
      }
    } SMARTLIST_FOREACH_END(curr);
  }

  return rv;
}

/**
 * Find channel by digest of the remote endpoint
 *
 * This function looks up a channel by the digest of its remote endpoint in
 * the channel digest map.  It's possible that more than one channel to a
677
 * given endpoint exists.  Use channel_next_with_digest() to walk the list.
678
679
680
681
682
 */

channel_t *
channel_find_by_remote_digest(const char *identity_digest)
{
683
  channel_t *rv = NULL;
684
  channel_idmap_entry_t *ent, search;
685
686
687

  tor_assert(identity_digest);

688
689
690
  memcpy(search.digest, identity_digest, DIGEST_LEN);
  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  if (ent) {
691
    rv = TOR_LIST_FIRST(&ent->channel_list);
692
693
694
695
696
697
  }

  return rv;
}

/**
698
 * Get next channel with digest
699
700
701
702
703
704
705
706
707
708
 *
 * This function takes a channel and finds the next channel in the list
 * with the same digest.
 */

channel_t *
channel_next_with_digest(channel_t *chan)
{
  tor_assert(chan);

709
  return TOR_LIST_NEXT(chan, next_with_same_id);
710
711
712
}

/**
713
 * Initialize a channel
714
715
716
717
718
719
720
 *
 * This function should be called by subclasses to set up some per-channel
 * variables.  I.e., this is the superclass constructor.  Before this, the
 * channel should be allocated with tor_malloc_zero().
 */

void
721
channel_init(channel_t *chan)
722
723
724
725
726
727
728
{
  tor_assert(chan);

  /* Assign an ID and bump the counter */
  chan->global_identifier = n_channels_allocated++;

  /* Init timestamp */
729
  chan->timestamp_last_added_nonpadding = time(NULL);
730
731

  /* Init next_circ_id */
732
  chan->next_circ_id = crypto_rand_int(1 << 15);
733

734
  /* Initialize queues. */
735
736
  TOR_SIMPLEQ_INIT(&chan->incoming_queue);
  TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
737

738
739
740
  /* Initialize list entries. */
  memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));

741
742
  /* Timestamp it */
  channel_timestamp_created(chan);
743
744
745

  /* It hasn't been open yet. */
  chan->has_been_open = 0;
746
747
748
}

/**
749
 * Initialize a channel listener
750
751
752
 *
 * This function should be called by subclasses to set up some per-channel
 * variables.  I.e., this is the superclass constructor.  Before this, the
753
 * channel listener should be allocated with tor_malloc_zero().
754
755
756
 */

void
757
channel_init_listener(channel_listener_t *chan_l)
758
{
759
  tor_assert(chan_l);
760
761

  /* Assign an ID and bump the counter */
762
  chan_l->global_identifier = n_channels_allocated++;
763
764

  /* Timestamp it */
765
  channel_listener_timestamp_created(chan_l);
766
767
768
}

/**
769
770
 * Free a channel; nothing outside of channel.c and subclasses should call
 * this - it frees channels after they have closed and been unregistered.
771
772
773
774
775
 */

void
channel_free(channel_t *chan)
{
776
777
  if (!chan) return;

778
779
780
781
782
783
  /* It must be closed or errored */
  tor_assert(chan->state == CHANNEL_STATE_CLOSED ||
             chan->state == CHANNEL_STATE_ERROR);
  /* It must be deregistered */
  tor_assert(!(chan->registered));

784
785
786
787
  log_debug(LD_CHANNEL,
            "Freeing channel " U64_FORMAT " at %p",
            U64_PRINTF_ARG(chan->global_identifier), chan);

788
789
790
791
792
793
794
795
  /*
   * Get rid of cmux policy before we do anything, so cmux policies don't
   * see channels in weird half-freed states.
   */
  if (chan->cmux) {
    circuitmux_set_policy(chan->cmux, NULL);
  }

796
797
798
  /* Call a free method if there is one */
  if (chan->free) chan->free(chan);

799
  channel_clear_remote_end(chan);
800

801
  /* Get rid of cmux */
802
803
  if (chan->cmux) {
    circuitmux_detach_all_circuits(chan->cmux);
804
    circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
805
806
    circuitmux_free(chan->cmux);
    chan->cmux = NULL;
807
808
809
810
811
812
813
814
  }

  /* We're in CLOSED or ERROR, so the cell queue is already empty */

  tor_free(chan);
}

/**
815
816
817
818
819
820
821
822
823
824
 * Free a channel listener; nothing outside of channel.c and subclasses
 * should call this - it frees channel listeners after they have closed and
 * been unregistered.
 */

void
channel_listener_free(channel_listener_t *chan_l)
{
  if (!chan_l) return;

825
826
827
828
829
  log_debug(LD_CHANNEL,
            "Freeing channel_listener_t " U64_FORMAT " at %p",
            U64_PRINTF_ARG(chan_l->global_identifier),
            chan_l);

830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
  /* It must be closed or errored */
  tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
             chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
  /* It must be deregistered */
  tor_assert(!(chan_l->registered));

  /* Call a free method if there is one */
  if (chan_l->free) chan_l->free(chan_l);

  /*
   * We're in CLOSED or ERROR, so the incoming channel queue is already
   * empty.
   */

  tor_free(chan_l);
}

/**
 * Free a channel and skip the state/registration asserts; this internal-
849
850
 * use-only function should be called only from channel_free_all() when
 * shutting down the Tor process.
851
852
 */

853
static void
854
855
channel_force_free(channel_t *chan)
{
856
  cell_queue_entry_t *cell, *cell_tmp;
857
858
  tor_assert(chan);

859
860
861
862
  log_debug(LD_CHANNEL,
            "Force-freeing channel " U64_FORMAT " at %p",
            U64_PRINTF_ARG(chan->global_identifier), chan);

863
864
865
866
867
868
869
870
  /*
   * Get rid of cmux policy before we do anything, so cmux policies don't
   * see channels in weird half-freed states.
   */
  if (chan->cmux) {
    circuitmux_set_policy(chan->cmux, NULL);
  }

871
872
873
  /* Call a free method if there is one */
  if (chan->free) chan->free(chan);

874
875
  channel_clear_remote_end(chan);

876
877
878
879
880
881
  /* Get rid of cmux */
  if (chan->cmux) {
    circuitmux_free(chan->cmux);
    chan->cmux = NULL;
  }

882
  /* We might still have a cell queue; kill it */
883
  TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
884
      cell_queue_entry_free(cell, 0);
885
  }
886
  TOR_SIMPLEQ_INIT(&chan->incoming_queue);
887

888
  /* Outgoing cell queue is similar, but we can have to free packed cells */
889
  TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
890
    cell_queue_entry_free(cell, 0);
891
  }
892
  TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
893
894
895
896
897

  tor_free(chan);
}

/**
898
899
900
901
902
903
904
905
906
907
 * Free a channel listener and skip the state/reigstration asserts; this
 * internal-use-only function should be called only from channel_free_all()
 * when shutting down the Tor process.
 */

static void
channel_listener_force_free(channel_listener_t *chan_l)
{
  tor_assert(chan_l);

908
909
910
911
912
  log_debug(LD_CHANNEL,
            "Force-freeing channel_listener_t " U64_FORMAT " at %p",
            U64_PRINTF_ARG(chan_l->global_identifier),
            chan_l);

913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
  /* Call a free method if there is one */
  if (chan_l->free) chan_l->free(chan_l);

  /*
   * The incoming list just gets emptied and freed; we request close on
   * any channels we find there, but since we got called while shutting
   * down they will get deregistered and freed elsewhere anyway.
   */
  if (chan_l->incoming_list) {
    SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
                            channel_t *, qchan) {
      channel_mark_for_close(qchan);
    } SMARTLIST_FOREACH_END(qchan);

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

  tor_free(chan_l);
}

/**
 * Return the current registered listener for a channel listener
936
937
 *
 * This function returns a function pointer to the current registered
938
 * handler for new incoming channels on a channel listener.
939
940
 */

941
channel_listener_fn_ptr
942
channel_listener_get_listener_fn(channel_listener_t *chan_l)
943
{
944
  tor_assert(chan_l);
945

946
947
  if (chan_l->state == CHANNEL_LISTENER_STATE_LISTENING)
    return chan_l->listener;
948
949
950
951
952

  return NULL;
}

/**
953
 * Set the listener for a channel listener
954
 *
955
956
 * This function sets the handler for new incoming channels on a channel
 * listener.
957
958
959
 */

void
960
961
channel_listener_set_listener_fn(channel_listener_t *chan_l,
                                channel_listener_fn_ptr listener)
962
{
963
964
  tor_assert(chan_l);
  tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
965
966

  log_debug(LD_CHANNEL,
967
968
969
970
           "Setting listener callback for channel listener %p "
           "(global ID " U64_FORMAT ") to %p",
           chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
           listener);
971

972
973
  chan_l->listener = listener;
  if (chan_l->listener) channel_listener_process_incoming(chan_l);
974
975
976
977
978
979
980
981
982
}

/**
 * Return the fixed-length cell handler for a channel
 *
 * This function gets the handler for incoming fixed-length cells installed
 * on a channel.
 */

983
984
channel_cell_handler_fn_ptr
channel_get_cell_handler(channel_t *chan)
985
986
987
988
989
990
{
  tor_assert(chan);

  if (chan->state == CHANNEL_STATE_OPENING ||
      chan->state == CHANNEL_STATE_OPEN ||
      chan->state == CHANNEL_STATE_MAINT)
991
    return chan->cell_handler;
992
993
994
995
996
997
998
999
1000

  return NULL;
}

/**
 * Return the variable-length cell handler for a channel
 *
 * This function gets the handler for incoming variable-length cells
 * installed on a channel.