connection_or.c 54.2 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright (c) 2001 Matej Pfajfar.
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4
 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5
/* See LICENSE for licensing information */
Roger Dingledine's avatar
Roger Dingledine committed
6

Roger Dingledine's avatar
Roger Dingledine committed
7
8
9
10
11
12
/**
 * \file connection_or.c
 * \brief Functions to handle OR connections, TLS handshaking, and
 * cells on the network.
 **/

Roger Dingledine's avatar
Roger Dingledine committed
13
#include "or.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
14
#include "buffers.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
15
#include "circuitbuild.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
16
#include "command.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
17
#include "config.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
18
#include "connection.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
19
#include "connection_or.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
20
#include "control.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
21
#include "dirserv.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
22
#include "geoip.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
23
#include "main.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
24
#include "networkstatus.h"
25
#include "nodelist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
26
#include "reasons.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
27
#include "relay.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
28
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
29
#include "router.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
30
#include "routerlist.h"
31

32
33
34
35
#ifdef USE_BUFFEREVENTS
#include <event2/bufferevent_ssl.h>
#endif

36
37
static int connection_tls_finish_handshake(or_connection_t *conn);
static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
38
static int connection_or_send_versions(or_connection_t *conn);
39
40
static int connection_init_or_handshake_state(or_connection_t *conn,
                                              int started_here);
41
42
43
static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
                                                   int started_here,
                                                   char *digest_rcvd_out);
44

45
46
static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);

47
48
49
50
51
52
#ifdef USE_BUFFEREVENTS
static void connection_or_handle_event_cb(struct bufferevent *bufev,
                                          short event, void *arg);
#include <event2/buffer.h>/*XXXX REMOVE */
#endif

Roger Dingledine's avatar
Roger Dingledine committed
53
54
/**************************************************************/

55
56
/** Map from identity digest of connected OR or desired OR to a connection_t
 * with that identity digest.  If there is more than one such connection_t,
Roger Dingledine's avatar
Roger Dingledine committed
57
 * they form a linked list, with next_with_same_id as the next pointer. */
58
59
60
static digestmap_t *orconn_identity_map = NULL;

/** If conn is listed in orconn_identity_map, remove it, and clear
61
 * conn->identity_digest.  Otherwise do nothing. */
62
void
63
connection_or_remove_from_identity_map(or_connection_t *conn)
64
{
65
  or_connection_t *tmp;
66
67
68
69
  tor_assert(conn);
  if (!orconn_identity_map)
    return;
  tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
70
71
  if (!tmp) {
    if (!tor_digest_is_zero(conn->identity_digest)) {
72
73
74
      log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
               "trying to remove it.",
               conn->nickname ? conn->nickname : "NULL");
75
    }
76
    return;
77
  }
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  if (conn == tmp) {
    if (conn->next_with_same_id)
      digestmap_set(orconn_identity_map, conn->identity_digest,
                    conn->next_with_same_id);
    else
      digestmap_remove(orconn_identity_map, conn->identity_digest);
  } else {
    while (tmp->next_with_same_id) {
      if (tmp->next_with_same_id == conn) {
        tmp->next_with_same_id = conn->next_with_same_id;
        break;
      }
      tmp = tmp->next_with_same_id;
    }
  }
  memset(conn->identity_digest, 0, DIGEST_LEN);
  conn->next_with_same_id = NULL;
}

97
98
99
100
101
/** Remove all entries from the identity-to-orconn map, and clear
 * all identities in OR conns.*/
void
connection_or_clear_identity_map(void)
{
102
103
104
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
105
    if (conn->type == CONN_TYPE_OR) {
106
107
108
      or_connection_t *or_conn = TO_OR_CONN(conn);
      memset(or_conn->identity_digest, 0, DIGEST_LEN);
      or_conn->next_with_same_id = NULL;
109
    }
110
  });
111

112
113
  digestmap_free(orconn_identity_map, NULL);
  orconn_identity_map = NULL;
114
115
}

116
/** Change conn->identity_digest to digest, and add conn into
117
 * orconn_digest_map. */
118
static void
119
connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
120
{
121
  or_connection_t *tmp;
122
123
124
125
126
  tor_assert(conn);
  tor_assert(digest);

  if (!orconn_identity_map)
    orconn_identity_map = digestmap_new();
127
  if (tor_memeq(conn->identity_digest, digest, DIGEST_LEN))
128
    return;
129
130
131

  /* If the identity was set previously, remove the old mapping. */
  if (! tor_digest_is_zero(conn->identity_digest))
132
133
134
    connection_or_remove_from_identity_map(conn);

  memcpy(conn->identity_digest, digest, DIGEST_LEN);
135

136
  /* If we're setting the ID to zero, don't add a mapping. */
137
138
139
  if (tor_digest_is_zero(digest))
    return;

140
141
142
  tmp = digestmap_set(orconn_identity_map, digest, conn);
  conn->next_with_same_id = tmp;

143
#if 1
144
  /* Testing code to check for bugs in representation. */
145
  for (; tmp; tmp = tmp->next_with_same_id) {
146
    tor_assert(tor_memeq(tmp->identity_digest, digest, DIGEST_LEN));
147
148
    tor_assert(tmp != conn);
  }
149
#endif
150
151
}

