add another heuristic for changes stanzas
[tor.git] / src / or / connection_or.c
blob4b932ec51e0b9cc7ae49881ed0adce4909dc7e20
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 (!memcmp(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(!memcmp(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(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
549 if (conn->_base.marked_for_close)
550 continue;
551 /* Never return a non-open connection. */
552 if (conn->_base.state != OR_CONN_STATE_OPEN) {
553 /* If the address matches, don't launch a new connection for this
554 * circuit. */
555 if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
556 ++n_inprogress_goodaddr;
557 continue;
559 /* Never return a connection that shouldn't be used for circs. */
560 if (conn->is_bad_for_new_circs) {
561 ++n_old;
562 continue;
564 /* Never return a non-canonical connection using a recent link protocol
565 * if the address is not what we wanted.
567 * (For old link protocols, we can't rely on is_canonical getting
568 * set properly if we're talking to the right address, since we might
569 * have an out-of-date descriptor, and we will get no NETINFO cell to
570 * tell us about the right address.) */
571 if (!conn->is_canonical && conn->link_proto >= 2 &&
572 tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
573 ++n_noncanonical;
574 continue;
577 ++n_possible;
579 if (!best) {
580 best = conn; /* If we have no 'best' so far, this one is good enough. */
581 continue;
584 if (connection_or_is_better(now, conn, best, 0))
585 best = conn;
588 if (best) {
589 *msg_out = "Connection is fine; using it.";
590 *launch_out = 0;
591 return best;
592 } else if (n_inprogress_goodaddr) {
593 *msg_out = "Connection in progress; waiting.";
594 *launch_out = 0;
595 return NULL;
596 } else if (n_old || n_noncanonical) {
597 *msg_out = "Connections all too old, or too non-canonical. "
598 " Launching a new one.";
599 *launch_out = 1;
600 return NULL;
601 } else {
602 *msg_out = "Not connected. Connecting.";
603 *launch_out = 1;
604 return NULL;
608 /** How old do we let a connection to an OR get before deciding it's
609 * too old for new circuits? */
610 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
612 /** Given the head of the linked list for all the or_connections with a given
613 * identity, set elements of that list as is_bad_for_new_circs as
614 * appropriate. Helper for connection_or_set_bad_connections().
616 * Specifically, we set the is_bad_for_new_circs flag on:
617 * - all connections if <b>force</b> is true.
618 * - all connections that are too old.
619 * - all open non-canonical connections for which a canonical connection
620 * exists to the same router.
621 * - all open canonical connections for which a 'better' canonical
622 * connection exists to the same router.
623 * - all open non-canonical connections for which a 'better' non-canonical
624 * connection exists to the same router at the same address.
626 * See connection_or_is_better() for our idea of what makes one OR connection
627 * better than another.
629 static void
630 connection_or_group_set_badness(or_connection_t *head, int force)
632 or_connection_t *or_conn = NULL, *best = NULL;
633 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
634 time_t now = time(NULL);
636 /* Pass 1: expire everything that's old, and see what the status of
637 * everything else is. */
638 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
639 if (or_conn->_base.marked_for_close ||
640 or_conn->is_bad_for_new_circs)
641 continue;
642 if (force ||
643 or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
644 < now) {
645 log_info(LD_OR,
646 "Marking OR conn to %s:%d as too old for new circuits "
647 "(fd %d, %d secs old).",
648 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
649 (int)(now - or_conn->_base.timestamp_created));
650 or_conn->is_bad_for_new_circs = 1;
653 if (or_conn->is_bad_for_new_circs) {
654 ++n_old;
655 } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
656 ++n_inprogress;
657 } else if (or_conn->is_canonical) {
658 ++n_canonical;
659 } else {
660 ++n_other;
664 /* Pass 2: We know how about how good the best connection is.
665 * expire everything that's worse, and find the very best if we can. */
666 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
667 if (or_conn->_base.marked_for_close ||
668 or_conn->is_bad_for_new_circs)
669 continue; /* This one doesn't need to be marked bad. */
670 if (or_conn->_base.state != OR_CONN_STATE_OPEN)
671 continue; /* Don't mark anything bad until we have seen what happens
672 * when the connection finishes. */
673 if (n_canonical && !or_conn->is_canonical) {
674 /* We have at least one open canonical connection to this router,
675 * and this one is open but not canonical. Mark it bad. */
676 log_info(LD_OR,
677 "Marking OR conn to %s:%d as unsuitable for new circuits: "
678 "(fd %d, %d secs old). It is not canonical, and we have "
679 "another connection to that OR that is.",
680 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
681 (int)(now - or_conn->_base.timestamp_created));
682 or_conn->is_bad_for_new_circs = 1;
683 continue;
686 if (!best || connection_or_is_better(now, or_conn, best, 0))
687 best = or_conn;
690 if (!best)
691 return;
693 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
694 * every other open connection. If it's non-canonical, mark as bad
695 * every other open connection to the same address.
697 * XXXX This isn't optimal; if we have connections to an OR at multiple
698 * addresses, we'd like to pick the best _for each address_, and mark as
699 * bad every open connection that isn't best for its address. But this
700 * can only occur in cases where the other OR is old (so we have no
701 * canonical connection to it), or where all the connections to the OR are
702 * at noncanonical addresses and we have no good direct connection (which
703 * means we aren't at risk of attaching circuits to it anyway). As
704 * 0.1.2.x dies out, the first case will go away, and the second one is
705 * "mostly harmless", so a fix can wait until somebody is bored.
707 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
708 if (or_conn->_base.marked_for_close ||
709 or_conn->is_bad_for_new_circs ||
710 or_conn->_base.state != OR_CONN_STATE_OPEN)
711 continue;
712 if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
713 /* This isn't the best conn, _and_ the best conn is better than it,
714 even when we're being forgiving. */
715 if (best->is_canonical) {
716 log_info(LD_OR,
717 "Marking OR conn to %s:%d as unsuitable for new circuits: "
718 "(fd %d, %d secs old). We have a better canonical one "
719 "(fd %d; %d secs old).",
720 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
721 (int)(now - or_conn->_base.timestamp_created),
722 best->_base.s, (int)(now - best->_base.timestamp_created));
723 or_conn->is_bad_for_new_circs = 1;
724 } else if (!tor_addr_compare(&or_conn->real_addr,
725 &best->real_addr, CMP_EXACT)) {
726 log_info(LD_OR,
727 "Marking OR conn to %s:%d as unsuitable for new circuits: "
728 "(fd %d, %d secs old). We have a better one with the "
729 "same address (fd %d; %d secs old).",
730 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
731 (int)(now - or_conn->_base.timestamp_created),
732 best->_base.s, (int)(now - best->_base.timestamp_created));
733 or_conn->is_bad_for_new_circs = 1;
739 /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
740 * the OR connections with that digest), and set the is_bad_for_new_circs
741 * flag based on the rules in connection_or_group_set_badness() (or just
742 * always set it if <b>force</b> is true).
744 void
745 connection_or_set_bad_connections(const char *digest, int force)
747 if (!orconn_identity_map)
748 return;
750 DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
751 if (!digest || !memcmp(digest, conn->identity_digest, DIGEST_LEN))
752 connection_or_group_set_badness(conn, force);
753 } DIGESTMAP_FOREACH_END;
756 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
757 * a TCP connection. Send notifications appropriately.
759 * <b>reason</b> specifies the or_conn_end_reason for the failure;
760 * <b>msg</b> specifies the strerror-style error message.
762 void
763 connection_or_connect_failed(or_connection_t *conn,
764 int reason, const char *msg)
766 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
767 if (!authdir_mode_tests_reachability(get_options()))
768 control_event_bootstrap_problem(msg, reason);
771 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
772 * handshake with an OR with identity digest <b>id_digest</b>.
774 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
775 * return that connection. If the connect() is in progress, set the
776 * new conn's state to 'connecting' and return it. If connect() succeeds,
777 * call connection_tls_start_handshake() on it.
779 * This function is called from router_retry_connections(), for
780 * ORs connecting to ORs, and circuit_establish_circuit(), for
781 * OPs connecting to ORs.
783 * Return the launched conn, or NULL if it failed.
785 or_connection_t *
786 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
787 const char *id_digest)
789 or_connection_t *conn;
790 or_options_t *options = get_options();
791 int socket_error = 0;
792 int using_proxy = 0;
793 tor_addr_t addr;
795 tor_assert(_addr);
796 tor_assert(id_digest);
797 tor_addr_copy(&addr, _addr);
799 if (server_mode(options) && router_digest_is_me(id_digest)) {
800 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
801 return NULL;
804 conn = or_connection_new(AF_INET);
806 /* set up conn so it's got all the data we need to remember */
807 connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
808 conn->_base.state = OR_CONN_STATE_CONNECTING;
809 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
811 /* use a proxy server if available */
812 if (options->HTTPSProxy) {
813 using_proxy = 1;
814 tor_addr_copy(&addr, &options->HTTPSProxyAddr);
815 port = options->HTTPSProxyPort;
816 } else if (options->Socks4Proxy) {
817 using_proxy = 1;
818 tor_addr_copy(&addr, &options->Socks4ProxyAddr);
819 port = options->Socks4ProxyPort;
820 } else if (options->Socks5Proxy) {
821 using_proxy = 1;
822 tor_addr_copy(&addr, &options->Socks5ProxyAddr);
823 port = options->Socks5ProxyPort;
826 switch (connection_connect(TO_CONN(conn), conn->_base.address,
827 &addr, port, &socket_error)) {
828 case -1:
829 /* If the connection failed immediately, and we're using
830 * a proxy, our proxy is down. Don't blame the Tor server. */
831 if (!using_proxy)
832 entry_guard_register_connect_status(conn->identity_digest,
833 0, 1, time(NULL));
834 connection_or_connect_failed(conn,
835 errno_to_orconn_end_reason(socket_error),
836 tor_socket_strerror(socket_error));
837 connection_free(TO_CONN(conn));
838 return NULL;
839 case 0:
840 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
841 /* writable indicates finish, readable indicates broken link,
842 error indicates broken link on windows */
843 return conn;
844 /* case 1: fall through */
847 if (connection_or_finished_connecting(conn) < 0) {
848 /* already marked for close */
849 return NULL;
851 return conn;
854 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
855 * we initiated the connection, else it's 1.
857 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
858 * pass <b>conn</b> to connection_tls_continue_handshake().
860 * Return -1 if <b>conn</b> is broken, else return 0.
863 connection_tls_start_handshake(or_connection_t *conn, int receiving)
865 conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
866 conn->tls = tor_tls_new(conn->_base.s, receiving);
867 tor_tls_set_logged_address(conn->tls, // XXX client and relay?
868 escaped_safe_str(conn->_base.address));
869 if (!conn->tls) {
870 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
871 return -1;
873 connection_start_reading(TO_CONN(conn));
874 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
875 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
877 if (connection_tls_continue_handshake(conn) < 0) {
878 return -1;
880 return 0;
883 /** Invoked on the server side from inside tor_tls_read() when the server
884 * gets a successful TLS renegotiation from the client. */
885 static void
886 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
888 or_connection_t *conn = _conn;
889 (void)tls;
891 /* Don't invoke this again. */
892 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
893 tor_tls_block_renegotiation(tls);
895 if (connection_tls_finish_handshake(conn) < 0) {
896 /* XXXX_TLS double-check that it's ok to do this from inside read. */
897 /* XXXX_TLS double-check that this verifies certificates. */
898 connection_mark_for_close(TO_CONN(conn));
902 /** Move forward with the tls handshake. If it finishes, hand
903 * <b>conn</b> to connection_tls_finish_handshake().
905 * Return -1 if <b>conn</b> is broken, else return 0.
908 connection_tls_continue_handshake(or_connection_t *conn)
910 int result;
911 check_no_tls_errors();
912 again:
913 if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
914 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
915 result = tor_tls_renegotiate(conn->tls);
916 // log_notice(LD_OR, "Result: %d", result);
917 } else {
918 tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
919 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
920 result = tor_tls_handshake(conn->tls);
921 // log_notice(LD_OR, "Result: %d", result);
923 switch (result) {
924 CASE_TOR_TLS_ERROR_ANY:
925 log_info(LD_OR,"tls error [%s]. breaking connection.",
926 tor_tls_err_to_string(result));
927 return -1;
928 case TOR_TLS_DONE:
929 if (! tor_tls_used_v1_handshake(conn->tls)) {
930 if (!tor_tls_is_server(conn->tls)) {
931 if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
932 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
933 conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
934 goto again;
936 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
937 } else {
938 /* improved handshake, but not a client. */
939 tor_tls_set_renegotiate_callback(conn->tls,
940 connection_or_tls_renegotiated_cb,
941 conn);
942 conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
943 connection_stop_writing(TO_CONN(conn));
944 connection_start_reading(TO_CONN(conn));
945 return 0;
948 return connection_tls_finish_handshake(conn);
949 case TOR_TLS_WANTWRITE:
950 connection_start_writing(TO_CONN(conn));
951 log_debug(LD_OR,"wanted write");
952 return 0;
953 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
954 log_debug(LD_OR,"wanted read");
955 return 0;
956 case TOR_TLS_CLOSE:
957 log_info(LD_OR,"tls closed. breaking connection.");
958 return -1;
960 return 0;
963 /** Return 1 if we initiated this connection, or 0 if it started
964 * out as an incoming connection.
967 connection_or_nonopen_was_started_here(or_connection_t *conn)
969 tor_assert(conn->_base.type == CONN_TYPE_OR);
970 if (!conn->tls)
971 return 1; /* it's still in proxy states or something */
972 if (conn->handshake_state)
973 return conn->handshake_state->started_here;
974 return !tor_tls_is_server(conn->tls);
977 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
978 * return -1 if he is lying, broken, or otherwise something is wrong.
980 * If we initiated this connection (<b>started_here</b> is true), make sure
981 * the other side sent a correctly formed certificate. If I initiated the
982 * connection, make sure it's the right guy.
984 * Otherwise (if we _didn't_ initiate this connection), it's okay for
985 * the certificate to be weird or absent.
987 * If we return 0, and the certificate is as expected, write a hash of the
988 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
989 * space in it.
990 * If the certificate is invalid or missing on an incoming connection,
991 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
992 * (If we return -1, the contents of this buffer are undefined.)
994 * As side effects,
995 * 1) Set conn->circ_id_type according to tor-spec.txt.
996 * 2) If we're an authdirserver and we initiated the connection: drop all
997 * descriptors that claim to be on that IP/port but that aren't
998 * this guy; and note that this guy is reachable.
999 * 3) If this is a bridge and we didn't configure its identity
1000 * fingerprint, remember the keyid we just learned.
1002 static int
1003 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1004 int started_here,
1005 char *digest_rcvd_out)
1007 crypto_pk_env_t *identity_rcvd=NULL;
1008 or_options_t *options = get_options();
1009 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1010 const char *safe_address =
1011 started_here ? conn->_base.address :
1012 safe_str_client(conn->_base.address);
1013 const char *conn_type = started_here ? "outgoing" : "incoming";
1014 crypto_pk_env_t *our_identity =
1015 started_here ? get_tlsclient_identity_key() :
1016 get_server_identity_key();
1017 int has_cert = 0, has_identity=0;
1019 check_no_tls_errors();
1020 has_cert = tor_tls_peer_has_cert(conn->tls);
1021 if (started_here && !has_cert) {
1022 log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1023 "send a cert! Closing.",
1024 safe_address, conn->_base.port);
1025 return -1;
1026 } else if (!has_cert) {
1027 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1028 "That's ok.");
1030 check_no_tls_errors();
1032 if (has_cert) {
1033 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1034 conn->tls, &identity_rcvd);
1035 if (started_here && v<0) {
1036 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1037 " has a cert but it's invalid. Closing.",
1038 safe_address, conn->_base.port);
1039 return -1;
1040 } else if (v<0) {
1041 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1042 "chain; ignoring.");
1043 } else {
1044 log_debug(LD_HANDSHAKE,
1045 "The certificate seems to be valid on %s connection "
1046 "with %s:%d", conn_type, safe_address, conn->_base.port);
1048 check_no_tls_errors();
1051 if (identity_rcvd) {
1052 has_identity = 1;
1053 crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
1054 if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
1055 conn->circ_id_type = CIRC_ID_TYPE_LOWER;
1056 } else {
1057 conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
1059 crypto_free_pk_env(identity_rcvd);
1060 } else {
1061 memset(digest_rcvd_out, 0, DIGEST_LEN);
1062 conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
1065 if (started_here && tor_digest_is_zero(conn->identity_digest)) {
1066 connection_or_set_identity_digest(conn, digest_rcvd_out);
1067 tor_free(conn->nickname);
1068 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1069 conn->nickname[0] = '$';
1070 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1071 conn->identity_digest, DIGEST_LEN);
1072 log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1073 "its key. Hoping for the best.",
1074 conn->nickname, conn->_base.address, conn->_base.port);
1075 /* if it's a bridge and we didn't know its identity fingerprint, now
1076 * we do -- remember it for future attempts. */
1077 learned_router_identity(&conn->_base.addr, conn->_base.port,
1078 digest_rcvd_out);
1081 if (started_here) {
1082 int as_advertised = 1;
1083 tor_assert(has_cert);
1084 tor_assert(has_identity);
1085 if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
1086 /* I was aiming for a particular digest. I didn't get it! */
1087 char seen[HEX_DIGEST_LEN+1];
1088 char expected[HEX_DIGEST_LEN+1];
1089 base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
1090 base16_encode(expected, sizeof(expected), conn->identity_digest,
1091 DIGEST_LEN);
1092 log_fn(severity, LD_HANDSHAKE,
1093 "Tried connecting to router at %s:%d, but identity key was not "
1094 "as expected: wanted %s but got %s.",
1095 conn->_base.address, conn->_base.port, expected, seen);
1096 entry_guard_register_connect_status(conn->identity_digest, 0, 1,
1097 time(NULL));
1098 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1099 END_OR_CONN_REASON_OR_IDENTITY);
1100 if (!authdir_mode_tests_reachability(options))
1101 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
1102 as_advertised = 0;
1104 if (authdir_mode_tests_reachability(options)) {
1105 dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
1106 digest_rcvd_out, as_advertised);
1108 if (!as_advertised)
1109 return -1;
1111 return 0;
1114 /** The tls handshake is finished.
1116 * Make sure we are happy with the person we just handshaked with.
1118 * If he initiated the connection, make sure he's not already connected,
1119 * then initialize conn from the information in router.
1121 * If all is successful, call circuit_n_conn_done() to handle events
1122 * that have been pending on the <tls handshake completion. Also set the
1123 * directory to be dirty (only matters if I'm an authdirserver).
1125 static int
1126 connection_tls_finish_handshake(or_connection_t *conn)
1128 char digest_rcvd[DIGEST_LEN];
1129 int started_here = connection_or_nonopen_was_started_here(conn);
1131 log_debug(LD_HANDSHAKE,"tls handshake with %s done. verifying.",
1132 safe_str_client(conn->_base.address));
1134 directory_set_dirty();
1136 if (connection_or_check_valid_tls_handshake(conn, started_here,
1137 digest_rcvd) < 0)
1138 return -1;
1140 circuit_build_times_network_is_live(&circ_times);
1142 if (tor_tls_used_v1_handshake(conn->tls)) {
1143 conn->link_proto = 1;
1144 if (!started_here) {
1145 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1146 conn->_base.port, digest_rcvd, 0);
1148 tor_tls_block_renegotiation(conn->tls);
1149 return connection_or_set_state_open(conn);
1150 } else {
1151 conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
1152 if (connection_init_or_handshake_state(conn, started_here) < 0)
1153 return -1;
1154 if (!started_here) {
1155 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1156 conn->_base.port, digest_rcvd, 0);
1158 return connection_or_send_versions(conn);
1162 /** Allocate a new connection handshake state for the connection
1163 * <b>conn</b>. Return 0 on success, -1 on failure. */
1164 static int
1165 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
1167 or_handshake_state_t *s;
1168 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
1169 s->started_here = started_here ? 1 : 0;
1170 return 0;
1173 /** Free all storage held by <b>state</b>. */
1174 void
1175 or_handshake_state_free(or_handshake_state_t *state)
1177 if (!state)
1178 return;
1179 memset(state, 0xBE, sizeof(or_handshake_state_t));
1180 tor_free(state);
1183 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1184 * as appropriate. Called when we are done with all TLS and OR handshaking.
1187 connection_or_set_state_open(or_connection_t *conn)
1189 int started_here = connection_or_nonopen_was_started_here(conn);
1190 time_t now = time(NULL);
1191 conn->_base.state = OR_CONN_STATE_OPEN;
1192 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
1194 if (started_here) {
1195 circuit_build_times_network_is_live(&circ_times);
1196 rep_hist_note_connect_succeeded(conn->identity_digest, now);
1197 if (entry_guard_register_connect_status(conn->identity_digest,
1198 1, 0, now) < 0) {
1199 /* Close any circuits pending on this conn. We leave it in state
1200 * 'open' though, because it didn't actually *fail* -- we just
1201 * chose not to use it. (Otherwise
1202 * connection_about_to_close_connection() will call a big pile of
1203 * functions to indicate we shouldn't try it again.) */
1204 log_debug(LD_OR, "New entry guard was reachable, but closing this "
1205 "connection so we can retry the earlier entry guards.");
1206 circuit_n_conn_done(conn, 0);
1207 return -1;
1209 router_set_status(conn->identity_digest, 1);
1210 } else {
1211 /* only report it to the geoip module if it's not a known router */
1212 if (!router_get_by_digest(conn->identity_digest)) {
1213 if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
1214 /*XXXX IP6 support ipv6 geoip.*/
1215 uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
1216 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
1221 or_handshake_state_free(conn->handshake_state);
1222 conn->handshake_state = NULL;
1224 connection_start_reading(TO_CONN(conn));
1225 circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
1227 return 0;
1230 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1231 * For cells that use or affect a circuit, this should only be called by
1232 * connection_or_flush_from_first_active_circuit().
1234 void
1235 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
1237 packed_cell_t networkcell;
1239 tor_assert(cell);
1240 tor_assert(conn);
1242 cell_pack(&networkcell, cell);
1244 connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
1246 if (cell->command != CELL_PADDING)
1247 conn->timestamp_last_added_nonpadding = approx_time();
1250 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1251 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1252 * affect a circuit.
1254 void
1255 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
1256 or_connection_t *conn)
1258 char hdr[VAR_CELL_HEADER_SIZE];
1259 tor_assert(cell);
1260 tor_assert(conn);
1261 var_cell_pack_header(cell, hdr);
1262 connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
1263 connection_write_to_buf((char*)cell->payload,
1264 cell->payload_len, TO_CONN(conn));
1265 if (cell->command != CELL_PADDING)
1266 conn->timestamp_last_added_nonpadding = approx_time();
1269 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1270 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1271 static int
1272 connection_fetch_var_cell_from_buf(or_connection_t *conn, var_cell_t **out)
1274 return fetch_var_cell_from_buf(conn->_base.inbuf, out, conn->link_proto);
1277 /** Process cells from <b>conn</b>'s inbuf.
1279 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1280 * and hand it to command_process_cell().
1282 * Always return 0.
1284 static int
1285 connection_or_process_cells_from_inbuf(or_connection_t *conn)
1287 var_cell_t *var_cell;
1289 while (1) {
1290 log_debug(LD_OR,
1291 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1292 conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
1293 tor_tls_get_pending_bytes(conn->tls));
1294 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
1295 if (!var_cell)
1296 return 0; /* not yet. */
1297 circuit_build_times_network_is_live(&circ_times);
1298 command_process_var_cell(var_cell, conn);
1299 var_cell_free(var_cell);
1300 } else {
1301 char buf[CELL_NETWORK_SIZE];
1302 cell_t cell;
1303 if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
1304 available? */
1305 return 0; /* not yet */
1307 circuit_build_times_network_is_live(&circ_times);
1308 connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
1310 /* retrieve cell info from buf (create the host-order struct from the
1311 * network-order string) */
1312 cell_unpack(&cell, buf);
1314 command_process_cell(&cell, conn);
1319 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1320 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1321 * we may want to propagate reasons from other cells.
1323 * Return 0.
1326 connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
1328 cell_t cell;
1330 tor_assert(conn);
1332 memset(&cell, 0, sizeof(cell_t));
1333 cell.circ_id = circ_id;
1334 cell.command = CELL_DESTROY;
1335 cell.payload[0] = (uint8_t) reason;
1336 log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
1338 connection_or_write_cell_to_buf(&cell, conn);
1339 return 0;
1342 /** Array of recognized link protocol versions. */
1343 static const uint16_t or_protocol_versions[] = { 1, 2 };
1344 /** Number of versions in <b>or_protocol_versions</b>. */
1345 static const int n_or_protocol_versions =
1346 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
1348 /** Return true iff <b>v</b> is a link protocol version that this Tor
1349 * implementation believes it can support. */
1351 is_or_protocol_version_known(uint16_t v)
1353 int i;
1354 for (i = 0; i < n_or_protocol_versions; ++i) {
1355 if (or_protocol_versions[i] == v)
1356 return 1;
1358 return 0;
1361 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1362 * link protocol versions that this Tor can support. */
1363 static int
1364 connection_or_send_versions(or_connection_t *conn)
1366 var_cell_t *cell;
1367 int i;
1368 tor_assert(conn->handshake_state &&
1369 !conn->handshake_state->sent_versions_at);
1370 cell = var_cell_new(n_or_protocol_versions * 2);
1371 cell->command = CELL_VERSIONS;
1372 for (i = 0; i < n_or_protocol_versions; ++i) {
1373 uint16_t v = or_protocol_versions[i];
1374 set_uint16(cell->payload+(2*i), htons(v));
1377 connection_or_write_var_cell_to_buf(cell, conn);
1378 conn->handshake_state->sent_versions_at = time(NULL);
1380 var_cell_free(cell);
1381 return 0;
1384 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1385 * about their address, our address, and the current time. */
1387 connection_or_send_netinfo(or_connection_t *conn)
1389 cell_t cell;
1390 time_t now = time(NULL);
1391 routerinfo_t *me;
1392 int len;
1393 uint8_t *out;
1395 memset(&cell, 0, sizeof(cell_t));
1396 cell.command = CELL_NETINFO;
1398 /* Timestamp. */
1399 set_uint32(cell.payload, htonl((uint32_t)now));
1401 /* Their address. */
1402 out = cell.payload + 4;
1403 len = append_address_to_payload(out, &conn->_base.addr);
1404 if (len<0)
1405 return -1;
1406 out += len;
1408 /* My address. */
1409 if ((me = router_get_my_routerinfo())) {
1410 tor_addr_t my_addr;
1411 *out++ = 1; /* only one address is supported. */
1413 tor_addr_from_ipv4h(&my_addr, me->addr);
1414 len = append_address_to_payload(out, &my_addr);
1415 if (len < 0)
1416 return -1;
1417 out += len;
1418 } else {
1419 *out++ = 0;
1422 connection_or_write_cell_to_buf(&cell, conn);
1424 return 0;