connection_or.c 26.3 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-2007, Roger Dingledine, Nick Mathewson. */
4
5
/* See LICENSE for licensing information */
/* $Id$ */
6
7
const char connection_or_c_id[] =
  "$Id$";
Roger Dingledine's avatar
Roger Dingledine committed
8

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

Roger Dingledine's avatar
Roger Dingledine committed
15
#include "or.h"
16

17
18
static int connection_tls_finish_handshake(or_connection_t *conn);
static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
19

Roger Dingledine's avatar
Roger Dingledine committed
20
21
/**************************************************************/

22
23
/** 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
24
 * they form a linked list, with next_with_same_id as the next pointer. */
25
26
27
static digestmap_t *orconn_identity_map = NULL;

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

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

78
79
80
81
  if (orconn_identity_map) {
    digestmap_free(orconn_identity_map, NULL);
    orconn_identity_map = NULL;
  }
82
83
}

84
/** Change conn->identity_digest to digest, and add conn into
85
 * orconn_digest_map. */
86
static void
87
connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
88
{
89
  or_connection_t *tmp;
90
91
92
93
94
95
96
  tor_assert(conn);
  tor_assert(digest);

  if (!orconn_identity_map)
    orconn_identity_map = digestmap_new();
  if (!memcmp(conn->identity_digest, digest, DIGEST_LEN))
    return;
97
98
99

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

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

104
  /* If we're setting the ID to zero, don't add a mapping. */
105
106
107
  if (tor_digest_is_zero(digest))
    return;

108
109
110
  tmp = digestmap_set(orconn_identity_map, digest, conn);
  conn->next_with_same_id = tmp;

111
#if 1
112
  /* Testing code to check for bugs in representation. */
113
114
115
116
  for (; tmp; tmp = tmp->next_with_same_id) {
    tor_assert(!memcmp(tmp->identity_digest, digest, DIGEST_LEN));
    tor_assert(tmp != conn);
  }
117
#endif
118
119
}

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

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

147
int
148
connection_or_reached_eof(or_connection_t *conn)
149
{
Roger Dingledine's avatar
Roger Dingledine committed
150
  log_info(LD_OR,"OR connection reached EOF. Closing.");
151
  connection_mark_for_close(TO_CONN(conn));
152
153
154
  return 0;
}

155
156
157
158
159
160
/** Read conn's inbuf. If the http response from the proxy is all
 * here, make sure it's good news, and begin the tls handshake. If
 * it's bad news, close the connection and return -1. Else return 0
 * and hope for better luck next time.
 */
static int
161
connection_or_read_proxy_response(or_connection_t *or_conn)
162
{
163
  char *headers;
164
  char *reason=NULL;
165
166
  int status_code;
  time_t date_header;
167
  connection_t *conn = TO_CONN(or_conn);
168
169
170

  switch (fetch_from_buf_http(conn->inbuf,
                              &headers, MAX_HEADERS_SIZE,
171
                              NULL, NULL, 10000, 0)) {
172
    case -1: /* overflow */
Roger Dingledine's avatar
Roger Dingledine committed
173
174
      log_warn(LD_PROTOCOL,
               "Your https proxy sent back an oversized response. Closing.");
175
176
      return -1;
    case 0:
Roger Dingledine's avatar
Roger Dingledine committed
177
      log_info(LD_OR,"https proxy response not all here yet. Waiting.");
178
179
180
181
182
      return 0;
    /* case 1, fall through */
  }

  if (parse_http_response(headers, &status_code, &date_header,
183
                          NULL, &reason) < 0) {
Roger Dingledine's avatar
Roger Dingledine committed
184
185
186
    log_warn(LD_OR,
             "Unparseable headers from proxy (connecting to '%s'). Closing.",
             conn->address);
187
188
189
    tor_free(headers);
    return -1;
  }
190
  if (!reason) reason = tor_strdup("[no reason given]");
191
192

  if (status_code == 200) {
Roger Dingledine's avatar
Roger Dingledine committed
193
    log_info(LD_OR,
194
195
             "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
             conn->address, escaped(reason));
196
    tor_free(reason);
197
    if (connection_tls_start_handshake(or_conn, 0) < 0) {
198
199
      /* TLS handshaking error of some kind. */
      connection_mark_for_close(conn);
200

201
202
203
204
205
      return -1;
    }
    return 0;
  }
  /* else, bad news on the status code */
Roger Dingledine's avatar
Roger Dingledine committed
206
  log_warn(LD_OR,
207
           "The https proxy sent back an unexpected status code %d (%s). "
Roger Dingledine's avatar
Roger Dingledine committed
208
           "Closing.",
209
           status_code, escaped(reason));
210
  tor_free(reason);
211
212
213
214
  connection_mark_for_close(conn);
  return -1;
}

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