Roger Dingledine's avatar
Roger Dingledine committed
152
153
/** Pack the cell_t host-order structure <b>src</b> into network-order
 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
154
 * wire format.
Roger Dingledine's avatar
Roger Dingledine committed
155
156
157
 *
 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
 * should set it or clear it as appropriate.
158
 */
159
160
void
cell_pack(packed_cell_t *dst, const cell_t *src)
161
{
162
  char *dest = dst->body;
163
  set_uint16(dest, htons(src->circ_id));
164
  *(uint8_t*)(dest+2) = src->command;
Roger Dingledine's avatar
Roger Dingledine committed
165
  memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
Roger Dingledine's avatar
Roger Dingledine committed
166
167
}

Roger Dingledine's avatar
Roger Dingledine committed
168
169
/** Unpack the network-order buffer <b>src</b> into a host-order
 * cell_t structure <b>dest</b>.
170
 */
171
172
173
static void
cell_unpack(cell_t *dest, const char *src)
{
174
  dest->circ_id = ntohs(get_uint16(src));
Roger Dingledine's avatar
Roger Dingledine committed
175
  dest->command = *(uint8_t*)(src+2);
Roger Dingledine's avatar
Roger Dingledine committed
176
  memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
Roger Dingledine's avatar
Roger Dingledine committed
177
178
}

179
180
/** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
 * bytes of <b>hdr_out</b>. */
181
void
182
var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
183
{
184
185
  set_uint16(hdr_out, htons(cell->circ_id));
  set_uint8(hdr_out+2, cell->command);
186
187
188
  set_uint16(hdr_out+3, htons(cell->payload_len));
}

189
190
/** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
 * payload space. */
191
192
193
var_cell_t *
var_cell_new(uint16_t payload_len)
{
194
195
  size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
  var_cell_t *cell = tor_malloc(size);
196
197
198
199
200
201
  cell->payload_len = payload_len;
  cell->command = 0;
  cell->circ_id = 0;
  return cell;
}

Roger Dingledine's avatar
Roger Dingledine committed
202
/** Release all space held by <b>cell</b>. */
203
204
205
206
207
208
void
var_cell_free(var_cell_t *cell)
{
  tor_free(cell);
}

