connection_or.c 44.9 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.
Karsten Loesing's avatar
Karsten Loesing committed
4
 * Copyright (c) 2007-2009, 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"
14

15
16
static int connection_tls_finish_handshake(or_connection_t *conn);
static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
17
static int connection_or_send_versions(or_connection_t *conn);
18
19
static int connection_init_or_handshake_state(or_connection_t *conn,
                                              int started_here);
20
21
22
static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
                                                   int started_here,
                                                   char *digest_rcvd_out);
23

Roger Dingledine's avatar
Roger Dingledine committed
24
25
/**************************************************************/

26
27
/** 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
28
 * they form a linked list, with next_with_same_id as the next pointer. */
29
30
31
static digestmap_t *orconn_identity_map = NULL;

/** If conn is listed in orconn_identity_map, remove it, and clear
32
 * conn->identity_digest.  Otherwise do nothing. */
33
void
34
connection_or_remove_from_identity_map(or_connection_t *conn)
35
{
36
  or_connection_t *tmp;
37
38
39
40
  tor_assert(conn);
  if (!orconn_identity_map)
    return;
  tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
41
42
  if (!tmp) {
    if (!tor_digest_is_zero(conn->identity_digest)) {
43
44
45
      log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
               "trying to remove it.",
               conn->nickname ? conn->nickname : "NULL");
46
    }
47
    return;
48
  }
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  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;
}

68
69
70
71
72
/** Remove all entries from the identity-to-orconn map, and clear
 * all identities in OR conns.*/
void
connection_or_clear_identity_map(void)
{
73
74
75
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
76
    if (conn->type == CONN_TYPE_OR) {
77
78
79
      or_connection_t *or_conn = TO_OR_CONN(conn);
      memset(or_conn->identity_digest, 0, DIGEST_LEN);
      or_conn->next_with_same_id = NULL;
80
    }
81
  });
82

83
84
85
86
  if (orconn_identity_map) {
    digestmap_free(orconn_identity_map, NULL);
    orconn_identity_map = NULL;
  }
87
88
}

89
/** Change conn->identity_digest to digest, and add conn into
90
 * orconn_digest_map. */
91
static void
92
connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
93
{
94
  or_connection_t *tmp;
95
96
97
98
99
100
101
  tor_assert(conn);
  tor_assert(digest);

  if (!orconn_identity_map)
    orconn_identity_map = digestmap_new();
  if (!memcmp(conn->identity_digest, digest, DIGEST_LEN))
    return;
102
103
104

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

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

109
  /* If we're setting the ID to zero, don't add a mapping. */
110
111
112
  if (tor_digest_is_zero(digest))
    return;

113
114
115
  tmp = digestmap_set(orconn_identity_map, digest, conn);
  conn->next_with_same_id = tmp;

116
#if 1
117
  /* Testing code to check for bugs in representation. */
118
119
120
121
  for (; tmp; tmp = tmp->next_with_same_id) {
    tor_assert(!memcmp(tmp->identity_digest, digest, DIGEST_LEN));
    tor_assert(tmp != conn);
  }
122
#endif
123
124
}

Roger Dingledine's avatar
Roger Dingledine committed
125
126
/** 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
127
 * wire format.
Roger Dingledine's avatar
Roger Dingledine committed
128
129
130
 *
 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
 * should set it or clear it as appropriate.
131
 */
132
133
void
cell_pack(packed_cell_t *dst, const cell_t *src)
134
{
135
  char *dest = dst->body;
136
137
  *(uint16_t*)dest    = htons(src->circ_id);
  *(uint8_t*)(dest+2) = src->command;
Roger Dingledine's avatar
Roger Dingledine committed
138
  memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
Roger Dingledine's avatar
Roger Dingledine committed
139
140
}

Roger Dingledine's avatar
Roger Dingledine committed
141
142
/** Unpack the network-order buffer <b>src</b> into a host-order
 * cell_t structure <b>dest</b>.
143
 */
144
145
146
static void
cell_unpack(cell_t *dest, const char *src)
{
147
  dest->circ_id = ntohs(*(uint16_t*)(src));
Roger Dingledine's avatar
Roger Dingledine committed
148
  dest->command = *(uint8_t*)(src+2);
Roger Dingledine's avatar
Roger Dingledine committed
149
  memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
Roger Dingledine's avatar
Roger Dingledine committed
150
151
}

