Don't use log_err for non-criticial warnings.
[tor/rransom.git] / src / or / connection_or.c
blob052da6763290620dc6c7ea7067634b61537e2e88
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-2010, 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 static void
358 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
359 or_options_t *options)
361 int rate, burst; /* per-connection rate limiting params */
362 if (connection_or_digest_is_known_relay(conn->identity_digest)) {
363 /* It's in the consensus, or we have a descriptor for it meaning it
364 * was probably in a recent consensus. It's a recognized relay:
365 * give it full bandwidth. */
366 rate = (int)options->BandwidthRate;
367 burst = (int)options->BandwidthBurst;
368 } else {
369 /* Not a recognized relay. Squeeze it down based on the suggested
370 * bandwidth parameters in the consensus, but allow local config
371 * options to override. */
372 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
373 (int)networkstatus_get_param(NULL, "perconnbwrate",
374 (int)options->BandwidthRate);
375 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
376 (int)networkstatus_get_param(NULL, "perconnbwburst",
377 (int)options->BandwidthBurst);
380 conn->bandwidthrate = rate;
381 conn->bandwidthburst = burst;
382 if (reset) { /* set up the token buckets to be full */
383 conn->read_bucket = conn->write_bucket = burst;
384 return;
386 /* If the new token bucket is smaller, take out the extra tokens.
387 * (If it's larger, don't -- the buckets can grow to reach the cap.) */
388 if (conn->read_bucket > burst)
389 conn->read_bucket = burst;
390 if (conn->write_bucket > burst)
391 conn->write_bucket = burst;
394 /** Either our set of relays or our per-conn rate limits have changed.
395 * Go through all the OR connections and update their token buckets. */
396 void
397 connection_or_update_token_buckets(smartlist_t *conns, or_options_t *options)
399 SMARTLIST_FOREACH(conns, connection_t *, conn,
401 if (connection_speaks_cells(conn))
402 connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
406 /** If we don't necessarily know the router we're connecting to, but we
407 * have an addr/port/id_digest, then fill in as much as we can. Start
408 * by checking to see if this describes a router we know. */
409 static void
410 connection_or_init_conn_from_address(or_connection_t *conn,
411 const tor_addr_t *addr, uint16_t port,
412 const char *id_digest,
413 int started_here)
415 routerinfo_t *r = router_get_by_digest(id_digest);
416 connection_or_set_identity_digest(conn, id_digest);
417 connection_or_update_token_buckets_helper(conn, 1, get_options());
419 conn->_base.port = port;
420 tor_addr_copy(&conn->_base.addr, addr);
421 tor_addr_copy(&conn->real_addr, addr);
422 if (r) {
423 /* XXXX proposal 118 will make this more complex. */
424 if (tor_addr_eq_ipv4h(&conn->_base.addr, r->addr))
425 conn->is_canonical = 1;
426 if (!started_here) {
427 /* Override the addr/port, so our log messages will make sense.
428 * This is dangerous, since if we ever try looking up a conn by
429 * its actual addr/port, we won't remember. Careful! */
430 /* XXXX arma: this is stupid, and it's the reason we need real_addr
431 * to track is_canonical properly. What requires it? */
432 /* XXXX <arma> i believe the reason we did this, originally, is because
433 * we wanted to log what OR a connection was to, and if we logged the
434 * right IP address and port 56244, that wouldn't be as helpful. now we
435 * log the "right" port too, so we know if it's moria1 or moria2.
437 tor_addr_from_ipv4h(&conn->_base.addr, r->addr);
438 conn->_base.port = r->or_port;
440 conn->nickname = tor_strdup(r->nickname);
441 tor_free(conn->_base.address);
442 conn->_base.address = tor_strdup(r->address);
443 } else {
444 const char *n;
445 /* If we're an authoritative directory server, we may know a
446 * nickname for this router. */
447 n = dirserv_get_nickname_by_digest(id_digest);
448 if (n) {
449 conn->nickname = tor_strdup(n);
450 } else {
451 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
452 conn->nickname[0] = '$';
453 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
454 conn->identity_digest, DIGEST_LEN);
456 tor_free(conn->_base.address);
457 conn->_base.address = tor_dup_addr(addr);
461 /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
463 * A more canonical connection is always better than a less canonical
464 * connection. That aside, a connection is better if it has circuits and the
465 * other does not, or if it was created more recently.
467 * Requires that both input connections are open; not is_bad_for_new_circs,
468 * and not impossibly non-canonical.
470 * If </b>forgive_new_connections</b> is true, then we do not call
471 * <b>a</b>better than <b>b</b> simply because b has no circuits,
472 * unless b is also relatively old.
474 static int
475 connection_or_is_better(time_t now,
476 const or_connection_t *a,
477 const or_connection_t *b,
478 int forgive_new_connections)
480 int newer;
481 /** Do not definitively deprecate a new connection with no circuits on it
482 * until this much time has passed. */
483 #define NEW_CONN_GRACE_PERIOD (15*60)
485 if (b->is_canonical && !a->is_canonical)
486 return 0; /* A canonical connection is better than a non-canonical
487 * one, no matter how new it is or which has circuits. */
489 newer = b->_base.timestamp_created < a->_base.timestamp_created;
491 if (
492 /* We prefer canonical connections regardless of newness. */
493 (!b->is_canonical && a->is_canonical) ||
494 /* If both have circuits we prefer the newer: */
495 (b->n_circuits && a->n_circuits && newer) ||
496 /* If neither has circuits we prefer the newer: */
497 (!b->n_circuits && !a->n_circuits && newer))
498 return 1;
500 /* If one has no circuits and the other does... */
501 if (!b->n_circuits && a->n_circuits) {
502 /* Then it's bad, unless it's in its grace period and we're forgiving. */
503 if (forgive_new_connections &&
504 now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
505 return 0;
506 else
507 return 1;
510 return 0;
513 /** Return the OR connection we should use to extend a circuit to the router
514 * whose identity is <b>digest</b>, and whose address we believe (or have been
515 * told in an extend cell) is <b>target_addr</b>. If there is no good
516 * connection, set *<b>msg_out</b> to a message describing the connection's
517 * state and our next action, and set <b>launch_out</b> to a boolean for
518 * whether we should launch a new connection or not.
520 or_connection_t *
521 connection_or_get_for_extend(const char *digest,
522 const tor_addr_t *target_addr,
523 const char **msg_out,
524 int *launch_out)
526 or_connection_t *conn, *best=NULL;
527 int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
528 time_t now = approx_time();
530 tor_assert(msg_out);
531 tor_assert(launch_out);
533 if (!orconn_identity_map) {
534 *msg_out = "Router not connected (nothing is). Connecting.";
535 *launch_out = 1;
536 return NULL;
539 conn = digestmap_get(orconn_identity_map, digest);
541 for (; conn; conn = conn->next_with_same_id) {
542 tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
543 tor_assert(conn->_base.type == CONN_TYPE_OR);
544 tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
545 if (conn->_base.marked_for_close)
546 continue;
547 /* Never return a non-open connection. */
548 if (conn->_base.state != OR_CONN_STATE_OPEN) {
549 /* If the address matches, don't launch a new connection for this
550 * circuit. */
551 if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
552 ++n_inprogress_goodaddr;
553 continue;
555 /* Never return a connection that shouldn't be used for circs. */
556 if (conn->is_bad_for_new_circs) {
557 ++n_old;
558 continue;
560 /* Never return a non-canonical connection using a recent link protocol
561 * if the address is not what we wanted.
563 * (For old link protocols, we can't rely on is_canonical getting
564 * set properly if we're talking to the right address, since we might
565 * have an out-of-date descriptor, and we will get no NETINFO cell to
566 * tell us about the right address.) */
567 if (!conn->is_canonical && conn->link_proto >= 2 &&
568 tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
569 ++n_noncanonical;
570 continue;
573 ++n_possible;
575 if (!best) {
576 best = conn; /* If we have no 'best' so far, this one is good enough. */
577 continue;
580 if (connection_or_is_better(now, conn, best, 0))
581 best = conn;
584 if (best) {
585 *msg_out = "Connection is fine; using it.";
586 *launch_out = 0;
587 return best;
588 } else if (n_inprogress_goodaddr) {
589 *msg_out = "Connection in progress; waiting.";
590 *launch_out = 0;
591 return NULL;
592 } else if (n_old || n_noncanonical) {
593 *msg_out = "Connections all too old, or too non-canonical. "
594 " Launching a new one.";
595 *launch_out = 1;
596 return NULL;
597 } else {
598 *msg_out = "Not connected. Connecting.";
599 *launch_out = 1;
600 return NULL;
604 /** How old do we let a connection to an OR get before deciding it's
605 * too old for new circuits? */
606 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
608 /** Given the head of the linked list for all the or_connections with a given
609 * identity, set elements of that list as is_bad_for_new_circs as
610 * appropriate. Helper for connection_or_set_bad_connections().
612 * Specifically, we set the is_bad_for_new_circs flag on:
613 * - all connections if <b>force</b> is true.
614 * - all connections that are too old.
615 * - all open non-canonical connections for which a canonical connection
616 * exists to the same router.
617 * - all open canonical connections for which a 'better' canonical
618 * connection exists to the same router.
619 * - all open non-canonical connections for which a 'better' non-canonical
620 * connection exists to the same router at the same address.
622 * See connection_or_is_better() for our idea of what makes one OR connection
623 * better than another.
625 static void
626 connection_or_group_set_badness(or_connection_t *head, int force)
628 or_connection_t *or_conn = NULL, *best = NULL;
629 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
630 time_t now = time(NULL);
632 /* Pass 1: expire everything that's old, and see what the status of
633 * everything else is. */
634 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
635 if (or_conn->_base.marked_for_close ||
636 or_conn->is_bad_for_new_circs)
637 continue;
638 if (force ||
639 or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
640 < now) {
641 log_info(LD_OR,
642 "Marking OR conn to %s:%d as too old for new circuits "
643 "(fd %d, %d secs old).",
644 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
645 (int)(now - or_conn->_base.timestamp_created));
646 or_conn->is_bad_for_new_circs = 1;
649 if (or_conn->is_bad_for_new_circs) {
650 ++n_old;
651 } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
652 ++n_inprogress;
653 } else if (or_conn->is_canonical) {
654 ++n_canonical;
655 } else {
656 ++n_other;
660 /* Pass 2: We know how about how good the best connection is.
661 * expire everything that's worse, and find the very best if we can. */
662 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
663 if (or_conn->_base.marked_for_close ||
664 or_conn->is_bad_for_new_circs)
665 continue; /* This one doesn't need to be marked bad. */
666 if (or_conn->_base.state != OR_CONN_STATE_OPEN)
667 continue; /* Don't mark anything bad until we have seen what happens
668 * when the connection finishes. */
669 if (n_canonical && !or_conn->is_canonical) {
670 /* We have at least one open canonical connection to this router,
671 * and this one is open but not canonical. Mark it bad. */
672 log_info(LD_OR,
673 "Marking OR conn to %s:%d as unsuitable for new circuits: "
674 "(fd %d, %d secs old). It is not canonical, and we have "
675 "another connection to that OR that is.",
676 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
677 (int)(now - or_conn->_base.timestamp_created));
678 or_conn->is_bad_for_new_circs = 1;
679 continue;
682 if (!best || connection_or_is_better(now, or_conn, best, 0))
683 best = or_conn;
686 if (!best)
687 return;
689 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
690 * every other open connection. If it's non-canonical, mark as bad
691 * every other open connection to the same address.
693 * XXXX This isn't optimal; if we have connections to an OR at multiple
694 * addresses, we'd like to pick the best _for each address_, and mark as
695 * bad every open connection that isn't best for its address. But this
696 * can only occur in cases where the other OR is old (so we have no
697 * canonical connection to it), or where all the connections to the OR are
698 * at noncanonical addresses and we have no good direct connection (which
699 * means we aren't at risk of attaching circuits to it anyway). As
700 * 0.1.2.x dies out, the first case will go away, and the second one is
701 * "mostly harmless", so a fix can wait until somebody is bored.
703 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
704 if (or_conn->_base.marked_for_close ||
705 or_conn->is_bad_for_new_circs ||
706 or_conn->_base.state != OR_CONN_STATE_OPEN)
707 continue;
708 if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
709 /* This isn't the best conn, _and_ the best conn is better than it,
710 even when we're being forgiving. */
711 if (best->is_canonical) {
712 log_info(LD_OR,
713 "Marking OR conn to %s:%d as unsuitable for new circuits: "
714 "(fd %d, %d secs old). We have a better canonical one "
715 "(fd %d; %d secs old).",
716 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
717 (int)(now - or_conn->_base.timestamp_created),
718 best->_base.s, (int)(now - best->_base.timestamp_created));
719 or_conn->is_bad_for_new_circs = 1;
720 } else if (!tor_addr_compare(&or_conn->real_addr,
721 &best->real_addr, CMP_EXACT)) {
722 log_info(LD_OR,
723 "Marking OR conn to %s:%d as unsuitable for new circuits: "
724 "(fd %d, %d secs old). We have a better one with the "
725 "same address (fd %d; %d secs old).",
726 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
727 (int)(now - or_conn->_base.timestamp_created),
728 best->_base.s, (int)(now - best->_base.timestamp_created));
729 or_conn->is_bad_for_new_circs = 1;
735 /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
736 * the OR connections with that digest), and set the is_bad_for_new_circs
737 * flag based on the rules in connection_or_group_set_badness() (or just
738 * always set it if <b>force</b> is true).
740 void
741 connection_or_set_bad_connections(const char *digest, int force)
743 if (!orconn_identity_map)
744 return;
746 DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
747 if (!digest || !memcmp(digest, conn->identity_digest, DIGEST_LEN))
748 connection_or_group_set_badness(conn, force);
749 } DIGESTMAP_FOREACH_END;
752 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
753 * a TCP connection. Send notifications appropriately.
755 * <b>reason</b> specifies the or_conn_end_reason for the failure;
756 * <b>msg</b> specifies the strerror-style error message.
758 void
759 connection_or_connect_failed(or_connection_t *conn,
760 int reason, const char *msg)
762 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
763 if (!authdir_mode_tests_reachability(get_options()))
764 control_event_bootstrap_problem(msg, reason);
767 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
768 * handshake with an OR with identity digest <b>id_digest</b>.
770 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
771 * return that connection. If the connect() is in progress, set the
772 * new conn's state to 'connecting' and return it. If connect() succeeds,
773 * call connection_tls_start_handshake() on it.
775 * This function is called from router_retry_connections(), for
776 * ORs connecting to ORs, and circuit_establish_circuit(), for
777 * OPs connecting to ORs.
779 * Return the launched conn, or NULL if it failed.
781 or_connection_t *
782 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
783 const char *id_digest)
785 or_connection_t *conn;
786 or_options_t *options = get_options();
787 int socket_error = 0;
788 int using_proxy = 0;
789 tor_addr_t addr;
791 tor_assert(_addr);
792 tor_assert(id_digest);
793 tor_addr_copy(&addr, _addr);
795 if (server_mode(options) && router_digest_is_me(id_digest)) {
796 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
797 return NULL;
800 conn = or_connection_new(AF_INET);
802 /* set up conn so it's got all the data we need to remember */
803 connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
804 conn->_base.state = OR_CONN_STATE_CONNECTING;
805 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
807 /* use a proxy server if available */
808 if (options->HttpsProxy) {
809 using_proxy = 1;
810 tor_addr_copy(&addr, &options->HttpsProxyAddr);
811 port = options->HttpsProxyPort;
812 } else if (options->Socks4Proxy) {
813 using_proxy = 1;
814 tor_addr_copy(&addr, &options->Socks4ProxyAddr);
815 port = options->Socks4ProxyPort;
816 } else if (options->Socks5Proxy) {
817 using_proxy = 1;
818 tor_addr_copy(&addr, &options->Socks5ProxyAddr);
819 port = options->Socks5ProxyPort;
822 switch (connection_connect(TO_CONN(conn), conn->_base.address,
823 &addr, port, &socket_error)) {
824 case -1:
825 /* If the connection failed immediately, and we're using
826 * a proxy, our proxy is down. Don't blame the Tor server. */
827 if (!using_proxy)
828 entry_guard_register_connect_status(conn->identity_digest,
829 0, 1, time(NULL));
830 connection_or_connect_failed(conn,
831 errno_to_orconn_end_reason(socket_error),
832 tor_socket_strerror(socket_error));
833 connection_free(TO_CONN(conn));
834 return NULL;
835 case 0:
836 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
837 /* writable indicates finish, readable indicates broken link,
838 error indicates broken link on windows */
839 return conn;
840 /* case 1: fall through */
843 if (connection_or_finished_connecting(conn) < 0) {
844 /* already marked for close */
845 return NULL;
847 return conn;
850 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
851 * we initiated the connection, else it's 1.
853 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
854 * pass <b>conn</b> to connection_tls_continue_handshake().
856 * Return -1 if <b>conn</b> is broken, else return 0.
859 connection_tls_start_handshake(or_connection_t *conn, int receiving)
861 conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
862 conn->tls = tor_tls_new(conn->_base.s, receiving);
863 tor_tls_set_logged_address(conn->tls, // XXX client and relay?
864 escaped_safe_str(conn->_base.address));
865 if (!conn->tls) {
866 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
867 return -1;
869 connection_start_reading(TO_CONN(conn));
870 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
871 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
873 if (connection_tls_continue_handshake(conn) < 0) {
874 return -1;
876 return 0;
879 /** Invoked on the server side from inside tor_tls_read() when the server
880 * gets a successful TLS renegotiation from the client. */
881 static void
882 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
884 or_connection_t *conn = _conn;
885 (void)tls;
887 /* Don't invoke this again. */
888 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
889 tor_tls_block_renegotiation(tls);
891 if (connection_tls_finish_handshake(conn) < 0) {
892 /* XXXX_TLS double-check that it's ok to do this from inside read. */
893 /* XXXX_TLS double-check that this verifies certificates. */
894 connection_mark_for_close(TO_CONN(conn));
898 /** Move forward with the tls handshake. If it finishes, hand
899 * <b>conn</b> to connection_tls_finish_handshake().
901 * Return -1 if <b>conn</b> is broken, else return 0.
904 connection_tls_continue_handshake(or_connection_t *conn)
906 int result;
907 check_no_tls_errors();
908 again:
909 if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
910 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
911 result = tor_tls_renegotiate(conn->tls);
912 // log_notice(LD_OR, "Result: %d", result);
913 } else {
914 tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
915 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
916 result = tor_tls_handshake(conn->tls);
917 // log_notice(LD_OR, "Result: %d", result);
919 switch (result) {
920 CASE_TOR_TLS_ERROR_ANY:
921 log_info(LD_OR,"tls error [%s]. breaking connection.",
922 tor_tls_err_to_string(result));
923 return -1;
924 case TOR_TLS_DONE:
925 if (! tor_tls_used_v1_handshake(conn->tls)) {
926 if (!tor_tls_is_server(conn->tls)) {
927 if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
928 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
929 conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
930 goto again;
932 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
933 } else {
934 /* improved handshake, but not a client. */
935 tor_tls_set_renegotiate_callback(conn->tls,
936 connection_or_tls_renegotiated_cb,
937 conn);
938 conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
939 connection_stop_writing(TO_CONN(conn));
940 connection_start_reading(TO_CONN(conn));
941 return 0;
944 return connection_tls_finish_handshake(conn);
945 case TOR_TLS_WANTWRITE:
946 connection_start_writing(TO_CONN(conn));
947 log_debug(LD_OR,"wanted write");
948 return 0;
949 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
950 log_debug(LD_OR,"wanted read");
951 return 0;
952 case TOR_TLS_CLOSE:
953 log_info(LD_OR,"tls closed. breaking connection.");
954 return -1;
956 return 0;
959 /** Return 1 if we initiated this connection, or 0 if it started
960 * out as an incoming connection.
963 connection_or_nonopen_was_started_here(or_connection_t *conn)
965 tor_assert(conn->_base.type == CONN_TYPE_OR);
966 if (!conn->tls)
967 return 1; /* it's still in proxy states or something */
968 if (conn->handshake_state)
969 return conn->handshake_state->started_here;
970 return !tor_tls_is_server(conn->tls);
973 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
974 * return -1 if he is lying, broken, or otherwise something is wrong.
976 * If we initiated this connection (<b>started_here</b> is true), make sure
977 * the other side sent a correctly formed certificate. If I initiated the
978 * connection, make sure it's the right guy.
980 * Otherwise (if we _didn't_ initiate this connection), it's okay for
981 * the certificate to be weird or absent.
983 * If we return 0, and the certificate is as expected, write a hash of the
984 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
985 * space in it.
986 * If the certificate is invalid or missing on an incoming connection,
987 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
988 * (If we return -1, the contents of this buffer are undefined.)
990 * As side effects,
991 * 1) Set conn->circ_id_type according to tor-spec.txt.
992 * 2) If we're an authdirserver and we initiated the connection: drop all
993 * descriptors that claim to be on that IP/port but that aren't
994 * this guy; and note that this guy is reachable.
995 * 3) If this is a bridge and we didn't configure its identity
996 * fingerprint, remember the keyid we just learned.
998 static int
999 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1000 int started_here,
1001 char *digest_rcvd_out)
1003 crypto_pk_env_t *identity_rcvd=NULL;
1004 or_options_t *options = get_options();
1005 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1006 const char *safe_address =
1007 started_here ? conn->_base.address :
1008 safe_str_client(conn->_base.address);
1009 const char *conn_type = started_here ? "outgoing" : "incoming";
1010 crypto_pk_env_t *our_identity =
1011 started_here ? get_tlsclient_identity_key() :
1012 get_server_identity_key();
1013 int has_cert = 0, has_identity=0;
1015 check_no_tls_errors();
1016 has_cert = tor_tls_peer_has_cert(conn->tls);
1017 if (started_here && !has_cert) {
1018 log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1019 "send a cert! Closing.",
1020 safe_address, conn->_base.port);
1021 return -1;
1022 } else if (!has_cert) {
1023 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1024 "That's ok.");
1026 check_no_tls_errors();
1028 if (has_cert) {
1029 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1030 conn->tls, &identity_rcvd);
1031 if (started_here && v<0) {
1032 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1033 " has a cert but it's invalid. Closing.",
1034 safe_address, conn->_base.port);
1035 return -1;
1036 } else if (v<0) {
1037 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1038 "chain; ignoring.");
1039 } else {
1040 log_debug(LD_HANDSHAKE,
1041 "The certificate seems to be valid on %s connection "
1042 "with %s:%d", conn_type, safe_address, conn->_base.port);
1044 check_no_tls_errors();
1047 if (identity_rcvd) {
1048 has_identity = 1;
1049 crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
1050 if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
1051 conn->circ_id_type = CIRC_ID_TYPE_LOWER;
1052 } else {
1053 conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
1055 crypto_free_pk_env(identity_rcvd);
1056 } else {
1057 memset(digest_rcvd_out, 0, DIGEST_LEN);
1058 conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
1061 if (started_here && tor_digest_is_zero(conn->identity_digest)) {
1062 connection_or_set_identity_digest(conn, digest_rcvd_out);
1063 tor_free(conn->nickname);
1064 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1065 conn->nickname[0] = '$';
1066 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1067 conn->identity_digest, DIGEST_LEN);
1068 log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1069 "its key. Hoping for the best.",
1070 conn->nickname, conn->_base.address, conn->_base.port);
1071 /* if it's a bridge and we didn't know its identity fingerprint, now
1072 * we do -- remember it for future attempts. */
1073 learned_router_identity(&conn->_base.addr, conn->_base.port,
1074 digest_rcvd_out);
1077 if (started_here) {
1078 int as_advertised = 1;
1079 tor_assert(has_cert);
1080 tor_assert(has_identity);
1081 if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
1082 /* I was aiming for a particular digest. I didn't get it! */
1083 char seen[HEX_DIGEST_LEN+1];
1084 char expected[HEX_DIGEST_LEN+1];
1085 base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
1086 base16_encode(expected, sizeof(expected), conn->identity_digest,
1087 DIGEST_LEN);
1088 log_fn(severity, LD_HANDSHAKE,
1089 "Tried connecting to router at %s:%d, but identity key was not "
1090 "as expected: wanted %s but got %s.",
1091 conn->_base.address, conn->_base.port, expected, seen);
1092 entry_guard_register_connect_status(conn->identity_digest, 0, 1,
1093 time(NULL));
1094 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1095 END_OR_CONN_REASON_OR_IDENTITY);
1096 if (!authdir_mode_tests_reachability(options))
1097 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
1098 as_advertised = 0;
1100 if (authdir_mode_tests_reachability(options)) {
1101 /* We initiated this connection to address:port. Drop all routers
1102 * with the same address:port and a different key.
1104 dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
1105 digest_rcvd_out, as_advertised);
1107 if (!as_advertised)
1108 return -1;
1110 return 0;
1113 /** The tls handshake is finished.
1115 * Make sure we are happy with the person we just handshaked with.
1117 * If he initiated the connection, make sure he's not already connected,
1118 * then initialize conn from the information in router.
1120 * If all is successful, call circuit_n_conn_done() to handle events
1121 * that have been pending on the <tls handshake completion. Also set the
1122 * directory to be dirty (only matters if I'm an authdirserver).
1124 static int
1125 connection_tls_finish_handshake(or_connection_t *conn)
1127 char digest_rcvd[DIGEST_LEN];
1128 int started_here = connection_or_nonopen_was_started_here(conn);
1130 log_debug(LD_HANDSHAKE,"tls handshake with %s done. verifying.",
1131 safe_str_client(conn->_base.address));
1133 directory_set_dirty();
1135 if (connection_or_check_valid_tls_handshake(conn, started_here,
1136 digest_rcvd) < 0)
1137 return -1;
1139 circuit_build_times_network_is_live(&circ_times);
1141 if (tor_tls_used_v1_handshake(conn->tls)) {
1142 conn->link_proto = 1;
1143 if (!started_here) {
1144 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1145 conn->_base.port, digest_rcvd, 0);
1147 tor_tls_block_renegotiation(conn->tls);
1148 return connection_or_set_state_open(conn);
1149 } else {
1150 conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
1151 if (connection_init_or_handshake_state(conn, started_here) < 0)
1152 return -1;
1153 if (!started_here) {
1154 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1155 conn->_base.port, digest_rcvd, 0);
1157 return connection_or_send_versions(conn);
1161 /** Allocate a new connection handshake state for the connection
1162 * <b>conn</b>. Return 0 on success, -1 on failure. */
1163 static int
1164 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
1166 or_handshake_state_t *s;
1167 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
1168 s->started_here = started_here ? 1 : 0;
1169 return 0;
1172 /** Free all storage held by <b>state</b>. */
1173 void
1174 or_handshake_state_free(or_handshake_state_t *state)
1176 if (!state)
1177 return;
1178 memset(state, 0xBE, sizeof(or_handshake_state_t));
1179 tor_free(state);
1182 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1183 * as appropriate. Called when we are done with all TLS and OR handshaking.
1186 connection_or_set_state_open(or_connection_t *conn)
1188 int started_here = connection_or_nonopen_was_started_here(conn);
1189 time_t now = time(NULL);
1190 conn->_base.state = OR_CONN_STATE_OPEN;
1191 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
1193 if (started_here) {
1194 circuit_build_times_network_is_live(&circ_times);
1195 rep_hist_note_connect_succeeded(conn->identity_digest, now);
1196 if (entry_guard_register_connect_status(conn->identity_digest,
1197 1, 0, now) < 0) {
1198 /* Close any circuits pending on this conn. We leave it in state
1199 * 'open' though, because it didn't actually *fail* -- we just
1200 * chose not to use it. (Otherwise
1201 * connection_about_to_close_connection() will call a big pile of
1202 * functions to indicate we shouldn't try it again.) */
1203 log_debug(LD_OR, "New entry guard was reachable, but closing this "
1204 "connection so we can retry the earlier entry guards.");
1205 circuit_n_conn_done(conn, 0);
1206 return -1;
1208 router_set_status(conn->identity_digest, 1);
1209 } else {
1210 /* only report it to the geoip module if it's not a known router */
1211 if (!router_get_by_digest(conn->identity_digest)) {
1212 if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
1213 /*XXXX IP6 support ipv6 geoip.*/
1214 uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
1215 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
1220 or_handshake_state_free(conn->handshake_state);
1221 conn->handshake_state = NULL;
1223 connection_start_reading(TO_CONN(conn));
1224 circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
1226 return 0;
1229 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1230 * For cells that use or affect a circuit, this should only be called by
1231 * connection_or_flush_from_first_active_circuit().
1233 void
1234 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
1236 packed_cell_t networkcell;
1238 tor_assert(cell);
1239 tor_assert(conn);
1241 cell_pack(&networkcell, cell);
1243 connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
1245 if (cell->command != CELL_PADDING)
1246 conn->timestamp_last_added_nonpadding = approx_time();
1249 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1250 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1251 * affect a circuit.
1253 void
1254 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
1255 or_connection_t *conn)
1257 char hdr[VAR_CELL_HEADER_SIZE];
1258 tor_assert(cell);
1259 tor_assert(conn);
1260 var_cell_pack_header(cell, hdr);
1261 connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
1262 connection_write_to_buf(cell->payload, cell->payload_len, TO_CONN(conn));
1263 if (cell->command != CELL_PADDING)
1264 conn->timestamp_last_added_nonpadding = approx_time();
1267 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1268 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1269 static int
1270 connection_fetch_var_cell_from_buf(or_connection_t *conn, var_cell_t **out)
1272 return fetch_var_cell_from_buf(conn->_base.inbuf, out, conn->link_proto);
1275 /** Process cells from <b>conn</b>'s inbuf.
1277 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1278 * and hand it to command_process_cell().
1280 * Always return 0.
1282 static int
1283 connection_or_process_cells_from_inbuf(or_connection_t *conn)
1285 var_cell_t *var_cell;
1287 while (1) {
1288 log_debug(LD_OR,
1289 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1290 conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
1291 tor_tls_get_pending_bytes(conn->tls));
1292 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
1293 if (!var_cell)
1294 return 0; /* not yet. */
1295 circuit_build_times_network_is_live(&circ_times);
1296 command_process_var_cell(var_cell, conn);
1297 var_cell_free(var_cell);
1298 } else {
1299 char buf[CELL_NETWORK_SIZE];
1300 cell_t cell;
1301 if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
1302 available? */
1303 return 0; /* not yet */
1305 circuit_build_times_network_is_live(&circ_times);
1306 connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
1308 /* retrieve cell info from buf (create the host-order struct from the
1309 * network-order string) */
1310 cell_unpack(&cell, buf);
1312 command_process_cell(&cell, conn);
1317 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1318 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1319 * we may want to propagate reasons from other cells.
1321 * Return 0.
1324 connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
1326 cell_t cell;
1328 tor_assert(conn);
1330 memset(&cell, 0, sizeof(cell_t));
1331 cell.circ_id = circ_id;
1332 cell.command = CELL_DESTROY;
1333 cell.payload[0] = (uint8_t) reason;
1334 log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
1336 connection_or_write_cell_to_buf(&cell, conn);
1337 return 0;
1340 /** Array of recognized link protocol versions. */
1341 static const uint16_t or_protocol_versions[] = { 1, 2 };
1342 /** Number of versions in <b>or_protocol_versions</b>. */
1343 static const int n_or_protocol_versions =
1344 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
1346 /** Return true iff <b>v</b> is a link protocol version that this Tor
1347 * implementation believes it can support. */
1349 is_or_protocol_version_known(uint16_t v)
1351 int i;
1352 for (i = 0; i < n_or_protocol_versions; ++i) {
1353 if (or_protocol_versions[i] == v)
1354 return 1;
1356 return 0;
1359 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1360 * link protocol versions that this Tor can support. */
1361 static int
1362 connection_or_send_versions(or_connection_t *conn)
1364 var_cell_t *cell;
1365 int i;
1366 tor_assert(conn->handshake_state &&
1367 !conn->handshake_state->sent_versions_at);
1368 cell = var_cell_new(n_or_protocol_versions * 2);
1369 cell->command = CELL_VERSIONS;
1370 for (i = 0; i < n_or_protocol_versions; ++i) {
1371 uint16_t v = or_protocol_versions[i];
1372 set_uint16(cell->payload+(2*i), htons(v));
1375 connection_or_write_var_cell_to_buf(cell, conn);
1376 conn->handshake_state->sent_versions_at = time(NULL);
1378 var_cell_free(cell);
1379 return 0;
1382 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1383 * about their address, our address, and the current time. */
1385 connection_or_send_netinfo(or_connection_t *conn)
1387 cell_t cell;
1388 time_t now = time(NULL);
1389 routerinfo_t *me;
1390 int len;
1391 char *out;
1393 memset(&cell, 0, sizeof(cell_t));
1394 cell.command = CELL_NETINFO;
1396 /* Timestamp. */
1397 set_uint32(cell.payload, htonl((uint32_t)now));
1399 /* Their address. */
1400 out = cell.payload + 4;
1401 len = append_address_to_payload(out, &conn->_base.addr);
1402 if (len<0)
1403 return -1;
1404 out += len;
1406 /* My address. */
1407 if ((me = router_get_my_routerinfo())) {
1408 tor_addr_t my_addr;
1409 *out++ = 1; /* only one address is supported. */
1411 tor_addr_from_ipv4h(&my_addr, me->addr);
1412 len = append_address_to_payload(out, &my_addr);
1413 if (len < 0)
1414 return -1;
1415 out += len;
1416 } else {
1417 *out++ = 0;
1420 connection_or_write_cell_to_buf(&cell, conn);
1422 return 0;