Roger Dingledine's avatar
Roger Dingledine committed
209
/** We've received an EOF from <b>conn</b>. Mark it for close and return. */
210
int
211
connection_or_reached_eof(or_connection_t *conn)
212
{
Roger Dingledine's avatar
Roger Dingledine committed
213
  log_info(LD_OR,"OR connection reached EOF. Closing.");
214
  connection_mark_for_close(TO_CONN(conn));
215
216
217
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
218
/** Handle any new bytes that have come in on connection <b>conn</b>.
219
220
221
222
 * If conn is in 'open' state, hand it to
 * connection_or_process_cells_from_inbuf()
 * (else do nothing).
 */
223
int
224
connection_or_process_inbuf(or_connection_t *conn)
225
{
226
  int ret;
227
  tor_assert(conn);
Roger Dingledine's avatar
Roger Dingledine committed
228

229
  switch (conn->_base.state) {
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    case OR_CONN_STATE_PROXY_HANDSHAKING:
      ret = connection_read_proxy_handshake(TO_CONN(conn));

      /* start TLS after handshake completion, or deal with error */
      if (ret == 1) {
        tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
        if (connection_tls_start_handshake(conn, 0) < 0)
          ret = -1;
      }
      if (ret < 0) {
        connection_mark_for_close(TO_CONN(conn));
      }

      return ret;
244
#ifdef USE_BUFFEREVENTS
245
246
247
248
249
250
    case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
      if (tor_tls_server_got_renegotiate(conn->tls))
        connection_or_tls_renegotiated_cb(conn->tls, conn);
      if (conn->_base.marked_for_close)
        return 0;
      /* fall through. */
251
#endif
252
    case OR_CONN_STATE_OPEN:
253
    case OR_CONN_STATE_OR_HANDSHAKING:
254
255
256
257
      return connection_or_process_cells_from_inbuf(conn);
    default:
      return 0; /* don't do anything */
  }
Roger Dingledine's avatar
Roger Dingledine committed
258
259
}

260
261
/** When adding cells to an OR connection's outbuf, keep adding until the
 * outbuf is at least this long, or we run out of cells. */
262
263
#define OR_CONN_HIGHWATER (32*1024)

264
265
/** Add cells to an OR connection's outbuf whenever the outbuf's data length
 * drops below this size. */
266
267
#define OR_CONN_LOWWATER (16*1024)

268
269
/** Called whenever we have flushed some data on an or_conn: add more data
 * from active circuits. */
270
271
272
int
connection_or_flushed_some(or_connection_t *conn)
{
273
  size_t datalen = connection_get_outbuf_len(TO_CONN(conn));
274
275
  /* If we're under the low water mark, add cells until we're just over the
   * high water mark. */
276
  if (datalen < OR_CONN_LOWWATER) {
277
    ssize_t n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, CELL_NETWORK_SIZE);
278
    time_t now = approx_time();
279
    while (conn->active_circuits && n > 0) {
280
281
      int flushed;
      flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
282
283
284
      n -= flushed;
    }
  }
285
286
287
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
288
/** Connection <b>conn</b> has finished writing and has no bytes left on
289
290
 * its outbuf.
 *
Nick Mathewson's avatar
Nick Mathewson committed
291
 * Otherwise it's in state "open": stop writing and return.
292
293
294
 *
 * If <b>conn</b> is broken, mark it for close and return -1, else
 * return 0.
295
 */
296
int
297
connection_or_finished_flushing(or_connection_t *conn)
298
{
299
  tor_assert(conn);
300
  assert_connection_ok(TO_CONN(conn),0);
Roger Dingledine's avatar
Roger Dingledine committed
301

302
  switch (conn->_base.state) {
303
    case OR_CONN_STATE_PROXY_HANDSHAKING:
304
    case OR_CONN_STATE_OPEN:
305
    case OR_CONN_STATE_OR_HANDSHAKING:
306
307
      break;
    default:
308
      log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
309
      tor_fragile_assert();
310
      return -1;
311
312
313
314
315
316
  }
  return 0;
}

/** Connected handler for OR connections: begin the TLS handshake.
 */
317
int
318
connection_or_finished_connecting(or_connection_t *or_conn)
319
{
320
  int proxy_type;
321
322
323
  connection_t *conn;
  tor_assert(or_conn);
  conn = TO_CONN(or_conn);
324
325
  tor_assert(conn->state == OR_CONN_STATE_CONNECTING);

326
  log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
Roger Dingledine's avatar
Roger Dingledine committed
327
            conn->address,conn->port);
328
  control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
329

330
  proxy_type = PROXY_NONE;
331

332
  if (get_options()->HTTPSProxy)
333
334
335
336
337
338
339
340
341
342
343
    proxy_type = PROXY_CONNECT;
  else if (get_options()->Socks4Proxy)
    proxy_type = PROXY_SOCKS4;
  else if (get_options()->Socks5Proxy)
    proxy_type = PROXY_SOCKS5;

  if (proxy_type != PROXY_NONE) {
    /* start proxy handshake */
    if (connection_proxy_connect(conn, proxy_type) < 0) {
      connection_mark_for_close(conn);
      return -1;
344
    }
345
346
347

    connection_start_reading(conn);
    conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
348
349
350
    return 0;
  }

351
  if (connection_tls_start_handshake(or_conn, 0) < 0) {
352
353
    /* TLS handshaking error of some kind. */
    connection_mark_for_close(conn);
354
    return -1;
Roger Dingledine's avatar
Roger Dingledine committed
355
  }
356
  return 0;
Roger Dingledine's avatar
Roger Dingledine committed
357
358
}

359
360
/** Return 1 if identity digest <b>id_digest</b> is known to be a
 * currently or recently running relay. Otherwise return 0. */
361
int
362
363
364
365
connection_or_digest_is_known_relay(const char *id_digest)
{
  if (router_get_consensus_status_by_id(id_digest))
    return 1; /* It's in the consensus: "yes" */
Sebastian Hahn's avatar
Sebastian Hahn committed
366
  if (router_get_by_id_digest(id_digest))
367
368
369
370
371
    return 1; /* Not in the consensus, but we have a descriptor for
               * it. Probably it was in a recent consensus. "Yes". */
  return 0;
}

372
373
374
375
376
/** Set the per-conn read and write limits for <b>conn</b>. If it's a known
 * relay, we will rely on the global read and write buckets, so give it
 * per-conn limits that are big enough they'll never matter. But if it's
 * not a known relay, first check if we set PerConnBwRate/Burst, then
 * check if the consensus sets them, else default to 'big enough'.
377
378
379
 *
 * If <b>reset</b> is true, set the bucket to be full.  Otherwise, just
 * clip the bucket if it happens to be <em>too</em> full.
380
 */
381
382
static void
connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
383
                                          const or_options_t *options)