152
153
/** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
 * bytes of <b>hdr_out</b>. */
154
void
155
var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
156
{
157
158
  set_uint16(hdr_out, htons(cell->circ_id));
  set_uint8(hdr_out+2, cell->command);
159
160
161
  set_uint16(hdr_out+3, htons(cell->payload_len));
}

162
163
/** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
 * payload space. */
164
165
166
167
168
169
170
171
172
173
var_cell_t *
var_cell_new(uint16_t payload_len)
{
  var_cell_t *cell = tor_malloc(sizeof(var_cell_t)+payload_len-1);
  cell->payload_len = payload_len;
  cell->command = 0;
  cell->circ_id = 0;
  return cell;
}

Roger Dingledine's avatar
Roger Dingledine committed
174
/** Release all space held by <b>cell</b>. */
175
176
177
178
179
180
void
var_cell_free(var_cell_t *cell)
{
  tor_free(cell);
}

Roger Dingledine's avatar
Roger Dingledine committed
181
/** We've received an EOF from <b>conn</b>. Mark it for close and return. */
182
int
183
connection_or_reached_eof(or_connection_t *conn)
184
{
Roger Dingledine's avatar
Roger Dingledine committed
185
  log_info(LD_OR,"OR connection reached EOF. Closing.");
186
  connection_mark_for_close(TO_CONN(conn));
187
188
189
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
190
/** Handle any new bytes that have come in on connection <b>conn</b>.
191
192
193
194
 * If conn is in 'open' state, hand it to
 * connection_or_process_cells_from_inbuf()
 * (else do nothing).
 */
195
int
196
connection_or_process_inbuf(or_connection_t *conn)
197
{
198
  int ret;
199
  tor_assert(conn);
Roger Dingledine's avatar
Roger Dingledine committed
200

201
  switch (conn->_base.state) {
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    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;
216
    case OR_CONN_STATE_OPEN:
217
    case OR_CONN_STATE_OR_HANDSHAKING:
218
219
220
221
      return connection_or_process_cells_from_inbuf(conn);
    default:
      return 0; /* don't do anything */
  }
Roger Dingledine's avatar
Roger Dingledine committed
222
223
}

224
225
/** 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. */
226
227
#define OR_CONN_HIGHWATER (32*1024)

228
229
/** Add cells to an OR connection's outbuf whenever the outbuf's data length
 * drops below this size. */
230
231
#define OR_CONN_LOWWATER (16*1024)

232
233
/** Called whenever we have flushed some data on an or_conn: add more data
 * from active circuits. */
234
235
236
int
connection_or_flushed_some(or_connection_t *conn)
{
237
  size_t datalen = buf_datalen(conn->_base.outbuf);
238
239
  /* If we're under the low water mark, add cells until we're just over the
   * high water mark. */
240
  if (datalen < OR_CONN_LOWWATER) {
241
    ssize_t n = (OR_CONN_HIGHWATER - datalen + CELL_NETWORK_SIZE-1)
242
      / CELL_NETWORK_SIZE;
243
    time_t now = approx_time();
244
    while (conn->active_circuits && n > 0) {
245
246
      int flushed;
      flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
247
248
249
      n -= flushed;
    }
  }
250
251
252
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
253
/** Connection <b>conn</b> has finished writing and has no bytes left on
254
255
 * its outbuf.
 *
Nick Mathewson's avatar
Nick Mathewson committed
256
 * Otherwise it's in state "open": stop writing and return.
257
258
259
 *
 * If <b>conn</b> is broken, mark it for close and return -1, else
 * return 0.
260
 */
261
int
262
connection_or_finished_flushing(or_connection_t *conn)
263
{
264
  tor_assert(conn);
265
  assert_connection_ok(TO_CONN(conn),0);
Roger Dingledine's avatar
Roger Dingledine committed
266

267
  switch (conn->_base.state) {
268
    case OR_CONN_STATE_PROXY_HANDSHAKING:
269
    case OR_CONN_STATE_OPEN:
270
    case OR_CONN_STATE_OR_HANDSHAKING:
271
      connection_stop_writing(TO_CONN(conn));
272
273
      break;
    default:
274
      log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
275
      tor_fragile_assert();
276
      return -1;
277
278
279
280
281
282
  }
  return 0;
}

/** Connected handler for OR connections: begin the TLS handshake.
 */
283
int
284
connection_or_finished_connecting(or_connection_t *or_conn)
285
{
286
  int proxy_type;
287
288
289
  connection_t *conn;
  tor_assert(or_conn);
  conn = TO_CONN(or_conn);
290
291
  tor_assert(conn->state == OR_CONN_STATE_CONNECTING);

292
  log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
Roger Dingledine's avatar
Roger Dingledine committed
293
            conn->address,conn->port);
294
  control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
295

296
  proxy_type = PROXY_NONE;
297

298
299
300
301
302
303
304
305
306
307
308
309
  if (get_options()->HttpsProxy)
    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;
310
    }
311
312
313

    connection_start_reading(conn);
    conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
314
315
316
    return 0;
  }