225
  switch (conn->_base.state) {
226
227
228
229
230
231
232
    case OR_CONN_STATE_PROXY_READING:
      return connection_or_read_proxy_response(conn);
    case OR_CONN_STATE_OPEN:
      return connection_or_process_cells_from_inbuf(conn);
    default:
      return 0; /* don't do anything */
  }
Roger Dingledine's avatar
Roger Dingledine committed
233
234
}

235
236
/** 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. */
237
238
#define OR_CONN_HIGHWATER (32*1024)

239
240
/** Add cells to an OR connection's outbuf whenever the outbuf's data length
 * drops below this size. */
241
242
#define OR_CONN_LOWWATER (16*1024)

243
244
/** Called whenever we have flushed some data on an or_conn: add more data
 * from active circuits. */
245
246
247
int
connection_or_flushed_some(or_connection_t *conn)
{
248
  size_t datalen = buf_datalen(conn->_base.outbuf);
249
250
  /* If we're under the low water mark, add cells until we're just over the
   * high water mark. */
251
  if (datalen < OR_CONN_LOWWATER) {
252
253
    int n = (OR_CONN_HIGHWATER - datalen + CELL_NETWORK_SIZE-1)
      / CELL_NETWORK_SIZE;
254
    while (conn->active_circuits && n > 0) {
255
      int flushed = connection_or_flush_from_first_active_circuit(conn, 1);
256
257
258
      n -= flushed;
    }
  }
259
260
261
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
262
/** Connection <b>conn</b> has finished writing and has no bytes left on
263
264
 * its outbuf.
 *
Nick Mathewson's avatar
Nick Mathewson committed
265
 * Otherwise it's in state "open": stop writing and return.
266
267
268
 *
 * If <b>conn</b> is broken, mark it for close and return -1, else
 * return 0.
269
 */
270
int
271
connection_or_finished_flushing(or_connection_t *conn)
272
{
273
  tor_assert(conn);
274
  assert_connection_ok(TO_CONN(conn),0);
Roger Dingledine's avatar
Roger Dingledine committed
275

276
  switch (conn->_base.state) {
277
    case OR_CONN_STATE_PROXY_FLUSHING:
Roger Dingledine's avatar
Roger Dingledine committed
278
      log_debug(LD_OR,"finished sending CONNECT to proxy.");
279
280
      conn->_base.state = OR_CONN_STATE_PROXY_READING;
      connection_stop_writing(TO_CONN(conn));
281
282
      break;
    case OR_CONN_STATE_OPEN:
283
      connection_stop_writing(TO_CONN(conn));
284
285
      break;
    default:
286
      log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
287
      tor_fragile_assert();
288
      return -1;
289
290
291
292
293
294
  }
  return 0;
}

/** Connected handler for OR connections: begin the TLS handshake.
 */
295
int
296
connection_or_finished_connecting(or_connection_t *or_conn)
297
{
298
299
300
  connection_t *conn;
  tor_assert(or_conn);
  conn = TO_CONN(or_conn);
301
302
  tor_assert(conn->state == OR_CONN_STATE_CONNECTING);

Roger Dingledine's avatar
Roger Dingledine committed
303
304
  log_debug(LD_OR,"OR connect() to router at %s:%u finished.",
            conn->address,conn->port);
305

306
307
308
309
  if (get_options()->HttpsProxy) {
    char buf[1024];
    char addrbuf[INET_NTOA_BUF_LEN];
    struct in_addr in;
310
    char *base64_authenticator=NULL;
311
    const char *authenticator = get_options()->HttpsProxyAuthenticator;
312
313
314

    in.s_addr = htonl(conn->addr);
    tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
315
316

    if (authenticator) {
317
318
      base64_authenticator = alloc_http_authenticator(authenticator);
      if (!base64_authenticator)
Roger Dingledine's avatar
Roger Dingledine committed
319
        log_warn(LD_OR, "Encoding https authenticator failed");
320
321
    }
    if (base64_authenticator) {
322
323
324
325
326
327
328
329
      tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
                   "Proxy-Authorization: Basic %s\r\n\r\n", addrbuf,
                   conn->port, base64_authenticator);
      tor_free(base64_authenticator);
    } else {
      tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
                   addrbuf, conn->port);
    }
330
331
332
333
334
    connection_write_to_buf(buf, strlen(buf), conn);
    conn->state = OR_CONN_STATE_PROXY_FLUSHING;
    return 0;
  }