384
{
385
  int rate, burst; /* per-connection rate limiting params */
386
  if (connection_or_digest_is_known_relay(conn->identity_digest)) {
387
388
389
    /* It's in the consensus, or we have a descriptor for it meaning it
     * was probably in a recent consensus. It's a recognized relay:
     * give it full bandwidth. */
390
391
392
393
394
395
396
    rate = (int)options->BandwidthRate;
    burst = (int)options->BandwidthBurst;
  } else {
    /* Not a recognized relay. Squeeze it down based on the suggested
     * bandwidth parameters in the consensus, but allow local config
     * options to override. */
    rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
397
398
        networkstatus_get_param(NULL, "perconnbwrate",
                                (int)options->BandwidthRate, 1, INT32_MAX);
399
    burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
400
401
        networkstatus_get_param(NULL, "perconnbwburst",
                                (int)options->BandwidthBurst, 1, INT32_MAX);
402
403
  }

404
  conn->bandwidthrate = rate;
405
  conn->bandwidthburst = burst;
406
407
408
409
410
411
412
413
414
415
416
417
418
#ifdef USE_BUFFEREVENTS
  {
    const struct timeval *tick = tor_libevent_get_one_tick_timeout();
    struct ev_token_bucket_cfg *cfg, *old_cfg;
    int rate_per_tick = rate / TOR_LIBEVENT_TICKS_PER_SECOND;
    cfg = ev_token_bucket_cfg_new(rate_per_tick, burst, rate_per_tick,
                                  burst, tick);
    old_cfg = conn->bucket_cfg;
    if (conn->_base.bufev)
      bufferevent_set_rate_limit(conn->_base.bufev, cfg);
    if (old_cfg)
      ev_token_bucket_cfg_free(old_cfg);
    conn->bucket_cfg = cfg;
419
    (void) reset; /* No way to do this with libevent yet. */
420
421
  }
#else
422
423
424
425
426
427
428
429
430
431
  if (reset) { /* set up the token buckets to be full */
    conn->read_bucket = conn->write_bucket = burst;
    return;
  }
  /* If the new token bucket is smaller, take out the extra tokens.
   * (If it's larger, don't -- the buckets can grow to reach the cap.) */
  if (conn->read_bucket > burst)
    conn->read_bucket = burst;
  if (conn->write_bucket > burst)
    conn->write_bucket = burst;
432
#endif
433
434
435
}

/** Either our set of relays or our per-conn rate limits have changed.
436
437
 * Go through all the OR connections and update their token buckets to make
 * sure they don't exceed their maximum values. */
438
void
439
440
connection_or_update_token_buckets(smartlist_t *conns,
                                   const or_options_t *options)
441
442
443
444
445
446
{
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
    if (connection_speaks_cells(conn))
      connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
  });
447
448
449
450
451
452
453
454
455
456
457
}

/** If we don't necessarily know the router we're connecting to, but we
 * have an addr/port/id_digest, then fill in as much as we can. Start
 * by checking to see if this describes a router we know. */
static void
connection_or_init_conn_from_address(or_connection_t *conn,
                                     const tor_addr_t *addr, uint16_t port,
                                     const char *id_digest,
                                     int started_here)
{
458
  const node_t *r = node_get_by_id(id_digest);
459
  connection_or_set_identity_digest(conn, id_digest);
460
  connection_or_update_token_buckets_helper(conn, 1, get_options());
461

462
  conn->_base.port = port;
463
464
  tor_addr_copy(&conn->_base.addr, addr);
  tor_addr_copy(&conn->real_addr, addr);
465
  if (r) {
466
467
    tor_addr_t node_addr;
    node_get_addr(r, &node_addr);
468
    /* XXXX proposal 118 will make this more complex. */
469
    if (tor_addr_eq(&conn->_base.addr, &node_addr))
470
      conn->is_canonical = 1;
471
472
473
474
    if (!started_here) {
      /* Override the addr/port, so our log messages will make sense.
       * This is dangerous, since if we ever try looking up a conn by
       * its actual addr/port, we won't remember. Careful! */
475
      /* XXXX arma: this is stupid, and it's the reason we need real_addr
476
       * to track is_canonical properly.  What requires it? */
477
478
479
480
      /* XXXX <arma> i believe the reason we did this, originally, is because
       * we wanted to log what OR a connection was to, and if we logged the
       * right IP address and port 56244, that wouldn't be as helpful. now we
       * log the "right" port too, so we know if it's moria1 or moria2.
481
       */
482
483
      tor_addr_copy(&conn->_base.addr, &node_addr);
      conn->_base.port = node_get_orport(r);
484
    }
485
    conn->nickname = tor_strdup(node_get_nickname(r));
486
    tor_free(conn->_base.address);
487
    conn->_base.address = tor_dup_addr(&node_addr);
488
  } else {
489
490
491
492
493
494
495
496
497
498
499
500
    const char *n;
    /* If we're an authoritative directory server, we may know a
     * nickname for this router. */
    n = dirserv_get_nickname_by_digest(id_digest);
    if (n) {
      conn->nickname = tor_strdup(n);
    } else {
      conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
      conn->nickname[0] = '$';
      base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
                    conn->identity_digest, DIGEST_LEN);
    }
501
    tor_free(conn->_base.address);
502
    conn->_base.address = tor_dup_addr(addr);
503
  }