317
  if (connection_tls_start_handshake(or_conn, 0) < 0) {
318
319
    /* TLS handshaking error of some kind. */
    connection_mark_for_close(conn);
320
    return -1;
Roger Dingledine's avatar
Roger Dingledine committed
321
  }
322
  return 0;
Roger Dingledine's avatar
Roger Dingledine committed
323
324
}

325
326
327
/** 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. */
328
static void
329
connection_or_init_conn_from_address(or_connection_t *conn,
330
                                     const tor_addr_t *addr, uint16_t port,
331
332
                                     const char *id_digest,
                                     int started_here)
333
{
334
335
  or_options_t *options = get_options();
  routerinfo_t *r = router_get_by_digest(id_digest);
336
  conn->bandwidthrate = (int)options->BandwidthRate;
337
  conn->read_bucket = conn->bandwidthburst = (int)options->BandwidthBurst;
338
  connection_or_set_identity_digest(conn, id_digest);
339

340
  conn->_base.port = port;
341
342
  tor_addr_copy(&conn->_base.addr, addr);
  tor_addr_copy(&conn->real_addr, addr);
343
  if (r) {
344
    /* XXXX proposal 118 will make this more complex. */
345
    if (tor_addr_eq_ipv4h(&conn->_base.addr, r->addr))
346
      conn->is_canonical = 1;
347
348
349
350
    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! */
351
      /* XXXX arma: this is stupid, and it's the reason we need real_addr
352
       * to track is_canonical properly.  What requires it? */
353
354
355
356
      /* 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.
357
358
       */
      tor_addr_from_ipv4h(&conn->_base.addr, r->addr);
359
      conn->_base.port = r->or_port;
360
361
    }
    conn->nickname = tor_strdup(r->nickname);
362
363
    tor_free(conn->_base.address);
    conn->_base.address = tor_strdup(r->address);
364
  } else {
365
366
367
368
369
370
371
372
373
374
375
376
    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);
    }
377
    tor_free(conn->_base.address);
378
    conn->_base.address = tor_dup_addr(addr);
379
  }
380
381
}

382
/** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
383
 *
384
385
386
387
388
389
 * 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.
390
391
392
393
 *
 * If </b>forgive_new_connections</b> is true, then we do not call
 * <b>a</b>better than <b>b</b> simply because b has no circuits,
 * unless b is also relatively old.
394
 */
395
static int
396
397
398
399
connection_or_is_better(time_t now,
                        const or_connection_t *a,
                        const or_connection_t *b,
                        int forgive_new_connections)
400
401
{
  int newer;
402
403
404
/** 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)
405
406
407
408
409
410
411

  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;

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
  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;
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
}

/** 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)
{
447
  or_connection_t *conn, *best=NULL;
448
  int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
449
  time_t now = approx_time();
450

451
452
453
454
455
456
  tor_assert(msg_out);
  tor_assert(launch_out);

  if (!orconn_identity_map) {
    *msg_out = "Router not connected (nothing is).  Connecting.";
    *launch_out = 1;
457
    return NULL;
458
  }
459
460
461
462

  conn = digestmap_get(orconn_identity_map, digest);

  for (; conn; conn = conn->next_with_same_id) {
463
464
    tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
    tor_assert(conn->_base.type == CONN_TYPE_OR);
465
    tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
466
    if (conn->_base.marked_for_close)
467
      continue;
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
    /* 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;

496
    if (!best) {
497
      best = conn; /* If we have no 'best' so far, this one is good enough. */
498
499
      continue;
    }
500

501
    if (connection_or_is_better(now, conn, best, 0))
502
      best = conn;
503
  }
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588

  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
 * identity, set elements of that list as is_bad_for_new_circs() as
 * appropriate.  Helper for connection_or_set_bad_connections().
 */
