Use real_addr in send_netinfo
[tor.git] / src / or / connection_or.c
blob1fffba7733ef9730d70c34cb10d905a91f6cde4f
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-2011, 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 **/
13 #include "or.h"
14 #include "buffers.h"
15 #include "circuitbuild.h"
16 #include "command.h"
17 #include "config.h"
18 #include "connection.h"
19 #include "connection_or.h"
20 #include "control.h"
21 #include "dirserv.h"
22 #include "geoip.h"
23 #include "main.h"
24 #include "networkstatus.h"
25 #include "reasons.h"
26 #include "relay.h"
27 #include "rephist.h"
28 #include "router.h"
29 #include "routerlist.h"
31 static int connection_tls_finish_handshake(or_connection_t *conn);
32 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
33 static int connection_or_send_versions(or_connection_t *conn);
34 static int connection_init_or_handshake_state(or_connection_t *conn,
35 int started_here);
36 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
37 int started_here,
38 char *digest_rcvd_out);
40 /**************************************************************/
42 /** Map from identity digest of connected OR or desired OR to a connection_t
43 * with that identity digest. If there is more than one such connection_t,
44 * they form a linked list, with next_with_same_id as the next pointer. */
45 static digestmap_t *orconn_identity_map = NULL;
47 /** If conn is listed in orconn_identity_map, remove it, and clear
48 * conn->identity_digest. Otherwise do nothing. */
49 void
50 connection_or_remove_from_identity_map(or_connection_t *conn)
52 or_connection_t *tmp;
53 tor_assert(conn);
54 if (!orconn_identity_map)
55 return;
56 tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
57 if (!tmp) {
58 if (!tor_digest_is_zero(conn->identity_digest)) {
59 log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
60 "trying to remove it.",
61 conn->nickname ? conn->nickname : "NULL");
63 return;
65 if (conn == tmp) {
66 if (conn->next_with_same_id)
67 digestmap_set(orconn_identity_map, conn->identity_digest,
68 conn->next_with_same_id);
69 else
70 digestmap_remove(orconn_identity_map, conn->identity_digest);
71 } else {
72 while (tmp->next_with_same_id) {
73 if (tmp->next_with_same_id == conn) {
74 tmp->next_with_same_id = conn->next_with_same_id;
75 break;
77 tmp = tmp->next_with_same_id;
80 memset(conn->identity_digest, 0, DIGEST_LEN);
81 conn->next_with_same_id = NULL;
84 /** Remove all entries from the identity-to-orconn map, and clear
85 * all identities in OR conns.*/
86 void
87 connection_or_clear_identity_map(void)
89 smartlist_t *conns = get_connection_array();
90 SMARTLIST_FOREACH(conns, connection_t *, conn,
92 if (conn->type == CONN_TYPE_OR) {
93 or_connection_t *or_conn = TO_OR_CONN(conn);
94 memset(or_conn->identity_digest, 0, DIGEST_LEN);
95 or_conn->next_with_same_id = NULL;
97 });
99 digestmap_free(orconn_identity_map, NULL);
100 orconn_identity_map = NULL;
103 /** Change conn->identity_digest to digest, and add conn into
104 * orconn_digest_map. */
105 static void
106 connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
108 or_connection_t *tmp;
109 tor_assert(conn);
110 tor_assert(digest);
112 if (!orconn_identity_map)
113 orconn_identity_map = digestmap_new();
114 if (tor_memeq(conn->identity_digest, digest, DIGEST_LEN))
115 return;
117 /* If the identity was set previously, remove the old mapping. */
118 if (! tor_digest_is_zero(conn->identity_digest))
119 connection_or_remove_from_identity_map(conn);
121 memcpy(conn->identity_digest, digest, DIGEST_LEN);
123 /* If we're setting the ID to zero, don't add a mapping. */
124 if (tor_digest_is_zero(digest))
125 return;
127 tmp = digestmap_set(orconn_identity_map, digest, conn);
128 conn->next_with_same_id = tmp;
130 #if 1
131 /* Testing code to check for bugs in representation. */
132 for (; tmp; tmp = tmp->next_with_same_id) {
133 tor_assert(tor_memeq(tmp->identity_digest, digest, DIGEST_LEN));
134 tor_assert(tmp != conn);
136 #endif
139 /** Pack the cell_t host-order structure <b>src</b> into network-order
140 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
141 * wire format.
143 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
144 * should set it or clear it as appropriate.
146 void
147 cell_pack(packed_cell_t *dst, const cell_t *src)
149 char *dest = dst->body;
150 set_uint16(dest, htons(src->circ_id));
151 *(uint8_t*)(dest+2) = src->command;
152 memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
155 /** Unpack the network-order buffer <b>src</b> into a host-order
156 * cell_t structure <b>dest</b>.
158 static void
159 cell_unpack(cell_t *dest, const char *src)
161 dest->circ_id = ntohs(get_uint16(src));
162 dest->command = *(uint8_t*)(src+2);
163 memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
166 /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
167 * bytes of <b>hdr_out</b>. */
168 void
169 var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
171 set_uint16(hdr_out, htons(cell->circ_id));
172 set_uint8(hdr_out+2, cell->command);
173 set_uint16(hdr_out+3, htons(cell->payload_len));
176 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
177 * payload space. */
178 var_cell_t *
179 var_cell_new(uint16_t payload_len)
181 var_cell_t *cell = tor_malloc(sizeof(var_cell_t)+payload_len-1);
182 cell->payload_len = payload_len;
183 cell->command = 0;
184 cell->circ_id = 0;
185 return cell;
188 /** Release all space held by <b>cell</b>. */
189 void
190 var_cell_free(var_cell_t *cell)
192 tor_free(cell);
195 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
197 connection_or_reached_eof(or_connection_t *conn)
199 log_info(LD_OR,"OR connection reached EOF. Closing.");
200 connection_mark_for_close(TO_CONN(conn));
201 return 0;
204 /** Handle any new bytes that have come in on connection <b>conn</b>.
205 * If conn is in 'open' state, hand it to
206 * connection_or_process_cells_from_inbuf()
207 * (else do nothing).
210 connection_or_process_inbuf(or_connection_t *conn)
212 int ret;
213 tor_assert(conn);
215 switch (conn->_base.state) {
216 case OR_CONN_STATE_PROXY_HANDSHAKING:
217 ret = connection_read_proxy_handshake(TO_CONN(conn));
219 /* start TLS after handshake completion, or deal with error */
220 if (ret == 1) {
221 tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
222 if (connection_tls_start_handshake(conn, 0) < 0)
223 ret = -1;
225 if (ret < 0) {
226 connection_mark_for_close(TO_CONN(conn));
229 return ret;
230 case OR_CONN_STATE_OPEN:
231 case OR_CONN_STATE_OR_HANDSHAKING:
232 return connection_or_process_cells_from_inbuf(conn);
233 default:
234 return 0; /* don't do anything */
238 /** When adding cells to an OR connection's outbuf, keep adding until the
239 * outbuf is at least this long, or we run out of cells. */
240 #define OR_CONN_HIGHWATER (32*1024)
242 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
243 * drops below this size. */
244 #define OR_CONN_LOWWATER (16*1024)
246 /** Called whenever we have flushed some data on an or_conn: add more data
247 * from active circuits. */
249 connection_or_flushed_some(or_connection_t *conn)
251 size_t datalen = buf_datalen(conn->_base.outbuf);
252 /* If we're under the low water mark, add cells until we're just over the
253 * high water mark. */
254 if (datalen < OR_CONN_LOWWATER) {
255 ssize_t n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, CELL_NETWORK_SIZE);
256 time_t now = approx_time();
257 while (conn->active_circuits && n > 0) {
258 int flushed;
259 flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
260 n -= flushed;
263 return 0;
266 /** Connection <b>conn</b> has finished writing and has no bytes left on
267 * its outbuf.
269 * Otherwise it's in state "open": stop writing and return.
271 * If <b>conn</b> is broken, mark it for close and return -1, else
272 * return 0.
275 connection_or_finished_flushing(or_connection_t *conn)
277 tor_assert(conn);
278 assert_connection_ok(TO_CONN(conn),0);
280 switch (conn->_base.state) {
281 case OR_CONN_STATE_PROXY_HANDSHAKING:
282 case OR_CONN_STATE_OPEN:
283 case OR_CONN_STATE_OR_HANDSHAKING:
284 connection_stop_writing(TO_CONN(conn));
285 break;
286 default:
287 log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
288 tor_fragile_assert();
289 return -1;
291 return 0;
294 /** Connected handler for OR connections: begin the TLS handshake.
297 connection_or_finished_connecting(or_connection_t *or_conn)
299 int proxy_type;
300 connection_t *conn;
301 tor_assert(or_conn);
302 conn = TO_CONN(or_conn);
303 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
305 log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
306 conn->address,conn->port);
307 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
309 proxy_type = PROXY_NONE;
311 if (get_options()->HTTPSProxy)
312 proxy_type = PROXY_CONNECT;
313 else if (get_options()->Socks4Proxy)
314 proxy_type = PROXY_SOCKS4;
315 else if (get_options()->Socks5Proxy)
316 proxy_type = PROXY_SOCKS5;
318 if (proxy_type != PROXY_NONE) {
319 /* start proxy handshake */
320 if (connection_proxy_connect(conn, proxy_type) < 0) {
321 connection_mark_for_close(conn);
322 return -1;
325 connection_start_reading(conn);
326 conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
327 return 0;
330 if (connection_tls_start_handshake(or_conn, 0) < 0) {
331 /* TLS handshaking error of some kind. */
332 connection_mark_for_close(conn);
333 return -1;
335 return 0;
338 /** Return 1 if identity digest <b>id_digest</b> is known to be a
339 * currently or recently running relay. Otherwise return 0. */
341 connection_or_digest_is_known_relay(const char *id_digest)
343 if (router_get_consensus_status_by_id(id_digest))
344 return 1; /* It's in the consensus: "yes" */
345 if (router_get_by_digest(id_digest))
346 return 1; /* Not in the consensus, but we have a descriptor for
347 * it. Probably it was in a recent consensus. "Yes". */
348 return 0;
351 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
352 * relay, we will rely on the global read and write buckets, so give it
353 * per-conn limits that are big enough they'll never matter. But if it's
354 * not a known relay, first check if we set PerConnBwRate/Burst, then
355 * check if the consensus sets them, else default to 'big enough'.
357 * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
358 * clip the bucket if it happens to be <em>too</em> full.
360 static void
361 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
362 or_options_t *options)
364 int rate, burst; /* per-connection rate limiting params */
365 if (connection_or_digest_is_known_relay(conn->identity_digest)) {
366 /* It's in the consensus, or we have a descriptor for it meaning it
367 * was probably in a recent consensus. It's a recognized relay:
368 * give it full bandwidth. */
369 rate = (int)options->BandwidthRate;
370 burst = (int)options->BandwidthBurst;
371 } else {
372 /* Not a recognized relay. Squeeze it down based on the suggested
373 * bandwidth parameters in the consensus, but allow local config
374 * options to override. */
375 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
376 networkstatus_get_param(NULL, "perconnbwrate",
377 (int)options->BandwidthRate, 1, INT32_MAX);
378 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
379 networkstatus_get_param(NULL, "perconnbwburst",
380 (int)options->BandwidthBurst, 1, INT32_MAX);
383 conn->bandwidthrate = rate;
384 conn->bandwidthburst = burst;
385 if (reset) { /* set up the token buckets to be full */
386 conn->read_bucket = conn->write_bucket = burst;
387 return;
389 /* If the new token bucket is smaller, take out the extra tokens.
390 * (If it's larger, don't -- the buckets can grow to reach the cap.) */
391 if (conn->read_bucket > burst)
392 conn->read_bucket = burst;
393 if (conn->write_bucket > burst)
394 conn->write_bucket = burst;
397 /** Either our set of relays or our per-conn rate limits have changed.
398 * Go through all the OR connections and update their token buckets to make
399 * sure they don't exceed their maximum values. */
400 void
401 connection_or_update_token_buckets(smartlist_t *conns, or_options_t *options)
403 SMARTLIST_FOREACH(conns, connection_t *, conn,
405 if (connection_speaks_cells(conn))
406 connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
410 /** If we don't necessarily know the router we're connecting to, but we
411 * have an addr/port/id_digest, then fill in as much as we can. Start
412 * by checking to see if this describes a router we know. */
413 static void
414 connection_or_init_conn_from_address(or_connection_t *conn,
415 const tor_addr_t *addr, uint16_t port,
416 const char *id_digest,
417 int started_here)
419 routerinfo_t *r = router_get_by_digest(id_digest);
420 connection_or_set_identity_digest(conn, id_digest);
421 connection_or_update_token_buckets_helper(conn, 1, get_options());
423 conn->_base.port = port;
424 tor_addr_copy(&conn->_base.addr, addr);
425 tor_addr_copy(&conn->real_addr, addr);
426 if (r) {
427 /* XXXX proposal 118 will make this more complex. */
428 if (tor_addr_eq_ipv4h(&conn->_base.addr, r->addr))
429 conn->is_canonical = 1;
430 if (!started_here) {
431 /* Override the addr/port, so our log messages will make sense.
432 * This is dangerous, since if we ever try looking up a conn by
433 * its actual addr/port, we won't remember. Careful! */
434 /* XXXX arma: this is stupid, and it's the reason we need real_addr
435 * to track is_canonical properly. What requires it? */
436 /* XXXX <arma> i believe the reason we did this, originally, is because
437 * we wanted to log what OR a connection was to, and if we logged the
438 * right IP address and port 56244, that wouldn't be as helpful. now we
439 * log the "right" port too, so we know if it's moria1 or moria2.
441 tor_addr_from_ipv4h(&conn->_base.addr, r->addr);
442 conn->_base.port = r->or_port;
444 conn->nickname = tor_strdup(r->nickname);
445 tor_free(conn->_base.address);
446 conn->_base.address = tor_strdup(r->address);
447 } else {
448 const char *n;
449 /* If we're an authoritative directory server, we may know a
450 * nickname for this router. */
451 n = dirserv_get_nickname_by_digest(id_digest);
452 if (n) {
453 conn->nickname = tor_strdup(n);
454 } else {
455 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
456 conn->nickname[0] = '$';
457 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
458 conn->identity_digest, DIGEST_LEN);
460 tor_free(conn->_base.address);
461 conn->_base.address = tor_dup_addr(addr);
465 /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
467 * A more canonical connection is always better than a less canonical
468 * connection. That aside, a connection is better if it has circuits and the
469 * other does not, or if it was created more recently.
471 * Requires that both input connections are open; not is_bad_for_new_circs,
472 * and not impossibly non-canonical.
474 * If <b>forgive_new_connections</b> is true, then we do not call
475 * <b>a</b>better than <b>b</b> simply because b has no circuits,
476 * unless b is also relatively old.
478 static int
479 connection_or_is_better(time_t now,
480 const or_connection_t *a,
481 const or_connection_t *b,
482 int forgive_new_connections)
484 int newer;
485 /** Do not definitively deprecate a new connection with no circuits on it
486 * until this much time has passed. */
487 #define NEW_CONN_GRACE_PERIOD (15*60)
489 if (b->is_canonical && !a->is_canonical)
490 return 0; /* A canonical connection is better than a non-canonical
491 * one, no matter how new it is or which has circuits. */
493 newer = b->_base.timestamp_created < a->_base.timestamp_created;
495 if (
496 /* We prefer canonical connections regardless of newness. */
497 (!b->is_canonical && a->is_canonical) ||
498 /* If both have circuits we prefer the newer: */
499 (b->n_circuits && a->n_circuits && newer) ||
500 /* If neither has circuits we prefer the newer: */
501 (!b->n_circuits && !a->n_circuits && newer))
502 return 1;
504 /* If one has no circuits and the other does... */
505 if (!b->n_circuits && a->n_circuits) {
506 /* Then it's bad, unless it's in its grace period and we're forgiving. */
507 if (forgive_new_connections &&
508 now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
509 return 0;
510 else
511 return 1;
514 return 0;
517 /** Return the OR connection we should use to extend a circuit to the router
518 * whose identity is <b>digest</b>, and whose address we believe (or have been
519 * told in an extend cell) is <b>target_addr</b>. If there is no good
520 * connection, set *<b>msg_out</b> to a message describing the connection's
521 * state and our next action, and set <b>launch_out</b> to a boolean for
522 * whether we should launch a new connection or not.
524 or_connection_t *
525 connection_or_get_for_extend(const char *digest,
526 const tor_addr_t *target_addr,
527 const char **msg_out,
528 int *launch_out)
530 or_connection_t *conn, *best=NULL;
531 int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
532 time_t now = approx_time();
534 tor_assert(msg_out);
535 tor_assert(launch_out);
537 if (!orconn_identity_map) {
538 *msg_out = "Router not connected (nothing is). Connecting.";
539 *launch_out = 1;
540 return NULL;
543 conn = digestmap_get(orconn_identity_map, digest);
545 for (; conn; conn = conn->next_with_same_id) {
546 tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
547 tor_assert(conn->_base.type == CONN_TYPE_OR);
548 tor_assert(tor_memeq(conn->identity_digest, digest, DIGEST_LEN));
549 if (conn->_base.marked_for_close)
550 continue;
551 /* Never return a connection on which the other end appears to be
552 * a client. */
553 if (conn->is_connection_with_client) {
554 continue;
556 /* Never return a non-open connection. */
557 if (conn->_base.state != OR_CONN_STATE_OPEN) {
558 /* If the address matches, don't launch a new connection for this
559 * circuit. */
560 if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
561 ++n_inprogress_goodaddr;
562 continue;
564 /* Never return a connection that shouldn't be used for circs. */
565 if (conn->is_bad_for_new_circs) {
566 ++n_old;
567 continue;
569 /* Never return a non-canonical connection using a recent link protocol
570 * if the address is not what we wanted.
572 * (For old link protocols, we can't rely on is_canonical getting
573 * set properly if we're talking to the right address, since we might
574 * have an out-of-date descriptor, and we will get no NETINFO cell to
575 * tell us about the right address.) */
576 if (!conn->is_canonical && conn->link_proto >= 2 &&
577 tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
578 ++n_noncanonical;
579 continue;
582 ++n_possible;
584 if (!best) {
585 best = conn; /* If we have no 'best' so far, this one is good enough. */
586 continue;
589 if (connection_or_is_better(now, conn, best, 0))
590 best = conn;
593 if (best) {
594 *msg_out = "Connection is fine; using it.";
595 *launch_out = 0;
596 return best;
597 } else if (n_inprogress_goodaddr) {
598 *msg_out = "Connection in progress; waiting.";
599 *launch_out = 0;
600 return NULL;
601 } else if (n_old || n_noncanonical) {
602 *msg_out = "Connections all too old, or too non-canonical. "
603 " Launching a new one.";
604 *launch_out = 1;
605 return NULL;
606 } else {
607 *msg_out = "Not connected. Connecting.";
608 *launch_out = 1;
609 return NULL;
613 /** How old do we let a connection to an OR get before deciding it's
614 * too old for new circuits? */
615 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
617 /** Given the head of the linked list for all the or_connections with a given
618 * identity, set elements of that list as is_bad_for_new_circs as
619 * appropriate. Helper for connection_or_set_bad_connections().
621 * Specifically, we set the is_bad_for_new_circs flag on:
622 * - all connections if <b>force</b> is true.
623 * - all connections that are too old.
624 * - all open non-canonical connections for which a canonical connection
625 * exists to the same router.
626 * - all open canonical connections for which a 'better' canonical
627 * connection exists to the same router.
628 * - all open non-canonical connections for which a 'better' non-canonical
629 * connection exists to the same router at the same address.
631 * See connection_or_is_better() for our idea of what makes one OR connection
632 * better than another.
634 static void
635 connection_or_group_set_badness(or_connection_t *head, int force)
637 or_connection_t *or_conn = NULL, *best = NULL;
638 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
639 time_t now = time(NULL);
641 /* Pass 1: expire everything that's old, and see what the status of
642 * everything else is. */
643 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
644 if (or_conn->_base.marked_for_close ||
645 or_conn->is_bad_for_new_circs)
646 continue;
647 if (force ||
648 or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
649 < now) {
650 log_info(LD_OR,
651 "Marking OR conn to %s:%d as too old for new circuits "
652 "(fd %d, %d secs old).",
653 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
654 (int)(now - or_conn->_base.timestamp_created));
655 or_conn->is_bad_for_new_circs = 1;
658 if (or_conn->is_bad_for_new_circs) {
659 ++n_old;
660 } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
661 ++n_inprogress;
662 } else if (or_conn->is_canonical) {
663 ++n_canonical;
664 } else {
665 ++n_other;
669 /* Pass 2: We know how about how good the best connection is.
670 * expire everything that's worse, and find the very best if we can. */
671 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
672 if (or_conn->_base.marked_for_close ||
673 or_conn->is_bad_for_new_circs)
674 continue; /* This one doesn't need to be marked bad. */
675 if (or_conn->_base.state != OR_CONN_STATE_OPEN)
676 continue; /* Don't mark anything bad until we have seen what happens
677 * when the connection finishes. */
678 if (n_canonical && !or_conn->is_canonical) {
679 /* We have at least one open canonical connection to this router,
680 * and this one is open but not canonical. Mark it bad. */
681 log_info(LD_OR,
682 "Marking OR conn to %s:%d as unsuitable for new circuits: "
683 "(fd %d, %d secs old). It is not canonical, and we have "
684 "another connection to that OR that is.",
685 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
686 (int)(now - or_conn->_base.timestamp_created));
687 or_conn->is_bad_for_new_circs = 1;
688 continue;
691 if (!best || connection_or_is_better(now, or_conn, best, 0))
692 best = or_conn;
695 if (!best)
696 return;
698 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
699 * every other open connection. If it's non-canonical, mark as bad
700 * every other open connection to the same address.
702 * XXXX This isn't optimal; if we have connections to an OR at multiple
703 * addresses, we'd like to pick the best _for each address_, and mark as
704 * bad every open connection that isn't best for its address. But this
705 * can only occur in cases where the other OR is old (so we have no
706 * canonical connection to it), or where all the connections to the OR are
707 * at noncanonical addresses and we have no good direct connection (which
708 * means we aren't at risk of attaching circuits to it anyway). As
709 * 0.1.2.x dies out, the first case will go away, and the second one is
710 * "mostly harmless", so a fix can wait until somebody is bored.
712 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
713 if (or_conn->_base.marked_for_close ||
714 or_conn->is_bad_for_new_circs ||
715 or_conn->_base.state != OR_CONN_STATE_OPEN)
716 continue;
717 if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
718 /* This isn't the best conn, _and_ the best conn is better than it,
719 even when we're being forgiving. */
720 if (best->is_canonical) {
721 log_info(LD_OR,
722 "Marking OR conn to %s:%d as unsuitable for new circuits: "
723 "(fd %d, %d secs old). We have a better canonical one "
724 "(fd %d; %d secs old).",
725 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
726 (int)(now - or_conn->_base.timestamp_created),
727 best->_base.s, (int)(now - best->_base.timestamp_created));
728 or_conn->is_bad_for_new_circs = 1;
729 } else if (!tor_addr_compare(&or_conn->real_addr,
730 &best->real_addr, CMP_EXACT)) {
731 log_info(LD_OR,
732 "Marking OR conn to %s:%d as unsuitable for new circuits: "
733 "(fd %d, %d secs old). We have a better one with the "
734 "same address (fd %d; %d secs old).",
735 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
736 (int)(now - or_conn->_base.timestamp_created),
737 best->_base.s, (int)(now - best->_base.timestamp_created));
738 or_conn->is_bad_for_new_circs = 1;
744 /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
745 * the OR connections with that digest), and set the is_bad_for_new_circs
746 * flag based on the rules in connection_or_group_set_badness() (or just
747 * always set it if <b>force</b> is true).
749 void
750 connection_or_set_bad_connections(const char *digest, int force)
752 if (!orconn_identity_map)
753 return;
755 DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
756 if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
757 connection_or_group_set_badness(conn, force);
758 } DIGESTMAP_FOREACH_END;
761 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
762 * a TCP connection. Send notifications appropriately.
764 * <b>reason</b> specifies the or_conn_end_reason for the failure;
765 * <b>msg</b> specifies the strerror-style error message.
767 void
768 connection_or_connect_failed(or_connection_t *conn,
769 int reason, const char *msg)
771 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
772 if (!authdir_mode_tests_reachability(get_options()))
773 control_event_bootstrap_problem(msg, reason);
776 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
777 * handshake with an OR with identity digest <b>id_digest</b>.
779 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
780 * return that connection. If the connect() is in progress, set the
781 * new conn's state to 'connecting' and return it. If connect() succeeds,
782 * call connection_tls_start_handshake() on it.
784 * This function is called from router_retry_connections(), for
785 * ORs connecting to ORs, and circuit_establish_circuit(), for
786 * OPs connecting to ORs.
788 * Return the launched conn, or NULL if it failed.
790 or_connection_t *
791 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
792 const char *id_digest)
794 or_connection_t *conn;
795 or_options_t *options = get_options();
796 int socket_error = 0;
797 int using_proxy = 0;
798 tor_addr_t addr;
800 tor_assert(_addr);
801 tor_assert(id_digest);
802 tor_addr_copy(&addr, _addr);
804 if (server_mode(options) && router_digest_is_me(id_digest)) {
805 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
806 return NULL;
809 conn = or_connection_new(AF_INET);
811 /* set up conn so it's got all the data we need to remember */
812 connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
813 conn->_base.state = OR_CONN_STATE_CONNECTING;
814 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
816 conn->is_outgoing = 1;
818 /* use a proxy server if available */
819 if (options->HTTPSProxy) {
820 using_proxy = 1;
821 tor_addr_copy(&addr, &options->HTTPSProxyAddr);
822 port = options->HTTPSProxyPort;
823 } else if (options->Socks4Proxy) {
824 using_proxy = 1;
825 tor_addr_copy(&addr, &options->Socks4ProxyAddr);
826 port = options->Socks4ProxyPort;
827 } else if (options->Socks5Proxy) {
828 using_proxy = 1;
829 tor_addr_copy(&addr, &options->Socks5ProxyAddr);
830 port = options->Socks5ProxyPort;
833 switch (connection_connect(TO_CONN(conn), conn->_base.address,
834 &addr, port, &socket_error)) {
835 case -1:
836 /* If the connection failed immediately, and we're using
837 * a proxy, our proxy is down. Don't blame the Tor server. */
838 if (!using_proxy)
839 entry_guard_register_connect_status(conn->identity_digest,
840 0, 1, time(NULL));
841 connection_or_connect_failed(conn,
842 errno_to_orconn_end_reason(socket_error),
843 tor_socket_strerror(socket_error));
844 connection_free(TO_CONN(conn));
845 return NULL;
846 case 0:
847 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
848 /* writable indicates finish, readable indicates broken link,
849 error indicates broken link on windows */
850 return conn;
851 /* case 1: fall through */
854 if (connection_or_finished_connecting(conn) < 0) {
855 /* already marked for close */
856 return NULL;
858 return conn;
861 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
862 * we initiated the connection, else it's 1.
864 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
865 * pass <b>conn</b> to connection_tls_continue_handshake().
867 * Return -1 if <b>conn</b> is broken, else return 0.
870 connection_tls_start_handshake(or_connection_t *conn, int receiving)
872 conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
873 conn->tls = tor_tls_new(conn->_base.s, receiving);
874 tor_tls_set_logged_address(conn->tls, // XXX client and relay?
875 escaped_safe_str(conn->_base.address));
876 if (!conn->tls) {
877 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
878 return -1;
880 connection_start_reading(TO_CONN(conn));
881 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
882 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
884 if (connection_tls_continue_handshake(conn) < 0) {
885 return -1;
887 return 0;
890 /** Invoked on the server side from inside tor_tls_read() when the server
891 * gets a successful TLS renegotiation from the client. */
892 static void
893 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
895 or_connection_t *conn = _conn;
896 (void)tls;
898 /* Don't invoke this again. */
899 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
900 tor_tls_block_renegotiation(tls);
902 if (connection_tls_finish_handshake(conn) < 0) {
903 /* XXXX_TLS double-check that it's ok to do this from inside read. */
904 /* XXXX_TLS double-check that this verifies certificates. */
905 connection_mark_for_close(TO_CONN(conn));
909 /** Move forward with the tls handshake. If it finishes, hand
910 * <b>conn</b> to connection_tls_finish_handshake().
912 * Return -1 if <b>conn</b> is broken, else return 0.
915 connection_tls_continue_handshake(or_connection_t *conn)
917 int result;
918 check_no_tls_errors();
919 again:
920 if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
921 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
922 result = tor_tls_renegotiate(conn->tls);
923 // log_notice(LD_OR, "Result: %d", result);
924 } else {
925 tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
926 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
927 result = tor_tls_handshake(conn->tls);
928 // log_notice(LD_OR, "Result: %d", result);
930 switch (result) {
931 CASE_TOR_TLS_ERROR_ANY:
932 log_info(LD_OR,"tls error [%s]. breaking connection.",
933 tor_tls_err_to_string(result));
934 return -1;
935 case TOR_TLS_DONE:
936 if (! tor_tls_used_v1_handshake(conn->tls)) {
937 if (!tor_tls_is_server(conn->tls)) {
938 if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
939 log_debug(LD_OR, "Done with initial SSL handshake (client-side). "
940 "Requesting renegotiation.");
941 conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
942 goto again;
944 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
945 } else {
946 /* improved handshake, but not a client. */
947 log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
948 "Expecting renegotiation.");
949 tor_tls_set_renegotiate_callback(conn->tls,
950 connection_or_tls_renegotiated_cb,
951 conn);
952 conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
953 connection_stop_writing(TO_CONN(conn));
954 connection_start_reading(TO_CONN(conn));
955 return 0;
958 return connection_tls_finish_handshake(conn);
959 case TOR_TLS_WANTWRITE:
960 connection_start_writing(TO_CONN(conn));
961 log_debug(LD_OR,"wanted write");
962 return 0;
963 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
964 log_debug(LD_OR,"wanted read");
965 return 0;
966 case TOR_TLS_CLOSE:
967 log_info(LD_OR,"tls closed. breaking connection.");
968 return -1;
970 return 0;
973 /** Return 1 if we initiated this connection, or 0 if it started
974 * out as an incoming connection.
977 connection_or_nonopen_was_started_here(or_connection_t *conn)
979 tor_assert(conn->_base.type == CONN_TYPE_OR);
980 if (!conn->tls)
981 return 1; /* it's still in proxy states or something */
982 if (conn->handshake_state)
983 return conn->handshake_state->started_here;
984 return !tor_tls_is_server(conn->tls);
987 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
988 * return -1 if he is lying, broken, or otherwise something is wrong.
990 * If we initiated this connection (<b>started_here</b> is true), make sure
991 * the other side sent a correctly formed certificate. If I initiated the
992 * connection, make sure it's the right guy.
994 * Otherwise (if we _didn't_ initiate this connection), it's okay for
995 * the certificate to be weird or absent.
997 * If we return 0, and the certificate is as expected, write a hash of the
998 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
999 * space in it.
1000 * If the certificate is invalid or missing on an incoming connection,
1001 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
1002 * (If we return -1, the contents of this buffer are undefined.)
1004 * As side effects,
1005 * 1) Set conn->circ_id_type according to tor-spec.txt.
1006 * 2) If we're an authdirserver and we initiated the connection: drop all
1007 * descriptors that claim to be on that IP/port but that aren't
1008 * this guy; and note that this guy is reachable.
1009 * 3) If this is a bridge and we didn't configure its identity
1010 * fingerprint, remember the keyid we just learned.
1012 static int
1013 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1014 int started_here,
1015 char *digest_rcvd_out)
1017 crypto_pk_env_t *identity_rcvd=NULL;
1018 or_options_t *options = get_options();
1019 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1020 const char *safe_address =
1021 started_here ? conn->_base.address :
1022 safe_str_client(conn->_base.address);
1023 const char *conn_type = started_here ? "outgoing" : "incoming";
1024 crypto_pk_env_t *our_identity =
1025 started_here ? get_tlsclient_identity_key() :
1026 get_server_identity_key();
1027 int has_cert = 0, has_identity=0;
1029 check_no_tls_errors();
1030 has_cert = tor_tls_peer_has_cert(conn->tls);
1031 if (started_here && !has_cert) {
1032 log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1033 "send a cert! Closing.",
1034 safe_address, conn->_base.port);
1035 return -1;
1036 } else if (!has_cert) {
1037 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1038 "That's ok.");
1040 check_no_tls_errors();
1042 if (has_cert) {
1043 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1044 conn->tls, &identity_rcvd);
1045 if (started_here && v<0) {
1046 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1047 " has a cert but it's invalid. Closing.",
1048 safe_address, conn->_base.port);
1049 return -1;
1050 } else if (v<0) {
1051 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1052 "chain; ignoring.");
1053 } else {
1054 log_debug(LD_HANDSHAKE,
1055 "The certificate seems to be valid on %s connection "
1056 "with %s:%d", conn_type, safe_address, conn->_base.port);
1058 check_no_tls_errors();
1061 if (identity_rcvd) {
1062 has_identity = 1;
1063 crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
1064 if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
1065 conn->circ_id_type = CIRC_ID_TYPE_LOWER;
1066 } else {
1067 conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
1069 crypto_free_pk_env(identity_rcvd);
1070 } else {
1071 memset(digest_rcvd_out, 0, DIGEST_LEN);
1072 conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
1075 if (started_here && tor_digest_is_zero(conn->identity_digest)) {
1076 connection_or_set_identity_digest(conn, digest_rcvd_out);
1077 tor_free(conn->nickname);
1078 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1079 conn->nickname[0] = '$';
1080 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1081 conn->identity_digest, DIGEST_LEN);
1082 log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1083 "its key. Hoping for the best.",
1084 conn->nickname, conn->_base.address, conn->_base.port);
1085 /* if it's a bridge and we didn't know its identity fingerprint, now
1086 * we do -- remember it for future attempts. */
1087 learned_router_identity(&conn->_base.addr, conn->_base.port,
1088 digest_rcvd_out);
1091 if (started_here) {
1092 int as_advertised = 1;
1093 tor_assert(has_cert);
1094 tor_assert(has_identity);
1095 if (tor_memneq(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
1096 /* I was aiming for a particular digest. I didn't get it! */
1097 char seen[HEX_DIGEST_LEN+1];
1098 char expected[HEX_DIGEST_LEN+1];
1099 base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
1100 base16_encode(expected, sizeof(expected), conn->identity_digest,
1101 DIGEST_LEN);
1102 log_fn(severity, LD_HANDSHAKE,
1103 "Tried connecting to router at %s:%d, but identity key was not "
1104 "as expected: wanted %s but got %s.",
1105 conn->_base.address, conn->_base.port, expected, seen);
1106 entry_guard_register_connect_status(conn->identity_digest, 0, 1,
1107 time(NULL));
1108 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1109 END_OR_CONN_REASON_OR_IDENTITY);
1110 if (!authdir_mode_tests_reachability(options))
1111 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
1112 as_advertised = 0;
1114 if (authdir_mode_tests_reachability(options)) {
1115 dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
1116 digest_rcvd_out, as_advertised);
1118 if (!as_advertised)
1119 return -1;
1121 return 0;
1124 /** The tls handshake is finished.
1126 * Make sure we are happy with the person we just handshaked with.
1128 * If he initiated the connection, make sure he's not already connected,
1129 * then initialize conn from the information in router.
1131 * If all is successful, call circuit_n_conn_done() to handle events
1132 * that have been pending on the <tls handshake completion. Also set the
1133 * directory to be dirty (only matters if I'm an authdirserver).
1135 static int
1136 connection_tls_finish_handshake(or_connection_t *conn)
1138 char digest_rcvd[DIGEST_LEN];
1139 int started_here = connection_or_nonopen_was_started_here(conn);
1141 log_debug(LD_HANDSHAKE,"tls handshake with %s done. verifying.",
1142 safe_str_client(conn->_base.address));
1144 directory_set_dirty();
1146 if (connection_or_check_valid_tls_handshake(conn, started_here,
1147 digest_rcvd) < 0)
1148 return -1;
1150 circuit_build_times_network_is_live(&circ_times);
1152 if (tor_tls_used_v1_handshake(conn->tls)) {
1153 conn->link_proto = 1;
1154 if (!started_here) {
1155 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1156 conn->_base.port, digest_rcvd, 0);
1158 tor_tls_block_renegotiation(conn->tls);
1159 return connection_or_set_state_open(conn);
1160 } else {
1161 conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
1162 if (connection_init_or_handshake_state(conn, started_here) < 0)
1163 return -1;
1164 if (!started_here) {
1165 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1166 conn->_base.port, digest_rcvd, 0);
1168 return connection_or_send_versions(conn);
1172 /** Allocate a new connection handshake state for the connection
1173 * <b>conn</b>. Return 0 on success, -1 on failure. */
1174 static int
1175 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
1177 or_handshake_state_t *s;
1178 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
1179 s->started_here = started_here ? 1 : 0;
1180 return 0;
1183 /** Free all storage held by <b>state</b>. */
1184 void
1185 or_handshake_state_free(or_handshake_state_t *state)
1187 if (!state)
1188 return;
1189 memset(state, 0xBE, sizeof(or_handshake_state_t));
1190 tor_free(state);
1193 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1194 * as appropriate. Called when we are done with all TLS and OR handshaking.
1197 connection_or_set_state_open(or_connection_t *conn)
1199 int started_here = connection_or_nonopen_was_started_here(conn);
1200 time_t now = time(NULL);
1201 conn->_base.state = OR_CONN_STATE_OPEN;
1202 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
1204 if (started_here) {
1205 circuit_build_times_network_is_live(&circ_times);
1206 rep_hist_note_connect_succeeded(conn->identity_digest, now);
1207 if (entry_guard_register_connect_status(conn->identity_digest,
1208 1, 0, now) < 0) {
1209 /* Close any circuits pending on this conn. We leave it in state
1210 * 'open' though, because it didn't actually *fail* -- we just
1211 * chose not to use it. (Otherwise
1212 * connection_about_to_close_connection() will call a big pile of
1213 * functions to indicate we shouldn't try it again.) */
1214 log_debug(LD_OR, "New entry guard was reachable, but closing this "
1215 "connection so we can retry the earlier entry guards.");
1216 circuit_n_conn_done(conn, 0);
1217 return -1;
1219 router_set_status(conn->identity_digest, 1);
1220 } else {
1221 /* only report it to the geoip module if it's not a known router */
1222 if (!router_get_by_digest(conn->identity_digest)) {
1223 if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
1224 /*XXXX IP6 support ipv6 geoip.*/
1225 uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
1226 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
1231 or_handshake_state_free(conn->handshake_state);
1232 conn->handshake_state = NULL;
1234 connection_start_reading(TO_CONN(conn));
1235 circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
1237 return 0;
1240 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1241 * For cells that use or affect a circuit, this should only be called by
1242 * connection_or_flush_from_first_active_circuit().
1244 void
1245 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
1247 packed_cell_t networkcell;
1249 tor_assert(cell);
1250 tor_assert(conn);
1252 cell_pack(&networkcell, cell);
1254 connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
1256 if (cell->command != CELL_PADDING)
1257 conn->timestamp_last_added_nonpadding = approx_time();
1260 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1261 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1262 * affect a circuit.
1264 void
1265 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
1266 or_connection_t *conn)
1268 char hdr[VAR_CELL_HEADER_SIZE];
1269 tor_assert(cell);
1270 tor_assert(conn);
1271 var_cell_pack_header(cell, hdr);
1272 connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
1273 connection_write_to_buf((char*)cell->payload,
1274 cell->payload_len, TO_CONN(conn));
1275 if (cell->command != CELL_PADDING)
1276 conn->timestamp_last_added_nonpadding = approx_time();
1279 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1280 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1281 static int
1282 connection_fetch_var_cell_from_buf(or_connection_t *conn, var_cell_t **out)
1284 return fetch_var_cell_from_buf(conn->_base.inbuf, out, conn->link_proto);
1287 /** Process cells from <b>conn</b>'s inbuf.
1289 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1290 * and hand it to command_process_cell().
1292 * Always return 0.
1294 static int
1295 connection_or_process_cells_from_inbuf(or_connection_t *conn)
1297 var_cell_t *var_cell;
1299 while (1) {
1300 log_debug(LD_OR,
1301 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1302 conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
1303 tor_tls_get_pending_bytes(conn->tls));
1304 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
1305 if (!var_cell)
1306 return 0; /* not yet. */
1307 circuit_build_times_network_is_live(&circ_times);
1308 command_process_var_cell(var_cell, conn);
1309 var_cell_free(var_cell);
1310 } else {
1311 char buf[CELL_NETWORK_SIZE];
1312 cell_t cell;
1313 if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
1314 available? */
1315 return 0; /* not yet */
1317 circuit_build_times_network_is_live(&circ_times);
1318 connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
1320 /* retrieve cell info from buf (create the host-order struct from the
1321 * network-order string) */
1322 cell_unpack(&cell, buf);
1324 command_process_cell(&cell, conn);
1329 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1330 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1331 * we may want to propagate reasons from other cells.
1333 * Return 0.
1336 connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
1338 cell_t cell;
1340 tor_assert(conn);
1342 memset(&cell, 0, sizeof(cell_t));
1343 cell.circ_id = circ_id;
1344 cell.command = CELL_DESTROY;
1345 cell.payload[0] = (uint8_t) reason;
1346 log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
1348 connection_or_write_cell_to_buf(&cell, conn);
1349 return 0;
1352 /** Array of recognized link protocol versions. */
1353 static const uint16_t or_protocol_versions[] = { 1, 2 };
1354 /** Number of versions in <b>or_protocol_versions</b>. */
1355 static const int n_or_protocol_versions =
1356 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
1358 /** Return true iff <b>v</b> is a link protocol version that this Tor
1359 * implementation believes it can support. */
1361 is_or_protocol_version_known(uint16_t v)
1363 int i;
1364 for (i = 0; i < n_or_protocol_versions; ++i) {
1365 if (or_protocol_versions[i] == v)
1366 return 1;
1368 return 0;
1371 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1372 * link protocol versions that this Tor can support. */
1373 static int
1374 connection_or_send_versions(or_connection_t *conn)
1376 var_cell_t *cell;
1377 int i;
1378 tor_assert(conn->handshake_state &&
1379 !conn->handshake_state->sent_versions_at);
1380 cell = var_cell_new(n_or_protocol_versions * 2);
1381 cell->command = CELL_VERSIONS;
1382 for (i = 0; i < n_or_protocol_versions; ++i) {
1383 uint16_t v = or_protocol_versions[i];
1384 set_uint16(cell->payload+(2*i), htons(v));
1387 connection_or_write_var_cell_to_buf(cell, conn);
1388 conn->handshake_state->sent_versions_at = time(NULL);
1390 var_cell_free(cell);
1391 return 0;
1394 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1395 * about their address, our address, and the current time. */
1397 connection_or_send_netinfo(or_connection_t *conn)
1399 cell_t cell;
1400 time_t now = time(NULL);
1401 routerinfo_t *me;
1402 int len;
1403 uint8_t *out;
1405 memset(&cell, 0, sizeof(cell_t));
1406 cell.command = CELL_NETINFO;
1408 /* Timestamp. */
1409 set_uint32(cell.payload, htonl((uint32_t)now));
1411 /* Their address. */
1412 out = cell.payload + 4;
1413 len = append_address_to_payload(out, &conn->real_addr);
1414 if (len<0)
1415 return -1;
1416 out += len;
1418 /* My address. */
1419 if ((me = router_get_my_routerinfo())) {
1420 tor_addr_t my_addr;
1421 *out++ = 1; /* only one address is supported. */
1423 tor_addr_from_ipv4h(&my_addr, me->addr);
1424 len = append_address_to_payload(out, &my_addr);
1425 if (len < 0)
1426 return -1;
1427 } else {
1428 *out = 0;
1431 connection_or_write_cell_to_buf(&cell, conn);
1433 return 0;