504
505
}

506
/** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
507
 *
508
509
510
511
512
513
 * A more canonical connection is always better than a less canonical
 * connection.  That aside, a connection is better if it has circuits and the
 * other does not, or if it was created more recently.
 *
 * Requires that both input connections are open; not is_bad_for_new_circs,
 * and not impossibly non-canonical.
514
 *
515
 * If <b>forgive_new_connections</b> is true, then we do not call
516
517
 * <b>a</b>better than <b>b</b> simply because b has no circuits,
 * unless b is also relatively old.
518
 */
519
static int
520
521
522
523
connection_or_is_better(time_t now,
                        const or_connection_t *a,
                        const or_connection_t *b,
                        int forgive_new_connections)
524
525
{
  int newer;
526
527
528
/** Do not definitively deprecate a new connection with no circuits on it
 * until this much time has passed. */
#define NEW_CONN_GRACE_PERIOD (15*60)
529
530
531
532
533
534
535

  if (b->is_canonical && !a->is_canonical)
    return 0; /* A canonical connection is better than a non-canonical
               * one, no matter how new it is or which has circuits. */

  newer = b->_base.timestamp_created < a->_base.timestamp_created;

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
  if (
      /* We prefer canonical connections regardless of newness. */
      (!b->is_canonical && a->is_canonical) ||
      /* If both have circuits we prefer the newer: */
      (b->n_circuits && a->n_circuits && newer) ||
      /* If neither has circuits we prefer the newer: */
      (!b->n_circuits && !a->n_circuits && newer))
    return 1;

  /* If one has no circuits and the other does... */
  if (!b->n_circuits && a->n_circuits) {
    /* Then it's bad, unless it's in its grace period and we're forgiving. */
    if (forgive_new_connections &&
        now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
      return 0;
    else
      return 1;
  }

  return 0;
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
}

/** Return the OR connection we should use to extend a circuit to the router
 * whose identity is <b>digest</b>, and whose address we believe (or have been
 * told in an extend cell) is <b>target_addr</b>.  If there is no good
 * connection, set *<b>msg_out</b> to a message describing the connection's
 * state and our next action, and set <b>launch_out</b> to a boolean for
 * whether we should launch a new connection or not.
 */
or_connection_t *
connection_or_get_for_extend(const char *digest,
                             const tor_addr_t *target_addr,
                             const char **msg_out,
                             int *launch_out)
{
571
  or_connection_t *conn, *best=NULL;
572
  int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
573
  time_t now = approx_time();
574

575
576
577
578
579
580
  tor_assert(msg_out);
  tor_assert(launch_out);

  if (!orconn_identity_map) {
    *msg_out = "Router not connected (nothing is).  Connecting.";
    *launch_out = 1;
581
    return NULL;
582
  }
583
584
585
586

  conn = digestmap_get(orconn_identity_map, digest);

  for (; conn; conn = conn->next_with_same_id) {
587
588
    tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
    tor_assert(conn->_base.type == CONN_TYPE_OR);
589
    tor_assert(tor_memeq(conn->identity_digest, digest, DIGEST_LEN));
590
    if (conn->_base.marked_for_close)
591
      continue;
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    /* Never return a non-open connection. */
    if (conn->_base.state != OR_CONN_STATE_OPEN) {
      /* If the address matches, don't launch a new connection for this
       * circuit. */
      if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
        ++n_inprogress_goodaddr;
      continue;
    }
    /* Never return a connection that shouldn't be used for circs. */
    if (conn->is_bad_for_new_circs) {
      ++n_old;
      continue;
    }
    /* Never return a non-canonical connection using a recent link protocol
     * if the address is not what we wanted.
     *
     * (For old link protocols, we can't rely on is_canonical getting
     * set properly if we're talking to the right address, since we might
     * have an out-of-date descriptor, and we will get no NETINFO cell to
     * tell us about the right address.) */
    if (!conn->is_canonical && conn->link_proto >= 2 &&
        tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
      ++n_noncanonical;
      continue;
    }

    ++n_possible;

620
    if (!best) {
621
      best = conn; /* If we have no 'best' so far, this one is good enough. */
622
623
      continue;
    }
624

625
    if (connection_or_is_better(now, conn, best, 0))
626
      best = conn;
627
  }
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653

  if (best) {
    *msg_out = "Connection is fine; using it.";
    *launch_out = 0;
    return best;
  } else if (n_inprogress_goodaddr) {
    *msg_out = "Connection in progress; waiting.";
    *launch_out = 0;
    return NULL;
  } else if (n_old || n_noncanonical) {
    *msg_out = "Connections all too old, or too non-canonical. "
      " Launching a new one.";
    *launch_out = 1;
    return NULL;
  } else {
    *msg_out = "Not connected. Connecting.";
    *launch_out = 1;
    return NULL;
  }
}

/** How old do we let a connection to an OR get before deciding it's
 * too old for new circuits? */
#define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)

/** Given the head of the linked list for all the or_connections with a given
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
 * identity, set elements of that list as is_bad_for_new_circs as
 * appropriate. Helper for connection_or_set_bad_connections().
 *
 * Specifically, we set the is_bad_for_new_circs flag on:
 *    - all connections if <b>force</b> is true.
 *    - all connections that are too old.
 *    - all open non-canonical connections for which a canonical connection
 *      exists to the same router.
 *    - all open canonical connections for which a 'better' canonical
 *      connection exists to the same router.
 *    - all open non-canonical connections for which a 'better' non-canonical
 *      connection exists to the same router at the same address.
 *
 * See connection_or_is_better() for our idea of what makes one OR connection
 * better than another.
669
670
 */
static void
671
connection_or_group_set_badness(or_connection_t *head, int force)
672
673
674
675
676
677
678
679
680
681
682
{
  or_connection_t *or_conn = NULL, *best = NULL;
  int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
  time_t now = time(NULL);

  /* Pass 1: expire everything that's old, and see what the status of
   * everything else is. */
  for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
    if (or_conn->_base.marked_for_close ||
        or_conn->is_bad_for_new_circs)
      continue;
683
684
685
    if (force ||
        or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
          < now) {
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
      log_info(LD_OR,
               "Marking OR conn to %s:%d as too old for new circuits "
               "(fd %d, %d secs old).",
               or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
               (int)(now - or_conn->_base.timestamp_created));
      or_conn->is_bad_for_new_circs = 1;
    }

    if (or_conn->is_bad_for_new_circs) {
      ++n_old;
    } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
      ++n_inprogress;
    } else if (or_conn->is_canonical) {
      ++n_canonical;
    } else {
      ++n_other;
    }
  }

  /* Pass 2: We know how about how good the best connection is.
   * expire everything that's worse, and find the very best if we can. */
  for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
    if (or_conn->_base.marked_for_close ||
        or_conn->is_bad_for_new_circs)
      continue; /* This one doesn't need to be marked bad. */
    if (or_conn->_base.state != OR_CONN_STATE_OPEN)
      continue; /* Don't mark anything bad until we have seen what happens
                 * when the connection finishes. */
    if (n_canonical && !or_conn->is_canonical) {
      /* We have at least one open canonical connection to this router,
       * and this one is open but not canonical.  Mark it bad. */
      log_info(LD_OR,
718
               "Marking OR conn to %s:%d as unsuitable for new circuits: "
719
720
721
722
723
724
725
726
               "(fd %d, %d secs old).  It is not canonical, and we have "
               "another connection to that OR that is.",
               or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
               (int)(now - or_conn->_base.timestamp_created));
      or_conn->is_bad_for_new_circs = 1;
      continue;
    }