static void
connection_or_group_set_badness(or_connection_t *head)
{
  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;
    if (or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
        < now) {
      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,
               "Marking OR conn to %s:%d as too old for new circuits: "
               "(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;
    }

589
    if (!best || connection_or_is_better(now, or_conn, best, 0))
590
591
592
593
594
595
596
597
598
599
      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.
   *
600
601
602
603
604
605
606
607
608
   * 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.
609
610
611
612
613
614
   */
  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;
615
616
617
    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. */
618
619
620
621
622
623
624
625
626
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
654
655
656
657
658
659
660
661
662
663
      if (best->is_canonical) {
        log_info(LD_OR,
                 "Marking OR conn to %s:%d as too old for new circuits: "
                 "(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,
                 "Marking OR conn to %s:%d as too old for new circuits: "
                 "(fd %d, %d secs old).  We have a better 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;
      }
    }
  }
}

/** Go through all the OR connections, and set the is_bad_for_new_circs
 * flag on:
 *    - 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.
 */
void
connection_or_set_bad_connections(void)
{
  if (!orconn_identity_map)
    return;

  DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
    connection_or_group_set_badness(conn);
  } DIGESTMAP_FOREACH_END;
664
665
}

666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/** <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);
}

681
682
/** 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>.
683
 *
684
 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
685
686
 * return that connection. If the connect() is in progress, set the
 * new conn's state to 'connecting' and return it. If connect() succeeds,
687
 * call connection_tls_start_handshake() on it.
688
 *
689
 * This function is called from router_retry_connections(), for
690
691
692
693
694
 * ORs connecting to ORs, and circuit_establish_circuit(), for
 * OPs connecting to ORs.
 *
 * Return the launched conn, or NULL if it failed.
 */
695
or_connection_t *
696
697
connection_or_connect(const tor_addr_t *_addr, uint16_t port,
                      const char *id_digest)
698
{
699
  or_connection_t *conn;
700
  or_options_t *options = get_options();
701
  int socket_error = 0;
702
  int using_proxy = 0;
703
  tor_addr_t addr;
Roger Dingledine's avatar
Roger Dingledine committed
704

705
  tor_assert(_addr);
706
  tor_assert(id_digest);
707
  tor_addr_copy(&addr, _addr);
708

709
  if (server_mode(options) && router_digest_is_me(id_digest)) {
Roger Dingledine's avatar
Roger Dingledine committed
710
    log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
711
712
713
    return NULL;
  }

714
  conn = or_connection_new(AF_INET);
Roger Dingledine's avatar
Roger Dingledine committed
715
716

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

721
  /* use a proxy server if available */
722
  if (options->HttpsProxy) {
723
    using_proxy = 1;
724
    tor_addr_copy(&addr, &options->HttpsProxyAddr);
725
    port = options->HttpsProxyPort;
726
727
  } else if (options->Socks4Proxy) {
    using_proxy = 1;
728
    tor_addr_copy(&addr, &options->Socks4ProxyAddr);
729
730
731
    port = options->Socks4ProxyPort;
  } else if (options->Socks5Proxy) {
    using_proxy = 1;
732
    tor_addr_copy(&addr, &options->Socks5ProxyAddr);
733
    port = options->Socks5ProxyPort;
734
735
  }

736
  switch (connection_connect(TO_CONN(conn), conn->_base.address,
737
                             &addr, port, &socket_error)) {
738
    case -1:
Roger Dingledine's avatar
Roger Dingledine committed
739
      /* If the connection failed immediately, and we're using
740
741
       * a proxy, our proxy is down. Don't blame the Tor server. */
      if (!using_proxy)
742
743
        entry_guard_register_connect_status(conn->identity_digest,
                                            0, 1, time(NULL));
744
745
746
      connection_or_connect_failed(conn,
                                   errno_to_orconn_end_reason(socket_error),
                                   tor_socket_strerror(socket_error));
747
      connection_free(TO_CONN(conn));
748
      return NULL;
749
    case 0:
750
      connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
751
752
      /* writable indicates finish, readable indicates broken link,
         error indicates broken link on windows */
753
      return conn;
754
    /* case 1: fall through */
755
756
  }

757
758
759
760
761
  if (connection_or_finished_connecting(conn) < 0) {
    /* already marked for close */
    return NULL;
  }
  return conn;
762
763
}