335
  if (connection_tls_start_handshake(or_conn, 0) < 0) {
336
337
    /* TLS handshaking error of some kind. */
    connection_mark_for_close(conn);
338
    return -1;
Roger Dingledine's avatar
Roger Dingledine committed
339
  }
340
  return 0;
Roger Dingledine's avatar
Roger Dingledine committed
341
342
}

343
344
345
/** 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. */
346
static void
347
connection_or_init_conn_from_address(or_connection_t *conn,
348
                                     uint32_t addr, uint16_t port,
349
350
                                     const char *id_digest,
                                     int started_here)
351
{
352
353
  or_options_t *options = get_options();
  routerinfo_t *r = router_get_by_digest(id_digest);
354
  conn->bandwidthrate = (int)options->BandwidthRate;
355
  conn->read_bucket = conn->bandwidthburst = (int)options->BandwidthBurst;
356
  connection_or_set_identity_digest(conn, id_digest);
357
358
  conn->_base.addr = addr;
  conn->_base.port = port;
359
  if (r) {
360
361
362
363
    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! */
364
365
      conn->_base.addr = r->addr;
      conn->_base.port = r->or_port;
366
367
    }
    conn->nickname = tor_strdup(r->nickname);
368
369
    tor_free(conn->_base.address);
    conn->_base.address = tor_strdup(r->address);
370
  } else {
371
372
373
374
375
376
377
378
379
380
381
382
    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);
    }
383
384
    tor_free(conn->_base.address);
    conn->_base.address = tor_dup_addr(addr);
385
  }
386
387
}

388
389
390
391
392
393
394
395
396
/** Return the best connection of type OR with the
 * digest <b>digest</b> that we have, or NULL if we have none.
 *
 * 1) Don't return it if it's marked for close.
 * 2) If there are any open conns, ignore non-open conns.
 * 3) If there are any non-obsolete conns, ignore obsolete conns.
 * 4) Then if there are any non-empty conns, ignore empty conns.
 * 5) Of the remaining conns, prefer newer conns.
 */