727
    if (!best || connection_or_is_better(now, or_conn, best, 0))
728
729
730
731
732
733
734
735
736
737
      best = or_conn;
  }

  if (!best)
    return;

  /* Pass 3: One connection to OR is best.  If it's canonical, mark as bad
   * every other open connection.  If it's non-canonical, mark as bad
   * every other open connection to the same address.
   *
738
739
740
741
742
743
744
745
746
   * XXXX This isn't optimal; if we have connections to an OR at multiple
   *   addresses, we'd like to pick the best _for each address_, and mark as
   *   bad every open connection that isn't best for its address.  But this
   *   can only occur in cases where the other OR is old (so we have no
   *   canonical connection to it), or where all the connections to the OR are
   *   at noncanonical addresses and we have no good direct connection (which
   *   means we aren't at risk of attaching circuits to it anyway).  As
   *   0.1.2.x dies out, the first case will go away, and the second one is
   *   "mostly harmless", so a fix can wait until somebody is bored.
747
748
749
750
751
752
   */
  for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
    if (or_conn->_base.marked_for_close ||
        or_conn->is_bad_for_new_circs ||
        or_conn->_base.state != OR_CONN_STATE_OPEN)
      continue;
753
754
755
    if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
      /* This isn't the best conn, _and_ the best conn is better than it,
         even when we're being forgiving. */