Roger Dingledine's avatar
Roger Dingledine committed
764
765
/** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
 * we initiated the connection, else it's 1.
766
 *
Roger Dingledine's avatar
Roger Dingledine committed
767
768
 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
 * pass <b>conn</b> to connection_tls_continue_handshake().
769
 *
Roger Dingledine's avatar
Roger Dingledine committed
770
 * Return -1 if <b>conn</b> is broken, else return 0.
771
 */
772
int
773
connection_tls_start_handshake(or_connection_t *conn, int receiving)
774
{
775
  conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
776
  conn->tls = tor_tls_new(conn->_base.s, receiving);
777
  tor_tls_set_logged_address(conn->tls, escaped_safe_str(conn->_base.address));
778
  if (!conn->tls) {
Roger Dingledine's avatar
Roger Dingledine committed
779
    log_warn(LD_BUG,"tor_tls_new failed. Closing.");
780
781
    return -1;
  }
782
  connection_start_reading(TO_CONN(conn));
783
  log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
784
785
  note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);

786
  if (connection_tls_continue_handshake(conn) < 0) {
787
    return -1;
788
  }
789
790
791
  return 0;
}

792
793
/** Invoked on the server side from inside tor_tls_read() when the server
 * gets a successful TLS renegotiation from the client. */
794
795
796
797
static void
connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
{
  or_connection_t *conn = _conn;
798
  (void)tls;
799

800
801
  /* Don't invoke this again. */
  tor_tls_set_renegotiate_callback(tls, NULL, NULL);
802
  tor_tls_block_renegotiation(tls);
803

804
  if (connection_tls_finish_handshake(conn) < 0) {
805
    /* XXXX_TLS double-check that it's ok to do this from inside read. */
806
    /* XXXX_TLS double-check that this verifies certificates. */
807
808
    connection_mark_for_close(TO_CONN(conn));
  }
809
810
}

Roger Dingledine's avatar
Roger Dingledine committed
811
812
/** Move forward with the tls handshake. If it finishes, hand
 * <b>conn</b> to connection_tls_finish_handshake().
813
 *
Roger Dingledine's avatar
Roger Dingledine committed
814
 * Return -1 if <b>conn</b> is broken, else return 0.
815
 */
816
int
817
connection_tls_continue_handshake(or_connection_t *conn)
818
{
819
  int result;
820
  check_no_tls_errors();
821
 again:
822
823
  if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
    // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
824
    result = tor_tls_renegotiate(conn->tls);
825
826
    // log_notice(LD_OR, "Result: %d", result);
  } else {
827
    tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
828
    // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
829
    result = tor_tls_handshake(conn->tls);
830
    // log_notice(LD_OR, "Result: %d", result);
831
  }
832
  switch (result) {
833
    CASE_TOR_TLS_ERROR_ANY:
834
835
    log_info(LD_OR,"tls error [%s]. breaking connection.",
             tor_tls_err_to_string(result));
836
837
      return -1;
    case TOR_TLS_DONE:
838
      if (! tor_tls_used_v1_handshake(conn->tls)) {
839
840
        if (!tor_tls_is_server(conn->tls)) {
          if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
841
            // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
842
            conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
843
844
            goto again;
          }
845
          // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
846
847
848
849
850
        } else {
          /* improved handshake, but not a client. */
          tor_tls_set_renegotiate_callback(conn->tls,
                                           connection_or_tls_renegotiated_cb,
                                           conn);
851
852
853
854
          conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
          connection_stop_writing(TO_CONN(conn));
          connection_start_reading(TO_CONN(conn));
          return 0;
855
        }
856
      }
857
      return connection_tls_finish_handshake(conn);
858
    case TOR_TLS_WANTWRITE:
859
      connection_start_writing(TO_CONN(conn));
Roger Dingledine's avatar
Roger Dingledine committed
860
      log_debug(LD_OR,"wanted write");
861
862
      return 0;
    case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
Roger Dingledine's avatar
Roger Dingledine committed
863
      log_debug(LD_OR,"wanted read");
864
      return 0;
865
866
867
    case TOR_TLS_CLOSE:
      log_info(LD_OR,"tls closed. breaking connection.");
      return -1;
868
869
870
871
  }
  return 0;
}

872
873
874
/** Return 1 if we initiated this connection, or 0 if it started
 * out as an incoming connection.
 */
