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.
16 static int relay_crypt(circuit_t
*circ
, cell_t
*cell
, int cell_direction
,
17 crypt_path_t
**layer_hint
, char *recognized
);
18 static connection_t
*relay_lookup_conn(circuit_t
*circ
, cell_t
*cell
, int cell_direction
);
21 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
23 crypt_path_t
*layer_hint
);
25 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
);
27 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
);
29 circuit_resume_edge_reading_helper(connection_t
*conn
,
31 crypt_path_t
*layer_hint
);
33 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
);
35 /** Stats: how many relay cells have originated at this hop, or have
36 * been relayed onward (not recognized at this hop)?
38 unsigned long stats_n_relay_cells_relayed
= 0;
39 /** Stats: how many relay cells have been delivered to streams at this
42 unsigned long stats_n_relay_cells_delivered
= 0;
44 /** Update digest from the payload of cell. Assign integrity part to
47 static void relay_set_digest(crypto_digest_env_t
*digest
, cell_t
*cell
) {
51 crypto_digest_add_bytes(digest
, cell
->payload
, CELL_PAYLOAD_SIZE
);
52 crypto_digest_get_digest(digest
, integrity
, 4);
53 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
54 // integrity[0], integrity[1], integrity[2], integrity[3]);
55 relay_header_unpack(&rh
, cell
->payload
);
56 memcpy(rh
.integrity
, integrity
, 4);
57 relay_header_pack(cell
->payload
, &rh
);
60 /** Does the digest for this circuit indicate that this cell is for us?
62 * Update digest from the payload of cell (with the integrity part set
63 * to 0). If the integrity part is valid, return 1, else restore digest
64 * and cell to their original state and return 0.
66 static int relay_digest_matches(crypto_digest_env_t
*digest
, cell_t
*cell
) {
67 char received_integrity
[4], calculated_integrity
[4];
69 crypto_digest_env_t
*backup_digest
=NULL
;
71 backup_digest
= crypto_digest_dup(digest
);
73 relay_header_unpack(&rh
, cell
->payload
);
74 memcpy(received_integrity
, rh
.integrity
, 4);
75 memset(rh
.integrity
, 0, 4);
76 relay_header_pack(cell
->payload
, &rh
);
78 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
79 // received_integrity[0], received_integrity[1],
80 // received_integrity[2], received_integrity[3]);
82 crypto_digest_add_bytes(digest
, cell
->payload
, CELL_PAYLOAD_SIZE
);
83 crypto_digest_get_digest(digest
, calculated_integrity
, 4);
85 if (memcmp(received_integrity
, calculated_integrity
, 4)) {
86 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
87 // (%d vs %d).", received_integrity, calculated_integrity);
88 /* restore digest to its old form */
89 crypto_digest_assign(digest
, backup_digest
);
90 /* restore the relay header */
91 memcpy(rh
.integrity
, received_integrity
, 4);
92 relay_header_pack(cell
->payload
, &rh
);
93 crypto_free_digest_env(backup_digest
);
96 crypto_free_digest_env(backup_digest
);
100 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
103 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
105 * Return -1 if the crypto fails, else return 0.
107 static int relay_crypt_one_payload(crypto_cipher_env_t
*cipher
, char *in
,
109 char out
[CELL_PAYLOAD_SIZE
]; /* 'in' must be this size too */
111 if (( encrypt_mode
&& crypto_cipher_encrypt(cipher
, out
, in
, CELL_PAYLOAD_SIZE
)) ||
112 (!encrypt_mode
&& crypto_cipher_decrypt(cipher
, out
, in
, CELL_PAYLOAD_SIZE
))) {
113 log_fn(LOG_WARN
,"Error during relay encryption");
116 memcpy(in
,out
,CELL_PAYLOAD_SIZE
);
120 /** Receive a relay cell:
121 * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
122 * - Check if recognized (if exitward).
123 * - If recognized and the digest checks out, then find if there's
124 * a conn that the cell is intended for, and deliver it to·
126 * - Else connection_or_write_cell_to_buf to the conn on the other
127 * side of the circuit.
129 int circuit_receive_relay_cell(cell_t
*cell
, circuit_t
*circ
,
130 int cell_direction
) {
131 connection_t
*conn
=NULL
;
132 crypt_path_t
*layer_hint
=NULL
;
137 tor_assert(cell_direction
== CELL_DIRECTION_OUT
||
138 cell_direction
== CELL_DIRECTION_IN
);
139 if (circ
->marked_for_close
)
142 if (relay_crypt(circ
, cell
, cell_direction
, &layer_hint
, &recognized
) < 0) {
143 log_fn(LOG_WARN
,"relay crypt failed. Dropping connection.");
148 conn
= relay_lookup_conn(circ
, cell
, cell_direction
);
149 if (cell_direction
== CELL_DIRECTION_OUT
) {
150 ++stats_n_relay_cells_delivered
;
151 log_fn(LOG_DEBUG
,"Sending away from origin.");
152 if (connection_edge_process_relay_cell(cell
, circ
, conn
, NULL
) < 0) {
153 log_fn(LOG_WARN
,"connection_edge_process_relay_cell (away from origin) failed.");
157 if (cell_direction
== CELL_DIRECTION_IN
) {
158 ++stats_n_relay_cells_delivered
;
159 log_fn(LOG_DEBUG
,"Sending to origin.");
160 if (connection_edge_process_relay_cell(cell
, circ
, conn
, layer_hint
) < 0) {
161 log_fn(LOG_WARN
,"connection_edge_process_relay_cell (at origin) failed.");
168 /* not recognized. pass it on. */
169 if (cell_direction
== CELL_DIRECTION_OUT
) {
170 cell
->circ_id
= circ
->n_circ_id
; /* switch it */
173 cell
->circ_id
= circ
->p_circ_id
; /* switch it */
178 if (circ
->rend_splice
&& cell_direction
== CELL_DIRECTION_OUT
) {
179 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_REND_ESTABLISHED
);
180 tor_assert(circ
->rend_splice
->purpose
== CIRCUIT_PURPOSE_REND_ESTABLISHED
);
181 cell
->circ_id
= circ
->rend_splice
->p_circ_id
;
182 if (circuit_receive_relay_cell(cell
, circ
->rend_splice
, CELL_DIRECTION_IN
)<0) {
183 log_fn(LOG_WARN
, "Error relaying cell across rendezvous; closing circuits");
184 circuit_mark_for_close(circ
); /* XXXX Do this here, or just return -1? */
189 log_fn(LOG_WARN
,"Didn't recognize cell, but circ stops here! Closing circ.");
193 log_fn(LOG_DEBUG
,"Passing on unrecognized cell.");
194 ++stats_n_relay_cells_relayed
;
195 connection_or_write_cell_to_buf(cell
, conn
);
199 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
200 * <b>circ</b> in direction <b>cell_direction</b>.
202 * If cell_direction == CELL_DIRECTION_IN:
203 * - If we're at the origin (we're the OP), for hops 1..N,
204 * decrypt cell. If recognized, stop.
205 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
207 * If cell_direction == CELL_DIRECTION_OUT:
208 * - decrypt one hop. Check if recognized.
210 * If cell is recognized, set *recognized to 1, and set
211 * *layer_hint to the hop that recognized it.
213 * Return -1 to indicate that we should mark the circuit for close,
216 /* wrap this into receive_relay_cell one day */
217 static int relay_crypt(circuit_t
*circ
, cell_t
*cell
, int cell_direction
,
218 crypt_path_t
**layer_hint
, char *recognized
) {
219 crypt_path_t
*thishop
;
224 tor_assert(recognized
);
225 tor_assert(cell_direction
== CELL_DIRECTION_IN
||
226 cell_direction
== CELL_DIRECTION_OUT
);
228 if (cell_direction
== CELL_DIRECTION_IN
) {
229 if (CIRCUIT_IS_ORIGIN(circ
)) { /* We're at the beginning of the circuit.
230 We'll want to do layered decrypts. */
231 tor_assert(circ
->cpath
);
232 thishop
= circ
->cpath
;
233 if (thishop
->state
!= CPATH_STATE_OPEN
) {
234 log_fn(LOG_WARN
,"Relay cell before first created cell? Closing.");
237 do { /* Remember: cpath is in forward order, that is, first hop first. */
240 if (relay_crypt_one_payload(thishop
->b_crypto
, cell
->payload
, 0) < 0)
243 relay_header_unpack(&rh
, cell
->payload
);
244 if (rh
.recognized
== 0) {
245 /* it's possibly recognized. have to check digest to be sure. */
246 if (relay_digest_matches(thishop
->b_digest
, cell
)) {
248 *layer_hint
= thishop
;
253 thishop
= thishop
->next
;
254 } while (thishop
!= circ
->cpath
&& thishop
->state
== CPATH_STATE_OPEN
);
255 log_fn(LOG_WARN
,"in-cell at OP not recognized. Closing.");
257 } else { /* we're in the middle. Just one crypt. */
258 if (relay_crypt_one_payload(circ
->p_crypto
, cell
->payload
, 1) < 0)
260 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
262 } else /* cell_direction == CELL_DIRECTION_OUT */ {
263 /* we're in the middle. Just one crypt. */
265 if (relay_crypt_one_payload(circ
->n_crypto
, cell
->payload
, 0) < 0)
268 relay_header_unpack(&rh
, cell
->payload
);
269 if (rh
.recognized
== 0) {
270 /* it's possibly recognized. have to check digest to be sure. */
271 if (relay_digest_matches(circ
->n_digest
, cell
)) {
280 /** Package a relay cell:
281 * - Encrypt it to the right layer
282 * - connection_or_write_cell_to_buf to the right conn
285 circuit_package_relay_cell(cell_t
*cell
, circuit_t
*circ
,
287 crypt_path_t
*layer_hint
)
289 connection_t
*conn
; /* where to send the cell */
290 crypt_path_t
*thishop
; /* counter for repeated crypts */
292 if (cell_direction
== CELL_DIRECTION_OUT
) {
295 log_fn(LOG_WARN
,"outgoing relay cell has n_conn==NULL. Dropping.");
296 return 0; /* just drop it */
298 relay_set_digest(layer_hint
->f_digest
, cell
);
300 thishop
= layer_hint
;
301 /* moving from farthest to nearest hop */
305 log_fn(LOG_DEBUG
,"crypting a layer of the relay cell.");
306 if (relay_crypt_one_payload(thishop
->f_crypto
, cell
->payload
, 1) < 0) {
310 thishop
= thishop
->prev
;
311 } while (thishop
!= circ
->cpath
->prev
);
313 } else { /* incoming cell */
316 log_fn(LOG_WARN
,"incoming relay cell has p_conn==NULL. Dropping.");
317 return 0; /* just drop it */
319 relay_set_digest(circ
->p_digest
, cell
);
320 if (relay_crypt_one_payload(circ
->p_crypto
, cell
->payload
, 1) < 0)
323 ++stats_n_relay_cells_relayed
;
324 connection_or_write_cell_to_buf(cell
, conn
);
328 /** If cell's stream_id matches the stream_id of any conn that's
329 * attached to circ, return that conn, else return NULL.
331 static connection_t
*
332 relay_lookup_conn(circuit_t
*circ
, cell_t
*cell
, int cell_direction
)
334 connection_t
*tmpconn
;
337 relay_header_unpack(&rh
, cell
->payload
);
342 /* IN or OUT cells could have come from either direction, now
343 * that we allow rendezvous *to* an OP.
346 for (tmpconn
= circ
->n_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
) {
347 if (rh
.stream_id
== tmpconn
->stream_id
&& !tmpconn
->marked_for_close
) {
348 log_fn(LOG_DEBUG
,"found conn for stream %d.", rh
.stream_id
);
349 if (cell_direction
== CELL_DIRECTION_OUT
||
350 connection_edge_is_rendezvous_stream(tmpconn
))
354 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
) {
355 if (rh
.stream_id
== tmpconn
->stream_id
&& !tmpconn
->marked_for_close
) {
356 log_fn(LOG_DEBUG
,"found conn for stream %d.", rh
.stream_id
);
360 for (tmpconn
= circ
->resolving_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
) {
361 if (rh
.stream_id
== tmpconn
->stream_id
&& !tmpconn
->marked_for_close
) {
362 log_fn(LOG_DEBUG
,"found conn for stream %d.", rh
.stream_id
);
366 return NULL
; /* probably a begin relay cell */
369 /** Pack the relay_header_t host-order structure <b>src</b> into
370 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
371 * about the wire format.
373 void relay_header_pack(char *dest
, const relay_header_t
*src
) {
374 *(uint8_t*)(dest
) = src
->command
;
376 set_uint16(dest
+1, htons(src
->recognized
));
377 set_uint16(dest
+3, htons(src
->stream_id
));
378 memcpy(dest
+5, src
->integrity
, 4);
379 set_uint16(dest
+9, htons(src
->length
));
382 /** Unpack the network-order buffer <b>src</b> into a host-order
383 * relay_header_t structure <b>dest</b>.
385 void relay_header_unpack(relay_header_t
*dest
, const char *src
) {
386 dest
->command
= *(uint8_t*)(src
);
388 dest
->recognized
= ntohs(get_uint16(src
+1));
389 dest
->stream_id
= ntohs(get_uint16(src
+3));
390 memcpy(dest
->integrity
, src
+5, 4);
391 dest
->length
= ntohs(get_uint16(src
+9));
394 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
395 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
396 * that's sending the relay cell, or NULL if it's a control cell.
397 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
400 * If you can't send the cell, mark the circuit for close and
401 * return -1. Else return 0.
403 int connection_edge_send_command(connection_t
*fromconn
, circuit_t
*circ
,
404 int relay_command
, const char *payload
,
405 size_t payload_len
, crypt_path_t
*cpath_layer
) {
410 if (fromconn
&& fromconn
->marked_for_close
) {
411 log_fn(LOG_WARN
,"Bug: called on conn that's already marked for close at %s:%d.",
412 fromconn
->marked_for_close_file
, fromconn
->marked_for_close
);
417 log_fn(LOG_WARN
,"no circ. Closing conn.");
418 tor_assert(fromconn
);
419 if (fromconn
->type
== CONN_TYPE_AP
) {
420 connection_mark_unattached_ap(fromconn
, END_STREAM_REASON_INTERNAL
);
422 fromconn
->has_sent_end
= 1; /* no circ to send to */
423 connection_mark_for_close(fromconn
);
428 memset(&cell
, 0, sizeof(cell_t
));
429 cell
.command
= CELL_RELAY
;
431 cell
.circ_id
= circ
->n_circ_id
;
432 cell_direction
= CELL_DIRECTION_OUT
;
434 cell
.circ_id
= circ
->p_circ_id
;
435 cell_direction
= CELL_DIRECTION_IN
;
438 memset(&rh
, 0, sizeof(rh
));
439 rh
.command
= relay_command
;
441 rh
.stream_id
= fromconn
->stream_id
; /* else it's 0 */
442 rh
.length
= payload_len
;
443 relay_header_pack(cell
.payload
, &rh
);
445 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
446 memcpy(cell
.payload
+RELAY_HEADER_SIZE
, payload
, payload_len
);
449 log_fn(LOG_DEBUG
,"delivering %d cell %s.", relay_command
,
450 cell_direction
== CELL_DIRECTION_OUT
? "forward" : "backward");
452 if (circuit_package_relay_cell(&cell
, circ
, cell_direction
, cpath_layer
) < 0) {
453 log_fn(LOG_WARN
,"circuit_package_relay_cell failed. Closing.");
454 circuit_mark_for_close(circ
);
460 /** Translate <b>reason</b>, which came from a relay 'end' cell,
461 * into a static const string describing why the stream is closing.
462 * <b>reason</b> is -1 if no reason was provided.
465 connection_edge_end_reason_str(int reason
) {
468 log_fn(LOG_WARN
,"End cell arrived with length 0. Should be at least 1.");
470 case END_STREAM_REASON_MISC
: return "misc error";
471 case END_STREAM_REASON_RESOLVEFAILED
: return "resolve failed";
472 case END_STREAM_REASON_CONNECTREFUSED
: return "connection refused";
473 case END_STREAM_REASON_EXITPOLICY
: return "exit policy failed";
474 case END_STREAM_REASON_DESTROY
: return "destroyed";
475 case END_STREAM_REASON_DONE
: return "closed normally";
476 case END_STREAM_REASON_TIMEOUT
: return "gave up (timeout)";
477 case END_STREAM_REASON_HIBERNATING
: return "server is hibernating";
478 case END_STREAM_REASON_INTERNAL
: return "internal error at server";
479 case END_STREAM_REASON_RESOURCELIMIT
: return "server out of resources";
480 case END_STREAM_REASON_CONNRESET
: return "connection reset";
481 case END_STREAM_REASON_TORPROTOCOL
: return "Tor protocol error";
483 log_fn(LOG_WARN
,"Reason for ending (%d) not recognized.",reason
);
488 /** Translate <b>reason</b> (as from a relay 'end' cell) into an
489 * appropriate SOCKS5 reply code.
491 socks5_reply_status_t
492 connection_edge_end_reason_socks5_response(int reason
)
495 case END_STREAM_REASON_MISC
:
496 return SOCKS5_GENERAL_ERROR
;
497 case END_STREAM_REASON_RESOLVEFAILED
:
498 return SOCKS5_HOST_UNREACHABLE
;
499 case END_STREAM_REASON_CONNECTREFUSED
:
500 return SOCKS5_CONNECTION_REFUSED
;
501 case END_STREAM_REASON_EXITPOLICY
:
502 return SOCKS5_NOT_ALLOWED
;
503 case END_STREAM_REASON_DESTROY
:
504 return SOCKS5_GENERAL_ERROR
;
505 case END_STREAM_REASON_DONE
:
506 return SOCKS5_SUCCEEDED
;
507 case END_STREAM_REASON_TIMEOUT
:
508 return SOCKS5_TTL_EXPIRED
;
509 case END_STREAM_REASON_RESOURCELIMIT
:
510 return SOCKS5_GENERAL_ERROR
;
511 case END_STREAM_REASON_HIBERNATING
:
512 return SOCKS5_GENERAL_ERROR
;
513 case END_STREAM_REASON_INTERNAL
:
514 return SOCKS5_GENERAL_ERROR
;
515 case END_STREAM_REASON_CONNRESET
:
516 return SOCKS5_CONNECTION_REFUSED
;
517 case END_STREAM_REASON_TORPROTOCOL
:
518 return SOCKS5_GENERAL_ERROR
;
520 case END_STREAM_REASON_ALREADY_SOCKS_REPLIED
:
521 return SOCKS5_SUCCEEDED
; /* never used */
522 case END_STREAM_REASON_CANT_ATTACH
:
523 return SOCKS5_GENERAL_ERROR
;
524 case END_STREAM_REASON_NET_UNREACHABLE
:
525 return SOCKS5_NET_UNREACHABLE
;
527 log_fn(LOG_WARN
,"Reason for ending (%d) not recognized.",reason
);
528 return SOCKS5_GENERAL_ERROR
;
532 /* We need to use a few macros to deal with the fact that Windows
533 * decided that their sockets interface should be a permakludge.
534 * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
535 * version, and S_CASE is for errors where windows has only a WSAEFOO
536 * version. (The E is for 'error', the S is for 'socket'). */
538 #define E_CASE(s) case s: case WSA ## s
539 #define S_CASE(s) case WSA ## s
541 #define E_CASE(s) case s
542 #define S_CASE(s) case s
546 errno_to_end_reason(int e
)
550 return END_STREAM_REASON_DONE
;
556 S_CASE(EPROTONOSUPPORT
):
557 S_CASE(EAFNOSUPPORT
):
561 return END_STREAM_REASON_INTERNAL
;
562 S_CASE(ECONNREFUSED
):
563 return END_STREAM_REASON_CONNECTREFUSED
;
565 return END_STREAM_REASON_CONNRESET
;
567 return END_STREAM_REASON_TIMEOUT
;
572 return END_STREAM_REASON_RESOURCELIMIT
;
574 log_fn(LOG_INFO
, "Didn't recognize errno %d (%s); telling the OP that we are ending a stream for 'misc' reason.",
575 e
, tor_socket_strerror(e
));
576 return END_STREAM_REASON_MISC
;
580 /** How many times will I retry a stream that fails due to DNS
583 #define MAX_RESOLVE_FAILURES 3
585 /** Return 1 if reason is something that you should retry if you
586 * get the end cell before you've connected; else return 0. */
588 edge_reason_is_retriable(int reason
) {
589 return reason
== END_STREAM_REASON_HIBERNATING
||
590 reason
== END_STREAM_REASON_RESOURCELIMIT
||
591 reason
== END_STREAM_REASON_EXITPOLICY
||
592 reason
== END_STREAM_REASON_RESOLVEFAILED
;
596 connection_edge_process_end_not_open(
597 relay_header_t
*rh
, cell_t
*cell
, circuit_t
*circ
,
598 connection_t
*conn
, crypt_path_t
*layer_hint
) {
600 routerinfo_t
*exitrouter
;
601 int reason
= *(cell
->payload
+RELAY_HEADER_SIZE
);
603 if (rh
->length
> 0 && edge_reason_is_retriable(reason
)) {
604 if (conn
->type
!= CONN_TYPE_AP
) {
605 log_fn(LOG_WARN
,"Got an end because of %s, but we're not an AP. Closing.",
606 connection_edge_end_reason_str(reason
));
609 log_fn(LOG_INFO
,"Address '%s' refused due to '%s'. Considering retrying.",
610 safe_str(conn
->socks_request
->address
),
611 connection_edge_end_reason_str(reason
));
612 exitrouter
= router_get_by_digest(circ
->build_state
->chosen_exit_digest
);
614 log_fn(LOG_INFO
,"Skipping broken circ (exit router vanished)");
615 return 0; /* this circuit is screwed and doesn't know it yet */
618 case END_STREAM_REASON_EXITPOLICY
:
619 if (rh
->length
>= 5) {
620 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+1));
622 log_fn(LOG_INFO
,"Address '%s' resolved to 0.0.0.0. Closing,",
623 safe_str(conn
->socks_request
->address
));
624 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
627 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
628 conn
->chosen_exit_name
);
630 /* check if he *ought* to have allowed it */
631 if (rh
->length
< 5 ||
632 (!tor_inet_aton(conn
->socks_request
->address
, &in
) &&
633 !conn
->chosen_exit_name
)) {
634 log_fn(LOG_NOTICE
,"Exitrouter '%s' seems to be more restrictive than its exit policy. Not using this router as exit for now.", exitrouter
->nickname
);
635 addr_policy_free(exitrouter
->exit_policy
);
636 exitrouter
->exit_policy
=
637 router_parse_addr_policy_from_string("reject *:*");
640 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
642 /* else, conn will get closed below */
644 case END_STREAM_REASON_RESOLVEFAILED
:
645 if (client_dns_incr_failures(conn
->socks_request
->address
)
646 < MAX_RESOLVE_FAILURES
) {
647 /* We haven't retried too many times; reattach the connection. */
648 circuit_log_path(LOG_INFO
,circ
);
649 tor_assert(circ
->timestamp_dirty
);
650 circ
->timestamp_dirty
-= get_options()->MaxCircuitDirtiness
;
652 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
654 /* else, conn will get closed below */
656 log_fn(LOG_NOTICE
,"Have tried resolving address '%s' at %d different places. Giving up.",
657 safe_str(conn
->socks_request
->address
), MAX_RESOLVE_FAILURES
);
660 case END_STREAM_REASON_HIBERNATING
:
661 case END_STREAM_REASON_RESOURCELIMIT
:
662 addr_policy_free(exitrouter
->exit_policy
);
663 exitrouter
->exit_policy
=
664 router_parse_addr_policy_from_string("reject *:*");
666 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
668 /* else, will close below */
671 log_fn(LOG_INFO
,"Giving up on retrying; conn can't be handled.");
674 log_fn(LOG_INFO
,"Edge got end (%s) before we're connected. Marking for close.",
675 connection_edge_end_reason_str(rh
->length
> 0 ? reason
: -1));
676 if (conn
->type
== CONN_TYPE_AP
) {
677 circuit_log_path(LOG_INFO
,circ
);
678 connection_mark_unattached_ap(conn
, reason
);
680 conn
->has_sent_end
= 1; /* we just got an 'end', don't need to send one */
681 connection_mark_for_close(conn
);
686 /** An incoming relay cell has arrived from circuit <b>circ</b> to
687 * stream <b>conn</b>.
689 * The arguments here are the same as in
690 * connection_edge_process_relay_cell() below; this function is called
691 * from there when <b>conn</b> is defined and not in an open state.
694 connection_edge_process_relay_cell_not_open(
695 relay_header_t
*rh
, cell_t
*cell
, circuit_t
*circ
,
696 connection_t
*conn
, crypt_path_t
*layer_hint
) {
698 if (rh
->command
== RELAY_COMMAND_END
)
699 return connection_edge_process_end_not_open(rh
, cell
, circ
, conn
, layer_hint
);
701 if (conn
->type
== CONN_TYPE_AP
&& rh
->command
== RELAY_COMMAND_CONNECTED
) {
702 if (conn
->state
!= AP_CONN_STATE_CONNECT_WAIT
) {
703 log_fn(LOG_WARN
,"Got 'connected' while not in state connect_wait. Dropping.");
706 // log_fn(LOG_INFO,"Connected! Notifying application.");
707 conn
->state
= AP_CONN_STATE_OPEN
;
708 log_fn(LOG_INFO
,"'connected' received after %d seconds.",
709 (int)(time(NULL
) - conn
->timestamp_lastread
));
710 if (rh
->length
>= 4) {
711 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
713 log_fn(LOG_INFO
,"...but it claims the IP address was 0.0.0.0. Closing.");
714 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
715 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
718 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
719 conn
->chosen_exit_name
);
721 circuit_log_path(LOG_INFO
,circ
);
722 connection_ap_handshake_socks_reply(conn
, NULL
, 0, SOCKS5_SUCCEEDED
);
723 /* handle anything that might have queued */
724 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
725 /* (We already sent an end cell if possible) */
726 connection_mark_for_close(conn
);
731 if (conn
->type
== CONN_TYPE_AP
&& rh
->command
== RELAY_COMMAND_RESOLVED
) {
732 if (conn
->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
733 log_fn(LOG_WARN
,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
736 tor_assert(conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE
);
737 if (rh
->length
< 2 || cell
->payload
[RELAY_HEADER_SIZE
+1]+2>rh
->length
) {
738 log_fn(LOG_WARN
, "Dropping malformed 'resolved' cell");
739 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
742 connection_ap_handshake_socks_resolved(conn
,
743 cell
->payload
[RELAY_HEADER_SIZE
], /*answer_type*/
744 cell
->payload
[RELAY_HEADER_SIZE
+1], /*answer_len*/
745 cell
->payload
+RELAY_HEADER_SIZE
+2); /* answer */
746 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
750 log_fn(LOG_WARN
,"Got an unexpected relay command %d, in state %d (%s). Closing.",
751 rh
->command
, conn
->state
, conn_state_to_string(conn
->type
, conn
->state
));
752 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
753 connection_mark_for_close(conn
);
757 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
758 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
759 * destined for <b>conn</b>.
761 * If <b>layer_hint</b> is defined, then we're the origin of the
762 * circuit, and it specifies the hop that packaged <b>cell</b>.
764 * Return -1 if you want to tear down the circuit, else 0.
767 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
769 crypt_path_t
*layer_hint
)
771 static int num_seen
=0;
777 relay_header_unpack(&rh
, cell
->payload
);
778 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
780 log_fn(LOG_DEBUG
,"Now seen %d relay cells here.", num_seen
);
782 /* either conn is NULL, in which case we've got a control cell, or else
783 * conn points to the recognized stream. */
785 if (conn
&& !connection_state_is_open(conn
))
786 return connection_edge_process_relay_cell_not_open(
787 &rh
, cell
, circ
, conn
, layer_hint
);
789 switch (rh
.command
) {
790 case RELAY_COMMAND_DROP
:
791 log_fn(LOG_INFO
,"Got a relay-level padding cell. Dropping.");
793 case RELAY_COMMAND_BEGIN
:
795 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
796 log_fn(LOG_WARN
,"relay begin request unsupported at AP. Dropping.");
800 log_fn(LOG_WARN
,"begin cell for known stream. Dropping.");
803 connection_exit_begin_conn(cell
, circ
);
805 case RELAY_COMMAND_DATA
:
806 ++stats_n_data_cells_received
;
807 if (( layer_hint
&& --layer_hint
->deliver_window
< 0) ||
808 (!layer_hint
&& --circ
->deliver_window
< 0)) {
809 log_fn(LOG_WARN
,"(relay data) circ deliver_window below 0. Killing.");
810 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
811 connection_mark_for_close(conn
);
814 log_fn(LOG_DEBUG
,"circ deliver_window now %d.", layer_hint
?
815 layer_hint
->deliver_window
: circ
->deliver_window
);
817 circuit_consider_sending_sendme(circ
, layer_hint
);
820 log_fn(LOG_INFO
,"data cell dropped, unknown stream.");
824 if (--conn
->deliver_window
< 0) { /* is it below 0 after decrement? */
825 log_fn(LOG_WARN
,"(relay data) conn deliver_window below 0. Killing.");
826 return -1; /* somebody's breaking protocol. kill the whole circuit. */
829 stats_n_data_bytes_received
+= rh
.length
;
830 if (conn
->type
== CONN_TYPE_AP
) {
831 conn
->stream_size
+= rh
.length
;
832 log_fn(LOG_DEBUG
,"%d: stream size now %d.", conn
->s
, (int)conn
->stream_size
);
834 connection_write_to_buf(cell
->payload
+ RELAY_HEADER_SIZE
,
836 connection_edge_consider_sending_sendme(conn
);
838 case RELAY_COMMAND_END
:
840 log_fn(LOG_INFO
,"end cell (%s) dropped, unknown stream.",
841 connection_edge_end_reason_str(rh
.length
> 0 ?
842 *(char *)(cell
->payload
+RELAY_HEADER_SIZE
) : -1));
845 /* XXX add to this log_fn the exit node's nickname? */
846 log_fn(LOG_INFO
,"%d: end cell (%s) for stream %d. Removing stream. Size %d.",
848 connection_edge_end_reason_str(rh
.length
> 0 ?
849 *(char *)(cell
->payload
+RELAY_HEADER_SIZE
) : -1),
850 conn
->stream_id
, (int)conn
->stream_size
);
851 if (conn
->socks_request
&& !conn
->socks_request
->has_finished
)
852 log_fn(LOG_WARN
,"Bug: open stream hasn't sent socks answer yet? Closing.");
854 conn
->done_sending
= 1;
855 shutdown(conn
->s
, 1); /* XXX check return; refactor NM */
856 if (conn
->done_receiving
) {
857 /* We just *got* an end; no reason to send one. */
858 conn
->has_sent_end
= 1;
859 connection_mark_for_close(conn
);
860 conn
->hold_open_until_flushed
= 1;
863 /* We just *got* an end; no reason to send one. */
864 conn
->has_sent_end
= 1;
865 if (!conn
->marked_for_close
) {
866 /* only mark it if not already marked. it's possible to
867 * get the 'end' right around when the client hangs up on us. */
868 connection_mark_for_close(conn
);
869 conn
->hold_open_until_flushed
= 1;
873 case RELAY_COMMAND_EXTEND
:
875 log_fn(LOG_WARN
,"'extend' for non-zero stream. Dropping.");
878 return circuit_extend(cell
, circ
);
879 case RELAY_COMMAND_EXTENDED
:
881 log_fn(LOG_WARN
,"'extended' unsupported at non-origin. Dropping.");
884 log_fn(LOG_DEBUG
,"Got an extended cell! Yay.");
885 if (circuit_finish_handshake(circ
, CELL_CREATED
,
886 cell
->payload
+RELAY_HEADER_SIZE
) < 0) {
887 log_fn(LOG_WARN
,"circuit_finish_handshake failed.");
890 if (circuit_send_next_onion_skin(circ
)<0) {
891 log_fn(LOG_INFO
,"circuit_send_next_onion_skin() failed.");
895 case RELAY_COMMAND_TRUNCATE
:
897 log_fn(LOG_WARN
,"'truncate' unsupported at origin. Dropping.");
901 connection_send_destroy(circ
->n_circ_id
, circ
->n_conn
);
902 circuit_set_circid_orconn(circ
, 0, NULL
, N_CONN_CHANGED
);
904 log_fn(LOG_DEBUG
, "Processed 'truncate', replying.");
905 connection_edge_send_command(NULL
, circ
, RELAY_COMMAND_TRUNCATED
,
908 case RELAY_COMMAND_TRUNCATED
:
910 log_fn(LOG_WARN
,"'truncated' unsupported at non-origin. Dropping.");
913 circuit_truncated(circ
, layer_hint
);
915 case RELAY_COMMAND_CONNECTED
:
917 log_fn(LOG_WARN
,"'connected' unsupported while open. Closing circ.");
920 log_fn(LOG_INFO
,"'connected' received, no conn attached anymore. Ignoring.");
922 case RELAY_COMMAND_SENDME
:
925 layer_hint
->package_window
+= CIRCWINDOW_INCREMENT
;
926 log_fn(LOG_DEBUG
,"circ-level sendme at origin, packagewindow %d.",
927 layer_hint
->package_window
);
928 circuit_resume_edge_reading(circ
, layer_hint
);
930 circ
->package_window
+= CIRCWINDOW_INCREMENT
;
931 log_fn(LOG_DEBUG
,"circ-level sendme at non-origin, packagewindow %d.",
932 circ
->package_window
);
933 circuit_resume_edge_reading(circ
, layer_hint
);
937 conn
->package_window
+= STREAMWINDOW_INCREMENT
;
938 log_fn(LOG_DEBUG
,"stream-level sendme, packagewindow now %d.", conn
->package_window
);
939 connection_start_reading(conn
);
940 /* handle whatever might still be on the inbuf */
941 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
942 /* (We already sent an end cell if possible) */
943 connection_mark_for_close(conn
);
947 case RELAY_COMMAND_RESOLVE
:
949 log_fn(LOG_WARN
,"resolve request unsupported at AP; dropping.");
952 log_fn(LOG_WARN
, "resolve request for known stream; dropping.");
954 } else if (circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
955 log_fn(LOG_WARN
, "resolve request on circ with purpose %d; dropping",
959 connection_exit_begin_resolve(cell
, circ
);
961 case RELAY_COMMAND_RESOLVED
:
963 log_fn(LOG_WARN
,"'resolved' unsupported while open. Closing circ.");
966 log_fn(LOG_INFO
,"'resolved' received, no conn attached anymore. Ignoring.");
968 case RELAY_COMMAND_ESTABLISH_INTRO
:
969 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS
:
970 case RELAY_COMMAND_INTRODUCE1
:
971 case RELAY_COMMAND_INTRODUCE2
:
972 case RELAY_COMMAND_INTRODUCE_ACK
:
973 case RELAY_COMMAND_RENDEZVOUS1
:
974 case RELAY_COMMAND_RENDEZVOUS2
:
975 case RELAY_COMMAND_INTRO_ESTABLISHED
:
976 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED
:
977 rend_process_relay_cell(circ
, rh
.command
, rh
.length
,
978 cell
->payload
+RELAY_HEADER_SIZE
);
981 log_fn(LOG_WARN
,"unknown relay command %d.",rh
.command
);
985 uint64_t stats_n_data_cells_packaged
= 0;
986 uint64_t stats_n_data_bytes_packaged
= 0;
987 uint64_t stats_n_data_cells_received
= 0;
988 uint64_t stats_n_data_bytes_received
= 0;
990 /** While conn->inbuf has an entire relay payload of bytes on it,
991 * and the appropriate package windows aren't empty, grab a cell
992 * and send it down the circuit.
994 * Return -1 (and send a RELAY_END cell if necessary) if conn should
995 * be marked for close, else return 0.
997 int connection_edge_package_raw_inbuf(connection_t
*conn
, int package_partial
) {
998 size_t amount_to_process
, length
;
999 char payload
[CELL_PAYLOAD_SIZE
];
1003 tor_assert(!connection_speaks_cells(conn
));
1004 if (conn
->marked_for_close
) {
1005 log_fn(LOG_WARN
,"Bug: called on conn that's already marked for close at %s:%d.",
1006 conn
->marked_for_close_file
, conn
->marked_for_close
);
1010 repeat_connection_edge_package_raw_inbuf
:
1012 circ
= circuit_get_by_edge_conn(conn
);
1014 log_fn(LOG_INFO
,"conn has no circuit! Closing.");
1018 if (circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
))
1021 if (conn
->package_window
<= 0) {
1022 log_fn(LOG_INFO
,"called with package_window %d. Skipping.", conn
->package_window
);
1023 connection_stop_reading(conn
);
1027 amount_to_process
= buf_datalen(conn
->inbuf
);
1029 if (!amount_to_process
)
1032 if (!package_partial
&& amount_to_process
< RELAY_PAYLOAD_SIZE
)
1035 if (amount_to_process
> RELAY_PAYLOAD_SIZE
) {
1036 length
= RELAY_PAYLOAD_SIZE
;
1038 length
= amount_to_process
;
1040 stats_n_data_bytes_packaged
+= length
;
1041 stats_n_data_cells_packaged
+= 1;
1043 connection_fetch_from_buf(payload
, length
, conn
);
1045 log_fn(LOG_DEBUG
,"(%d) Packaging %d bytes (%d waiting).", conn
->s
,
1046 (int)length
, (int)buf_datalen(conn
->inbuf
));
1047 if (conn
->type
== CONN_TYPE_EXIT
) {
1048 conn
->stream_size
+= length
;
1049 log_fn(LOG_DEBUG
,"%d: Stream size now %d.", conn
->s
, (int)conn
->stream_size
);
1052 if (connection_edge_send_command(conn
, circ
, RELAY_COMMAND_DATA
,
1053 payload
, length
, conn
->cpath_layer
) < 0)
1054 /* circuit got marked for close, don't continue, don't need to mark conn */
1057 if (!conn
->cpath_layer
) { /* non-rendezvous exit */
1058 tor_assert(circ
->package_window
> 0);
1059 circ
->package_window
--;
1060 } else { /* we're an AP, or an exit on a rendezvous circ */
1061 tor_assert(conn
->cpath_layer
->package_window
> 0);
1062 conn
->cpath_layer
->package_window
--;
1065 if (--conn
->package_window
<= 0) { /* is it 0 after decrement? */
1066 connection_stop_reading(conn
);
1067 log_fn(LOG_DEBUG
,"conn->package_window reached 0.");
1068 circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
);
1069 return 0; /* don't process the inbuf any more */
1071 log_fn(LOG_DEBUG
,"conn->package_window is now %d",conn
->package_window
);
1073 /* handle more if there's more, or return 0 if there isn't */
1074 goto repeat_connection_edge_package_raw_inbuf
;
1077 /** Called when we've just received a relay data cell, or when
1078 * we've just finished flushing all bytes to stream <b>conn</b>.
1080 * If conn->outbuf is not too full, and our deliver window is
1081 * low, send back a suitable number of stream-level sendme cells.
1083 void connection_edge_consider_sending_sendme(connection_t
*conn
) {
1086 if (connection_outbuf_too_full(conn
))
1089 circ
= circuit_get_by_edge_conn(conn
);
1091 /* this can legitimately happen if the destroy has already
1092 * arrived and torn down the circuit */
1093 log_fn(LOG_INFO
,"No circuit associated with conn. Skipping.");
1097 while (conn
->deliver_window
< STREAMWINDOW_START
- STREAMWINDOW_INCREMENT
) {
1098 log_fn(LOG_DEBUG
,"Outbuf %d, Queueing stream sendme.", (int)conn
->outbuf_flushlen
);
1099 conn
->deliver_window
+= STREAMWINDOW_INCREMENT
;
1100 if (connection_edge_send_command(conn
, circ
, RELAY_COMMAND_SENDME
,
1101 NULL
, 0, conn
->cpath_layer
) < 0) {
1102 log_fn(LOG_WARN
,"connection_edge_send_command failed. Returning.");
1103 return; /* the circuit's closed, don't continue */
1108 /** The circuit <b>circ</b> has received a circuit-level sendme
1109 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1110 * attached streams and let them resume reading and packaging, if
1111 * their stream windows allow it.
1114 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1117 log_fn(LOG_DEBUG
,"resuming");
1119 /* have to check both n_streams and p_streams, to handle rendezvous */
1120 if (circuit_resume_edge_reading_helper(circ
->n_streams
, circ
, layer_hint
) >= 0)
1121 circuit_resume_edge_reading_helper(circ
->p_streams
, circ
, layer_hint
);
1124 /** A helper function for circuit_resume_edge_reading() above.
1125 * The arguments are the same, except that <b>conn</b> is the head
1126 * of a linked list of edge streams that should each be considered.
1129 circuit_resume_edge_reading_helper(connection_t
*conn
,
1131 crypt_path_t
*layer_hint
) {
1133 for ( ; conn
; conn
=conn
->next_stream
) {
1134 if (conn
->marked_for_close
)
1136 if ((!layer_hint
&& conn
->package_window
> 0) ||
1137 (layer_hint
&& conn
->package_window
> 0 && conn
->cpath_layer
== layer_hint
)) {
1138 connection_start_reading(conn
);
1139 /* handle whatever might still be on the inbuf */
1140 if (connection_edge_package_raw_inbuf(conn
, 1)<0) {
1141 /* (We already sent an end cell if possible) */
1142 connection_mark_for_close(conn
);
1146 /* If the circuit won't accept any more data, return without looking
1147 * at any more of the streams. Any connections that should be stopped
1148 * have already been stopped by connection_edge_package_raw_inbuf. */
1149 if (circuit_consider_stop_edge_reading(circ
, layer_hint
))
1156 /** Check if the package window for <b>circ</b> is empty (at
1157 * hop <b>layer_hint</b> if it's defined).
1159 * If yes, tell edge streams to stop reading and return 1.
1163 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1165 connection_t
*conn
= NULL
;
1168 log_fn(LOG_DEBUG
,"considering circ->package_window %d", circ
->package_window
);
1169 if (circ
->package_window
<= 0) {
1170 log_fn(LOG_DEBUG
,"yes, not-at-origin. stopped.");
1171 for (conn
= circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1172 connection_stop_reading(conn
);
1177 /* else, layer hint is defined, use it */
1178 log_fn(LOG_DEBUG
,"considering layer_hint->package_window %d", layer_hint
->package_window
);
1179 if (layer_hint
->package_window
<= 0) {
1180 log_fn(LOG_DEBUG
,"yes, at-origin. stopped.");
1181 for (conn
= circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1182 if (conn
->cpath_layer
== layer_hint
)
1183 connection_stop_reading(conn
);
1184 for (conn
= circ
->p_streams
; conn
; conn
=conn
->next_stream
)
1185 if (conn
->cpath_layer
== layer_hint
)
1186 connection_stop_reading(conn
);
1192 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1193 * <b>layer_hint</b> if it's defined) is low enough that we should
1194 * send a circuit-level sendme back down the circuit. If so, send
1195 * enough sendmes that the window would be overfull if we sent any
1199 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1201 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1202 // layer_hint ? "defined" : "null");
1203 while ((layer_hint
? layer_hint
->deliver_window
: circ
->deliver_window
) <
1204 CIRCWINDOW_START
- CIRCWINDOW_INCREMENT
) {
1205 log_fn(LOG_DEBUG
,"Queueing circuit sendme.");
1207 layer_hint
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1209 circ
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1210 if (connection_edge_send_command(NULL
, circ
, RELAY_COMMAND_SENDME
,
1211 NULL
, 0, layer_hint
) < 0) {
1212 log_fn(LOG_WARN
,"connection_edge_send_command failed. Circuit's closed.");
1213 return; /* the circuit's closed, don't continue */