756
757
      if (best->is_canonical) {
        log_info(LD_OR,
758
                 "Marking OR conn to %s:%d as unsuitable for new circuits: "
759
760
761
762
763
764
765
766
767
                 "(fd %d, %d secs old).  We have a better canonical one "
                 "(fd %d; %d secs old).",
                 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
                 (int)(now - or_conn->_base.timestamp_created),
                 best->_base.s, (int)(now - best->_base.timestamp_created));
        or_conn->is_bad_for_new_circs = 1;
      } else if (!tor_addr_compare(&or_conn->real_addr,
                                   &best->real_addr, CMP_EXACT)) {
        log_info(LD_OR,
768
769
770
                 "Marking OR conn to %s:%d as unsuitable for new circuits: "
                 "(fd %d, %d secs old).  We have a better one with the "
                 "same address (fd %d; %d secs old).",
771
772
773
774
775
776
777
778
779
                 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
                 (int)(now - or_conn->_base.timestamp_created),
                 best->_base.s, (int)(now - best->_base.timestamp_created));
        or_conn->is_bad_for_new_circs = 1;
      }
    }
  }
}

780
781
/** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
 * the OR connections with that digest), and set the is_bad_for_new_circs
782
783
 * flag based on the rules in connection_or_group_set_badness() (or just
 * always set it if <b>force</b> is true).
784
785
 */
void
786
connection_or_set_bad_connections(const char *digest, int force)
787
788
789
790
791
{
  if (!orconn_identity_map)
    return;

  DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
792
    if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
793
      connection_or_group_set_badness(conn, force);
794
  } DIGESTMAP_FOREACH_END;
795
796
}

797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
/** <b>conn</b> is in the 'connecting' state, and it failed to complete
 * a TCP connection. Send notifications appropriately.
 *
 * <b>reason</b> specifies the or_conn_end_reason for the failure;
 * <b>msg</b> specifies the strerror-style error message.
 */
void
connection_or_connect_failed(or_connection_t *conn,
                             int reason, const char *msg)
{
  control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
  if (!authdir_mode_tests_reachability(get_options()))
    control_event_bootstrap_problem(msg, reason);
}

812
813
/** 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>.
814
 *
815
 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
816
817
 * return that connection. If the connect() is in progress, set the
 * new conn's state to 'connecting' and return it. If connect() succeeds,
818
 * call connection_tls_start_handshake() on it.
819
 *
820
 * This function is called from router_retry_connections(), for
821
822
823
824
825
 * ORs connecting to ORs, and circuit_establish_circuit(), for
 * OPs connecting to ORs.
 *
 * Return the launched conn, or NULL if it failed.
 */
826
or_connection_t *
827
828
connection_or_connect(const tor_addr_t *_addr, uint16_t port,
                      const char *id_digest)
829
{
830
  or_connection_t *conn;
831
  const or_options_t *options = get_options();
832
  int socket_error = 0;
833
  int using_proxy = 0;
834
  tor_addr_t addr;
Roger Dingledine's avatar
Roger Dingledine committed
835

836
  tor_assert(_addr);
837
  tor_assert(id_digest);
838
  tor_addr_copy(&addr, _addr);
839

840
  if (server_mode(options) && router_digest_is_me(id_digest)) {
Roger Dingledine's avatar
Roger Dingledine committed
841
    log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
842
843
844
    return NULL;
  }

845
  conn = or_connection_new(AF_INET);
Roger Dingledine's avatar
Roger Dingledine committed
846
847

  /* set up conn so it's got all the data we need to remember */
848
  connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
849
  conn->_base.state = OR_CONN_STATE_CONNECTING;
850
  control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
Roger Dingledine's avatar
Roger Dingledine committed
851

852
  /* use a proxy server if available */
853
  if (options->HTTPSProxy) {
854
    using_proxy = 1;
855
856
    tor_addr_copy(&addr, &options->HTTPSProxyAddr);
    port = options->HTTPSProxyPort;
857
858
  } else if (options->Socks4Proxy) {
    using_proxy = 1;
859
    tor_addr_copy(&addr, &options->Socks4ProxyAddr);
860
861
862
    port = options->Socks4ProxyPort;
  } else if (options->Socks5Proxy) {
    using_proxy = 1;
863
    tor_addr_copy(&addr, &options->Socks5ProxyAddr);
864
    port = options->Socks5ProxyPort;
865
866
  }

867
  switch (connection_connect(TO_CONN(conn), conn->_base.address,
868
                             &addr, port, &socket_error)) {
869
    case -1:
Roger Dingledine's avatar
Roger Dingledine committed
870
      /* If the connection failed immediately, and we're using
871
872
       * a proxy, our proxy is down. Don't blame the Tor server. */
      if (!using_proxy)
873
874
        entry_guard_register_connect_status(conn->identity_digest,
                                            0, 1, time(NULL));
875
876
877
      connection_or_connect_failed(conn,
                                   errno_to_orconn_end_reason(socket_error),
                                   tor_socket_strerror(socket_error));
878
      connection_free(TO_CONN(conn));
879
      return NULL;
880
    case 0:
881
      connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
882
883
      /* writable indicates finish, readable indicates broken link,
         error indicates broken link on windows */
884
      return conn;
885
    /* case 1: fall through */
886
887
  }

888
889
890
891
892
  if (connection_or_finished_connecting(conn) < 0) {
    /* already marked for close */
    return NULL;
  }
  return conn;
893
894
}