875
int
876
connection_or_nonopen_was_started_here(or_connection_t *conn)
877
{
878
  tor_assert(conn->_base.type == CONN_TYPE_OR);
879
880
  if (!conn->tls)
    return 1; /* it's still in proxy states or something */
881
882
  if (conn->handshake_state)
    return conn->handshake_state->started_here;
883
  return !tor_tls_is_server(conn->tls);
884
885
}

886
/** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
887
 * return -1 if he is lying, broken, or otherwise something is wrong.
888
 *
889
890
891
 * If we initiated this connection (<b>started_here</b> is true), make sure
 * the other side sent sent a correctly formed certificate. If I initiated the
 * connection, make sure it's the right guy.
892
 *
893
894
895
896
897
898
899
900
 * Otherwise (if we _didn't_ initiate this connection), it's okay for
 * the certificate to be weird or absent.
 *
 * If we return 0, and the certificate is as expected, write a hash of the
 * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
 * we return -1 this buffer is undefined.)  If the certificate is invalid
 * or missing on an incoming connection, we return 0 and set digest_rcvd to
 * DIGEST_LEN 0 bytes.
901
 *
902
 * As side effects,
Roger Dingledine's avatar
Roger Dingledine committed
903
 * 1) Set conn->circ_id_type according to tor-spec.txt.
904
905
906
 * 2) If we're an authdirserver and we initiated the connection: drop all
 *    descriptors that claim to be on that IP/port but that aren't
 *    this guy; and note that this guy is reachable.
907
 */
908
static int
909
910
911
connection_or_check_valid_tls_handshake(or_connection_t *conn,
                                        int started_here,
                                        char *digest_rcvd_out)
912
{
913
  crypto_pk_env_t *identity_rcvd=NULL;
914
  or_options_t *options = get_options();
Roger Dingledine's avatar
Roger Dingledine committed
915
  int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
916
917
  const char *safe_address =
    started_here ? conn->_base.address : safe_str(conn->_base.address);
918
  const char *conn_type = started_here ? "outgoing" : "incoming";
919
  int has_cert = 0, has_identity=0;
920

921
  check_no_tls_errors();
922
923
  has_cert = tor_tls_peer_has_cert(conn->tls);
  if (started_here && !has_cert) {
924
    log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
925
926
             "send a cert! Closing.",
             safe_address, conn->_base.port);
927
    return -1;
928
  } else if (!has_cert) {
929
    log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
930
              "That's ok.");
931
  }
932
  check_no_tls_errors();
933

934
  if (has_cert) {
935
936
    int v = tor_tls_verify(started_here?severity:LOG_INFO,
                           conn->tls, &identity_rcvd);
937
    if (started_here && v<0) {
938
      log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
939
940
             " has a cert but it's invalid. Closing.",
             safe_address, conn->_base.port);
941
        return -1;
942
    } else if (v<0) {
943
      log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
944
945
               "chain; ignoring.");
    } else {
946
947
      log_debug(LD_HANDSHAKE,
                "The certificate seems to be valid on %s connection "
948
                "with %s:%d", conn_type, safe_address, conn->_base.port);
949
    }
950
    check_no_tls_errors();
951
  }
952

953
  if (identity_rcvd) {
954
    has_identity = 1;
955
    crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
956
957
958
959
960
961
    if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
      conn->circ_id_type = CIRC_ID_TYPE_LOWER;
    } else {
      conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
    }
    crypto_free_pk_env(identity_rcvd);
962
  } else {
963
    memset(digest_rcvd_out, 0, DIGEST_LEN);
964
    conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
965
  }
966

967
  if (started_here && tor_digest_is_zero(conn->identity_digest)) {
968
    connection_or_set_identity_digest(conn, digest_rcvd_out);
969
    tor_free(conn->nickname);
970
971
972
973
    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);
974
    log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
975
976
977
978
                    "its key. Hoping for the best.",
                    conn->nickname, conn->_base.address, conn->_base.port);
  }

979
  if (started_here) {
980
    int as_advertised = 1;
981
982
    tor_assert(has_cert);
    tor_assert(has_identity);
983
    if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
984
985
986
      /* I was aiming for a particular digest. I didn't get it! */
      char seen[HEX_DIGEST_LEN+1];
      char expected[HEX_DIGEST_LEN+1];
987
      base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
988
989
      base16_encode(expected, sizeof(expected), conn->identity_digest,
                    DIGEST_LEN);
990
      log_fn(severity, LD_HANDSHAKE,
991
             "Tried connecting to router at %s:%d, but identity key was not "