397
or_connection_t *
398
399
400
connection_or_get_by_identity_digest(const char *digest)
{
  int newer;
401
  or_connection_t *conn, *best=NULL;
402
403
404
405
406
407
408

  if (!orconn_identity_map)
    return NULL;

  conn = digestmap_get(orconn_identity_map, digest);

  for (; conn; conn = conn->next_with_same_id) {
409
410
    tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
    tor_assert(conn->_base.type == CONN_TYPE_OR);
411
    tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
412
    if (conn->_base.marked_for_close)
413
414
415
416
417
      continue;
    if (!best) {
      best = conn; /* whatever it is, it's better than nothing. */
      continue;
    }
418
419
    if (best->_base.state == OR_CONN_STATE_OPEN &&
        conn->_base.state != OR_CONN_STATE_OPEN)
420
      continue; /* avoid non-open conns if we can */
421
    newer = best->_base.timestamp_created < conn->_base.timestamp_created;
422

423
    if (!best->_base.or_is_obsolete && conn->_base.or_is_obsolete)
424
425
      continue; /* We never prefer obsolete over non-obsolete connections. */

426
427
    if (
      /* We prefer non-obsolete connections: */
428
        (best->_base.or_is_obsolete && !conn->_base.or_is_obsolete) ||
429
430
431
432
433
434
435
436
      /* If both have circuits we prefer the newer: */
        (best->n_circuits && conn->n_circuits && newer) ||
      /* If neither has circuits we prefer the newer: */
        (!best->n_circuits && !conn->n_circuits && newer) ||
      /* We prefer connections with circuits: */
        (!best->n_circuits && conn->n_circuits)) {
      best = conn;
    };
437
438
439
440
  }
  return best;
}

441
442
/** 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>.
443
 *
444
 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
445
446
 * return that connection. If the connect() is in progress, set the
 * new conn's state to 'connecting' and return it. If connect() succeeds,
447
 * call connection_tls_start_handshake() on it.
448
 *
449
 * This function is called from router_retry_connections(), for
450
451
452
453
454
 * ORs connecting to ORs, and circuit_establish_circuit(), for
 * OPs connecting to ORs.
 *
 * Return the launched conn, or NULL if it failed.
 */
455
or_connection_t *
456
457
connection_or_connect(uint32_t addr, uint16_t port, const char *id_digest)
{
458
  or_connection_t *conn;
459
  or_options_t *options = get_options();
Roger Dingledine's avatar
Roger Dingledine committed
460

461
  tor_assert(id_digest);
462

463
  if (server_mode(options) && router_digest_is_me(id_digest)) {
Roger Dingledine's avatar
Roger Dingledine committed
464
    log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
465
466
467
    return NULL;
  }

468
  conn = TO_OR_CONN(connection_new(CONN_TYPE_OR));
Roger Dingledine's avatar
Roger Dingledine committed
469
470

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

475
476
477
478
479
480
  if (options->HttpsProxy) {
    /* we shouldn't connect directly. use the https proxy instead. */
    addr = options->HttpsProxyAddr;
    port = options->HttpsProxyPort;
  }

481
  switch (connection_connect(TO_CONN(conn), conn->_base.address, addr, port)) {
482
    case -1:
Roger Dingledine's avatar
Roger Dingledine committed
483
484
485
      /* If the connection failed immediately, and we're using
       * an https proxy, our https proxy is down. Don't blame the
       * Tor server. */
486
      if (!options->HttpsProxy) {
487
488
        entry_guard_register_connect_status(conn->identity_digest, 0,
                                            time(NULL));
489
        router_set_status(conn->identity_digest, 0);
490
      }
491
      control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
492
              END_OR_CONN_REASON_TCP_REFUSED);
493
      connection_free(TO_CONN(conn));
494
      return NULL;
495
    case 0:
496
      connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
497
498
      /* writable indicates finish, readable indicates broken link,
         error indicates broken link on windows */
499
      return conn;
500
    /* case 1: fall through */
501
502
  }

503
504
505
506
507
  if (connection_or_finished_connecting(conn) < 0) {
    /* already marked for close */
    return NULL;
  }
  return conn;
508
509
}

