In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / connection_or.c
blobc372270b4ce8b4ccaf140c927d1857382671270d
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_or.c
9 * \brief Functions to handle OR connections, TLS handshaking, and
10 * cells on the network.
11 **/
12 #include "or.h"
13 #include "buffers.h"
15 * Define this so we get channel internal functions, since we're implementing
16 * part of a subclass (channel_tls_t).
18 #define TOR_CHANNEL_INTERNAL_
19 #include "channel.h"
20 #include "channeltls.h"
21 #include "circuitbuild.h"
22 #include "circuitlist.h"
23 #include "circuitstats.h"
24 #include "command.h"
25 #include "config.h"
26 #include "connection.h"
27 #include "connection_or.h"
28 #include "control.h"
29 #include "dirserv.h"
30 #include "entrynodes.h"
31 #include "geoip.h"
32 #include "main.h"
33 #include "networkstatus.h"
34 #include "nodelist.h"
35 #include "reasons.h"
36 #include "relay.h"
37 #include "rephist.h"
38 #include "router.h"
39 #include "routerlist.h"
40 #include "ext_orport.h"
41 #ifdef USE_BUFFEREVENTS
42 #include <event2/bufferevent_ssl.h>
43 #endif
45 static int connection_tls_finish_handshake(or_connection_t *conn);
46 static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
47 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
48 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
49 int started_here,
50 char *digest_rcvd_out);
52 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
54 static unsigned int
55 connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
56 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
59 * Call this when changing connection state, so notifications to the owning
60 * channel can be handled.
63 static void connection_or_change_state(or_connection_t *conn, uint8_t state);
65 #ifdef USE_BUFFEREVENTS
66 static void connection_or_handle_event_cb(struct bufferevent *bufev,
67 short event, void *arg);
68 #include <event2/buffer.h>/*XXXX REMOVE */
69 #endif
71 /**************************************************************/
73 /** Map from identity digest of connected OR or desired OR to a connection_t
74 * with that identity digest. If there is more than one such connection_t,
75 * they form a linked list, with next_with_same_id as the next pointer. */
76 static digestmap_t *orconn_identity_map = NULL;
78 /** Global map between Extended ORPort identifiers and OR
79 * connections. */
80 static digestmap_t *orconn_ext_or_id_map = NULL;
82 /** If conn is listed in orconn_identity_map, remove it, and clear
83 * conn->identity_digest. Otherwise do nothing. */
84 void
85 connection_or_remove_from_identity_map(or_connection_t *conn)
87 or_connection_t *tmp;
88 tor_assert(conn);
89 if (!orconn_identity_map)
90 return;
91 tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
92 if (!tmp) {
93 if (!tor_digest_is_zero(conn->identity_digest)) {
94 log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
95 "trying to remove it.",
96 conn->nickname ? conn->nickname : "NULL");
98 return;
100 if (conn == tmp) {
101 if (conn->next_with_same_id)
102 digestmap_set(orconn_identity_map, conn->identity_digest,
103 conn->next_with_same_id);
104 else
105 digestmap_remove(orconn_identity_map, conn->identity_digest);
106 } else {
107 while (tmp->next_with_same_id) {
108 if (tmp->next_with_same_id == conn) {
109 tmp->next_with_same_id = conn->next_with_same_id;
110 break;
112 tmp = tmp->next_with_same_id;
115 memset(conn->identity_digest, 0, DIGEST_LEN);
116 conn->next_with_same_id = NULL;
119 /** Remove all entries from the identity-to-orconn map, and clear
120 * all identities in OR conns.*/
121 void
122 connection_or_clear_identity_map(void)
124 smartlist_t *conns = get_connection_array();
125 SMARTLIST_FOREACH(conns, connection_t *, conn,
127 if (conn->type == CONN_TYPE_OR) {
128 or_connection_t *or_conn = TO_OR_CONN(conn);
129 memset(or_conn->identity_digest, 0, DIGEST_LEN);
130 or_conn->next_with_same_id = NULL;
134 digestmap_free(orconn_identity_map, NULL);
135 orconn_identity_map = NULL;
138 /** Change conn->identity_digest to digest, and add conn into
139 * orconn_digest_map. */
140 static void
141 connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
143 or_connection_t *tmp;
144 tor_assert(conn);
145 tor_assert(digest);
147 if (!orconn_identity_map)
148 orconn_identity_map = digestmap_new();
149 if (tor_memeq(conn->identity_digest, digest, DIGEST_LEN))
150 return;
152 /* If the identity was set previously, remove the old mapping. */
153 if (! tor_digest_is_zero(conn->identity_digest)) {
154 connection_or_remove_from_identity_map(conn);
155 if (conn->chan)
156 channel_clear_identity_digest(TLS_CHAN_TO_BASE(conn->chan));
159 memcpy(conn->identity_digest, digest, DIGEST_LEN);
161 /* If we're setting the ID to zero, don't add a mapping. */
162 if (tor_digest_is_zero(digest))
163 return;
165 tmp = digestmap_set(orconn_identity_map, digest, conn);
166 conn->next_with_same_id = tmp;
168 /* Deal with channels */
169 if (conn->chan)
170 channel_set_identity_digest(TLS_CHAN_TO_BASE(conn->chan), digest);
172 #if 1
173 /* Testing code to check for bugs in representation. */
174 for (; tmp; tmp = tmp->next_with_same_id) {
175 tor_assert(tor_memeq(tmp->identity_digest, digest, DIGEST_LEN));
176 tor_assert(tmp != conn);
178 #endif
181 /** Remove the Extended ORPort identifier of <b>conn</b> from the
182 * global identifier list. Also, clear the identifier from the
183 * connection itself. */
184 void
185 connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
187 or_connection_t *tmp;
188 if (!orconn_ext_or_id_map)
189 return;
190 if (!conn->ext_or_conn_id)
191 return;
193 tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
194 if (!tor_digest_is_zero(conn->ext_or_conn_id))
195 tor_assert(tmp == conn);
197 memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
200 /** Return the connection whose ext_or_id is <b>id</b>. Return NULL if no such
201 * connection is found. */
202 or_connection_t *
203 connection_or_get_by_ext_or_id(const char *id)
205 if (!orconn_ext_or_id_map)
206 return NULL;
207 return digestmap_get(orconn_ext_or_id_map, id);
210 /** Deallocate the global Extended ORPort identifier list */
211 void
212 connection_or_clear_ext_or_id_map(void)
214 digestmap_free(orconn_ext_or_id_map, NULL);
215 orconn_ext_or_id_map = NULL;
218 /** Creates an Extended ORPort identifier for <b>conn</b> and deposits
219 * it into the global list of identifiers. */
220 void
221 connection_or_set_ext_or_identifier(or_connection_t *conn)
223 char random_id[EXT_OR_CONN_ID_LEN];
224 or_connection_t *tmp;
226 if (!orconn_ext_or_id_map)
227 orconn_ext_or_id_map = digestmap_new();
229 /* Remove any previous identifiers: */
230 if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
231 connection_or_remove_from_ext_or_id_map(conn);
233 do {
234 crypto_rand(random_id, sizeof(random_id));
235 } while (digestmap_get(orconn_ext_or_id_map, random_id));
237 if (!conn->ext_or_conn_id)
238 conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
240 memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
242 tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
243 tor_assert(!tmp);
246 /**************************************************************/
248 /** Map from a string describing what a non-open OR connection was doing when
249 * failed, to an intptr_t describing the count of connections that failed that
250 * way. Note that the count is stored _as_ the pointer.
252 static strmap_t *broken_connection_counts;
254 /** If true, do not record information in <b>broken_connection_counts</b>. */
255 static int disable_broken_connection_counts = 0;
257 /** Record that an OR connection failed in <b>state</b>. */
258 static void
259 note_broken_connection(const char *state)
261 void *ptr;
262 intptr_t val;
263 if (disable_broken_connection_counts)
264 return;
266 if (!broken_connection_counts)
267 broken_connection_counts = strmap_new();
269 ptr = strmap_get(broken_connection_counts, state);
270 val = (intptr_t)ptr;
271 val++;
272 ptr = (void*)val;
273 strmap_set(broken_connection_counts, state, ptr);
276 /** Forget all recorded states for failed connections. If
277 * <b>stop_recording</b> is true, don't record any more. */
278 void
279 clear_broken_connection_map(int stop_recording)
281 if (broken_connection_counts)
282 strmap_free(broken_connection_counts, NULL);
283 broken_connection_counts = NULL;
284 if (stop_recording)
285 disable_broken_connection_counts = 1;
288 /** Write a detailed description the state of <b>orconn</b> into the
289 * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
290 * only the OR-conn level state but also the TLS state. It's useful for
291 * diagnosing broken handshakes. */
292 static void
293 connection_or_get_state_description(or_connection_t *orconn,
294 char *buf, size_t buflen)
296 connection_t *conn = TO_CONN(orconn);
297 const char *conn_state;
298 char tls_state[256];
300 tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
302 conn_state = conn_state_to_string(conn->type, conn->state);
303 tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
305 tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
308 /** Record the current state of <b>orconn</b> as the state of a broken
309 * connection. */
310 static void
311 connection_or_note_state_when_broken(or_connection_t *orconn)
313 char buf[256];
314 if (disable_broken_connection_counts)
315 return;
316 connection_or_get_state_description(orconn, buf, sizeof(buf));
317 log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
318 note_broken_connection(buf);
321 /** Helper type used to sort connection states and find the most frequent. */
322 typedef struct broken_state_count_t {
323 intptr_t count;
324 const char *state;
325 } broken_state_count_t;
327 /** Helper function used to sort broken_state_count_t by frequency. */
328 static int
329 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
331 const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
332 if (b->count < a->count)
333 return -1;
334 else if (b->count == a->count)
335 return 0;
336 else
337 return 1;
340 /** Upper limit on the number of different states to report for connection
341 * failure. */
342 #define MAX_REASONS_TO_REPORT 10
344 /** Report a list of the top states for failed OR connections at log level
345 * <b>severity</b>, in log domain <b>domain</b>. */
346 void
347 connection_or_report_broken_states(int severity, int domain)
349 int total = 0;
350 smartlist_t *items;
352 if (!broken_connection_counts || disable_broken_connection_counts)
353 return;
355 items = smartlist_new();
356 STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
357 broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
358 c->count = (intptr_t)countptr;
359 total += (int)c->count;
360 c->state = state;
361 smartlist_add(items, c);
362 } STRMAP_FOREACH_END;
364 smartlist_sort(items, broken_state_count_compare);
366 tor_log(severity, domain, "%d connections have failed%s", total,
367 smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
369 SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
370 if (c_sl_idx > MAX_REASONS_TO_REPORT)
371 break;
372 tor_log(severity, domain,
373 " %d connections died in state %s", (int)c->count, c->state);
374 } SMARTLIST_FOREACH_END(c);
376 SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
377 smartlist_free(items);
380 /** Call this to change or_connection_t states, so the owning channel_tls_t can
381 * be notified.
384 static void
385 connection_or_change_state(or_connection_t *conn, uint8_t state)
387 uint8_t old_state;
389 tor_assert(conn);
391 old_state = conn->base_.state;
392 conn->base_.state = state;
394 if (conn->chan)
395 channel_tls_handle_state_change_on_orconn(conn->chan, conn,
396 old_state, state);
399 /** Return the number of circuits using an or_connection_t; this used to
400 * be an or_connection_t field, but it got moved to channel_t and we
401 * shouldn't maintain two copies. */
404 connection_or_get_num_circuits(or_connection_t *conn)
406 tor_assert(conn);
408 if (conn->chan) {
409 return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
410 } else return 0;
413 /**************************************************************/
415 /** Pack the cell_t host-order structure <b>src</b> into network-order
416 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
417 * wire format.
419 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
420 * should set it or clear it as appropriate.
422 void
423 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
425 char *dest = dst->body;
426 if (wide_circ_ids) {
427 set_uint32(dest, htonl(src->circ_id));
428 dest += 4;
429 } else {
430 set_uint16(dest, htons(src->circ_id));
431 dest += 2;
432 memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2); /*make sure it's clear */
434 set_uint8(dest, src->command);
435 memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
438 /** Unpack the network-order buffer <b>src</b> into a host-order
439 * cell_t structure <b>dest</b>.
441 static void
442 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
444 if (wide_circ_ids) {
445 dest->circ_id = ntohl(get_uint32(src));
446 src += 4;
447 } else {
448 dest->circ_id = ntohs(get_uint16(src));
449 src += 2;
451 dest->command = get_uint8(src);
452 memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
455 /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
456 * bytes of <b>hdr_out</b>. Returns number of bytes used. */
458 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
460 int r;
461 if (wide_circ_ids) {
462 set_uint32(hdr_out, htonl(cell->circ_id));
463 hdr_out += 4;
464 r = VAR_CELL_MAX_HEADER_SIZE;
465 } else {
466 set_uint16(hdr_out, htons(cell->circ_id));
467 hdr_out += 2;
468 r = VAR_CELL_MAX_HEADER_SIZE - 2;
470 set_uint8(hdr_out, cell->command);
471 set_uint16(hdr_out+1, htons(cell->payload_len));
472 return r;
475 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
476 * payload space. */
477 var_cell_t *
478 var_cell_new(uint16_t payload_len)
480 size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
481 var_cell_t *cell = tor_malloc_zero(size);
482 cell->payload_len = payload_len;
483 cell->command = 0;
484 cell->circ_id = 0;
485 return cell;
488 /** Release all space held by <b>cell</b>. */
489 void
490 var_cell_free(var_cell_t *cell)
492 tor_free(cell);
495 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
497 connection_or_reached_eof(or_connection_t *conn)
499 tor_assert(conn);
501 log_info(LD_OR,"OR connection reached EOF. Closing.");
502 connection_or_close_normally(conn, 1);
504 return 0;
507 /** Handle any new bytes that have come in on connection <b>conn</b>.
508 * If conn is in 'open' state, hand it to
509 * connection_or_process_cells_from_inbuf()
510 * (else do nothing).
513 connection_or_process_inbuf(or_connection_t *conn)
515 /** Don't let the inbuf of a nonopen OR connection grow beyond this many
516 * bytes: it's either a broken client, a non-Tor client, or a DOS
517 * attempt. */
518 #define MAX_OR_INBUF_WHEN_NONOPEN 0
520 int ret = 0;
521 tor_assert(conn);
523 switch (conn->base_.state) {
524 case OR_CONN_STATE_PROXY_HANDSHAKING:
525 ret = connection_read_proxy_handshake(TO_CONN(conn));
527 /* start TLS after handshake completion, or deal with error */
528 if (ret == 1) {
529 tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
530 if (connection_tls_start_handshake(conn, 0) < 0)
531 ret = -1;
532 /* Touch the channel's active timestamp if there is one */
533 if (conn->chan)
534 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
536 if (ret < 0) {
537 connection_or_close_for_error(conn, 0);
540 return ret;
541 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
542 #ifdef USE_BUFFEREVENTS
543 if (tor_tls_server_got_renegotiate(conn->tls))
544 connection_or_tls_renegotiated_cb(conn->tls, conn);
545 if (conn->base_.marked_for_close)
546 return 0;
547 /* fall through. */
548 #endif
549 case OR_CONN_STATE_OPEN:
550 case OR_CONN_STATE_OR_HANDSHAKING_V2:
551 case OR_CONN_STATE_OR_HANDSHAKING_V3:
552 return connection_or_process_cells_from_inbuf(conn);
553 default:
554 break; /* don't do anything */
557 /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
558 * check would otherwise just let data accumulate. It serves no purpose
559 * in 0.2.3.
561 * XXX024 Remove this check once we verify that the above paragraph is
562 * 100% true. */
563 if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
564 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
565 "on nonopen OR connection %s %s:%u in state %s; closing.",
566 (int)buf_datalen(conn->base_.inbuf),
567 connection_or_nonopen_was_started_here(conn) ? "to" : "from",
568 conn->base_.address, conn->base_.port,
569 conn_state_to_string(conn->base_.type, conn->base_.state));
570 connection_or_close_for_error(conn, 0);
571 ret = -1;
574 return ret;
577 /** When adding cells to an OR connection's outbuf, keep adding until the
578 * outbuf is at least this long, or we run out of cells. */
579 #define OR_CONN_HIGHWATER (32*1024)
581 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
582 * drops below this size. */
583 #define OR_CONN_LOWWATER (16*1024)
585 /** Called whenever we have flushed some data on an or_conn: add more data
586 * from active circuits. */
588 connection_or_flushed_some(or_connection_t *conn)
590 size_t datalen, temp;
591 ssize_t n, flushed;
592 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
594 /* If we're under the low water mark, add cells until we're just over the
595 * high water mark. */
596 datalen = connection_get_outbuf_len(TO_CONN(conn));
597 if (datalen < OR_CONN_LOWWATER) {
598 while ((conn->chan) && channel_tls_more_to_flush(conn->chan)) {
599 /* Compute how many more cells we want at most */
600 n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
601 /* Bail out if we don't want any more */
602 if (n <= 0) break;
603 /* We're still here; try to flush some more cells */
604 flushed = channel_tls_flush_some_cells(conn->chan, n);
605 /* Bail out if it says it didn't flush anything */
606 if (flushed <= 0) break;
607 /* How much in the outbuf now? */
608 temp = connection_get_outbuf_len(TO_CONN(conn));
609 /* Bail out if we didn't actually increase the outbuf size */
610 if (temp <= datalen) break;
611 /* Update datalen for the next iteration */
612 datalen = temp;
616 return 0;
619 /** Connection <b>conn</b> has finished writing and has no bytes left on
620 * its outbuf.
622 * Otherwise it's in state "open": stop writing and return.
624 * If <b>conn</b> is broken, mark it for close and return -1, else
625 * return 0.
628 connection_or_finished_flushing(or_connection_t *conn)
630 tor_assert(conn);
631 assert_connection_ok(TO_CONN(conn),0);
633 switch (conn->base_.state) {
634 case OR_CONN_STATE_PROXY_HANDSHAKING:
635 case OR_CONN_STATE_OPEN:
636 case OR_CONN_STATE_OR_HANDSHAKING_V2:
637 case OR_CONN_STATE_OR_HANDSHAKING_V3:
638 break;
639 default:
640 log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
641 tor_fragile_assert();
642 return -1;
644 return 0;
647 /** Connected handler for OR connections: begin the TLS handshake.
650 connection_or_finished_connecting(or_connection_t *or_conn)
652 const int proxy_type = or_conn->proxy_type;
653 connection_t *conn;
655 tor_assert(or_conn);
656 conn = TO_CONN(or_conn);
657 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
659 log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
660 conn->address,conn->port);
661 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
663 if (proxy_type != PROXY_NONE) {
664 /* start proxy handshake */
665 if (connection_proxy_connect(conn, proxy_type) < 0) {
666 connection_or_close_for_error(or_conn, 0);
667 return -1;
670 connection_start_reading(conn);
671 connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
672 return 0;
675 if (connection_tls_start_handshake(or_conn, 0) < 0) {
676 /* TLS handshaking error of some kind. */
677 connection_or_close_for_error(or_conn, 0);
678 return -1;
680 return 0;
683 /** Called when we're about to finally unlink and free an OR connection:
684 * perform necessary accounting and cleanup */
685 void
686 connection_or_about_to_close(or_connection_t *or_conn)
688 time_t now = time(NULL);
689 connection_t *conn = TO_CONN(or_conn);
691 /* Tell the controlling channel we're closed */
692 if (or_conn->chan) {
693 channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
695 * NULL this out because the channel might hang around a little
696 * longer before channel_run_cleanup() gets it.
698 or_conn->chan->conn = NULL;
699 or_conn->chan = NULL;
702 /* Remember why we're closing this connection. */
703 if (conn->state != OR_CONN_STATE_OPEN) {
704 /* now mark things down as needed */
705 if (connection_or_nonopen_was_started_here(or_conn)) {
706 const or_options_t *options = get_options();
707 connection_or_note_state_when_broken(or_conn);
708 rep_hist_note_connect_failed(or_conn->identity_digest, now);
709 entry_guard_register_connect_status(or_conn->identity_digest,0,
710 !options->HTTPSProxy, now);
711 if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
712 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
713 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
714 reason);
715 if (!authdir_mode_tests_reachability(options))
716 control_event_bootstrap_problem(
717 orconn_end_reason_to_control_string(reason),
718 reason, or_conn);
721 } else if (conn->hold_open_until_flushed) {
722 /* We only set hold_open_until_flushed when we're intentionally
723 * closing a connection. */
724 rep_hist_note_disconnect(or_conn->identity_digest, now);
725 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
726 tls_error_to_orconn_end_reason(or_conn->tls_error));
727 } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
728 rep_hist_note_connection_died(or_conn->identity_digest, now);
729 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
730 tls_error_to_orconn_end_reason(or_conn->tls_error));
734 /** Return 1 if identity digest <b>id_digest</b> is known to be a
735 * currently or recently running relay. Otherwise return 0. */
737 connection_or_digest_is_known_relay(const char *id_digest)
739 if (router_get_consensus_status_by_id(id_digest))
740 return 1; /* It's in the consensus: "yes" */
741 if (router_get_by_id_digest(id_digest))
742 return 1; /* Not in the consensus, but we have a descriptor for
743 * it. Probably it was in a recent consensus. "Yes". */
744 return 0;
747 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
748 * relay, we will rely on the global read and write buckets, so give it
749 * per-conn limits that are big enough they'll never matter. But if it's
750 * not a known relay, first check if we set PerConnBwRate/Burst, then
751 * check if the consensus sets them, else default to 'big enough'.
753 * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
754 * clip the bucket if it happens to be <em>too</em> full.
756 static void
757 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
758 const or_options_t *options)
760 int rate, burst; /* per-connection rate limiting params */
761 if (connection_or_digest_is_known_relay(conn->identity_digest)) {
762 /* It's in the consensus, or we have a descriptor for it meaning it
763 * was probably in a recent consensus. It's a recognized relay:
764 * give it full bandwidth. */
765 rate = (int)options->BandwidthRate;
766 burst = (int)options->BandwidthBurst;
767 } else {
768 /* Not a recognized relay. Squeeze it down based on the suggested
769 * bandwidth parameters in the consensus, but allow local config
770 * options to override. */
771 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
772 networkstatus_get_param(NULL, "perconnbwrate",
773 (int)options->BandwidthRate, 1, INT32_MAX);
774 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
775 networkstatus_get_param(NULL, "perconnbwburst",
776 (int)options->BandwidthBurst, 1, INT32_MAX);
779 conn->bandwidthrate = rate;
780 conn->bandwidthburst = burst;
781 #ifdef USE_BUFFEREVENTS
783 const struct timeval *tick = tor_libevent_get_one_tick_timeout();
784 struct ev_token_bucket_cfg *cfg, *old_cfg;
785 int64_t rate64 = (((int64_t)rate) * options->TokenBucketRefillInterval)
786 / 1000;
787 /* This can't overflow, since TokenBucketRefillInterval <= 1000,
788 * and rate started out less than INT_MAX. */
789 int rate_per_tick = (int) rate64;
791 cfg = ev_token_bucket_cfg_new(rate_per_tick, burst, rate_per_tick,
792 burst, tick);
793 old_cfg = conn->bucket_cfg;
794 if (conn->base_.bufev)
795 tor_set_bufferevent_rate_limit(conn->base_.bufev, cfg);
796 if (old_cfg)
797 ev_token_bucket_cfg_free(old_cfg);
798 conn->bucket_cfg = cfg;
799 (void) reset; /* No way to do this with libevent yet. */
801 #else
802 if (reset) { /* set up the token buckets to be full */
803 conn->read_bucket = conn->write_bucket = burst;
804 return;
806 /* If the new token bucket is smaller, take out the extra tokens.
807 * (If it's larger, don't -- the buckets can grow to reach the cap.) */
808 if (conn->read_bucket > burst)
809 conn->read_bucket = burst;
810 if (conn->write_bucket > burst)
811 conn->write_bucket = burst;
812 #endif
815 /** Either our set of relays or our per-conn rate limits have changed.
816 * Go through all the OR connections and update their token buckets to make
817 * sure they don't exceed their maximum values. */
818 void
819 connection_or_update_token_buckets(smartlist_t *conns,
820 const or_options_t *options)
822 SMARTLIST_FOREACH(conns, connection_t *, conn,
824 if (connection_speaks_cells(conn))
825 connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
829 /** How long do we wait before killing non-canonical OR connections with no
830 * circuits? In Tor versions up to 0.2.1.25 and 0.2.2.12-alpha, we waited 15
831 * minutes before cancelling these connections, which caused fast relays to
832 * accrue many many idle connections. Hopefully 3-4.5 minutes is low enough
833 * that it kills most idle connections, without being so low that we cause
834 * clients to bounce on and off.
836 * For canonical connections, the limit is higher, at 15-22.5 minutes.
838 * For each OR connection, we randomly add up to 50% extra to its idle_timeout
839 * field, to avoid exposing when exactly the last circuit closed. Since we're
840 * storing idle_timeout in a uint16_t, don't let these values get higher than
841 * 12 hours or so without revising connection_or_set_canonical and/or expanding
842 * idle_timeout.
844 #define IDLE_OR_CONN_TIMEOUT_NONCANONICAL 180
845 #define IDLE_OR_CONN_TIMEOUT_CANONICAL 900
847 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
848 * non-canonical otherwise. Adjust idle_timeout accordingly.
850 void
851 connection_or_set_canonical(or_connection_t *or_conn,
852 int is_canonical)
854 const unsigned int timeout_base = is_canonical ?
855 IDLE_OR_CONN_TIMEOUT_CANONICAL : IDLE_OR_CONN_TIMEOUT_NONCANONICAL;
857 if (bool_eq(is_canonical, or_conn->is_canonical) &&
858 or_conn->idle_timeout != 0) {
859 /* Don't recalculate an existing idle_timeout unless the canonical
860 * status changed. */
861 return;
864 or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
865 or_conn->idle_timeout = timeout_base + crypto_rand_int(timeout_base / 2);
868 /** If we don't necessarily know the router we're connecting to, but we
869 * have an addr/port/id_digest, then fill in as much as we can. Start
870 * by checking to see if this describes a router we know.
871 * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
872 * 0 if it's an incoming connection. */
873 void
874 connection_or_init_conn_from_address(or_connection_t *conn,
875 const tor_addr_t *addr, uint16_t port,
876 const char *id_digest,
877 int started_here)
879 const node_t *r = node_get_by_id(id_digest);
880 connection_or_set_identity_digest(conn, id_digest);
881 connection_or_update_token_buckets_helper(conn, 1, get_options());
883 conn->base_.port = port;
884 tor_addr_copy(&conn->base_.addr, addr);
885 tor_addr_copy(&conn->real_addr, addr);
886 if (r) {
887 tor_addr_port_t node_ap;
888 node_get_pref_orport(r, &node_ap);
889 /* XXXX proposal 186 is making this more complex. For now, a conn
890 is canonical when it uses the _preferred_ address. */
891 if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
892 connection_or_set_canonical(conn, 1);
893 if (!started_here) {
894 /* Override the addr/port, so our log messages will make sense.
895 * This is dangerous, since if we ever try looking up a conn by
896 * its actual addr/port, we won't remember. Careful! */
897 /* XXXX arma: this is stupid, and it's the reason we need real_addr
898 * to track is_canonical properly. What requires it? */
899 /* XXXX <arma> i believe the reason we did this, originally, is because
900 * we wanted to log what OR a connection was to, and if we logged the
901 * right IP address and port 56244, that wouldn't be as helpful. now we
902 * log the "right" port too, so we know if it's moria1 or moria2.
904 tor_addr_copy(&conn->base_.addr, &node_ap.addr);
905 conn->base_.port = node_ap.port;
907 conn->nickname = tor_strdup(node_get_nickname(r));
908 tor_free(conn->base_.address);
909 conn->base_.address = tor_dup_addr(&node_ap.addr);
910 } else {
911 const char *n;
912 /* If we're an authoritative directory server, we may know a
913 * nickname for this router. */
914 n = dirserv_get_nickname_by_digest(id_digest);
915 if (n) {
916 conn->nickname = tor_strdup(n);
917 } else {
918 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
919 conn->nickname[0] = '$';
920 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
921 conn->identity_digest, DIGEST_LEN);
923 tor_free(conn->base_.address);
924 conn->base_.address = tor_dup_addr(addr);
928 * We have to tell channeltls.c to update the channel marks (local, in
929 * particular), since we may have changed the address.
932 if (conn->chan) {
933 channel_tls_update_marks(conn);
937 /** These just pass all the is_bad_for_new_circs manipulation on to
938 * channel_t */
940 static unsigned int
941 connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
943 tor_assert(or_conn);
945 if (or_conn->chan)
946 return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
947 else return 0;
950 static void
951 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
953 tor_assert(or_conn);
955 if (or_conn->chan)
956 channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
959 /** How old do we let a connection to an OR get before deciding it's
960 * too old for new circuits? */
961 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
963 /** Given the head of the linked list for all the or_connections with a given
964 * identity, set elements of that list as is_bad_for_new_circs as
965 * appropriate. Helper for connection_or_set_bad_connections().
967 * Specifically, we set the is_bad_for_new_circs flag on:
968 * - all connections if <b>force</b> is true.
969 * - all connections that are too old.
970 * - all open non-canonical connections for which a canonical connection
971 * exists to the same router.
972 * - all open canonical connections for which a 'better' canonical
973 * connection exists to the same router.
974 * - all open non-canonical connections for which a 'better' non-canonical
975 * connection exists to the same router at the same address.
977 * See channel_is_better() in channel.c for our idea of what makes one OR
978 * connection better than another.
980 static void
981 connection_or_group_set_badness(or_connection_t *head, int force)
983 or_connection_t *or_conn = NULL, *best = NULL;
984 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
985 time_t now = time(NULL);
987 /* Pass 1: expire everything that's old, and see what the status of
988 * everything else is. */
989 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
990 if (or_conn->base_.marked_for_close ||
991 connection_or_is_bad_for_new_circs(or_conn))
992 continue;
993 if (force ||
994 or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
995 < now) {
996 log_info(LD_OR,
997 "Marking OR conn to %s:%d as too old for new circuits "
998 "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
999 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1000 (int)(now - or_conn->base_.timestamp_created));
1001 connection_or_mark_bad_for_new_circs(or_conn);
1004 if (connection_or_is_bad_for_new_circs(or_conn)) {
1005 ++n_old;
1006 } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
1007 ++n_inprogress;
1008 } else if (or_conn->is_canonical) {
1009 ++n_canonical;
1010 } else {
1011 ++n_other;
1015 /* Pass 2: We know how about how good the best connection is.
1016 * expire everything that's worse, and find the very best if we can. */
1017 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
1018 if (or_conn->base_.marked_for_close ||
1019 connection_or_is_bad_for_new_circs(or_conn))
1020 continue; /* This one doesn't need to be marked bad. */
1021 if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1022 continue; /* Don't mark anything bad until we have seen what happens
1023 * when the connection finishes. */
1024 if (n_canonical && !or_conn->is_canonical) {
1025 /* We have at least one open canonical connection to this router,
1026 * and this one is open but not canonical. Mark it bad. */
1027 log_info(LD_OR,
1028 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1029 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1030 "canonical, and we have another connection to that OR that is.",
1031 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1032 (int)(now - or_conn->base_.timestamp_created));
1033 connection_or_mark_bad_for_new_circs(or_conn);
1034 continue;
1037 if (!best ||
1038 channel_is_better(now,
1039 TLS_CHAN_TO_BASE(or_conn->chan),
1040 TLS_CHAN_TO_BASE(best->chan),
1041 0)) {
1042 best = or_conn;
1046 if (!best)
1047 return;
1049 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1050 * every other open connection. If it's non-canonical, mark as bad
1051 * every other open connection to the same address.
1053 * XXXX This isn't optimal; if we have connections to an OR at multiple
1054 * addresses, we'd like to pick the best _for each address_, and mark as
1055 * bad every open connection that isn't best for its address. But this
1056 * can only occur in cases where the other OR is old (so we have no
1057 * canonical connection to it), or where all the connections to the OR are
1058 * at noncanonical addresses and we have no good direct connection (which
1059 * means we aren't at risk of attaching circuits to it anyway). As
1060 * 0.1.2.x dies out, the first case will go away, and the second one is
1061 * "mostly harmless", so a fix can wait until somebody is bored.
1063 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
1064 if (or_conn->base_.marked_for_close ||
1065 connection_or_is_bad_for_new_circs(or_conn) ||
1066 or_conn->base_.state != OR_CONN_STATE_OPEN)
1067 continue;
1068 if (or_conn != best &&
1069 channel_is_better(now,
1070 TLS_CHAN_TO_BASE(best->chan),
1071 TLS_CHAN_TO_BASE(or_conn->chan), 1)) {
1072 /* This isn't the best conn, _and_ the best conn is better than it,
1073 even when we're being forgiving. */
1074 if (best->is_canonical) {
1075 log_info(LD_OR,
1076 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1077 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1078 "We have a better canonical one "
1079 "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1080 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1081 (int)(now - or_conn->base_.timestamp_created),
1082 best->base_.s, (int)(now - best->base_.timestamp_created));
1083 connection_or_mark_bad_for_new_circs(or_conn);
1084 } else if (!tor_addr_compare(&or_conn->real_addr,
1085 &best->real_addr, CMP_EXACT)) {
1086 log_info(LD_OR,
1087 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1088 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1089 "one with the "
1090 "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1091 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1092 (int)(now - or_conn->base_.timestamp_created),
1093 best->base_.s, (int)(now - best->base_.timestamp_created));
1094 connection_or_mark_bad_for_new_circs(or_conn);
1100 /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
1101 * the OR connections with that digest), and set the is_bad_for_new_circs
1102 * flag based on the rules in connection_or_group_set_badness() (or just
1103 * always set it if <b>force</b> is true).
1105 void
1106 connection_or_set_bad_connections(const char *digest, int force)
1108 if (!orconn_identity_map)
1109 return;
1111 DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
1112 if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
1113 connection_or_group_set_badness(conn, force);
1114 } DIGESTMAP_FOREACH_END;
1117 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
1118 * a TCP connection. Send notifications appropriately.
1120 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1121 * <b>msg</b> specifies the strerror-style error message.
1123 void
1124 connection_or_connect_failed(or_connection_t *conn,
1125 int reason, const char *msg)
1127 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
1128 if (!authdir_mode_tests_reachability(get_options()))
1129 control_event_bootstrap_problem(msg, reason, conn);
1132 /** <b>conn</b> got an error in connection_handle_read_impl() or
1133 * connection_handle_write_impl() and is going to die soon.
1135 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1136 * <b>msg</b> specifies the strerror-style error message.
1138 void
1139 connection_or_notify_error(or_connection_t *conn,
1140 int reason, const char *msg)
1142 channel_t *chan;
1144 tor_assert(conn);
1146 /* If we're connecting, call connect_failed() too */
1147 if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1148 connection_or_connect_failed(conn, reason, msg);
1150 /* Tell the controlling channel if we have one */
1151 if (conn->chan) {
1152 chan = TLS_CHAN_TO_BASE(conn->chan);
1153 /* Don't transition if we're already in closing, closed or error */
1154 if (!(chan->state == CHANNEL_STATE_CLOSING ||
1155 chan->state == CHANNEL_STATE_CLOSED ||
1156 chan->state == CHANNEL_STATE_ERROR)) {
1157 channel_close_for_error(chan);
1161 /* No need to mark for error because connection.c is about to do that */
1164 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
1165 * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
1166 * pass in a pointer to a channel using this connection.
1168 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
1169 * return that connection. If the connect() is in progress, set the
1170 * new conn's state to 'connecting' and return it. If connect() succeeds,
1171 * call connection_tls_start_handshake() on it.
1173 * This function is called from router_retry_connections(), for
1174 * ORs connecting to ORs, and circuit_establish_circuit(), for
1175 * OPs connecting to ORs.
1177 * Return the launched conn, or NULL if it failed.
1179 or_connection_t *
1180 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
1181 const char *id_digest,
1182 channel_tls_t *chan)
1184 or_connection_t *conn;
1185 const or_options_t *options = get_options();
1186 int socket_error = 0;
1187 tor_addr_t addr;
1189 int r;
1190 tor_addr_t proxy_addr;
1191 uint16_t proxy_port;
1192 int proxy_type;
1194 tor_assert(_addr);
1195 tor_assert(id_digest);
1196 tor_addr_copy(&addr, _addr);
1198 if (server_mode(options) && router_digest_is_me(id_digest)) {
1199 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1200 return NULL;
1203 conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
1206 * Set up conn so it's got all the data we need to remember for channels
1208 * This stuff needs to happen before connection_or_init_conn_from_address()
1209 * so connection_or_set_identity_digest() and such know where to look to
1210 * keep the channel up to date.
1212 conn->chan = chan;
1213 chan->conn = conn;
1214 connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
1215 connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
1216 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1218 conn->is_outgoing = 1;
1220 /* If we are using a proxy server, find it and use it. */
1221 r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
1222 if (r == 0) {
1223 conn->proxy_type = proxy_type;
1224 if (proxy_type != PROXY_NONE) {
1225 tor_addr_copy(&addr, &proxy_addr);
1226 port = proxy_port;
1227 conn->base_.proxy_state = PROXY_INFANT;
1229 } else {
1230 /* get_proxy_addrport() might fail if we have a Bridge line that
1231 references a transport, but no ClientTransportPlugin lines
1232 defining its transport proxy. If this is the case, let's try to
1233 output a useful log message to the user. */
1234 const char *transport_name =
1235 find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
1236 TO_CONN(conn)->port);
1238 if (transport_name) {
1239 log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1240 "using pluggable transport '%s', but we can't find a pluggable "
1241 "transport proxy supporting '%s'. This can happen if you "
1242 "haven't provided a ClientTransportPlugin line, or if "
1243 "your pluggable transport proxy stopped running.",
1244 fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
1245 transport_name, transport_name);
1247 control_event_bootstrap_problem(
1248 "Can't connect to bridge",
1249 END_OR_CONN_REASON_PT_MISSING,
1250 conn);
1252 } else {
1253 log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
1254 "the proxy address could not be found.",
1255 fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
1258 connection_free(TO_CONN(conn));
1259 return NULL;
1262 switch (connection_connect(TO_CONN(conn), conn->base_.address,
1263 &addr, port, &socket_error)) {
1264 case -1:
1265 /* If the connection failed immediately, and we're using
1266 * a proxy, our proxy is down. Don't blame the Tor server. */
1267 if (conn->base_.proxy_state == PROXY_INFANT)
1268 entry_guard_register_connect_status(conn->identity_digest,
1269 0, 1, time(NULL));
1270 connection_or_connect_failed(conn,
1271 errno_to_orconn_end_reason(socket_error),
1272 tor_socket_strerror(socket_error));
1273 connection_free(TO_CONN(conn));
1274 return NULL;
1275 case 0:
1276 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
1277 /* writable indicates finish, readable indicates broken link,
1278 error indicates broken link on windows */
1279 return conn;
1280 /* case 1: fall through */
1283 if (connection_or_finished_connecting(conn) < 0) {
1284 /* already marked for close */
1285 return NULL;
1287 return conn;
1290 /** Mark orconn for close and transition the associated channel, if any, to
1291 * the closing state.
1293 * It's safe to call this and connection_or_close_for_error() any time, and
1294 * channel layer will treat it as a connection closing for reasons outside
1295 * its control, like the remote end closing it. It can also be a local
1296 * reason that's specific to connection_t/or_connection_t rather than
1297 * the channel mechanism, such as expiration of old connections in
1298 * run_connection_housekeeping(). If you want to close a channel_t
1299 * from somewhere that logically works in terms of generic channels
1300 * rather than connections, use channel_mark_for_close(); see also
1301 * the comment on that function in channel.c.
1304 void
1305 connection_or_close_normally(or_connection_t *orconn, int flush)
1307 channel_t *chan = NULL;
1309 tor_assert(orconn);
1310 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1311 else connection_mark_for_close_internal(TO_CONN(orconn));
1312 if (orconn->chan) {
1313 chan = TLS_CHAN_TO_BASE(orconn->chan);
1314 /* Don't transition if we're already in closing, closed or error */
1315 if (!(chan->state == CHANNEL_STATE_CLOSING ||
1316 chan->state == CHANNEL_STATE_CLOSED ||
1317 chan->state == CHANNEL_STATE_ERROR)) {
1318 channel_close_from_lower_layer(chan);
1323 /** Mark orconn for close and transition the associated channel, if any, to
1324 * the error state.
1327 void
1328 connection_or_close_for_error(or_connection_t *orconn, int flush)
1330 channel_t *chan = NULL;
1332 tor_assert(orconn);
1333 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1334 else connection_mark_for_close_internal(TO_CONN(orconn));
1335 if (orconn->chan) {
1336 chan = TLS_CHAN_TO_BASE(orconn->chan);
1337 /* Don't transition if we're already in closing, closed or error */
1338 if (!(chan->state == CHANNEL_STATE_CLOSING ||
1339 chan->state == CHANNEL_STATE_CLOSED ||
1340 chan->state == CHANNEL_STATE_ERROR)) {
1341 channel_close_for_error(chan);
1346 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
1347 * we initiated the connection, else it's 1.
1349 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
1350 * pass <b>conn</b> to connection_tls_continue_handshake().
1352 * Return -1 if <b>conn</b> is broken, else return 0.
1354 MOCK_IMPL(int,
1355 connection_tls_start_handshake,(or_connection_t *conn, int receiving))
1357 channel_listener_t *chan_listener;
1358 channel_t *chan;
1360 /* Incoming connections will need a new channel passed to the
1361 * channel_tls_listener */
1362 if (receiving) {
1363 /* It shouldn't already be set */
1364 tor_assert(!(conn->chan));
1365 chan_listener = channel_tls_get_listener();
1366 if (!chan_listener) {
1367 chan_listener = channel_tls_start_listener();
1368 command_setup_listener(chan_listener);
1370 chan = channel_tls_handle_incoming(conn);
1371 channel_listener_queue_incoming(chan_listener, chan);
1374 connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
1375 tor_assert(!conn->tls);
1376 conn->tls = tor_tls_new(conn->base_.s, receiving);
1377 if (!conn->tls) {
1378 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1379 return -1;
1381 tor_tls_set_logged_address(conn->tls, // XXX client and relay?
1382 escaped_safe_str(conn->base_.address));
1384 #ifdef USE_BUFFEREVENTS
1385 if (connection_type_uses_bufferevent(TO_CONN(conn))) {
1386 const int filtering = get_options()->UseFilteringSSLBufferevents;
1387 struct bufferevent *b =
1388 tor_tls_init_bufferevent(conn->tls, conn->base_.bufev, conn->base_.s,
1389 receiving, filtering);
1390 if (!b) {
1391 log_warn(LD_BUG,"tor_tls_init_bufferevent failed. Closing.");
1392 return -1;
1394 conn->base_.bufev = b;
1395 if (conn->bucket_cfg)
1396 tor_set_bufferevent_rate_limit(conn->base_.bufev, conn->bucket_cfg);
1397 connection_enable_rate_limiting(TO_CONN(conn));
1399 connection_configure_bufferevent_callbacks(TO_CONN(conn));
1400 bufferevent_setcb(b,
1401 connection_handle_read_cb,
1402 connection_handle_write_cb,
1403 connection_or_handle_event_cb,/* overriding this one*/
1404 TO_CONN(conn));
1406 #endif
1407 connection_start_reading(TO_CONN(conn));
1408 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1409 conn->base_.s);
1410 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
1412 IF_HAS_BUFFEREVENT(TO_CONN(conn), {
1413 /* ???? */;
1414 }) ELSE_IF_NO_BUFFEREVENT {
1415 if (connection_tls_continue_handshake(conn) < 0)
1416 return -1;
1418 return 0;
1421 /** Block all future attempts to renegotiate on 'conn' */
1422 void
1423 connection_or_block_renegotiation(or_connection_t *conn)
1425 tor_tls_t *tls = conn->tls;
1426 if (!tls)
1427 return;
1428 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
1429 tor_tls_block_renegotiation(tls);
1432 /** Invoked on the server side from inside tor_tls_read() when the server
1433 * gets a successful TLS renegotiation from the client. */
1434 static void
1435 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
1437 or_connection_t *conn = _conn;
1438 (void)tls;
1440 /* Don't invoke this again. */
1441 connection_or_block_renegotiation(conn);
1443 if (connection_tls_finish_handshake(conn) < 0) {
1444 /* XXXX_TLS double-check that it's ok to do this from inside read. */
1445 /* XXXX_TLS double-check that this verifies certificates. */
1446 connection_or_close_for_error(conn, 0);
1450 /** Move forward with the tls handshake. If it finishes, hand
1451 * <b>conn</b> to connection_tls_finish_handshake().
1453 * Return -1 if <b>conn</b> is broken, else return 0.
1456 connection_tls_continue_handshake(or_connection_t *conn)
1458 int result;
1459 check_no_tls_errors();
1460 again:
1461 if (conn->base_.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
1462 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
1463 result = tor_tls_renegotiate(conn->tls);
1464 // log_notice(LD_OR, "Result: %d", result);
1465 } else {
1466 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1467 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1468 result = tor_tls_handshake(conn->tls);
1469 // log_notice(LD_OR, "Result: %d", result);
1471 switch (result) {
1472 CASE_TOR_TLS_ERROR_ANY:
1473 log_info(LD_OR,"tls error [%s]. breaking connection.",
1474 tor_tls_err_to_string(result));
1475 return -1;
1476 case TOR_TLS_DONE:
1477 if (! tor_tls_used_v1_handshake(conn->tls)) {
1478 if (!tor_tls_is_server(conn->tls)) {
1479 if (conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING) {
1480 if (tor_tls_received_v3_certificate(conn->tls)) {
1481 log_info(LD_OR, "Client got a v3 cert! Moving on to v3 "
1482 "handshake with ciphersuite %s",
1483 tor_tls_get_ciphersuite_name(conn->tls));
1484 return connection_or_launch_v3_or_handshake(conn);
1485 } else {
1486 log_debug(LD_OR, "Done with initial SSL handshake (client-side)."
1487 " Requesting renegotiation.");
1488 connection_or_change_state(conn,
1489 OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING);
1490 goto again;
1493 // log_notice(LD_OR,"Done. state was %d.", conn->base_.state);
1494 } else {
1495 /* v2/v3 handshake, but not a client. */
1496 log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1497 "Expecting renegotiation or VERSIONS cell");
1498 tor_tls_set_renegotiate_callback(conn->tls,
1499 connection_or_tls_renegotiated_cb,
1500 conn);
1501 connection_or_change_state(conn,
1502 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1503 connection_stop_writing(TO_CONN(conn));
1504 connection_start_reading(TO_CONN(conn));
1505 return 0;
1508 return connection_tls_finish_handshake(conn);
1509 case TOR_TLS_WANTWRITE:
1510 connection_start_writing(TO_CONN(conn));
1511 log_debug(LD_OR,"wanted write");
1512 return 0;
1513 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1514 log_debug(LD_OR,"wanted read");
1515 return 0;
1516 case TOR_TLS_CLOSE:
1517 log_info(LD_OR,"tls closed. breaking connection.");
1518 return -1;
1520 return 0;
1523 #ifdef USE_BUFFEREVENTS
1524 static void
1525 connection_or_handle_event_cb(struct bufferevent *bufev, short event,
1526 void *arg)
1528 struct or_connection_t *conn = TO_OR_CONN(arg);
1530 /* XXXX cut-and-paste code; should become a function. */
1531 if (event & BEV_EVENT_CONNECTED) {
1532 if (conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING) {
1533 if (tor_tls_finish_handshake(conn->tls) < 0) {
1534 log_warn(LD_OR, "Problem finishing handshake");
1535 connection_or_close_for_error(conn, 0);
1536 return;
1540 if (! tor_tls_used_v1_handshake(conn->tls)) {
1541 if (!tor_tls_is_server(conn->tls)) {
1542 if (conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING) {
1543 if (tor_tls_received_v3_certificate(conn->tls)) {
1544 log_info(LD_OR, "Client got a v3 cert!");
1545 if (connection_or_launch_v3_or_handshake(conn) < 0)
1546 connection_or_close_for_error(conn, 0);
1547 return;
1548 } else {
1549 connection_or_change_state(conn,
1550 OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING);
1551 tor_tls_unblock_renegotiation(conn->tls);
1552 if (bufferevent_ssl_renegotiate(conn->base_.bufev)<0) {
1553 log_warn(LD_OR, "Start_renegotiating went badly.");
1554 connection_or_close_for_error(conn, 0);
1556 tor_tls_unblock_renegotiation(conn->tls);
1557 return; /* ???? */
1560 } else {
1561 const int handshakes = tor_tls_get_num_server_handshakes(conn->tls);
1563 if (handshakes == 1) {
1564 /* v2 or v3 handshake, as a server. Only got one handshake, so
1565 * wait for the next one. */
1566 tor_tls_set_renegotiate_callback(conn->tls,
1567 connection_or_tls_renegotiated_cb,
1568 conn);
1569 connection_or_change_state(conn,
1570 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1571 } else if (handshakes == 2) {
1572 /* v2 handshake, as a server. Two handshakes happened already,
1573 * so we treat renegotiation as done.
1575 connection_or_tls_renegotiated_cb(conn->tls, conn);
1576 } else if (handshakes > 2) {
1577 log_warn(LD_OR, "More than two handshakes done on connection. "
1578 "Closing.");
1579 connection_or_close_for_error(conn, 0);
1580 } else {
1581 log_warn(LD_BUG, "We were unexpectedly told that a connection "
1582 "got %d handshakes. Closing.", handshakes);
1583 connection_or_close_for_error(conn, 0);
1585 return;
1588 connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
1589 if (connection_tls_finish_handshake(conn) < 0)
1590 connection_or_close_for_error(conn, 0); /* ???? */
1591 return;
1594 if (event & BEV_EVENT_ERROR) {
1595 unsigned long err;
1596 while ((err = bufferevent_get_openssl_error(bufev))) {
1597 tor_tls_log_one_error(conn->tls, err, LOG_WARN, LD_OR,
1598 "handshaking (with bufferevent)");
1602 connection_handle_event_cb(bufev, event, arg);
1604 #endif
1606 /** Return 1 if we initiated this connection, or 0 if it started
1607 * out as an incoming connection.
1610 connection_or_nonopen_was_started_here(or_connection_t *conn)
1612 tor_assert(conn->base_.type == CONN_TYPE_OR ||
1613 conn->base_.type == CONN_TYPE_EXT_OR);
1614 if (!conn->tls)
1615 return 1; /* it's still in proxy states or something */
1616 if (conn->handshake_state)
1617 return conn->handshake_state->started_here;
1618 return !tor_tls_is_server(conn->tls);
1621 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
1622 * return -1 if he is lying, broken, or otherwise something is wrong.
1624 * If we initiated this connection (<b>started_here</b> is true), make sure
1625 * the other side sent a correctly formed certificate. If I initiated the
1626 * connection, make sure it's the right guy.
1628 * Otherwise (if we _didn't_ initiate this connection), it's okay for
1629 * the certificate to be weird or absent.
1631 * If we return 0, and the certificate is as expected, write a hash of the
1632 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
1633 * space in it.
1634 * If the certificate is invalid or missing on an incoming connection,
1635 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
1636 * (If we return -1, the contents of this buffer are undefined.)
1638 * As side effects,
1639 * 1) Set conn->circ_id_type according to tor-spec.txt.
1640 * 2) If we're an authdirserver and we initiated the connection: drop all
1641 * descriptors that claim to be on that IP/port but that aren't
1642 * this guy; and note that this guy is reachable.
1643 * 3) If this is a bridge and we didn't configure its identity
1644 * fingerprint, remember the keyid we just learned.
1646 static int
1647 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1648 int started_here,
1649 char *digest_rcvd_out)
1651 crypto_pk_t *identity_rcvd=NULL;
1652 const or_options_t *options = get_options();
1653 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1654 const char *safe_address =
1655 started_here ? conn->base_.address :
1656 safe_str_client(conn->base_.address);
1657 const char *conn_type = started_here ? "outgoing" : "incoming";
1658 int has_cert = 0;
1660 check_no_tls_errors();
1661 has_cert = tor_tls_peer_has_cert(conn->tls);
1662 if (started_here && !has_cert) {
1663 log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1664 "send a cert! Closing.",
1665 safe_address, conn->base_.port);
1666 return -1;
1667 } else if (!has_cert) {
1668 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1669 "That's ok.");
1671 check_no_tls_errors();
1673 if (has_cert) {
1674 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1675 conn->tls, &identity_rcvd);
1676 if (started_here && v<0) {
1677 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1678 " has a cert but it's invalid. Closing.",
1679 safe_address, conn->base_.port);
1680 return -1;
1681 } else if (v<0) {
1682 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1683 "chain; ignoring.");
1684 } else {
1685 log_debug(LD_HANDSHAKE,
1686 "The certificate seems to be valid on %s connection "
1687 "with %s:%d", conn_type, safe_address, conn->base_.port);
1689 check_no_tls_errors();
1692 if (identity_rcvd) {
1693 crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
1694 } else {
1695 memset(digest_rcvd_out, 0, DIGEST_LEN);
1698 tor_assert(conn->chan);
1699 channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
1701 crypto_pk_free(identity_rcvd);
1703 if (started_here)
1704 return connection_or_client_learned_peer_id(conn,
1705 (const uint8_t*)digest_rcvd_out);
1707 return 0;
1710 /** Called when we (as a connection initiator) have definitively,
1711 * authenticatedly, learned that ID of the Tor instance on the other
1712 * side of <b>conn</b> is <b>peer_id</b>. For v1 and v2 handshakes,
1713 * this is right after we get a certificate chain in a TLS handshake
1714 * or renegotiation. For v3 handshakes, this is right after we get a
1715 * certificate chain in a CERTS cell.
1717 * If we want any particular ID before, record the one we got.
1719 * If we wanted an ID, but we didn't get it, log a warning and return -1.
1721 * If we're testing reachability, remember what we learned.
1723 * Return 0 on success, -1 on failure.
1726 connection_or_client_learned_peer_id(or_connection_t *conn,
1727 const uint8_t *peer_id)
1729 const or_options_t *options = get_options();
1730 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1732 if (tor_digest_is_zero(conn->identity_digest)) {
1733 connection_or_set_identity_digest(conn, (const char*)peer_id);
1734 tor_free(conn->nickname);
1735 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1736 conn->nickname[0] = '$';
1737 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1738 conn->identity_digest, DIGEST_LEN);
1739 log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1740 "its key. Hoping for the best.",
1741 conn->nickname, conn->base_.address, conn->base_.port);
1742 /* if it's a bridge and we didn't know its identity fingerprint, now
1743 * we do -- remember it for future attempts. */
1744 learned_router_identity(&conn->base_.addr, conn->base_.port,
1745 (const char*)peer_id);
1748 if (tor_memneq(peer_id, conn->identity_digest, DIGEST_LEN)) {
1749 /* I was aiming for a particular digest. I didn't get it! */
1750 char seen[HEX_DIGEST_LEN+1];
1751 char expected[HEX_DIGEST_LEN+1];
1752 base16_encode(seen, sizeof(seen), (const char*)peer_id, DIGEST_LEN);
1753 base16_encode(expected, sizeof(expected), conn->identity_digest,
1754 DIGEST_LEN);
1755 log_fn(severity, LD_HANDSHAKE,
1756 "Tried connecting to router at %s:%d, but identity key was not "
1757 "as expected: wanted %s but got %s.",
1758 conn->base_.address, conn->base_.port, expected, seen);
1759 entry_guard_register_connect_status(conn->identity_digest, 0, 1,
1760 time(NULL));
1761 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1762 END_OR_CONN_REASON_OR_IDENTITY);
1763 if (!authdir_mode_tests_reachability(options))
1764 control_event_bootstrap_problem(
1765 "Unexpected identity in router certificate",
1766 END_OR_CONN_REASON_OR_IDENTITY,
1767 conn);
1768 return -1;
1770 if (authdir_mode_tests_reachability(options)) {
1771 dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
1772 (const char*)peer_id);
1775 return 0;
1778 /** Return when a client used this, for connection.c, since client_used
1779 * is now one of the timestamps of channel_t */
1781 time_t
1782 connection_or_client_used(or_connection_t *conn)
1784 tor_assert(conn);
1786 if (conn->chan) {
1787 return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
1788 } else return 0;
1791 /** The v1/v2 TLS handshake is finished.
1793 * Make sure we are happy with the person we just handshaked with.
1795 * If he initiated the connection, make sure he's not already connected,
1796 * then initialize conn from the information in router.
1798 * If all is successful, call circuit_n_conn_done() to handle events
1799 * that have been pending on the <tls handshake completion. Also set the
1800 * directory to be dirty (only matters if I'm an authdirserver).
1802 * If this is a v2 TLS handshake, send a versions cell.
1804 static int
1805 connection_tls_finish_handshake(or_connection_t *conn)
1807 char digest_rcvd[DIGEST_LEN];
1808 int started_here = connection_or_nonopen_was_started_here(conn);
1810 log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
1811 "ciphersuite %s. verifying.",
1812 started_here?"outgoing":"incoming",
1813 conn,
1814 safe_str_client(conn->base_.address),
1815 tor_tls_get_ciphersuite_name(conn->tls));
1817 if (connection_or_check_valid_tls_handshake(conn, started_here,
1818 digest_rcvd) < 0)
1819 return -1;
1821 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1823 if (tor_tls_used_v1_handshake(conn->tls)) {
1824 conn->link_proto = 1;
1825 if (!started_here) {
1826 connection_or_init_conn_from_address(conn, &conn->base_.addr,
1827 conn->base_.port, digest_rcvd, 0);
1829 tor_tls_block_renegotiation(conn->tls);
1830 return connection_or_set_state_open(conn);
1831 } else {
1832 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V2);
1833 if (connection_init_or_handshake_state(conn, started_here) < 0)
1834 return -1;
1835 if (!started_here) {
1836 connection_or_init_conn_from_address(conn, &conn->base_.addr,
1837 conn->base_.port, digest_rcvd, 0);
1839 return connection_or_send_versions(conn, 0);
1844 * Called as client when initial TLS handshake is done, and we notice
1845 * that we got a v3-handshake signalling certificate from the server.
1846 * Set up structures, do bookkeeping, and send the versions cell.
1847 * Return 0 on success and -1 on failure.
1849 static int
1850 connection_or_launch_v3_or_handshake(or_connection_t *conn)
1852 tor_assert(connection_or_nonopen_was_started_here(conn));
1853 tor_assert(tor_tls_received_v3_certificate(conn->tls));
1855 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1857 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
1858 if (connection_init_or_handshake_state(conn, 1) < 0)
1859 return -1;
1861 return connection_or_send_versions(conn, 1);
1864 /** Allocate a new connection handshake state for the connection
1865 * <b>conn</b>. Return 0 on success, -1 on failure. */
1867 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
1869 or_handshake_state_t *s;
1870 if (conn->handshake_state) {
1871 log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
1872 return 0;
1874 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
1875 s->started_here = started_here ? 1 : 0;
1876 s->digest_sent_data = 1;
1877 s->digest_received_data = 1;
1878 return 0;
1881 /** Free all storage held by <b>state</b>. */
1882 void
1883 or_handshake_state_free(or_handshake_state_t *state)
1885 if (!state)
1886 return;
1887 crypto_digest_free(state->digest_sent);
1888 crypto_digest_free(state->digest_received);
1889 tor_cert_free(state->auth_cert);
1890 tor_cert_free(state->id_cert);
1891 memwipe(state, 0xBE, sizeof(or_handshake_state_t));
1892 tor_free(state);
1896 * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
1897 * false) or received (if <b>incoming</b> is true) during a V3 handshake using
1898 * <b>state</b>.
1900 * (We don't record the cell, but we keep a digest of everything sent or
1901 * received during the v3 handshake, and the client signs it in an
1902 * authenticate cell.)
1904 void
1905 or_handshake_state_record_cell(or_connection_t *conn,
1906 or_handshake_state_t *state,
1907 const cell_t *cell,
1908 int incoming)
1910 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
1911 crypto_digest_t *d, **dptr;
1912 packed_cell_t packed;
1913 if (incoming) {
1914 if (!state->digest_received_data)
1915 return;
1916 } else {
1917 if (!state->digest_sent_data)
1918 return;
1920 if (!incoming) {
1921 log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
1922 "while making a handshake digest. But we think we are sending "
1923 "one with type %d.", (int)cell->command);
1925 dptr = incoming ? &state->digest_received : &state->digest_sent;
1926 if (! *dptr)
1927 *dptr = crypto_digest256_new(DIGEST_SHA256);
1929 d = *dptr;
1930 /* Re-packing like this is a little inefficient, but we don't have to do
1931 this very often at all. */
1932 cell_pack(&packed, cell, conn->wide_circ_ids);
1933 crypto_digest_add_bytes(d, packed.body, cell_network_size);
1934 memwipe(&packed, 0, sizeof(packed));
1937 /** Remember that a variable-length <b>cell</b> has been transmitted (if
1938 * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
1939 * V3 handshake using <b>state</b>.
1941 * (We don't record the cell, but we keep a digest of everything sent or
1942 * received during the v3 handshake, and the client signs it in an
1943 * authenticate cell.)
1945 void
1946 or_handshake_state_record_var_cell(or_connection_t *conn,
1947 or_handshake_state_t *state,
1948 const var_cell_t *cell,
1949 int incoming)
1951 crypto_digest_t *d, **dptr;
1952 int n;
1953 char buf[VAR_CELL_MAX_HEADER_SIZE];
1954 if (incoming) {
1955 if (!state->digest_received_data)
1956 return;
1957 } else {
1958 if (!state->digest_sent_data)
1959 return;
1961 dptr = incoming ? &state->digest_received : &state->digest_sent;
1962 if (! *dptr)
1963 *dptr = crypto_digest256_new(DIGEST_SHA256);
1965 d = *dptr;
1967 n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
1968 crypto_digest_add_bytes(d, buf, n);
1969 crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
1971 memwipe(buf, 0, sizeof(buf));
1974 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1975 * as appropriate. Called when we are done with all TLS and OR handshaking.
1978 connection_or_set_state_open(or_connection_t *conn)
1980 connection_or_change_state(conn, OR_CONN_STATE_OPEN);
1981 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
1983 or_handshake_state_free(conn->handshake_state);
1984 conn->handshake_state = NULL;
1985 IF_HAS_BUFFEREVENT(TO_CONN(conn), {
1986 connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
1987 }) ELSE_IF_NO_BUFFEREVENT {
1988 connection_start_reading(TO_CONN(conn));
1991 return 0;
1994 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1995 * For cells that use or affect a circuit, this should only be called by
1996 * connection_or_flush_from_first_active_circuit().
1998 void
1999 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
2001 packed_cell_t networkcell;
2002 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2004 tor_assert(cell);
2005 tor_assert(conn);
2007 cell_pack(&networkcell, cell, conn->wide_circ_ids);
2009 connection_write_to_buf(networkcell.body, cell_network_size, TO_CONN(conn));
2011 /* Touch the channel's active timestamp if there is one */
2012 if (conn->chan)
2013 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2015 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2016 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2019 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
2020 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
2021 * affect a circuit.
2023 void
2024 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
2025 or_connection_t *conn)
2027 int n;
2028 char hdr[VAR_CELL_MAX_HEADER_SIZE];
2029 tor_assert(cell);
2030 tor_assert(conn);
2031 n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2032 connection_write_to_buf(hdr, n, TO_CONN(conn));
2033 connection_write_to_buf((char*)cell->payload,
2034 cell->payload_len, TO_CONN(conn));
2035 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2036 or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
2038 /* Touch the channel's active timestamp if there is one */
2039 if (conn->chan)
2040 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2043 /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
2044 * inbuf. Return values as for fetch_var_cell_from_buf(). */
2045 static int
2046 connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
2048 connection_t *conn = TO_CONN(or_conn);
2049 IF_HAS_BUFFEREVENT(conn, {
2050 struct evbuffer *input = bufferevent_get_input(conn->bufev);
2051 return fetch_var_cell_from_evbuffer(input, out, or_conn->link_proto);
2052 }) ELSE_IF_NO_BUFFEREVENT {
2053 return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2057 /** Process cells from <b>conn</b>'s inbuf.
2059 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
2060 * and hand it to command_process_cell().
2062 * Always return 0.
2064 static int
2065 connection_or_process_cells_from_inbuf(or_connection_t *conn)
2067 var_cell_t *var_cell;
2069 while (1) {
2070 log_debug(LD_OR,
2071 TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2072 "(%d pending in tls object).",
2073 conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2074 tor_tls_get_pending_bytes(conn->tls));
2075 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2076 if (!var_cell)
2077 return 0; /* not yet. */
2079 /* Touch the channel's active timestamp if there is one */
2080 if (conn->chan)
2081 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2083 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2084 channel_tls_handle_var_cell(var_cell, conn);
2085 var_cell_free(var_cell);
2086 } else {
2087 const int wide_circ_ids = conn->wide_circ_ids;
2088 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2089 char buf[CELL_MAX_NETWORK_SIZE];
2090 cell_t cell;
2091 if (connection_get_inbuf_len(TO_CONN(conn))
2092 < cell_network_size) /* whole response available? */
2093 return 0; /* not yet */
2095 /* Touch the channel's active timestamp if there is one */
2096 if (conn->chan)
2097 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2099 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2100 connection_fetch_from_buf(buf, cell_network_size, TO_CONN(conn));
2102 /* retrieve cell info from buf (create the host-order struct from the
2103 * network-order string) */
2104 cell_unpack(&cell, buf, wide_circ_ids);
2106 channel_tls_handle_cell(&cell, conn);
2111 /** Array of recognized link protocol versions. */
2112 static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4 };
2113 /** Number of versions in <b>or_protocol_versions</b>. */
2114 static const int n_or_protocol_versions =
2115 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2117 /** Return true iff <b>v</b> is a link protocol version that this Tor
2118 * implementation believes it can support. */
2120 is_or_protocol_version_known(uint16_t v)
2122 int i;
2123 for (i = 0; i < n_or_protocol_versions; ++i) {
2124 if (or_protocol_versions[i] == v)
2125 return 1;
2127 return 0;
2130 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
2131 * link protocol versions that this Tor can support.
2133 * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
2134 * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
2135 * not part of a v3 protocol handshake, so don't allow protocol v3 or
2136 * later.
2139 connection_or_send_versions(or_connection_t *conn, int v3_plus)
2141 var_cell_t *cell;
2142 int i;
2143 int n_versions = 0;
2144 const int min_version = v3_plus ? 3 : 0;
2145 const int max_version = v3_plus ? UINT16_MAX : 2;
2146 tor_assert(conn->handshake_state &&
2147 !conn->handshake_state->sent_versions_at);
2148 cell = var_cell_new(n_or_protocol_versions * 2);
2149 cell->command = CELL_VERSIONS;
2150 for (i = 0; i < n_or_protocol_versions; ++i) {
2151 uint16_t v = or_protocol_versions[i];
2152 if (v < min_version || v > max_version)
2153 continue;
2154 set_uint16(cell->payload+(2*n_versions), htons(v));
2155 ++n_versions;
2157 cell->payload_len = n_versions * 2;
2159 connection_or_write_var_cell_to_buf(cell, conn);
2160 conn->handshake_state->sent_versions_at = time(NULL);
2162 var_cell_free(cell);
2163 return 0;
2166 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
2167 * about their address, our address, and the current time. */
2169 connection_or_send_netinfo(or_connection_t *conn)
2171 cell_t cell;
2172 time_t now = time(NULL);
2173 const routerinfo_t *me;
2174 int len;
2175 uint8_t *out;
2177 tor_assert(conn->handshake_state);
2179 if (conn->handshake_state->sent_netinfo) {
2180 log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2181 "where we already sent one.");
2182 return 0;
2185 memset(&cell, 0, sizeof(cell_t));
2186 cell.command = CELL_NETINFO;
2188 /* Timestamp, if we're a relay. */
2189 if (public_server_mode(get_options()) || ! conn->is_outgoing)
2190 set_uint32(cell.payload, htonl((uint32_t)now));
2192 /* Their address. */
2193 out = cell.payload + 4;
2194 /* We use &conn->real_addr below, unless it hasn't yet been set. If it
2195 * hasn't yet been set, we know that base_.addr hasn't been tampered with
2196 * yet either. */
2197 len = append_address_to_payload(out, !tor_addr_is_null(&conn->real_addr)
2198 ? &conn->real_addr : &conn->base_.addr);
2199 if (len<0)
2200 return -1;
2201 out += len;
2203 /* My address -- only include it if I'm a public relay, or if I'm a
2204 * bridge and this is an incoming connection. If I'm a bridge and this
2205 * is an outgoing connection, act like a normal client and omit it. */
2206 if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2207 (me = router_get_my_routerinfo())) {
2208 tor_addr_t my_addr;
2209 *out++ = 1 + !tor_addr_is_null(&me->ipv6_addr);
2211 tor_addr_from_ipv4h(&my_addr, me->addr);
2212 len = append_address_to_payload(out, &my_addr);
2213 if (len < 0)
2214 return -1;
2215 out += len;
2217 if (!tor_addr_is_null(&me->ipv6_addr)) {
2218 len = append_address_to_payload(out, &me->ipv6_addr);
2219 if (len < 0)
2220 return -1;
2222 } else {
2223 *out = 0;
2226 conn->handshake_state->digest_sent_data = 0;
2227 conn->handshake_state->sent_netinfo = 1;
2228 connection_or_write_cell_to_buf(&cell, conn);
2230 return 0;
2233 /** Send a CERTS cell on the connection <b>conn</b>. Return 0 on success, -1
2234 * on failure. */
2236 connection_or_send_certs_cell(or_connection_t *conn)
2238 const tor_cert_t *link_cert = NULL, *id_cert = NULL;
2239 const uint8_t *link_encoded = NULL, *id_encoded = NULL;
2240 size_t link_len, id_len;
2241 var_cell_t *cell;
2242 size_t cell_len;
2243 ssize_t pos;
2244 int server_mode;
2246 tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
2248 if (! conn->handshake_state)
2249 return -1;
2250 server_mode = ! conn->handshake_state->started_here;
2251 if (tor_tls_get_my_certs(server_mode, &link_cert, &id_cert) < 0)
2252 return -1;
2253 tor_cert_get_der(link_cert, &link_encoded, &link_len);
2254 tor_cert_get_der(id_cert, &id_encoded, &id_len);
2256 cell_len = 1 /* 1 byte: num certs in cell */ +
2257 2 * ( 1 + 2 ) /* For each cert: 1 byte for type, 2 for length */ +
2258 link_len + id_len;
2259 cell = var_cell_new(cell_len);
2260 cell->command = CELL_CERTS;
2261 cell->payload[0] = 2;
2262 pos = 1;
2264 if (server_mode)
2265 cell->payload[pos] = OR_CERT_TYPE_TLS_LINK; /* Link cert */
2266 else
2267 cell->payload[pos] = OR_CERT_TYPE_AUTH_1024; /* client authentication */
2268 set_uint16(&cell->payload[pos+1], htons(link_len));
2269 memcpy(&cell->payload[pos+3], link_encoded, link_len);
2270 pos += 3 + link_len;
2272 cell->payload[pos] = OR_CERT_TYPE_ID_1024; /* ID cert */
2273 set_uint16(&cell->payload[pos+1], htons(id_len));
2274 memcpy(&cell->payload[pos+3], id_encoded, id_len);
2275 pos += 3 + id_len;
2277 tor_assert(pos == (int)cell_len); /* Otherwise we just smashed the heap */
2279 connection_or_write_var_cell_to_buf(cell, conn);
2280 var_cell_free(cell);
2282 return 0;
2285 /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
2286 * on success, -1 on failure. */
2288 connection_or_send_auth_challenge_cell(or_connection_t *conn)
2290 var_cell_t *cell;
2291 uint8_t *cp;
2292 uint8_t challenge[OR_AUTH_CHALLENGE_LEN];
2293 tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
2295 if (! conn->handshake_state)
2296 return -1;
2298 if (crypto_rand((char*)challenge, OR_AUTH_CHALLENGE_LEN) < 0)
2299 return -1;
2300 cell = var_cell_new(OR_AUTH_CHALLENGE_LEN + 4);
2301 cell->command = CELL_AUTH_CHALLENGE;
2302 memcpy(cell->payload, challenge, OR_AUTH_CHALLENGE_LEN);
2303 cp = cell->payload + OR_AUTH_CHALLENGE_LEN;
2304 set_uint16(cp, htons(1)); /* We recognize one authentication type. */
2305 set_uint16(cp+2, htons(AUTHTYPE_RSA_SHA256_TLSSECRET));
2307 connection_or_write_var_cell_to_buf(cell, conn);
2308 var_cell_free(cell);
2309 memwipe(challenge, 0, sizeof(challenge));
2311 return 0;
2314 /** Compute the main body of an AUTHENTICATE cell that a client can use
2315 * to authenticate itself on a v3 handshake for <b>conn</b>. Write it to the
2316 * <b>outlen</b>-byte buffer at <b>out</b>.
2318 * If <b>server</b> is true, only calculate the first
2319 * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
2320 * determined by the rest of the handshake, and which match the provided value
2321 * exactly.
2323 * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
2324 * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
2325 * that should be signed), but don't actually sign it.
2327 * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
2328 * entire authenticator, signed with <b>signing_key</b>.
2330 * Return the length of the cell body on success, and -1 on failure.
2333 connection_or_compute_authenticate_cell_body(or_connection_t *conn,
2334 uint8_t *out, size_t outlen,
2335 crypto_pk_t *signing_key,
2336 int server)
2338 uint8_t *ptr;
2340 /* assert state is reasonable XXXX */
2342 if (outlen < V3_AUTH_FIXED_PART_LEN ||
2343 (!server && outlen < V3_AUTH_BODY_LEN))
2344 return -1;
2346 ptr = out;
2348 /* Type: 8 bytes. */
2349 memcpy(ptr, "AUTH0001", 8);
2350 ptr += 8;
2353 const tor_cert_t *id_cert=NULL, *link_cert=NULL;
2354 const digests_t *my_digests, *their_digests;
2355 const uint8_t *my_id, *their_id, *client_id, *server_id;
2356 if (tor_tls_get_my_certs(server, &link_cert, &id_cert))
2357 return -1;
2358 my_digests = tor_cert_get_id_digests(id_cert);
2359 their_digests = tor_cert_get_id_digests(conn->handshake_state->id_cert);
2360 tor_assert(my_digests);
2361 tor_assert(their_digests);
2362 my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
2363 their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
2365 client_id = server ? their_id : my_id;
2366 server_id = server ? my_id : their_id;
2368 /* Client ID digest: 32 octets. */
2369 memcpy(ptr, client_id, 32);
2370 ptr += 32;
2372 /* Server ID digest: 32 octets. */
2373 memcpy(ptr, server_id, 32);
2374 ptr += 32;
2378 crypto_digest_t *server_d, *client_d;
2379 if (server) {
2380 server_d = conn->handshake_state->digest_sent;
2381 client_d = conn->handshake_state->digest_received;
2382 } else {
2383 client_d = conn->handshake_state->digest_sent;
2384 server_d = conn->handshake_state->digest_received;
2387 /* Server log digest : 32 octets */
2388 crypto_digest_get_digest(server_d, (char*)ptr, 32);
2389 ptr += 32;
2391 /* Client log digest : 32 octets */
2392 crypto_digest_get_digest(client_d, (char*)ptr, 32);
2393 ptr += 32;
2397 /* Digest of cert used on TLS link : 32 octets. */
2398 const tor_cert_t *cert = NULL;
2399 tor_cert_t *freecert = NULL;
2400 if (server) {
2401 tor_tls_get_my_certs(1, &cert, NULL);
2402 } else {
2403 freecert = tor_tls_get_peer_cert(conn->tls);
2404 cert = freecert;
2406 if (!cert)
2407 return -1;
2408 memcpy(ptr, tor_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
2410 if (freecert)
2411 tor_cert_free(freecert);
2412 ptr += 32;
2415 /* HMAC of clientrandom and serverrandom using master key : 32 octets */
2416 tor_tls_get_tlssecrets(conn->tls, ptr);
2417 ptr += 32;
2419 tor_assert(ptr - out == V3_AUTH_FIXED_PART_LEN);
2421 if (server)
2422 return V3_AUTH_FIXED_PART_LEN; // ptr-out
2424 /* 8 octets were reserved for the current time, but we're trying to get out
2425 * of the habit of sending time around willynilly. Fortunately, nothing
2426 * checks it. That's followed by 16 bytes of nonce. */
2427 crypto_rand((char*)ptr, 24);
2428 ptr += 24;
2430 tor_assert(ptr - out == V3_AUTH_BODY_LEN);
2432 if (!signing_key)
2433 return V3_AUTH_BODY_LEN; // ptr - out
2436 int siglen;
2437 char d[32];
2438 crypto_digest256(d, (char*)out, ptr-out, DIGEST_SHA256);
2439 siglen = crypto_pk_private_sign(signing_key,
2440 (char*)ptr, outlen - (ptr-out),
2441 d, 32);
2442 if (siglen < 0)
2443 return -1;
2445 ptr += siglen;
2446 tor_assert(ptr <= out+outlen);
2447 return (int)(ptr - out);
2451 /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
2452 * success, -1 on failure */
2454 connection_or_send_authenticate_cell(or_connection_t *conn, int authtype)
2456 var_cell_t *cell;
2457 crypto_pk_t *pk = tor_tls_get_my_client_auth_key();
2458 int authlen;
2459 size_t cell_maxlen;
2460 /* XXXX make sure we're actually supposed to send this! */
2462 if (!pk) {
2463 log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
2464 return -1;
2466 if (authtype != AUTHTYPE_RSA_SHA256_TLSSECRET) {
2467 log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
2468 "authentication type %d", authtype);
2469 return -1;
2472 cell_maxlen = 4 + /* overhead */
2473 V3_AUTH_BODY_LEN + /* Authentication body */
2474 crypto_pk_keysize(pk) + /* Max signature length */
2475 16 /* add a few extra bytes just in case. */;
2477 cell = var_cell_new(cell_maxlen);
2478 cell->command = CELL_AUTHENTICATE;
2479 set_uint16(cell->payload, htons(AUTHTYPE_RSA_SHA256_TLSSECRET));
2480 /* skip over length ; we don't know that yet. */
2482 authlen = connection_or_compute_authenticate_cell_body(conn,
2483 cell->payload+4,
2484 cell_maxlen-4,
2486 0 /* not server */);
2487 if (authlen < 0) {
2488 log_warn(LD_BUG, "Unable to compute authenticate cell!");
2489 var_cell_free(cell);
2490 return -1;
2492 tor_assert(authlen + 4 <= cell->payload_len);
2493 set_uint16(cell->payload+2, htons(authlen));
2494 cell->payload_len = authlen + 4;
2496 connection_or_write_var_cell_to_buf(cell, conn);
2497 var_cell_free(cell);
2499 return 0;