Roger Dingledine's avatar
Roger Dingledine committed
895
896
/** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
 * we initiated the connection, else it's 1.
897
 *
Roger Dingledine's avatar
Roger Dingledine committed
898
899
 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
 * pass <b>conn</b> to connection_tls_continue_handshake().
900
 *
Roger Dingledine's avatar
Roger Dingledine committed
901
 * Return -1 if <b>conn</b> is broken, else return 0.
902
 */
903
int
904
connection_tls_start_handshake(or_connection_t *conn, int receiving)
905
{
906
  conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
907
  tor_assert(!conn->tls);
908
  conn->tls = tor_tls_new(conn->_base.s, receiving);
909
  tor_tls_set_logged_address(conn->tls, // XXX client and relay?
910
      escaped_safe_str(conn->_base.address));
911
  if (!conn->tls) {
Roger Dingledine's avatar
Roger Dingledine committed
912
    log_warn(LD_BUG,"tor_tls_new failed. Closing.");
913
914
    return -1;
  }
915
916
#ifdef USE_BUFFEREVENTS
  if (connection_type_uses_bufferevent(TO_CONN(conn))) {
917
    const int filtering = get_options()->_UseFilteringSSLBufferevents;
918
919
    struct bufferevent *b =
      tor_tls_init_bufferevent(conn->tls, conn->_base.bufev, conn->_base.s,
920
                               receiving, filtering);
921
922
923
924
925
    if (!b) {
      log_warn(LD_BUG,"tor_tls_init_bufferevent failed. Closing.");
      return -1;
    }
    conn->_base.bufev = b;
926
927
928
    if (conn->bucket_cfg)
      bufferevent_set_rate_limit(conn->_base.bufev, conn->bucket_cfg);
    connection_enable_rate_limiting(TO_CONN(conn));
929
930
931
932

    connection_configure_bufferevent_callbacks(TO_CONN(conn));
    bufferevent_setcb(b,
                      connection_handle_read_cb,
933
                      connection_handle_write_cb,
934
                      connection_or_handle_event_cb,/* overriding this one*/
935
936
937
                      TO_CONN(conn));
  }
#endif
938
  connection_start_reading(TO_CONN(conn));
939
  log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
940
941
  note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);

942
943
944
945
946
  IF_HAS_BUFFEREVENT(TO_CONN(conn), {
    /* ???? */;
  }) ELSE_IF_NO_BUFFEREVENT {
    if (connection_tls_continue_handshake(conn) < 0)
      return -1;
947
  }
948
949
950
  return 0;
}

951
952
/** Invoked on the server side from inside tor_tls_read() when the server
 * gets a successful TLS renegotiation from the client. */
953
954
955
956
static void
connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
{
  or_connection_t *conn = _conn;
957
  (void)tls;
958

959
960
  /* Don't invoke this again. */
  tor_tls_set_renegotiate_callback(tls, NULL, NULL);
961
  tor_tls_block_renegotiation(tls);
962

963
  if (connection_tls_finish_handshake(conn) < 0) {
964
    /* XXXX_TLS double-check that it's ok to do this from inside read. */
965
    /* XXXX_TLS double-check that this verifies certificates. */
966
967
    connection_mark_for_close(TO_CONN(conn));
  }
968
969
}

Roger Dingledine's avatar
Roger Dingledine committed
970
971
/** Move forward with the tls handshake. If it finishes, hand
 * <b>conn</b> to connection_tls_finish_handshake().
972
 *
Roger Dingledine's avatar
Roger Dingledine committed
973
 * Return -1 if <b>conn</b> is broken, else return 0.
974
 */
975
int
976
connection_tls_continue_handshake(or_connection_t *conn)
977
{
978
  int result;
979
  check_no_tls_errors();
980
 again:
981
982
  if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
    // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
983
    result = tor_tls_renegotiate(conn->tls);
984
985
    // log_notice(LD_OR, "Result: %d", result);
  } else {
986
    tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
987
    // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
988
    result = tor_tls_handshake(conn->tls);
989
    // log_notice(LD_OR, "Result: %d", result);
990
  }
991
  switch (result) {
992
    CASE_TOR_TLS_ERROR_ANY:
993
994
    log_info(LD_OR,"tls error [%s]. breaking connection.",
             tor_tls_err_to_string(result));
995
996
      return -1;
    case TOR_TLS_DONE:
997
      if (! tor_tls_used_v1_handshake(conn->tls)) {
998
999
        if (!tor_tls_is_server(conn->tls)) {
          if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
1000
            // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");