Roger Dingledine's avatar
Roger Dingledine committed
510
511
/** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
 * we initiated the connection, else it's 1.
512
 *
Roger Dingledine's avatar
Roger Dingledine committed
513
514
 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
 * pass <b>conn</b> to connection_tls_continue_handshake().
515
 *
Roger Dingledine's avatar
Roger Dingledine committed
516
 * Return -1 if <b>conn</b> is broken, else return 0.
517
 */
518
int
519
connection_tls_start_handshake(or_connection_t *conn, int receiving)
520
{
521
522
  conn->_base.state = OR_CONN_STATE_HANDSHAKING;
  conn->tls = tor_tls_new(conn->_base.s, receiving);
523
  if (!conn->tls) {
Roger Dingledine's avatar
Roger Dingledine committed
524
    log_warn(LD_BUG,"tor_tls_new failed. Closing.");
525
526
    return -1;
  }
527
528
  connection_start_reading(TO_CONN(conn));
  log_debug(LD_OR,"starting TLS handshake on fd %d", conn->_base.s);
529
530
  note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);

531
  if (connection_tls_continue_handshake(conn) < 0) {
532
    return -1;
533
  }
534
535
536
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
537
538
/** Move forward with the tls handshake. If it finishes, hand
 * <b>conn</b> to connection_tls_finish_handshake().
539
 *
Roger Dingledine's avatar
Roger Dingledine committed
540
 * Return -1 if <b>conn</b> is broken, else return 0.
541
 */
542
int
543
connection_tls_continue_handshake(or_connection_t *conn)
544
{
545
  check_no_tls_errors();
546
  switch (tor_tls_handshake(conn->tls)) {
547
    CASE_TOR_TLS_ERROR_ANY:
Roger Dingledine's avatar
Roger Dingledine committed
548
      log_info(LD_OR,"tls error. breaking connection.");
549
550
      return -1;
    case TOR_TLS_DONE:
551
      return connection_tls_finish_handshake(conn);
552
    case TOR_TLS_WANTWRITE:
553
      connection_start_writing(TO_CONN(conn));
Roger Dingledine's avatar
Roger Dingledine committed
554
      log_debug(LD_OR,"wanted write");
555
556
      return 0;
    case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
Roger Dingledine's avatar
Roger Dingledine committed
557
      log_debug(LD_OR,"wanted read");
558
      return 0;
559
560
561
    case TOR_TLS_CLOSE:
      log_info(LD_OR,"tls closed. breaking connection.");
      return -1;
562
563
564
565
  }
  return 0;
}

566
567
568
/** Return 1 if we initiated this connection, or 0 if it started
 * out as an incoming connection.
 */
569
int
570
connection_or_nonopen_was_started_here(or_connection_t *conn)
571
{
572
  tor_assert(conn->_base.type == CONN_TYPE_OR);
573
574
575
  if (!conn->tls)
    return 1; /* it's still in proxy states or something */
  return !tor_tls_is_server(conn->tls);
576
577
}

578
/** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
579
 * return -1 if he is lying, broken, or otherwise something is wrong.
580
 *
581
582
583
 * 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.
584
 *
585
586
587
588
589
590
591
592
 * 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.
593
 *
594
 * As side effects,
Roger Dingledine's avatar
Roger Dingledine committed
595
 * 1) Set conn->circ_id_type according to tor-spec.txt.
596
597
598
 * 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.
599
 */
600
static int
601
602
connection_or_check_valid_handshake(or_connection_t *conn, int started_here,
                                    char *digest_rcvd)
