1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char relay_c_id
[] = "$Id$";
10 * \brief Handle relay cell encryption/decryption, plus packaging and
11 * receiving from circuits.
14 #define NEW_LOG_INTERFACE
17 static int relay_crypt(circuit_t
*circ
, cell_t
*cell
, int cell_direction
,
18 crypt_path_t
**layer_hint
, char *recognized
);
19 static connection_t
*relay_lookup_conn(circuit_t
*circ
, cell_t
*cell
, int cell_direction
);
22 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
24 crypt_path_t
*layer_hint
);
26 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
);
28 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
);
30 circuit_resume_edge_reading_helper(connection_t
*conn
,
32 crypt_path_t
*layer_hint
);
34 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
);
36 /** Stats: how many relay cells have originated at this hop, or have
37 * been relayed onward (not recognized at this hop)?
39 unsigned long stats_n_relay_cells_relayed
= 0;
40 /** Stats: how many relay cells have been delivered to streams at this
43 unsigned long stats_n_relay_cells_delivered
= 0;
45 /** Update digest from the payload of cell. Assign integrity part to
49 relay_set_digest(crypto_digest_env_t
*digest
, cell_t
*cell
)
54 crypto_digest_add_bytes(digest
, cell
->payload
, CELL_PAYLOAD_SIZE
);
55 crypto_digest_get_digest(digest
, integrity
, 4);
56 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
57 // integrity[0], integrity[1], integrity[2], integrity[3]);
58 relay_header_unpack(&rh
, cell
->payload
);
59 memcpy(rh
.integrity
, integrity
, 4);
60 relay_header_pack(cell
->payload
, &rh
);
63 /** Does the digest for this circuit indicate that this cell is for us?
65 * Update digest from the payload of cell (with the integrity part set
66 * to 0). If the integrity part is valid, return 1, else restore digest
67 * and cell to their original state and return 0.
70 relay_digest_matches(crypto_digest_env_t
*digest
, cell_t
*cell
)
72 char received_integrity
[4], calculated_integrity
[4];
74 crypto_digest_env_t
*backup_digest
=NULL
;
76 backup_digest
= crypto_digest_dup(digest
);
78 relay_header_unpack(&rh
, cell
->payload
);
79 memcpy(received_integrity
, rh
.integrity
, 4);
80 memset(rh
.integrity
, 0, 4);
81 relay_header_pack(cell
->payload
, &rh
);
83 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
84 // received_integrity[0], received_integrity[1],
85 // received_integrity[2], received_integrity[3]);
87 crypto_digest_add_bytes(digest
, cell
->payload
, CELL_PAYLOAD_SIZE
);
88 crypto_digest_get_digest(digest
, calculated_integrity
, 4);
90 if (memcmp(received_integrity
, calculated_integrity
, 4)) {
91 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
92 // (%d vs %d).", received_integrity, calculated_integrity);
93 /* restore digest to its old form */
94 crypto_digest_assign(digest
, backup_digest
);
95 /* restore the relay header */
96 memcpy(rh
.integrity
, received_integrity
, 4);
97 relay_header_pack(cell
->payload
, &rh
);
98 crypto_free_digest_env(backup_digest
);
101 crypto_free_digest_env(backup_digest
);
105 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
108 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
110 * Return -1 if the crypto fails, else return 0.
113 relay_crypt_one_payload(crypto_cipher_env_t
*cipher
, char *in
,
116 char out
[CELL_PAYLOAD_SIZE
]; /* 'in' must be this size too */
118 if (( encrypt_mode
&& crypto_cipher_encrypt(cipher
, out
, in
, CELL_PAYLOAD_SIZE
)) ||
119 (!encrypt_mode
&& crypto_cipher_decrypt(cipher
, out
, in
, CELL_PAYLOAD_SIZE
))) {
120 warn(LD_BUG
,"Error during relay encryption");
123 memcpy(in
,out
,CELL_PAYLOAD_SIZE
);
127 /** Receive a relay cell:
128 * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
129 * - Check if recognized (if exitward).
130 * - If recognized and the digest checks out, then find if there's
131 * a conn that the cell is intended for, and deliver it to
133 * - Else connection_or_write_cell_to_buf to the conn on the other
134 * side of the circuit.
137 circuit_receive_relay_cell(cell_t
*cell
, circuit_t
*circ
, int cell_direction
)
139 connection_t
*conn
=NULL
;
140 crypt_path_t
*layer_hint
=NULL
;
145 tor_assert(cell_direction
== CELL_DIRECTION_OUT
||
146 cell_direction
== CELL_DIRECTION_IN
);
147 if (circ
->marked_for_close
)
150 if (relay_crypt(circ
, cell
, cell_direction
, &layer_hint
, &recognized
) < 0) {
151 warn(LD_BUG
,"relay crypt failed. Dropping connection.");
156 conn
= relay_lookup_conn(circ
, cell
, cell_direction
);
157 if (cell_direction
== CELL_DIRECTION_OUT
) {
158 ++stats_n_relay_cells_delivered
;
159 debug(LD_OR
,"Sending away from origin.");
160 if (connection_edge_process_relay_cell(cell
, circ
, conn
, NULL
) < 0) {
161 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
162 "connection_edge_process_relay_cell (away from origin) failed.");
166 if (cell_direction
== CELL_DIRECTION_IN
) {
167 ++stats_n_relay_cells_delivered
;
168 debug(LD_OR
,"Sending to origin.");
169 if (connection_edge_process_relay_cell(cell
, circ
, conn
, layer_hint
) < 0) {
170 warn(LD_OR
,"connection_edge_process_relay_cell (at origin) failed.");
177 /* not recognized. pass it on. */
178 if (cell_direction
== CELL_DIRECTION_OUT
) {
179 cell
->circ_id
= circ
->n_circ_id
; /* switch it */
182 cell
->circ_id
= circ
->p_circ_id
; /* switch it */
187 if (circ
->rend_splice
&& cell_direction
== CELL_DIRECTION_OUT
) {
188 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_REND_ESTABLISHED
);
189 tor_assert(circ
->rend_splice
->purpose
== CIRCUIT_PURPOSE_REND_ESTABLISHED
);
190 cell
->circ_id
= circ
->rend_splice
->p_circ_id
;
191 if (circuit_receive_relay_cell(cell
, circ
->rend_splice
, CELL_DIRECTION_IN
)<0) {
192 warn(LD_REND
, "Error relaying cell across rendezvous; closing circuits");
193 circuit_mark_for_close(circ
); /* XXXX Do this here, or just return -1? */
198 log_fn(LOG_PROTOCOL_WARN
,LD_PROTOCOL
,"Didn't recognize cell, but circ stops here! Closing circ.");
202 debug(LD_OR
,"Passing on unrecognized cell.");
203 ++stats_n_relay_cells_relayed
;
204 connection_or_write_cell_to_buf(cell
, conn
);
208 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
209 * <b>circ</b> in direction <b>cell_direction</b>.
211 * If cell_direction == CELL_DIRECTION_IN:
212 * - If we're at the origin (we're the OP), for hops 1..N,
213 * decrypt cell. If recognized, stop.
214 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
216 * If cell_direction == CELL_DIRECTION_OUT:
217 * - decrypt one hop. Check if recognized.
219 * If cell is recognized, set *recognized to 1, and set
220 * *layer_hint to the hop that recognized it.
222 * Return -1 to indicate that we should mark the circuit for close,
225 /* wrap this into receive_relay_cell one day */
227 relay_crypt(circuit_t
*circ
, cell_t
*cell
, int cell_direction
,
228 crypt_path_t
**layer_hint
, char *recognized
)
230 crypt_path_t
*thishop
;
235 tor_assert(recognized
);
236 tor_assert(cell_direction
== CELL_DIRECTION_IN
||
237 cell_direction
== CELL_DIRECTION_OUT
);
239 if (cell_direction
== CELL_DIRECTION_IN
) {
240 if (CIRCUIT_IS_ORIGIN(circ
)) { /* We're at the beginning of the circuit.
241 We'll want to do layered decrypts. */
242 tor_assert(circ
->cpath
);
243 thishop
= circ
->cpath
;
244 if (thishop
->state
!= CPATH_STATE_OPEN
) {
245 log_fn(LOG_PROTOCOL_WARN
,LD_PROTOCOL
,"Relay cell before first created cell? Closing.");
248 do { /* Remember: cpath is in forward order, that is, first hop first. */
251 if (relay_crypt_one_payload(thishop
->b_crypto
, cell
->payload
, 0) < 0)
254 relay_header_unpack(&rh
, cell
->payload
);
255 if (rh
.recognized
== 0) {
256 /* it's possibly recognized. have to check digest to be sure. */
257 if (relay_digest_matches(thishop
->b_digest
, cell
)) {
259 *layer_hint
= thishop
;
264 thishop
= thishop
->next
;
265 } while (thishop
!= circ
->cpath
&& thishop
->state
== CPATH_STATE_OPEN
);
266 warn(LD_OR
,"in-cell at OP not recognized. Closing.");
268 } else { /* we're in the middle. Just one crypt. */
269 if (relay_crypt_one_payload(circ
->p_crypto
, cell
->payload
, 1) < 0)
271 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
273 } else /* cell_direction == CELL_DIRECTION_OUT */ {
274 /* we're in the middle. Just one crypt. */
276 if (relay_crypt_one_payload(circ
->n_crypto
, cell
->payload
, 0) < 0)
279 relay_header_unpack(&rh
, cell
->payload
);
280 if (rh
.recognized
== 0) {
281 /* it's possibly recognized. have to check digest to be sure. */
282 if (relay_digest_matches(circ
->n_digest
, cell
)) {
291 /** Package a relay cell:
292 * - Encrypt it to the right layer
293 * - connection_or_write_cell_to_buf to the right conn
296 circuit_package_relay_cell(cell_t
*cell
, circuit_t
*circ
,
298 crypt_path_t
*layer_hint
)
300 connection_t
*conn
; /* where to send the cell */
301 crypt_path_t
*thishop
; /* counter for repeated crypts */
303 if (cell_direction
== CELL_DIRECTION_OUT
) {
306 warn(LD_BUG
,"outgoing relay cell has n_conn==NULL. Dropping.");
307 return 0; /* just drop it */
309 relay_set_digest(layer_hint
->f_digest
, cell
);
311 thishop
= layer_hint
;
312 /* moving from farthest to nearest hop */
315 /* XXXX RD This is a bug, right? */
316 debug(LD_OR
,"crypting a layer of the relay cell.");
317 if (relay_crypt_one_payload(thishop
->f_crypto
, cell
->payload
, 1) < 0) {
321 thishop
= thishop
->prev
;
322 } while (thishop
!= circ
->cpath
->prev
);
324 } else { /* incoming cell */
327 /* XXXX RD This is a bug, right? */
328 warn(LD_BUG
,"incoming relay cell has p_conn==NULL. Dropping.");
329 return 0; /* just drop it */
331 relay_set_digest(circ
->p_digest
, cell
);
332 if (relay_crypt_one_payload(circ
->p_crypto
, cell
->payload
, 1) < 0)
335 ++stats_n_relay_cells_relayed
;
336 connection_or_write_cell_to_buf(cell
, conn
);
340 /** If cell's stream_id matches the stream_id of any conn that's
341 * attached to circ, return that conn, else return NULL.
343 static connection_t
*
344 relay_lookup_conn(circuit_t
*circ
, cell_t
*cell
, int cell_direction
)
346 connection_t
*tmpconn
;
349 relay_header_unpack(&rh
, cell
->payload
);
354 /* IN or OUT cells could have come from either direction, now
355 * that we allow rendezvous *to* an OP.
358 for (tmpconn
= circ
->n_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
) {
359 if (rh
.stream_id
== tmpconn
->stream_id
&& !tmpconn
->marked_for_close
) {
360 debug(LD_EXIT
,"found conn for stream %d.", rh
.stream_id
);
361 if (cell_direction
== CELL_DIRECTION_OUT
||
362 connection_edge_is_rendezvous_stream(tmpconn
))
366 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
) {
367 if (rh
.stream_id
== tmpconn
->stream_id
&& !tmpconn
->marked_for_close
) {
368 debug(LD_APP
,"found conn for stream %d.", rh
.stream_id
);
372 for (tmpconn
= circ
->resolving_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
) {
373 if (rh
.stream_id
== tmpconn
->stream_id
&& !tmpconn
->marked_for_close
) {
374 debug(LD_EXIT
,"found conn for stream %d.", rh
.stream_id
);
378 return NULL
; /* probably a begin relay cell */
381 /** Pack the relay_header_t host-order structure <b>src</b> into
382 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
383 * about the wire format.
386 relay_header_pack(char *dest
, const relay_header_t
*src
)
388 *(uint8_t*)(dest
) = src
->command
;
390 set_uint16(dest
+1, htons(src
->recognized
));
391 set_uint16(dest
+3, htons(src
->stream_id
));
392 memcpy(dest
+5, src
->integrity
, 4);
393 set_uint16(dest
+9, htons(src
->length
));
396 /** Unpack the network-order buffer <b>src</b> into a host-order
397 * relay_header_t structure <b>dest</b>.
400 relay_header_unpack(relay_header_t
*dest
, const char *src
)
402 dest
->command
= *(uint8_t*)(src
);
404 dest
->recognized
= ntohs(get_uint16(src
+1));
405 dest
->stream_id
= ntohs(get_uint16(src
+3));
406 memcpy(dest
->integrity
, src
+5, 4);
407 dest
->length
= ntohs(get_uint16(src
+9));
410 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
411 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
412 * that's sending the relay cell, or NULL if it's a control cell.
413 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
416 * If you can't send the cell, mark the circuit for close and
417 * return -1. Else return 0.
420 connection_edge_send_command(connection_t
*fromconn
, circuit_t
*circ
,
421 int relay_command
, const char *payload
,
422 size_t payload_len
, crypt_path_t
*cpath_layer
)
428 if (fromconn
&& fromconn
->marked_for_close
) {
429 warn(LD_BUG
,"Bug: called on conn that's already marked for close at %s:%d.",
430 fromconn
->marked_for_close_file
, fromconn
->marked_for_close
);
435 tor_assert(fromconn
);
436 if (fromconn
->type
== CONN_TYPE_AP
) {
437 info(LD_APP
,"no circ. Closing conn.");
438 connection_mark_unattached_ap(fromconn
, END_STREAM_REASON_INTERNAL
);
440 info(LD_EXIT
,"no circ. Closing conn.");
441 fromconn
->has_sent_end
= 1; /* no circ to send to */
442 connection_mark_for_close(fromconn
);
447 memset(&cell
, 0, sizeof(cell_t
));
448 cell
.command
= CELL_RELAY
;
450 cell
.circ_id
= circ
->n_circ_id
;
451 cell_direction
= CELL_DIRECTION_OUT
;
453 cell
.circ_id
= circ
->p_circ_id
;
454 cell_direction
= CELL_DIRECTION_IN
;
457 memset(&rh
, 0, sizeof(rh
));
458 rh
.command
= relay_command
;
460 rh
.stream_id
= fromconn
->stream_id
; /* else it's 0 */
461 rh
.length
= payload_len
;
462 relay_header_pack(cell
.payload
, &rh
);
464 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
465 memcpy(cell
.payload
+RELAY_HEADER_SIZE
, payload
, payload_len
);
468 debug(LD_OR
,"delivering %d cell %s.", relay_command
,
469 cell_direction
== CELL_DIRECTION_OUT
? "forward" : "backward");
471 if (circuit_package_relay_cell(&cell
, circ
, cell_direction
, cpath_layer
) < 0) {
472 warn(LD_BUG
,"circuit_package_relay_cell failed. Closing.");
473 circuit_mark_for_close(circ
);
479 /** Translate <b>reason</b>, which came from a relay 'end' cell,
480 * into a static const string describing why the stream is closing.
481 * <b>reason</b> is -1 if no reason was provided.
484 connection_edge_end_reason_str(int reason
)
488 warn(LD_PROTOCOL
,"End cell arrived with length 0. Should be at least 1.");
490 case END_STREAM_REASON_MISC
: return "misc error";
491 case END_STREAM_REASON_RESOLVEFAILED
: return "resolve failed";
492 case END_STREAM_REASON_CONNECTREFUSED
: return "connection refused";
493 case END_STREAM_REASON_EXITPOLICY
: return "exit policy failed";
494 case END_STREAM_REASON_DESTROY
: return "destroyed";
495 case END_STREAM_REASON_DONE
: return "closed normally";
496 case END_STREAM_REASON_TIMEOUT
: return "gave up (timeout)";
497 case END_STREAM_REASON_HIBERNATING
: return "server is hibernating";
498 case END_STREAM_REASON_INTERNAL
: return "internal error at server";
499 case END_STREAM_REASON_RESOURCELIMIT
: return "server out of resources";
500 case END_STREAM_REASON_CONNRESET
: return "connection reset";
501 case END_STREAM_REASON_TORPROTOCOL
: return "Tor protocol error";
503 warn(LD_PROTOCOL
,"Reason for ending (%d) not recognized.",reason
);
508 /** Translate <b>reason</b> (as from a relay 'end' cell) into an
509 * appropriate SOCKS5 reply code.
511 socks5_reply_status_t
512 connection_edge_end_reason_socks5_response(int reason
)
515 case END_STREAM_REASON_MISC
:
516 return SOCKS5_GENERAL_ERROR
;
517 case END_STREAM_REASON_RESOLVEFAILED
:
518 return SOCKS5_HOST_UNREACHABLE
;
519 case END_STREAM_REASON_CONNECTREFUSED
:
520 return SOCKS5_CONNECTION_REFUSED
;
521 case END_STREAM_REASON_EXITPOLICY
:
522 return SOCKS5_NOT_ALLOWED
;
523 case END_STREAM_REASON_DESTROY
:
524 return SOCKS5_GENERAL_ERROR
;
525 case END_STREAM_REASON_DONE
:
526 return SOCKS5_SUCCEEDED
;
527 case END_STREAM_REASON_TIMEOUT
:
528 return SOCKS5_TTL_EXPIRED
;
529 case END_STREAM_REASON_RESOURCELIMIT
:
530 return SOCKS5_GENERAL_ERROR
;
531 case END_STREAM_REASON_HIBERNATING
:
532 return SOCKS5_GENERAL_ERROR
;
533 case END_STREAM_REASON_INTERNAL
:
534 return SOCKS5_GENERAL_ERROR
;
535 case END_STREAM_REASON_CONNRESET
:
536 return SOCKS5_CONNECTION_REFUSED
;
537 case END_STREAM_REASON_TORPROTOCOL
:
538 return SOCKS5_GENERAL_ERROR
;
540 case END_STREAM_REASON_ALREADY_SOCKS_REPLIED
:
541 return SOCKS5_SUCCEEDED
; /* never used */
542 case END_STREAM_REASON_CANT_ATTACH
:
543 return SOCKS5_GENERAL_ERROR
;
544 case END_STREAM_REASON_NET_UNREACHABLE
:
545 return SOCKS5_NET_UNREACHABLE
;
547 warn(LD_PROTOCOL
,"Reason for ending (%d) not recognized.",reason
);
548 return SOCKS5_GENERAL_ERROR
;
552 /* We need to use a few macros to deal with the fact that Windows
553 * decided that their sockets interface should be a permakludge.
554 * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
555 * version, and S_CASE is for errors where windows has only a WSAEFOO
556 * version. (The E is for 'error', the S is for 'socket'). */
558 #define E_CASE(s) case s: case WSA ## s
559 #define S_CASE(s) case WSA ## s
561 #define E_CASE(s) case s
562 #define S_CASE(s) case s
565 /** Given an errno from a failed exit connection, return a reason code
566 * appropriate for use in a RELAY END cell.
569 errno_to_end_reason(int e
)
573 return END_STREAM_REASON_DONE
;
579 S_CASE(EPROTONOSUPPORT
):
580 S_CASE(EAFNOSUPPORT
):
584 return END_STREAM_REASON_INTERNAL
;
585 S_CASE(ECONNREFUSED
):
586 return END_STREAM_REASON_CONNECTREFUSED
;
588 return END_STREAM_REASON_CONNRESET
;
590 return END_STREAM_REASON_TIMEOUT
;
595 return END_STREAM_REASON_RESOURCELIMIT
;
597 info(LD_EXIT
, "Didn't recognize errno %d (%s); telling the OP that we are ending a stream for 'misc' reason.",
598 e
, tor_socket_strerror(e
));
599 return END_STREAM_REASON_MISC
;
603 /** How many times will I retry a stream that fails due to DNS
604 * resolve failure or misc error?
606 #define MAX_RESOLVE_FAILURES 3
608 /** Return 1 if reason is something that you should retry if you
609 * get the end cell before you've connected; else return 0. */
611 edge_reason_is_retriable(int reason
)
613 return reason
== END_STREAM_REASON_HIBERNATING
||
614 reason
== END_STREAM_REASON_RESOURCELIMIT
||
615 reason
== END_STREAM_REASON_EXITPOLICY
||
616 reason
== END_STREAM_REASON_RESOLVEFAILED
||
617 reason
== END_STREAM_REASON_MISC
;
620 /** Called when we receive an END cell on a stream that isn't open yet.
621 * Arguments are as for connection_edge_process_relay_cell().
624 connection_edge_process_end_not_open(
625 relay_header_t
*rh
, cell_t
*cell
, circuit_t
*circ
,
626 connection_t
*conn
, crypt_path_t
*layer_hint
)
629 routerinfo_t
*exitrouter
;
630 int reason
= *(cell
->payload
+RELAY_HEADER_SIZE
);
632 if (rh
->length
> 0 && edge_reason_is_retriable(reason
)) {
633 if (conn
->type
!= CONN_TYPE_AP
) {
634 warn(LD_PROTOCOL
,"Got an end because of %s, but we're not an AP. Closing.",
635 connection_edge_end_reason_str(reason
));
638 info(LD_APP
,"Address '%s' refused due to '%s'. Considering retrying.",
639 safe_str(conn
->socks_request
->address
),
640 connection_edge_end_reason_str(reason
));
642 router_get_by_digest(circ
->build_state
->chosen_exit
->identity_digest
);
644 case END_STREAM_REASON_EXITPOLICY
:
645 if (rh
->length
>= 5) {
646 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+1));
649 info(LD_APP
,"Address '%s' resolved to 0.0.0.0. Closing,",
650 safe_str(conn
->socks_request
->address
));
651 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
655 ttl
= (int)ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+5));
658 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
659 conn
->chosen_exit_name
, ttl
);
661 /* check if he *ought* to have allowed it */
664 (tor_inet_aton(conn
->socks_request
->address
, &in
) &&
665 !conn
->chosen_exit_name
))) {
666 notice(LD_APP
,"Exitrouter '%s' seems to be more restrictive than its exit policy. Not using this router as exit for now.", exitrouter
->nickname
);
667 addr_policy_free(exitrouter
->exit_policy
);
668 exitrouter
->exit_policy
=
669 router_parse_addr_policy_from_string("reject *:*", -1);
671 /* rewrite it to an IP if we learned one. */
672 addressmap_rewrite(conn
->socks_request
->address
,
673 sizeof(conn
->socks_request
->address
));
674 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
676 /* else, conn will get closed below */
678 case END_STREAM_REASON_RESOLVEFAILED
:
679 case END_STREAM_REASON_MISC
:
680 if (client_dns_incr_failures(conn
->socks_request
->address
)
681 < MAX_RESOLVE_FAILURES
) {
682 /* We haven't retried too many times; reattach the connection. */
683 circuit_log_path(LOG_INFO
,LD_APP
,circ
);
684 tor_assert(circ
->timestamp_dirty
);
685 circ
->timestamp_dirty
-= get_options()->MaxCircuitDirtiness
;
687 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
689 /* else, conn will get closed below */
691 notice(LD_APP
,"Have tried resolving address '%s' at %d different places. Giving up.",
692 safe_str(conn
->socks_request
->address
), MAX_RESOLVE_FAILURES
);
693 /* clear the failures, so it will have a full try next time */
694 client_dns_clear_failures(conn
->socks_request
->address
);
697 case END_STREAM_REASON_HIBERNATING
:
698 case END_STREAM_REASON_RESOURCELIMIT
:
700 addr_policy_free(exitrouter
->exit_policy
);
701 exitrouter
->exit_policy
=
702 router_parse_addr_policy_from_string("reject *:*", -1);
704 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
706 /* else, will close below */
709 info(LD_APP
,"Giving up on retrying; conn can't be handled.");
712 info(LD_APP
,"Edge got end (%s) before we're connected. Marking for close.",
713 connection_edge_end_reason_str(rh
->length
> 0 ? reason
: -1));
714 if (conn
->type
== CONN_TYPE_AP
) {
715 circuit_log_path(LOG_INFO
,LD_APP
,circ
);
716 connection_mark_unattached_ap(conn
, reason
);
718 conn
->has_sent_end
= 1; /* we just got an 'end', don't need to send one */
719 connection_mark_for_close(conn
);
724 /** An incoming relay cell has arrived from circuit <b>circ</b> to
725 * stream <b>conn</b>.
727 * The arguments here are the same as in
728 * connection_edge_process_relay_cell() below; this function is called
729 * from there when <b>conn</b> is defined and not in an open state.
732 connection_edge_process_relay_cell_not_open(
733 relay_header_t
*rh
, cell_t
*cell
, circuit_t
*circ
,
734 connection_t
*conn
, crypt_path_t
*layer_hint
)
736 if (rh
->command
== RELAY_COMMAND_END
)
737 return connection_edge_process_end_not_open(rh
, cell
, circ
, conn
, layer_hint
);
739 if (conn
->type
== CONN_TYPE_AP
&& rh
->command
== RELAY_COMMAND_CONNECTED
) {
740 if (conn
->state
!= AP_CONN_STATE_CONNECT_WAIT
) {
741 warn(LD_APP
,"Got 'connected' while not in state connect_wait. Dropping.");
744 // log_fn(LOG_INFO,"Connected! Notifying application.");
745 conn
->state
= AP_CONN_STATE_OPEN
;
746 info(LD_APP
,"'connected' received after %d seconds.",
747 (int)(time(NULL
) - conn
->timestamp_lastread
));
748 if (rh
->length
>= 4) {
749 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
752 info(LD_APP
,"...but it claims the IP address was 0.0.0.0. Closing.");
753 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
754 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
758 ttl
= (int)ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+4));
761 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
762 conn
->chosen_exit_name
, ttl
);
764 circuit_log_path(LOG_INFO
,LD_APP
,circ
);
765 connection_ap_handshake_socks_reply(conn
, NULL
, 0, SOCKS5_SUCCEEDED
);
766 /* handle anything that might have queued */
767 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
768 /* (We already sent an end cell if possible) */
769 connection_mark_for_close(conn
);
774 if (conn
->type
== CONN_TYPE_AP
&& rh
->command
== RELAY_COMMAND_RESOLVED
) {
777 if (conn
->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
778 warn(LD_APP
,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
781 tor_assert(conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE
);
782 answer_len
= cell
->payload
[RELAY_HEADER_SIZE
+1];
783 if (rh
->length
< 2 || answer_len
+2>rh
->length
) {
784 warn(LD_PROTOCOL
, "Dropping malformed 'resolved' cell");
785 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
788 if (rh
->length
>= answer_len
+6)
789 ttl
= (int)ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+2+answer_len
));
792 connection_ap_handshake_socks_resolved(conn
,
793 cell
->payload
[RELAY_HEADER_SIZE
], /*answer_type*/
794 cell
->payload
[RELAY_HEADER_SIZE
+1], /*answer_len*/
795 cell
->payload
+RELAY_HEADER_SIZE
+2, /*answer*/
797 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
802 "Got an unexpected relay command %d, in state %d (%s). Closing.",
803 rh
->command
, conn
->state
, conn_state_to_string(conn
->type
, conn
->state
));
804 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
805 connection_mark_for_close(conn
);
809 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
810 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
811 * destined for <b>conn</b>.
813 * If <b>layer_hint</b> is defined, then we're the origin of the
814 * circuit, and it specifies the hop that packaged <b>cell</b>.
816 * Return -1 if you want to warn and tear down the circuit, else 0.
819 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
821 crypt_path_t
*layer_hint
)
823 static int num_seen
=0;
825 unsigned domain
= layer_hint
?LD_APP
:LD_EXIT
;
830 relay_header_unpack(&rh
, cell
->payload
);
831 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
833 debug(domain
, "Now seen %d relay cells here.", num_seen
);
835 if (rh
.length
> RELAY_PAYLOAD_SIZE
) {
836 warn(LD_PROTOCOL
, "Relay cell length field too long. Closing circuit.");
840 /* either conn is NULL, in which case we've got a control cell, or else
841 * conn points to the recognized stream. */
843 if (conn
&& !connection_state_is_open(conn
))
844 return connection_edge_process_relay_cell_not_open(
845 &rh
, cell
, circ
, conn
, layer_hint
);
847 switch (rh
.command
) {
848 case RELAY_COMMAND_DROP
:
849 info(domain
,"Got a relay-level padding cell. Dropping.");
851 case RELAY_COMMAND_BEGIN
:
853 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
854 warn(LD_APP
,"relay begin request unsupported at AP. Dropping.");
858 warn(domain
,"begin cell for known stream. Dropping.");
861 connection_exit_begin_conn(cell
, circ
);
863 case RELAY_COMMAND_DATA
:
864 ++stats_n_data_cells_received
;
865 if (( layer_hint
&& --layer_hint
->deliver_window
< 0) ||
866 (!layer_hint
&& --circ
->deliver_window
< 0)) {
867 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
868 "(relay data) circ deliver_window below 0. Killing.");
869 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
,
871 connection_mark_for_close(conn
);
874 debug(domain
,"circ deliver_window now %d.", layer_hint
?
875 layer_hint
->deliver_window
: circ
->deliver_window
);
877 circuit_consider_sending_sendme(circ
, layer_hint
);
880 info(domain
,"data cell dropped, unknown stream.");
884 if (--conn
->deliver_window
< 0) { /* is it below 0 after decrement? */
885 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
886 "(relay data) conn deliver_window below 0. Killing.");
887 return -1; /* somebody's breaking protocol. kill the whole circuit. */
890 stats_n_data_bytes_received
+= rh
.length
;
891 connection_write_to_buf(cell
->payload
+ RELAY_HEADER_SIZE
,
893 connection_edge_consider_sending_sendme(conn
);
895 case RELAY_COMMAND_END
:
897 info(domain
,"end cell (%s) dropped, unknown stream.",
898 connection_edge_end_reason_str(rh
.length
> 0 ?
899 *(char *)(cell
->payload
+RELAY_HEADER_SIZE
) : -1));
902 /* XXX add to this log_fn the exit node's nickname? */
903 info(domain
,"%d: end cell (%s) for stream %d. Removing stream.",
905 connection_edge_end_reason_str(rh
.length
> 0 ?
906 *(char *)(cell
->payload
+RELAY_HEADER_SIZE
) : -1),
908 if (conn
->socks_request
&& !conn
->socks_request
->has_finished
)
909 warn(LD_BUG
,"Bug: open stream hasn't sent socks answer yet? Closing.");
911 conn
->done_sending
= 1;
912 shutdown(conn
->s
, 1); /* XXX check return; refactor NM */
913 if (conn
->done_receiving
) {
914 /* We just *got* an end; no reason to send one. */
915 conn
->has_sent_end
= 1;
916 connection_mark_for_close(conn
);
917 conn
->hold_open_until_flushed
= 1;
920 /* We just *got* an end; no reason to send one. */
921 conn
->has_sent_end
= 1;
922 if (!conn
->marked_for_close
) {
923 /* only mark it if not already marked. it's possible to
924 * get the 'end' right around when the client hangs up on us. */
925 connection_mark_for_close(conn
);
926 conn
->hold_open_until_flushed
= 1;
930 case RELAY_COMMAND_EXTEND
:
932 warn(domain
,"'extend' for non-zero stream. Dropping.");
935 return circuit_extend(cell
, circ
);
936 case RELAY_COMMAND_EXTENDED
:
938 warn(LD_PROTOCOL
,"'extended' unsupported at non-origin. Dropping.");
941 debug(domain
,"Got an extended cell! Yay.");
942 if (circuit_finish_handshake(circ
, CELL_CREATED
,
943 cell
->payload
+RELAY_HEADER_SIZE
) < 0) {
944 warn(domain
,"circuit_finish_handshake failed.");
947 if (circuit_send_next_onion_skin(circ
)<0) {
948 info(domain
,"circuit_send_next_onion_skin() failed.");
952 case RELAY_COMMAND_TRUNCATE
:
954 warn(LD_APP
,"'truncate' unsupported at origin. Dropping.");
958 connection_send_destroy(circ
->n_circ_id
, circ
->n_conn
);
959 circuit_set_circid_orconn(circ
, 0, NULL
, N_CONN_CHANGED
);
961 debug(LD_EXIT
, "Processed 'truncate', replying.");
962 connection_edge_send_command(NULL
, circ
, RELAY_COMMAND_TRUNCATED
,
965 case RELAY_COMMAND_TRUNCATED
:
967 warn(LD_EXIT
,"'truncated' unsupported at non-origin. Dropping.");
970 circuit_truncated(circ
, layer_hint
);
972 case RELAY_COMMAND_CONNECTED
:
974 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
975 "'connected' unsupported while open. Closing circ.");
978 info(domain
,"'connected' received, no conn attached anymore. Ignoring.");
980 case RELAY_COMMAND_SENDME
:
983 layer_hint
->package_window
+= CIRCWINDOW_INCREMENT
;
984 debug(LD_APP
,"circ-level sendme at origin, packagewindow %d.",
985 layer_hint
->package_window
);
986 circuit_resume_edge_reading(circ
, layer_hint
);
988 circ
->package_window
+= CIRCWINDOW_INCREMENT
;
989 debug(LD_APP
,"circ-level sendme at non-origin, packagewindow %d.",
990 circ
->package_window
);
991 circuit_resume_edge_reading(circ
, layer_hint
);
995 conn
->package_window
+= STREAMWINDOW_INCREMENT
;
996 debug(domain
,"stream-level sendme, packagewindow now %d.", conn
->package_window
);
997 connection_start_reading(conn
);
998 /* handle whatever might still be on the inbuf */
999 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
1000 /* (We already sent an end cell if possible) */
1001 connection_mark_for_close(conn
);
1005 case RELAY_COMMAND_RESOLVE
:
1007 warn(LD_APP
,"resolve request unsupported at AP; dropping.");
1010 warn(domain
, "resolve request for known stream; dropping.");
1012 } else if (circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
1013 warn(domain
, "resolve request on circ with purpose %d; dropping",
1017 connection_exit_begin_resolve(cell
, circ
);
1019 case RELAY_COMMAND_RESOLVED
:
1021 warn(domain
,"'resolved' unsupported while open. Closing circ.");
1024 info(domain
,"'resolved' received, no conn attached anymore. Ignoring.");
1026 case RELAY_COMMAND_ESTABLISH_INTRO
:
1027 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS
:
1028 case RELAY_COMMAND_INTRODUCE1
:
1029 case RELAY_COMMAND_INTRODUCE2
:
1030 case RELAY_COMMAND_INTRODUCE_ACK
:
1031 case RELAY_COMMAND_RENDEZVOUS1
:
1032 case RELAY_COMMAND_RENDEZVOUS2
:
1033 case RELAY_COMMAND_INTRO_ESTABLISHED
:
1034 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED
:
1035 rend_process_relay_cell(circ
, rh
.command
, rh
.length
,
1036 cell
->payload
+RELAY_HEADER_SIZE
);
1039 warn(LD_PROTOCOL
,"unknown relay command %d.",rh
.command
);
1043 uint64_t stats_n_data_cells_packaged
= 0;
1044 uint64_t stats_n_data_bytes_packaged
= 0;
1045 uint64_t stats_n_data_cells_received
= 0;
1046 uint64_t stats_n_data_bytes_received
= 0;
1048 /** While conn->inbuf has an entire relay payload of bytes on it,
1049 * and the appropriate package windows aren't empty, grab a cell
1050 * and send it down the circuit.
1052 * Return -1 (and send a RELAY_END cell if necessary) if conn should
1053 * be marked for close, else return 0.
1056 connection_edge_package_raw_inbuf(connection_t
*conn
, int package_partial
)
1058 size_t amount_to_process
, length
;
1059 char payload
[CELL_PAYLOAD_SIZE
];
1061 unsigned domain
= conn
->cpath_layer
? LD_APP
: LD_EXIT
;
1064 tor_assert(!connection_speaks_cells(conn
));
1065 if (conn
->marked_for_close
) {
1066 warn(LD_BUG
,"Bug: called on conn that's already marked for close at %s:%d.",
1067 conn
->marked_for_close_file
, conn
->marked_for_close
);
1071 repeat_connection_edge_package_raw_inbuf
:
1073 circ
= circuit_get_by_edge_conn(conn
);
1075 info(domain
,"conn has no circuit! Closing.");
1079 if (circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
))
1082 if (conn
->package_window
<= 0) {
1083 info(domain
,"called with package_window %d. Skipping.", conn
->package_window
);
1084 connection_stop_reading(conn
);
1088 amount_to_process
= buf_datalen(conn
->inbuf
);
1090 if (!amount_to_process
)
1093 if (!package_partial
&& amount_to_process
< RELAY_PAYLOAD_SIZE
)
1096 if (amount_to_process
> RELAY_PAYLOAD_SIZE
) {
1097 length
= RELAY_PAYLOAD_SIZE
;
1099 length
= amount_to_process
;
1101 stats_n_data_bytes_packaged
+= length
;
1102 stats_n_data_cells_packaged
+= 1;
1104 connection_fetch_from_buf(payload
, length
, conn
);
1106 debug(domain
,"(%d) Packaging %d bytes (%d waiting).", conn
->s
,
1107 (int)length
, (int)buf_datalen(conn
->inbuf
));
1109 if (connection_edge_send_command(conn
, circ
, RELAY_COMMAND_DATA
,
1110 payload
, length
, conn
->cpath_layer
) < 0)
1111 /* circuit got marked for close, don't continue, don't need to mark conn */
1114 if (!conn
->cpath_layer
) { /* non-rendezvous exit */
1115 tor_assert(circ
->package_window
> 0);
1116 circ
->package_window
--;
1117 } else { /* we're an AP, or an exit on a rendezvous circ */
1118 tor_assert(conn
->cpath_layer
->package_window
> 0);
1119 conn
->cpath_layer
->package_window
--;
1122 if (--conn
->package_window
<= 0) { /* is it 0 after decrement? */
1123 connection_stop_reading(conn
);
1124 debug(domain
,"conn->package_window reached 0.");
1125 circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
);
1126 return 0; /* don't process the inbuf any more */
1128 debug(domain
,"conn->package_window is now %d",conn
->package_window
);
1130 /* handle more if there's more, or return 0 if there isn't */
1131 goto repeat_connection_edge_package_raw_inbuf
;
1134 /** Called when we've just received a relay data cell, or when
1135 * we've just finished flushing all bytes to stream <b>conn</b>.
1137 * If conn->outbuf is not too full, and our deliver window is
1138 * low, send back a suitable number of stream-level sendme cells.
1141 connection_edge_consider_sending_sendme(connection_t
*conn
)
1145 if (connection_outbuf_too_full(conn
))
1148 circ
= circuit_get_by_edge_conn(conn
);
1150 /* this can legitimately happen if the destroy has already
1151 * arrived and torn down the circuit */
1152 info(LD_APP
,"No circuit associated with conn. Skipping.");
1156 while (conn
->deliver_window
< STREAMWINDOW_START
- STREAMWINDOW_INCREMENT
) {
1157 debug(conn
->cpath_layer
?LD_APP
:LD_EXIT
,"Outbuf %d, Queueing stream sendme.", (int)conn
->outbuf_flushlen
);
1158 conn
->deliver_window
+= STREAMWINDOW_INCREMENT
;
1159 if (connection_edge_send_command(conn
, circ
, RELAY_COMMAND_SENDME
,
1160 NULL
, 0, conn
->cpath_layer
) < 0) {
1161 warn(LD_APP
,"connection_edge_send_command failed. Returning.");
1162 return; /* the circuit's closed, don't continue */
1167 /** The circuit <b>circ</b> has received a circuit-level sendme
1168 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1169 * attached streams and let them resume reading and packaging, if
1170 * their stream windows allow it.
1173 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1176 debug(layer_hint
?LD_APP
:LD_EXIT
,"resuming");
1178 /* have to check both n_streams and p_streams, to handle rendezvous */
1179 if (circuit_resume_edge_reading_helper(circ
->n_streams
, circ
, layer_hint
) >= 0)
1180 circuit_resume_edge_reading_helper(circ
->p_streams
, circ
, layer_hint
);
1183 /** A helper function for circuit_resume_edge_reading() above.
1184 * The arguments are the same, except that <b>conn</b> is the head
1185 * of a linked list of edge streams that should each be considered.
1188 circuit_resume_edge_reading_helper(connection_t
*conn
,
1190 crypt_path_t
*layer_hint
)
1192 for ( ; conn
; conn
=conn
->next_stream
) {
1193 if (conn
->marked_for_close
)
1195 if ((!layer_hint
&& conn
->package_window
> 0) ||
1196 (layer_hint
&& conn
->package_window
> 0 && conn
->cpath_layer
== layer_hint
)) {
1197 connection_start_reading(conn
);
1198 /* handle whatever might still be on the inbuf */
1199 if (connection_edge_package_raw_inbuf(conn
, 1)<0) {
1200 /* (We already sent an end cell if possible) */
1201 connection_mark_for_close(conn
);
1205 /* If the circuit won't accept any more data, return without looking
1206 * at any more of the streams. Any connections that should be stopped
1207 * have already been stopped by connection_edge_package_raw_inbuf. */
1208 if (circuit_consider_stop_edge_reading(circ
, layer_hint
))
1215 /** Check if the package window for <b>circ</b> is empty (at
1216 * hop <b>layer_hint</b> if it's defined).
1218 * If yes, tell edge streams to stop reading and return 1.
1222 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1224 connection_t
*conn
= NULL
;
1225 unsigned domain
= conn
->cpath_layer
? LD_APP
: LD_EXIT
;
1228 debug(domain
,"considering circ->package_window %d", circ
->package_window
);
1229 if (circ
->package_window
<= 0) {
1230 debug(domain
,"yes, not-at-origin. stopped.");
1231 for (conn
= circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1232 connection_stop_reading(conn
);
1237 /* else, layer hint is defined, use it */
1238 debug(domain
,"considering layer_hint->package_window %d", layer_hint
->package_window
);
1239 if (layer_hint
->package_window
<= 0) {
1240 debug(domain
,"yes, at-origin. stopped.");
1241 for (conn
= circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1242 if (conn
->cpath_layer
== layer_hint
)
1243 connection_stop_reading(conn
);
1244 for (conn
= circ
->p_streams
; conn
; conn
=conn
->next_stream
)
1245 if (conn
->cpath_layer
== layer_hint
)
1246 connection_stop_reading(conn
);
1252 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1253 * <b>layer_hint</b> if it's defined) is low enough that we should
1254 * send a circuit-level sendme back down the circuit. If so, send
1255 * enough sendmes that the window would be overfull if we sent any
1259 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1261 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1262 // layer_hint ? "defined" : "null");
1263 while ((layer_hint
? layer_hint
->deliver_window
: circ
->deliver_window
) <
1264 CIRCWINDOW_START
- CIRCWINDOW_INCREMENT
) {
1265 debug(LD_CIRC
,"Queueing circuit sendme.");
1267 layer_hint
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1269 circ
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1270 if (connection_edge_send_command(NULL
, circ
, RELAY_COMMAND_SENDME
,
1271 NULL
, 0, layer_hint
) < 0) {
1272 warn(LD_CIRC
,"connection_edge_send_command failed. Circuit's closed.");
1273 return; /* the circuit's closed, don't continue */