Detect and disallow compression bombs
[tor/rransom.git] / src / or / connection_or.c
blobe70edc7c8fae7248c607f8bc80d58b5fd4ab4b4c
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"
15 static int connection_tls_finish_handshake(or_connection_t *conn);
16 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
17 static int connection_or_send_versions(or_connection_t *conn);
18 static int connection_init_or_handshake_state(or_connection_t *conn,
19 int started_here);
20 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
21 int started_here,
22 char *digest_rcvd_out);
24 /**************************************************************/
26 /** Map from identity digest of connected OR or desired OR to a connection_t
27 * with that identity digest. If there is more than one such connection_t,
28 * they form a linked list, with next_with_same_id as the next pointer. */
29 static digestmap_t *orconn_identity_map = NULL;
31 /** If conn is listed in orconn_identity_map, remove it, and clear
32 * conn->identity_digest. Otherwise do nothing. */
33 void
34 connection_or_remove_from_identity_map(or_connection_t *conn)
36 or_connection_t *tmp;
37 tor_assert(conn);
38 if (!orconn_identity_map)
39 return;
40 tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
41 if (!tmp) {
42 if (!tor_digest_is_zero(conn->identity_digest)) {
43 log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
44 "trying to remove it.",
45 conn->nickname ? conn->nickname : "NULL");
47 return;
49 if (conn == tmp) {
50 if (conn->next_with_same_id)
51 digestmap_set(orconn_identity_map, conn->identity_digest,
52 conn->next_with_same_id);
53 else
54 digestmap_remove(orconn_identity_map, conn->identity_digest);
55 } else {
56 while (tmp->next_with_same_id) {
57 if (tmp->next_with_same_id == conn) {
58 tmp->next_with_same_id = conn->next_with_same_id;
59 break;
61 tmp = tmp->next_with_same_id;
64 memset(conn->identity_digest, 0, DIGEST_LEN);
65 conn->next_with_same_id = NULL;
68 /** Remove all entries from the identity-to-orconn map, and clear
69 * all identities in OR conns.*/
70 void
71 connection_or_clear_identity_map(void)
73 smartlist_t *conns = get_connection_array();
74 SMARTLIST_FOREACH(conns, connection_t *, conn,
76 if (conn->type == CONN_TYPE_OR) {
77 or_connection_t *or_conn = TO_OR_CONN(conn);
78 memset(or_conn->identity_digest, 0, DIGEST_LEN);
79 or_conn->next_with_same_id = NULL;
81 });
83 if (orconn_identity_map) {
84 digestmap_free(orconn_identity_map, NULL);
85 orconn_identity_map = NULL;
89 /** Change conn->identity_digest to digest, and add conn into
90 * orconn_digest_map. */
91 static void
92 connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
94 or_connection_t *tmp;
95 tor_assert(conn);
96 tor_assert(digest);
98 if (!orconn_identity_map)
99 orconn_identity_map = digestmap_new();
100 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN))
101 return;
103 /* If the identity was set previously, remove the old mapping. */
104 if (! tor_digest_is_zero(conn->identity_digest))
105 connection_or_remove_from_identity_map(conn);
107 memcpy(conn->identity_digest, digest, DIGEST_LEN);
109 /* If we're setting the ID to zero, don't add a mapping. */
110 if (tor_digest_is_zero(digest))
111 return;
113 tmp = digestmap_set(orconn_identity_map, digest, conn);
114 conn->next_with_same_id = tmp;
116 #if 1
117 /* Testing code to check for bugs in representation. */
118 for (; tmp; tmp = tmp->next_with_same_id) {
119 tor_assert(!memcmp(tmp->identity_digest, digest, DIGEST_LEN));
120 tor_assert(tmp != conn);
122 #endif
125 /** Pack the cell_t host-order structure <b>src</b> into network-order
126 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
127 * wire format.
129 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
130 * should set it or clear it as appropriate.
132 void
133 cell_pack(packed_cell_t *dst, const cell_t *src)
135 char *dest = dst->body;
136 *(uint16_t*)dest = htons(src->circ_id);
137 *(uint8_t*)(dest+2) = src->command;
138 memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
141 /** Unpack the network-order buffer <b>src</b> into a host-order
142 * cell_t structure <b>dest</b>.
144 static void
145 cell_unpack(cell_t *dest, const char *src)
147 dest->circ_id = ntohs(*(uint16_t*)(src));
148 dest->command = *(uint8_t*)(src+2);
149 memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
152 /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
153 * bytes of <b>hdr_out</b>. */
154 void
155 var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
157 set_uint16(hdr_out, htons(cell->circ_id));
158 set_uint8(hdr_out+2, cell->command);
159 set_uint16(hdr_out+3, htons(cell->payload_len));
162 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
163 * payload space. */
164 var_cell_t *
165 var_cell_new(uint16_t payload_len)
167 var_cell_t *cell = tor_malloc(sizeof(var_cell_t)+payload_len-1);
168 cell->payload_len = payload_len;
169 cell->command = 0;
170 cell->circ_id = 0;
171 return cell;
174 /** Release all space held by <b>cell</b>. */
175 void
176 var_cell_free(var_cell_t *cell)
178 tor_free(cell);
181 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
183 connection_or_reached_eof(or_connection_t *conn)
185 log_info(LD_OR,"OR connection reached EOF. Closing.");
186 connection_mark_for_close(TO_CONN(conn));
187 return 0;
190 /** Read conn's inbuf. If the http response from the proxy is all
191 * here, make sure it's good news, and begin the tls handshake. If
192 * it's bad news, close the connection and return -1. Else return 0
193 * and hope for better luck next time.
195 static int
196 connection_or_read_proxy_response(or_connection_t *or_conn)
198 char *headers;
199 char *reason=NULL;
200 int status_code;
201 time_t date_header;
202 connection_t *conn = TO_CONN(or_conn);
204 switch (fetch_from_buf_http(conn->inbuf,
205 &headers, MAX_HEADERS_SIZE,
206 NULL, NULL, 10000, 0)) {
207 case -1: /* overflow */
208 log_warn(LD_PROTOCOL,
209 "Your https proxy sent back an oversized response. Closing.");
210 return -1;
211 case 0:
212 log_info(LD_OR,"https proxy response not all here yet. Waiting.");
213 return 0;
214 /* case 1, fall through */
217 if (parse_http_response(headers, &status_code, &date_header,
218 NULL, &reason) < 0) {
219 log_warn(LD_OR,
220 "Unparseable headers from proxy (connecting to '%s'). Closing.",
221 conn->address);
222 tor_free(headers);
223 return -1;
225 if (!reason) reason = tor_strdup("[no reason given]");
227 if (status_code == 200) {
228 log_info(LD_OR,
229 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
230 conn->address, escaped(reason));
231 tor_free(reason);
232 if (connection_tls_start_handshake(or_conn, 0) < 0) {
233 /* TLS handshaking error of some kind. */
234 connection_mark_for_close(conn);
236 return -1;
238 return 0;
240 /* else, bad news on the status code */
241 log_warn(LD_OR,
242 "The https proxy sent back an unexpected status code %d (%s). "
243 "Closing.",
244 status_code, escaped(reason));
245 tor_free(reason);
246 connection_mark_for_close(conn);
247 return -1;
250 /** Handle any new bytes that have come in on connection <b>conn</b>.
251 * If conn is in 'open' state, hand it to
252 * connection_or_process_cells_from_inbuf()
253 * (else do nothing).
256 connection_or_process_inbuf(or_connection_t *conn)
258 tor_assert(conn);
260 switch (conn->_base.state) {
261 case OR_CONN_STATE_PROXY_READING:
262 return connection_or_read_proxy_response(conn);
263 case OR_CONN_STATE_OPEN:
264 case OR_CONN_STATE_OR_HANDSHAKING:
265 return connection_or_process_cells_from_inbuf(conn);
266 default:
267 return 0; /* don't do anything */
271 /** When adding cells to an OR connection's outbuf, keep adding until the
272 * outbuf is at least this long, or we run out of cells. */
273 #define OR_CONN_HIGHWATER (32*1024)
275 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
276 * drops below this size. */
277 #define OR_CONN_LOWWATER (16*1024)
279 /** Called whenever we have flushed some data on an or_conn: add more data
280 * from active circuits. */
282 connection_or_flushed_some(or_connection_t *conn)
284 size_t datalen = buf_datalen(conn->_base.outbuf);
285 /* If we're under the low water mark, add cells until we're just over the
286 * high water mark. */
287 if (datalen < OR_CONN_LOWWATER) {
288 ssize_t n = (OR_CONN_HIGHWATER - datalen + CELL_NETWORK_SIZE-1)
289 / CELL_NETWORK_SIZE;
290 time_t now = approx_time();
291 while (conn->active_circuits && n > 0) {
292 int flushed;
293 flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
294 n -= flushed;
297 return 0;
300 /** Connection <b>conn</b> has finished writing and has no bytes left on
301 * its outbuf.
303 * Otherwise it's in state "open": stop writing and return.
305 * If <b>conn</b> is broken, mark it for close and return -1, else
306 * return 0.
309 connection_or_finished_flushing(or_connection_t *conn)
311 tor_assert(conn);
312 assert_connection_ok(TO_CONN(conn),0);
314 switch (conn->_base.state) {
315 case OR_CONN_STATE_PROXY_FLUSHING:
316 log_debug(LD_OR,"finished sending CONNECT to proxy.");
317 conn->_base.state = OR_CONN_STATE_PROXY_READING;
318 connection_stop_writing(TO_CONN(conn));
319 break;
320 case OR_CONN_STATE_OPEN:
321 case OR_CONN_STATE_OR_HANDSHAKING:
322 connection_stop_writing(TO_CONN(conn));
323 break;
324 default:
325 log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
326 tor_fragile_assert();
327 return -1;
329 return 0;
332 /** Connected handler for OR connections: begin the TLS handshake.
335 connection_or_finished_connecting(or_connection_t *or_conn)
337 connection_t *conn;
338 tor_assert(or_conn);
339 conn = TO_CONN(or_conn);
340 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
342 log_debug(LD_OR,"OR connect() to router at %s:%u finished.",
343 conn->address,conn->port);
344 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
346 if (get_options()->HttpsProxy) {
347 char buf[1024];
348 char *base64_authenticator=NULL;
349 const char *authenticator = get_options()->HttpsProxyAuthenticator;
351 if (authenticator) {
352 base64_authenticator = alloc_http_authenticator(authenticator);
353 if (!base64_authenticator)
354 log_warn(LD_OR, "Encoding https authenticator failed");
356 if (base64_authenticator) {
357 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
358 "Proxy-Authorization: Basic %s\r\n\r\n",
359 fmt_addr(&conn->addr),
360 conn->port, base64_authenticator);
361 tor_free(base64_authenticator);
362 } else {
363 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
364 fmt_addr(&conn->addr), conn->port);
366 connection_write_to_buf(buf, strlen(buf), conn);
367 conn->state = OR_CONN_STATE_PROXY_FLUSHING;
368 return 0;
371 if (connection_tls_start_handshake(or_conn, 0) < 0) {
372 /* TLS handshaking error of some kind. */
373 connection_mark_for_close(conn);
374 return -1;
376 return 0;
379 /** If we don't necessarily know the router we're connecting to, but we
380 * have an addr/port/id_digest, then fill in as much as we can. Start
381 * by checking to see if this describes a router we know. */
382 static void
383 connection_or_init_conn_from_address(or_connection_t *conn,
384 const tor_addr_t *addr, uint16_t port,
385 const char *id_digest,
386 int started_here)
388 or_options_t *options = get_options();
389 routerinfo_t *r = router_get_by_digest(id_digest);
390 conn->bandwidthrate = (int)options->BandwidthRate;
391 conn->read_bucket = conn->bandwidthburst = (int)options->BandwidthBurst;
392 connection_or_set_identity_digest(conn, id_digest);
394 conn->_base.port = port;
395 tor_addr_copy(&conn->_base.addr, addr);
396 tor_addr_copy(&conn->real_addr, addr);
397 if (r) {
398 /* XXXX proposal 118 will make this more complex. */
399 if (tor_addr_eq_ipv4h(&conn->_base.addr, r->addr))
400 conn->is_canonical = 1;
401 if (!started_here) {
402 /* Override the addr/port, so our log messages will make sense.
403 * This is dangerous, since if we ever try looking up a conn by
404 * its actual addr/port, we won't remember. Careful! */
405 /* XXXX arma: this is stupid, and it's the reason we need real_addr
406 * to track is_canonical properly. What requires it? */
407 /* XXXX <arma> i believe the reason we did this, originally, is because
408 * we wanted to log what OR a connection was to, and if we logged the
409 * right IP address and port 56244, that wouldn't be as helpful. now we
410 * log the "right" port too, so we know if it's moria1 or moria2.
412 tor_addr_from_ipv4h(&conn->_base.addr, r->addr);
413 conn->_base.port = r->or_port;
415 conn->nickname = tor_strdup(r->nickname);
416 tor_free(conn->_base.address);
417 conn->_base.address = tor_strdup(r->address);
418 } else {
419 const char *n;
420 /* If we're an authoritative directory server, we may know a
421 * nickname for this router. */
422 n = dirserv_get_nickname_by_digest(id_digest);
423 if (n) {
424 conn->nickname = tor_strdup(n);
425 } else {
426 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
427 conn->nickname[0] = '$';
428 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
429 conn->identity_digest, DIGEST_LEN);
431 tor_free(conn->_base.address);
432 conn->_base.address = tor_dup_addr(addr);
436 /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
438 * A more canonical connection is always better than a less canonical
439 * connection. That aside, a connection is better if it has circuits and the
440 * other does not, or if it was created more recently.
442 * Requires that both input connections are open; not is_bad_for_new_circs,
443 * and not impossibly non-canonical.
445 * If </b>forgive_new_connections</b> is true, then we do not call
446 * <b>a</b>better than <b>b</b> simply because b has no circuits,
447 * unless b is also relatively old.
449 static int
450 connection_or_is_better(time_t now,
451 const or_connection_t *a,
452 const or_connection_t *b,
453 int forgive_new_connections)
455 int newer;
456 /** Do not definitively deprecate a new connection with no circuits on it
457 * until this much time has passed. */
458 #define NEW_CONN_GRACE_PERIOD (15*60)
460 if (b->is_canonical && !a->is_canonical)
461 return 0; /* A canonical connection is better than a non-canonical
462 * one, no matter how new it is or which has circuits. */
464 newer = b->_base.timestamp_created < a->_base.timestamp_created;
466 if (
467 /* We prefer canonical connections regardless of newness. */
468 (!b->is_canonical && a->is_canonical) ||
469 /* If both have circuits we prefer the newer: */
470 (b->n_circuits && a->n_circuits && newer) ||
471 /* If neither has circuits we prefer the newer: */
472 (!b->n_circuits && !a->n_circuits && newer))
473 return 1;
475 /* If one has no circuits and the other does... */
476 if (!b->n_circuits && a->n_circuits) {
477 /* Then it's bad, unless it's in its grace period and we're forgiving. */
478 if (forgive_new_connections &&
479 now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
480 return 0;
481 else
482 return 1;
485 return 0;
488 /** Return the OR connection we should use to extend a circuit to the router
489 * whose identity is <b>digest</b>, and whose address we believe (or have been
490 * told in an extend cell) is <b>target_addr</b>. If there is no good
491 * connection, set *<b>msg_out</b> to a message describing the connection's
492 * state and our next action, and set <b>launch_out</b> to a boolean for
493 * whether we should launch a new connection or not.
495 or_connection_t *
496 connection_or_get_for_extend(const char *digest,
497 const tor_addr_t *target_addr,
498 const char **msg_out,
499 int *launch_out)
501 or_connection_t *conn, *best=NULL;
502 int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
503 time_t now = approx_time();
505 tor_assert(msg_out);
506 tor_assert(launch_out);
508 if (!orconn_identity_map) {
509 *msg_out = "Router not connected (nothing is). Connecting.";
510 *launch_out = 1;
511 return NULL;
514 conn = digestmap_get(orconn_identity_map, digest);
516 for (; conn; conn = conn->next_with_same_id) {
517 tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
518 tor_assert(conn->_base.type == CONN_TYPE_OR);
519 tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
520 if (conn->_base.marked_for_close)
521 continue;
522 /* Never return a non-open connection. */
523 if (conn->_base.state != OR_CONN_STATE_OPEN) {
524 /* If the address matches, don't launch a new connection for this
525 * circuit. */
526 if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
527 ++n_inprogress_goodaddr;
528 continue;
530 /* Never return a connection that shouldn't be used for circs. */
531 if (conn->is_bad_for_new_circs) {
532 ++n_old;
533 continue;
535 /* Never return a non-canonical connection using a recent link protocol
536 * if the address is not what we wanted.
538 * (For old link protocols, we can't rely on is_canonical getting
539 * set properly if we're talking to the right address, since we might
540 * have an out-of-date descriptor, and we will get no NETINFO cell to
541 * tell us about the right address.) */
542 if (!conn->is_canonical && conn->link_proto >= 2 &&
543 tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
544 ++n_noncanonical;
545 continue;
548 ++n_possible;
550 if (!best) {
551 best = conn; /* If we have no 'best' so far, this one is good enough. */
552 continue;
555 if (connection_or_is_better(now, conn, best, 0))
556 best = conn;
559 if (best) {
560 *msg_out = "Connection is fine; using it.";
561 *launch_out = 0;
562 return best;
563 } else if (n_inprogress_goodaddr) {
564 *msg_out = "Connection in progress; waiting.";
565 *launch_out = 0;
566 return NULL;
567 } else if (n_old || n_noncanonical) {
568 *msg_out = "Connections all too old, or too non-canonical. "
569 " Launching a new one.";
570 *launch_out = 1;
571 return NULL;
572 } else {
573 *msg_out = "Not connected. Connecting.";
574 *launch_out = 1;
575 return NULL;
579 /** How old do we let a connection to an OR get before deciding it's
580 * too old for new circuits? */
581 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
583 /** Given the head of the linked list for all the or_connections with a given
584 * identity, set elements of that list as is_bad_for_new_circs() as
585 * appropriate. Helper for connection_or_set_bad_connections().
587 static void
588 connection_or_group_set_badness(or_connection_t *head)
590 or_connection_t *or_conn = NULL, *best = NULL;
591 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
592 time_t now = time(NULL);
594 /* Pass 1: expire everything that's old, and see what the status of
595 * everything else is. */
596 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
597 if (or_conn->_base.marked_for_close ||
598 or_conn->is_bad_for_new_circs)
599 continue;
600 if (or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
601 < now) {
602 log_info(LD_OR,
603 "Marking OR conn to %s:%d as too old for new circuits "
604 "(fd %d, %d secs old).",
605 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
606 (int)(now - or_conn->_base.timestamp_created));
607 or_conn->is_bad_for_new_circs = 1;
610 if (or_conn->is_bad_for_new_circs) {
611 ++n_old;
612 } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
613 ++n_inprogress;
614 } else if (or_conn->is_canonical) {
615 ++n_canonical;
616 } else {
617 ++n_other;
621 /* Pass 2: We know how about how good the best connection is.
622 * expire everything that's worse, and find the very best if we can. */
623 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
624 if (or_conn->_base.marked_for_close ||
625 or_conn->is_bad_for_new_circs)
626 continue; /* This one doesn't need to be marked bad. */
627 if (or_conn->_base.state != OR_CONN_STATE_OPEN)
628 continue; /* Don't mark anything bad until we have seen what happens
629 * when the connection finishes. */
630 if (n_canonical && !or_conn->is_canonical) {
631 /* We have at least one open canonical connection to this router,
632 * and this one is open but not canonical. Mark it bad. */
633 log_info(LD_OR,
634 "Marking OR conn to %s:%d as too old for new circuits: "
635 "(fd %d, %d secs old). It is not canonical, and we have "
636 "another connection to that OR that is.",
637 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
638 (int)(now - or_conn->_base.timestamp_created));
639 or_conn->is_bad_for_new_circs = 1;
640 continue;
643 if (!best || connection_or_is_better(now, or_conn, best, 0))
644 best = or_conn;
647 if (!best)
648 return;
650 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
651 * every other open connection. If it's non-canonical, mark as bad
652 * every other open connection to the same address.
654 * XXXX This isn't optimal; if we have connections to an OR at multiple
655 * addresses, we'd like to pick the best _for each address_, and mark as
656 * bad every open connection that isn't best for its address. But this
657 * can only occur in cases where the other OR is old (so we have no
658 * canonical connection to it), or where all the connections to the OR are
659 * at noncanonical addresses and we have no good direct connection (which
660 * means we aren't at risk of attaching circuits to it anyway). As
661 * 0.1.2.x dies out, the first case will go away, and the second one is
662 * "mostly harmless", so a fix can wait until somebody is bored.
664 for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
665 if (or_conn->_base.marked_for_close ||
666 or_conn->is_bad_for_new_circs ||
667 or_conn->_base.state != OR_CONN_STATE_OPEN)
668 continue;
669 if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
670 /* This isn't the best conn, _and_ the best conn is better than it,
671 even when we're being forgiving. */
672 if (best->is_canonical) {
673 log_info(LD_OR,
674 "Marking OR conn to %s:%d as too old for new circuits: "
675 "(fd %d, %d secs old). We have a better canonical one "
676 "(fd %d; %d secs old).",
677 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
678 (int)(now - or_conn->_base.timestamp_created),
679 best->_base.s, (int)(now - best->_base.timestamp_created));
680 or_conn->is_bad_for_new_circs = 1;
681 } else if (!tor_addr_compare(&or_conn->real_addr,
682 &best->real_addr, CMP_EXACT)) {
683 log_info(LD_OR,
684 "Marking OR conn to %s:%d as too old for new circuits: "
685 "(fd %d, %d secs old). We have a better one "
686 "(fd %d; %d secs old).",
687 or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
688 (int)(now - or_conn->_base.timestamp_created),
689 best->_base.s, (int)(now - best->_base.timestamp_created));
690 or_conn->is_bad_for_new_circs = 1;
696 /** Go through all the OR connections, and set the is_bad_for_new_circs
697 * flag on:
698 * - all connections that are too old.
699 * - all open non-canonical connections for which a canonical connection
700 * exists to the same router.
701 * - all open canonical connections for which a 'better' canonical
702 * connection exists to the same router.
703 * - all open non-canonical connections for which a 'better' non-canonical
704 * connection exists to the same router at the same address.
706 * See connection_or_is_better() for our idea of what makes one OR connection
707 * better than another.
709 void
710 connection_or_set_bad_connections(void)
712 if (!orconn_identity_map)
713 return;
715 DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
716 connection_or_group_set_badness(conn);
717 } DIGESTMAP_FOREACH_END;
720 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
721 * a TCP connection. Send notifications appropriately.
723 * <b>reason</b> specifies the or_conn_end_reason for the failure;
724 * <b>msg</b> specifies the strerror-style error message.
726 void
727 connection_or_connect_failed(or_connection_t *conn,
728 int reason, const char *msg)
730 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
731 if (!authdir_mode_tests_reachability(get_options()))
732 control_event_bootstrap_problem(msg, reason);
735 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
736 * handshake with an OR with identity digest <b>id_digest</b>.
738 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
739 * return that connection. If the connect() is in progress, set the
740 * new conn's state to 'connecting' and return it. If connect() succeeds,
741 * call connection_tls_start_handshake() on it.
743 * This function is called from router_retry_connections(), for
744 * ORs connecting to ORs, and circuit_establish_circuit(), for
745 * OPs connecting to ORs.
747 * Return the launched conn, or NULL if it failed.
749 or_connection_t *
750 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
751 const char *id_digest)
753 or_connection_t *conn;
754 or_options_t *options = get_options();
755 int socket_error = 0;
756 tor_addr_t addr;
758 tor_assert(_addr);
759 tor_assert(id_digest);
760 tor_addr_copy(&addr, _addr);
762 if (server_mode(options) && router_digest_is_me(id_digest)) {
763 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
764 return NULL;
767 conn = or_connection_new(AF_INET);
769 /* set up conn so it's got all the data we need to remember */
770 connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
771 conn->_base.state = OR_CONN_STATE_CONNECTING;
772 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
774 if (options->HttpsProxy) {
775 /* we shouldn't connect directly. use the https proxy instead. */
776 tor_addr_from_ipv4h(&addr, options->HttpsProxyAddr);
777 port = options->HttpsProxyPort;
780 switch (connection_connect(TO_CONN(conn), conn->_base.address,
781 &addr, port, &socket_error)) {
782 case -1:
783 /* If the connection failed immediately, and we're using
784 * an https proxy, our https proxy is down. Don't blame the
785 * Tor server. */
786 if (!options->HttpsProxy)
787 entry_guard_register_connect_status(conn->identity_digest,
788 0, 1, time(NULL));
789 connection_or_connect_failed(conn,
790 errno_to_orconn_end_reason(socket_error),
791 tor_socket_strerror(socket_error));
792 connection_free(TO_CONN(conn));
793 return NULL;
794 case 0:
795 connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
796 /* writable indicates finish, readable indicates broken link,
797 error indicates broken link on windows */
798 return conn;
799 /* case 1: fall through */
802 if (connection_or_finished_connecting(conn) < 0) {
803 /* already marked for close */
804 return NULL;
806 return conn;
809 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
810 * we initiated the connection, else it's 1.
812 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
813 * pass <b>conn</b> to connection_tls_continue_handshake().
815 * Return -1 if <b>conn</b> is broken, else return 0.
818 connection_tls_start_handshake(or_connection_t *conn, int receiving)
820 conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
821 conn->tls = tor_tls_new(conn->_base.s, receiving);
822 tor_tls_set_logged_address(conn->tls, escaped_safe_str(conn->_base.address));
823 if (!conn->tls) {
824 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
825 return -1;
827 connection_start_reading(TO_CONN(conn));
828 log_debug(LD_OR,"starting TLS handshake on fd %d", conn->_base.s);
829 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
831 if (connection_tls_continue_handshake(conn) < 0) {
832 return -1;
834 return 0;
837 /** Invoked on the server side from inside tor_tls_read() when the server
838 * gets a successful TLS renegotiation from the client. */
839 static void
840 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
842 or_connection_t *conn = _conn;
843 (void)tls;
845 /* Don't invoke this again. */
846 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
847 tor_tls_block_renegotiation(tls);
849 if (connection_tls_finish_handshake(conn) < 0) {
850 /* XXXX_TLS double-check that it's ok to do this from inside read. */
851 /* XXXX_TLS double-check that this verifies certificates. */
852 connection_mark_for_close(TO_CONN(conn));
856 /** Move forward with the tls handshake. If it finishes, hand
857 * <b>conn</b> to connection_tls_finish_handshake().
859 * Return -1 if <b>conn</b> is broken, else return 0.
862 connection_tls_continue_handshake(or_connection_t *conn)
864 int result;
865 check_no_tls_errors();
866 again:
867 if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
868 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
869 result = tor_tls_renegotiate(conn->tls);
870 // log_notice(LD_OR, "Result: %d", result);
871 } else {
872 tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
873 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
874 result = tor_tls_handshake(conn->tls);
875 // log_notice(LD_OR, "Result: %d", result);
877 switch (result) {
878 CASE_TOR_TLS_ERROR_ANY:
879 log_info(LD_OR,"tls error [%s]. breaking connection.",
880 tor_tls_err_to_string(result));
881 return -1;
882 case TOR_TLS_DONE:
883 if (! tor_tls_used_v1_handshake(conn->tls)) {
884 if (!tor_tls_is_server(conn->tls)) {
885 if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
886 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
887 conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
888 goto again;
890 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
891 } else {
892 /* improved handshake, but not a client. */
893 tor_tls_set_renegotiate_callback(conn->tls,
894 connection_or_tls_renegotiated_cb,
895 conn);
896 conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
897 connection_stop_writing(TO_CONN(conn));
898 connection_start_reading(TO_CONN(conn));
899 return 0;
902 return connection_tls_finish_handshake(conn);
903 case TOR_TLS_WANTWRITE:
904 connection_start_writing(TO_CONN(conn));
905 log_debug(LD_OR,"wanted write");
906 return 0;
907 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
908 log_debug(LD_OR,"wanted read");
909 return 0;
910 case TOR_TLS_CLOSE:
911 log_info(LD_OR,"tls closed. breaking connection.");
912 return -1;
914 return 0;
917 /** Return 1 if we initiated this connection, or 0 if it started
918 * out as an incoming connection.
921 connection_or_nonopen_was_started_here(or_connection_t *conn)
923 tor_assert(conn->_base.type == CONN_TYPE_OR);
924 if (!conn->tls)
925 return 1; /* it's still in proxy states or something */
926 if (conn->handshake_state)
927 return conn->handshake_state->started_here;
928 return !tor_tls_is_server(conn->tls);
931 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
932 * return -1 if he is lying, broken, or otherwise something is wrong.
934 * If we initiated this connection (<b>started_here</b> is true), make sure
935 * the other side sent sent a correctly formed certificate. If I initiated the
936 * connection, make sure it's the right guy.
938 * Otherwise (if we _didn't_ initiate this connection), it's okay for
939 * the certificate to be weird or absent.
941 * If we return 0, and the certificate is as expected, write a hash of the
942 * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
943 * we return -1 this buffer is undefined.) If the certificate is invalid
944 * or missing on an incoming connection, we return 0 and set digest_rcvd to
945 * DIGEST_LEN 0 bytes.
947 * As side effects,
948 * 1) Set conn->circ_id_type according to tor-spec.txt.
949 * 2) If we're an authdirserver and we initiated the connection: drop all
950 * descriptors that claim to be on that IP/port but that aren't
951 * this guy; and note that this guy is reachable.
953 static int
954 connection_or_check_valid_tls_handshake(or_connection_t *conn,
955 int started_here,
956 char *digest_rcvd_out)
958 crypto_pk_env_t *identity_rcvd=NULL;
959 or_options_t *options = get_options();
960 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
961 const char *safe_address =
962 started_here ? conn->_base.address : safe_str(conn->_base.address);
963 const char *conn_type = started_here ? "outgoing" : "incoming";
964 int has_cert = 0, has_identity=0;
966 check_no_tls_errors();
967 has_cert = tor_tls_peer_has_cert(conn->tls);
968 if (started_here && !has_cert) {
969 log_info(LD_PROTOCOL,"Tried connecting to router at %s:%d, but it didn't "
970 "send a cert! Closing.",
971 safe_address, conn->_base.port);
972 return -1;
973 } else if (!has_cert) {
974 log_debug(LD_PROTOCOL,"Got incoming connection with no certificate. "
975 "That's ok.");
977 check_no_tls_errors();
979 if (has_cert) {
980 int v = tor_tls_verify(started_here?severity:LOG_INFO,
981 conn->tls, &identity_rcvd);
982 if (started_here && v<0) {
983 log_fn(severity,LD_OR,"Tried connecting to router at %s:%d: It"
984 " has a cert but it's invalid. Closing.",
985 safe_address, conn->_base.port);
986 return -1;
987 } else if (v<0) {
988 log_info(LD_PROTOCOL,"Incoming connection gave us an invalid cert "
989 "chain; ignoring.");
990 } else {
991 log_debug(LD_OR,"The certificate seems to be valid on %s connection "
992 "with %s:%d", conn_type, safe_address, conn->_base.port);
994 check_no_tls_errors();
997 if (identity_rcvd) {
998 has_identity = 1;
999 crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
1000 if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
1001 conn->circ_id_type = CIRC_ID_TYPE_LOWER;
1002 } else {
1003 conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
1005 crypto_free_pk_env(identity_rcvd);
1006 } else {
1007 memset(digest_rcvd_out, 0, DIGEST_LEN);
1008 conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
1011 if (started_here && tor_digest_is_zero(conn->identity_digest)) {
1012 connection_or_set_identity_digest(conn, digest_rcvd_out);
1013 tor_free(conn->nickname);
1014 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1015 conn->nickname[0] = '$';
1016 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1017 conn->identity_digest, DIGEST_LEN);
1018 log_info(LD_OR, "Connected to router %s at %s:%d without knowing "
1019 "its key. Hoping for the best.",
1020 conn->nickname, conn->_base.address, conn->_base.port);
1023 if (started_here) {
1024 int as_advertised = 1;
1025 tor_assert(has_cert);
1026 tor_assert(has_identity);
1027 if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
1028 /* I was aiming for a particular digest. I didn't get it! */
1029 char seen[HEX_DIGEST_LEN+1];
1030 char expected[HEX_DIGEST_LEN+1];
1031 base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
1032 base16_encode(expected, sizeof(expected), conn->identity_digest,
1033 DIGEST_LEN);
1034 log_fn(severity, LD_OR,
1035 "Tried connecting to router at %s:%d, but identity key was not "
1036 "as expected: wanted %s but got %s.",
1037 conn->_base.address, conn->_base.port, expected, seen);
1038 entry_guard_register_connect_status(conn->identity_digest, 0, 1,
1039 time(NULL));
1040 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1041 END_OR_CONN_REASON_OR_IDENTITY);
1042 if (!authdir_mode_tests_reachability(options))
1043 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
1044 as_advertised = 0;
1046 if (authdir_mode_tests_reachability(options)) {
1047 /* We initiated this connection to address:port. Drop all routers
1048 * with the same address:port and a different key.
1050 dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
1051 digest_rcvd_out, as_advertised);
1053 if (!as_advertised)
1054 return -1;
1056 return 0;
1059 /** The tls handshake is finished.
1061 * Make sure we are happy with the person we just handshaked with.
1063 * If he initiated the connection, make sure he's not already connected,
1064 * then initialize conn from the information in router.
1066 * If all is successful, call circuit_n_conn_done() to handle events
1067 * that have been pending on the <tls handshake completion. Also set the
1068 * directory to be dirty (only matters if I'm an authdirserver).
1070 static int
1071 connection_tls_finish_handshake(or_connection_t *conn)
1073 char digest_rcvd[DIGEST_LEN];
1074 int started_here = connection_or_nonopen_was_started_here(conn);
1076 log_debug(LD_OR,"tls handshake with %s done. verifying.",
1077 safe_str(conn->_base.address));
1079 directory_set_dirty();
1081 if (connection_or_check_valid_tls_handshake(conn, started_here,
1082 digest_rcvd) < 0)
1083 return -1;
1085 if (tor_tls_used_v1_handshake(conn->tls)) {
1086 conn->link_proto = 1;
1087 if (!started_here) {
1088 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1089 conn->_base.port, digest_rcvd, 0);
1091 tor_tls_block_renegotiation(conn->tls);
1092 return connection_or_set_state_open(conn);
1093 } else {
1094 conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
1095 if (connection_init_or_handshake_state(conn, started_here) < 0)
1096 return -1;
1097 if (!started_here) {
1098 connection_or_init_conn_from_address(conn, &conn->_base.addr,
1099 conn->_base.port, digest_rcvd, 0);
1101 return connection_or_send_versions(conn);
1105 /** Allocate a new connection handshake state for the connection
1106 * <b>conn</b>. Return 0 on success, -1 on failure. */
1107 static int
1108 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
1110 or_handshake_state_t *s;
1111 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
1112 s->started_here = started_here ? 1 : 0;
1113 return 0;
1116 /** Free all storage held by <b>state</b>. */
1117 void
1118 or_handshake_state_free(or_handshake_state_t *state)
1120 tor_assert(state);
1121 memset(state, 0xBE, sizeof(or_handshake_state_t));
1122 tor_free(state);
1125 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1126 * as appropriate. Called when we are done with all TLS and OR handshaking.
1129 connection_or_set_state_open(or_connection_t *conn)
1131 int started_here = connection_or_nonopen_was_started_here(conn);
1132 time_t now = time(NULL);
1133 conn->_base.state = OR_CONN_STATE_OPEN;
1134 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
1136 if (started_here) {
1137 rep_hist_note_connect_succeeded(conn->identity_digest, now);
1138 if (entry_guard_register_connect_status(conn->identity_digest,
1139 1, 0, now) < 0) {
1140 /* Close any circuits pending on this conn. We leave it in state
1141 * 'open' though, because it didn't actually *fail* -- we just
1142 * chose not to use it. (Otherwise
1143 * connection_about_to_close_connection() will call a big pile of
1144 * functions to indicate we shouldn't try it again.) */
1145 log_debug(LD_OR, "New entry guard was reachable, but closing this "
1146 "connection so we can retry the earlier entry guards.");
1147 circuit_n_conn_done(conn, 0);
1148 return -1;
1150 router_set_status(conn->identity_digest, 1);
1151 } else {
1152 /* only report it to the geoip module if it's not a known router */
1153 if (!router_get_by_digest(conn->identity_digest)) {
1154 if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
1155 /*XXXX IP6 support ipv6 geoip.*/
1156 uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
1157 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
1161 if (conn->handshake_state) {
1162 or_handshake_state_free(conn->handshake_state);
1163 conn->handshake_state = NULL;
1165 connection_start_reading(TO_CONN(conn));
1166 circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
1168 return 0;
1171 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1172 * For cells that use or affect a circuit, this should only be called by
1173 * connection_or_flush_from_first_active_circuit().
1175 void
1176 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
1178 packed_cell_t networkcell;
1180 tor_assert(cell);
1181 tor_assert(conn);
1183 cell_pack(&networkcell, cell);
1185 connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
1187 if (cell->command != CELL_PADDING)
1188 conn->timestamp_last_added_nonpadding = approx_time();
1191 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1192 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1193 * affect a circuit.
1195 void
1196 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
1197 or_connection_t *conn)
1199 char hdr[VAR_CELL_HEADER_SIZE];
1200 tor_assert(cell);
1201 tor_assert(conn);
1202 var_cell_pack_header(cell, hdr);
1203 connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
1204 connection_write_to_buf((char*)cell->payload,
1205 cell->payload_len, TO_CONN(conn));
1206 if (cell->command != CELL_PADDING)
1207 conn->timestamp_last_added_nonpadding = approx_time();
1210 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1211 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1212 static int
1213 connection_fetch_var_cell_from_buf(or_connection_t *conn, var_cell_t **out)
1215 return fetch_var_cell_from_buf(conn->_base.inbuf, out, conn->link_proto);
1218 /** Process cells from <b>conn</b>'s inbuf.
1220 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1221 * and hand it to command_process_cell().
1223 * Always return 0.
1225 static int
1226 connection_or_process_cells_from_inbuf(or_connection_t *conn)
1228 var_cell_t *var_cell;
1230 while (1) {
1231 log_debug(LD_OR,
1232 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1233 conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
1234 tor_tls_get_pending_bytes(conn->tls));
1235 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
1236 if (!var_cell)
1237 return 0; /* not yet. */
1238 command_process_var_cell(var_cell, conn);
1239 var_cell_free(var_cell);
1240 } else {
1241 char buf[CELL_NETWORK_SIZE];
1242 cell_t cell;
1243 if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
1244 available? */
1245 return 0; /* not yet */
1247 connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
1249 /* retrieve cell info from buf (create the host-order struct from the
1250 * network-order string) */
1251 cell_unpack(&cell, buf);
1253 command_process_cell(&cell, conn);
1258 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1259 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1260 * we may want to propagate reasons from other cells.
1262 * Return 0.
1265 connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
1267 cell_t cell;
1269 tor_assert(conn);
1271 memset(&cell, 0, sizeof(cell_t));
1272 cell.circ_id = circ_id;
1273 cell.command = CELL_DESTROY;
1274 cell.payload[0] = (uint8_t) reason;
1275 log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
1277 /* XXXX It's possible that under some circumstances, we want the destroy
1278 * to take precedence over other data waiting on the circuit's cell queue.
1281 connection_or_write_cell_to_buf(&cell, conn);
1282 return 0;
1285 /** Array of recognized link protocol versions. */
1286 static const uint16_t or_protocol_versions[] = { 1, 2 };
1287 /** Number of versions in <b>or_protocol_versions</b>. */
1288 static const int n_or_protocol_versions =
1289 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
1291 /** Return true iff <b>v</b> is a link protocol version that this Tor
1292 * implementation believes it can support. */
1294 is_or_protocol_version_known(uint16_t v)
1296 int i;
1297 for (i = 0; i < n_or_protocol_versions; ++i) {
1298 if (or_protocol_versions[i] == v)
1299 return 1;
1301 return 0;
1304 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1305 * link protocol versions that this Tor can support. */
1306 static int
1307 connection_or_send_versions(or_connection_t *conn)
1309 var_cell_t *cell;
1310 int i;
1311 tor_assert(conn->handshake_state &&
1312 !conn->handshake_state->sent_versions_at);
1313 cell = var_cell_new(n_or_protocol_versions * 2);
1314 cell->command = CELL_VERSIONS;
1315 for (i = 0; i < n_or_protocol_versions; ++i) {
1316 uint16_t v = or_protocol_versions[i];
1317 set_uint16(cell->payload+(2*i), htons(v));
1320 connection_or_write_var_cell_to_buf(cell, conn);
1321 conn->handshake_state->sent_versions_at = time(NULL);
1323 var_cell_free(cell);
1324 return 0;
1327 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1328 * about their address, our address, and the current time. */
1330 connection_or_send_netinfo(or_connection_t *conn)
1332 cell_t cell;
1333 time_t now = time(NULL);
1334 routerinfo_t *me;
1335 int len;
1336 uint8_t *out;
1338 memset(&cell, 0, sizeof(cell_t));
1339 cell.command = CELL_NETINFO;
1341 /* Timestamp. */
1342 set_uint32(cell.payload, htonl((uint32_t)now));
1344 /* Their address. */
1345 out = cell.payload + 4;
1346 len = append_address_to_payload(out, &conn->_base.addr);
1347 if (len<0)
1348 return -1;
1349 out += len;
1351 /* My address. */
1352 if ((me = router_get_my_routerinfo())) {
1353 tor_addr_t my_addr;
1354 *out++ = 1; /* only one address is supported. */
1356 tor_addr_from_ipv4h(&my_addr, me->addr);
1357 len = append_address_to_payload(out, &my_addr);
1358 if (len < 0)
1359 return -1;
1360 out += len;
1361 } else {
1362 *out++ = 0;
1365 connection_or_write_cell_to_buf(&cell, conn);
1367 return 0;