603
{
604
  crypto_pk_env_t *identity_rcvd=NULL;
605
  or_options_t *options = get_options();
Roger Dingledine's avatar
Roger Dingledine committed
606
  int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
607
608
  const char *safe_address =
    started_here ? conn->_base.address : safe_str(conn->_base.address);
609
610
  const char *conn_type = started_here ? "outgoing" : "incoming";
  int has_cert = 0, has_identity = 0;
611

612
  check_no_tls_errors();
613
614
615
616
617
  has_cert = tor_tls_peer_has_cert(conn->tls);
  if (started_here && !has_cert) {
    log_info(LD_PROTOCOL,"Tried connecting to router at %s:%d, but it didn't "
             "send a cert! Closing.",
             safe_address, conn->_base.port);
618
    return -1;
619
620
621
  } else if (!has_cert) {
    log_debug(LD_PROTOCOL,"Got incoming connection with no certificate. "
              "That's ok.");
622
  }
623
  check_no_tls_errors();
624

625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
  if (has_cert) {
    int v = tor_tls_verify(started_here?severity:LOG_INFO,
                           conn->tls, &identity_rcvd);
    if (started_here && v<0) {
      log_fn(severity,LD_OR,"Tried connecting to router at %s:%d: It"
             " has a cert but it's invalid. Closing.",
             safe_address, conn->_base.port);
      return -1;
    } else if (v<0) {
      log_info(LD_PROTOCOL,"Incoming connection gave us an invalid cert "
               "chain; ignoring.");
    } else {
      log_debug(LD_OR,"The certificate seems to be valid on %s connection "
                "with %s:%d", conn_type, safe_address, conn->_base.port);
    }
    check_no_tls_errors();
641
  }
642

643
644
645
646
647
648
649
650
651
652
  if (identity_rcvd) {
    has_identity=1;
    crypto_pk_get_digest(identity_rcvd, digest_rcvd);

    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);
653
  } else {
654
655
    memset(digest_rcvd, 0, DIGEST_LEN);
    conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
656
  }
657

658
  if (started_here) {
659
    int as_advertised = 1;
660
661
    tor_assert(has_cert);
    tor_assert(has_identity);
662
663
664
665
666
    if (memcmp(digest_rcvd, conn->identity_digest, DIGEST_LEN)) {
      /* I was aiming for a particular digest. I didn't get it! */
      char seen[HEX_DIGEST_LEN+1];
      char expected[HEX_DIGEST_LEN+1];
      base16_encode(seen, sizeof(seen), digest_rcvd, DIGEST_LEN);
667
668
      base16_encode(expected, sizeof(expected), conn->identity_digest,
                    DIGEST_LEN);
669
      log_fn(severity, LD_OR,
670
             "Tried connecting to router at %s:%d, but identity key was not "
671
             "as expected: wanted %s but got %s.",
672
             conn->_base.address, conn->_base.port, expected, seen);
673
      entry_guard_register_connect_status(conn->identity_digest,0,time(NULL));
674
      router_set_status(conn->identity_digest, 0);
675
676
      control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
              END_OR_CONN_REASON_OR_IDENTITY);
677
      as_advertised = 0;
678
    }
679
    if (authdir_mode_handles_descs(options)) {
680
      /* We initiated this connection to address:port.  Drop all routers
681
       * with the same address:port and a different key.
682
       */
683
      dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
684
                              digest_rcvd, as_advertised);
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
    }
    if (!as_advertised)
      return -1;
  }
  return 0;
}

/** The tls handshake is finished.
 *
 * Make sure we are happy with the person we just handshaked with.
 *
 * If he initiated the connection, make sure he's not already connected,
 * then initialize conn from the information in router.
 *
 * If all is successful, call circuit_n_conn_done() to handle events
700
 * that have been pending on the <tls handshake completion. Also set the
701
702
703
 * directory to be dirty (only matters if I'm an authdirserver).
 */
static int
704
connection_tls_finish_handshake(or_connection_t *conn)
705
706
{
  char digest_rcvd[DIGEST_LEN];
707
  int started_here = connection_or_nonopen_was_started_here(conn);
708

Roger Dingledine's avatar
Roger Dingledine committed
709
  log_debug(LD_OR,"tls handshake done. verifying.");
710
  if (connection_or_check_valid_handshake(conn, started_here, digest_rcvd) < 0)
711
712
    return -1;

713
  if (!started_here) {
714
715
    connection_or_init_conn_from_address(conn,conn->_base.addr,
                                         conn->_base.port, digest_rcvd, 0);
716
  }
717

718
  directory_set_dirty();
719
  conn->_base.state = OR_CONN_STATE_OPEN;
720
  control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
721
722
  if (started_here) {
    rep_hist_note_connect_succeeded(conn->identity_digest, time(NULL));
723
724
    if (entry_guard_register_connect_status(conn->identity_digest, 1,
                                            time(NULL)) < 0) {
725
726
727
      /* pending circs get closed in circuit_about_to_close_connection() */
      return -1;
    }
728
    router_set_status(conn->identity_digest, 1);
729
  }
730
  connection_watch_events(TO_CONN(conn), EV_READ);
731
  circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
732
733
734
  return 0;
}

735
736
737
/** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
 * For cells that use or affect a circuit, this should only be called by
 * connection_or_flush_from_first_active_circuit()
738
 */
739
void
740
connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
741
{
742
  packed_cell_t networkcell;
743

744
745
  tor_assert(cell);
  tor_assert(conn);
Nick Mathewson's avatar
Nick Mathewson committed
746

747
  cell_pack(&networkcell, cell);
Roger Dingledine's avatar
Roger Dingledine committed
748

749
  connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
750
751
}

Roger Dingledine's avatar
Roger Dingledine committed
752
753
754
755
756
/** Process cells from <b>conn</b>'s inbuf.
 *
 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
 * and hand it to command_process_cell().
 *
757
758
 * Always return 0.
 */
759
static int
760
connection_or_process_cells_from_inbuf(or_connection_t *conn)
761
{
762
763
  char buf[CELL_NETWORK_SIZE];
  cell_t cell;
764

765
loop:
Roger Dingledine's avatar
Roger Dingledine committed
766
767
  log_debug(LD_OR,
            "%d: starting, inbuf_datalen %d (%d pending in tls object).",
768
            conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
Roger Dingledine's avatar
Roger Dingledine committed
769
            tor_tls_get_pending_bytes(conn->tls));
770
771
  if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
                                                             available? */
772
    return 0; /* not yet */
Roger Dingledine's avatar
Roger Dingledine committed
773

774
  connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
Roger Dingledine's avatar
Roger Dingledine committed
775

776
777
  /* retrieve cell info from buf (create the host-order struct from the
   * network-order string) */
778
  cell_unpack(&cell, buf);
Roger Dingledine's avatar
Roger Dingledine committed
779

780
  command_process_cell(&cell, conn);
Nick Mathewson's avatar
Nick Mathewson committed
781

782
  goto loop; /* process the remainder of the buffer */
783
}
784

785
786
787
788
789
790
791
/** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
 * onto OR connection <b>conn</b>.  Don't perform range-checking on reason:
 * we may want to propagate reasons from other cells.
 *
 * Return 0.
 */
int
792
connection_or_send_destroy(uint16_t circ_id, or_connection_t *conn, int reason)
793
794
795
796
797
798
799
800
801
{
  cell_t cell;

  tor_assert(conn);

  memset(&cell, 0, sizeof(cell_t));
  cell.circ_id = circ_id;
  cell.command = CELL_DESTROY;
  cell.payload[0] = (uint8_t) reason;
Roger Dingledine's avatar
Roger Dingledine committed
802
  log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
803

804
805
806
#if 0
  /* XXXX020 Actually, don't kill the cell queue: it may have data that we're
   * waiting to flush.  We need to do something more sensible here. */
807
808
809
810
  /* Clear the cell queue on the circuit, so that our destroy cell will
   * be the very next thing written.*/
  circ = circuit_get_by_circid_orconn(circ_id, conn);
  circuit_clear_cell_queue(circ, conn);
811
#endif
812

813
814
815
816
  connection_or_write_cell_to_buf(&cell, conn);
  return 0;
}