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_close_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 the <b>payload</b> of length <b>length</b>, which
461 * came from a relay 'end' cell, into a static const string describing
462 * why the stream is closing.
465 connection_edge_end_reason_str(char *payload
, uint16_t length
) {
467 log_fn(LOG_WARN
,"End cell arrived with length 0. Should be at least 1.");
471 case END_STREAM_REASON_MISC
: return "misc error";
472 case END_STREAM_REASON_RESOLVEFAILED
: return "resolve failed";
473 case END_STREAM_REASON_CONNECTREFUSED
: return "connection refused";
474 case END_STREAM_REASON_EXITPOLICY
: return "exit policy failed";
475 case END_STREAM_REASON_DESTROY
: return "destroyed";
476 case END_STREAM_REASON_DONE
: return "closed normally";
477 case END_STREAM_REASON_TIMEOUT
: return "gave up (timeout)";
478 case END_STREAM_REASON_HIBERNATING
: return "server is hibernating";
479 case END_STREAM_REASON_INTERNAL
: return "internal error at server";
480 case END_STREAM_REASON_RESOURCELIMIT
: return "server out of resources";
481 case END_STREAM_REASON_CONNRESET
: return "connection reset";
482 case END_STREAM_REASON_TORPROTOCOL
: return "Tor protocol error";
484 log_fn(LOG_WARN
,"Reason for ending (%d) not recognized.",*payload
);
489 /** Translate <b>reason</b> (as from a relay 'end' cell) into an
490 * appropriate SOCKS5 reply code.
492 socks5_reply_status_t
493 connection_edge_end_reason_socks5_response(int reason
)
496 case END_STREAM_REASON_MISC
:
497 return SOCKS5_GENERAL_ERROR
;
498 case END_STREAM_REASON_RESOLVEFAILED
:
499 return SOCKS5_HOST_UNREACHABLE
;
500 case END_STREAM_REASON_CONNECTREFUSED
:
501 return SOCKS5_CONNECTION_REFUSED
;
502 case END_STREAM_REASON_EXITPOLICY
:
503 return SOCKS5_NOT_ALLOWED
;
504 case END_STREAM_REASON_DESTROY
:
505 return SOCKS5_GENERAL_ERROR
;
506 case END_STREAM_REASON_DONE
:
507 return SOCKS5_SUCCEEDED
;
508 case END_STREAM_REASON_TIMEOUT
:
509 return SOCKS5_TTL_EXPIRED
;
510 case END_STREAM_REASON_RESOURCELIMIT
:
511 return SOCKS5_GENERAL_ERROR
;
512 case END_STREAM_REASON_HIBERNATING
:
513 return SOCKS5_GENERAL_ERROR
;
514 case END_STREAM_REASON_INTERNAL
:
515 return SOCKS5_GENERAL_ERROR
;
516 case END_STREAM_REASON_CONNRESET
:
517 return SOCKS5_CONNECTION_REFUSED
;
518 case END_STREAM_REASON_TORPROTOCOL
:
519 return SOCKS5_GENERAL_ERROR
;
521 case END_STREAM_REASON_ALREADY_SOCKS_REPLIED
:
522 return SOCKS5_SUCCEEDED
; /* never used */
523 case END_STREAM_REASON_CANT_ATTACH
:
524 return SOCKS5_GENERAL_ERROR
;
525 case END_STREAM_REASON_NET_UNREACHABLE
:
526 return SOCKS5_NET_UNREACHABLE
;
528 log_fn(LOG_WARN
,"Reason for ending (%d) not recognized.",reason
);
529 return SOCKS5_GENERAL_ERROR
;
533 /* We need to use a few macros to deal with the fact that Windows
534 * decided that their sockets interface should be a permakludge.
535 * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
536 * version, and S_CASE is for errors where windows has only a WSAEFOO
537 * version. (The E is for 'error', the S is for 'socket'). */
539 #define E_CASE(s) case s: case WSA ## s
540 #define S_CASE(s) case WSA ## s
542 #define E_CASE(s) case s
543 #define S_CASE(s) case s
547 errno_to_end_reason(int e
)
551 return END_STREAM_REASON_DONE
;
557 S_CASE(EPROTONOSUPPORT
):
558 S_CASE(EAFNOSUPPORT
):
562 return END_STREAM_REASON_INTERNAL
;
563 S_CASE(ECONNREFUSED
):
564 return END_STREAM_REASON_CONNECTREFUSED
;
566 return END_STREAM_REASON_CONNRESET
;
568 return END_STREAM_REASON_TIMEOUT
;
573 return END_STREAM_REASON_RESOURCELIMIT
;
575 log_fn(LOG_INFO
, "Didn't recognize errno %d (%s); telling the OP that we are ending a stream for 'misc' reason.",
576 e
, tor_socket_strerror(e
));
577 return END_STREAM_REASON_MISC
;
581 /** How many times will I retry a stream that fails due to DNS
584 #define MAX_RESOLVE_FAILURES 3
586 /** An incoming relay cell has arrived from circuit <b>circ</b> to
587 * stream <b>conn</b>.
589 * The arguments here are the same as in
590 * connection_edge_process_relay_cell() below; this function is called
591 * from there when <b>conn</b> is defined and not in an open state.
594 connection_edge_process_relay_cell_not_open(
595 relay_header_t
*rh
, cell_t
*cell
, circuit_t
*circ
,
596 connection_t
*conn
, crypt_path_t
*layer_hint
) {
600 routerinfo_t
*exitrouter
;
602 if (rh
->command
== RELAY_COMMAND_END
) {
603 reason
= *(cell
->payload
+RELAY_HEADER_SIZE
);
604 /* We have to check this here, since we aren't connected yet. */
605 if (rh
->length
>= 5 && reason
== END_STREAM_REASON_EXITPOLICY
) {
606 if (conn
->type
!= CONN_TYPE_AP
) {
607 log_fn(LOG_WARN
,"Got an end because of exitpolicy, but we're not an AP. Closing.");
610 addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+1));
612 log_fn(LOG_INFO
,"Address '%s' refused due to exit policy. Retrying.",
613 conn
->socks_request
->address
);
615 log_fn(LOG_INFO
,"Address '%s' resolved to 0.0.0.0. Closing,",
616 conn
->socks_request
->address
);
617 connection_close_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
620 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
621 conn
->chosen_exit_name
);
623 /* check if he *ought* to have allowed it */
624 exitrouter
= router_get_by_digest(circ
->build_state
->chosen_exit_digest
);
626 log_fn(LOG_INFO
,"Skipping broken circ (exit router vanished)");
627 return 0; /* this circuit is screwed and doesn't know it yet */
629 if (!tor_inet_aton(conn
->socks_request
->address
, &in
) &&
630 !conn
->chosen_exit_name
) {
631 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
);
632 addr_policy_free(exitrouter
->exit_policy
);
633 exitrouter
->exit_policy
=
634 router_parse_addr_policy_from_string("reject *:*");
637 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
640 log_fn(LOG_INFO
,"Giving up on retrying (from exitpolicy); conn can't be handled.");
641 /* else, conn will get closed below */
642 } else if (rh
->length
&& reason
== END_STREAM_REASON_RESOLVEFAILED
) {
643 if (conn
->type
!= CONN_TYPE_AP
) {
644 log_fn(LOG_WARN
,"Got an end because of resolvefailed, but we're not an AP. Closing.");
647 if (client_dns_incr_failures(conn
->socks_request
->address
)
648 < MAX_RESOLVE_FAILURES
) {
649 /* We haven't retried too many times; reattach the connection. */
650 log_fn(LOG_INFO
,"Resolve of '%s' failed, trying again.",
651 conn
->socks_request
->address
);
652 circuit_log_path(LOG_INFO
,circ
);
653 tor_assert(circ
->timestamp_dirty
);
654 circ
->timestamp_dirty
-= get_options()->MaxCircuitDirtiness
;
656 if (connection_ap_detach_retriable(conn
, circ
) >= 0)
659 /* else, conn will get closed below */
660 log_fn(LOG_INFO
,"Giving up on retrying (from resolvefailed); conn can't be handled.");
662 log_fn(LOG_NOTICE
,"Have tried resolving address '%s' at %d different places. Giving up.",
663 conn
->socks_request
->address
, MAX_RESOLVE_FAILURES
);
666 log_fn(LOG_INFO
,"Edge got end (%s) before we're connected. Marking for close.",
667 connection_edge_end_reason_str(cell
->payload
+RELAY_HEADER_SIZE
,
669 if (CIRCUIT_IS_ORIGIN(circ
))
670 circuit_log_path(LOG_INFO
,circ
);
671 if (conn
->type
== CONN_TYPE_AP
) {
672 connection_close_unattached_ap(conn
,
673 *(char *)(cell
->payload
+RELAY_HEADER_SIZE
));
675 conn
->has_sent_end
= 1; /* we just got an 'end', don't need to send one */
676 connection_mark_for_close(conn
);
681 if (conn
->type
== CONN_TYPE_AP
&& rh
->command
== RELAY_COMMAND_CONNECTED
) {
682 if (conn
->state
!= AP_CONN_STATE_CONNECT_WAIT
) {
683 log_fn(LOG_WARN
,"Got 'connected' while not in state connect_wait. Dropping.");
686 // log_fn(LOG_INFO,"Connected! Notifying application.");
687 conn
->state
= AP_CONN_STATE_OPEN
;
688 log_fn(LOG_INFO
,"'connected' received after %d seconds.",
689 (int)(time(NULL
) - conn
->timestamp_lastread
));
690 if (rh
->length
>= 4) {
691 addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
693 log_fn(LOG_INFO
,"...but it claims the IP address was 0.0.0.0. Closing.");
694 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
695 connection_close_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
698 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
699 conn
->chosen_exit_name
);
701 circuit_log_path(LOG_INFO
,circ
);
702 connection_ap_handshake_socks_reply(conn
, NULL
, 0, SOCKS5_SUCCEEDED
);
703 /* handle anything that might have queued */
704 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
705 /* (We already sent an end cell if possible) */
706 connection_mark_for_close(conn
);
711 if (conn
->type
== CONN_TYPE_AP
&& rh
->command
== RELAY_COMMAND_RESOLVED
) {
712 if (conn
->state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
713 log_fn(LOG_WARN
,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
716 tor_assert(conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE
);
717 if (rh
->length
< 2 || cell
->payload
[RELAY_HEADER_SIZE
+1]+2>rh
->length
) {
718 log_fn(LOG_WARN
, "Dropping malformed 'resolved' cell");
719 connection_close_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
722 connection_ap_handshake_socks_resolved(conn
,
723 cell
->payload
[RELAY_HEADER_SIZE
], /*answer_type*/
724 cell
->payload
[RELAY_HEADER_SIZE
+1], /*answer_len*/
725 cell
->payload
+RELAY_HEADER_SIZE
+2); /* answer */
726 connection_close_unattached_ap(conn
, END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
730 log_fn(LOG_WARN
,"Got an unexpected relay command %d, in state %d (%s). Closing.",
731 rh
->command
, conn
->state
, conn_state_to_string
[conn
->type
][conn
->state
]);
732 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
733 connection_mark_for_close(conn
);
737 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
738 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
739 * destined for <b>conn</b>.
741 * If <b>layer_hint</b> is defined, then we're the origin of the
742 * circuit, and it specifies the hop that packaged <b>cell</b>.
744 * Return -1 if you want to tear down the circuit, else 0.
747 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
749 crypt_path_t
*layer_hint
)
751 static int num_seen
=0;
757 relay_header_unpack(&rh
, cell
->payload
);
758 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
760 log_fn(LOG_DEBUG
,"Now seen %d relay cells here.", num_seen
);
762 /* either conn is NULL, in which case we've got a control cell, or else
763 * conn points to the recognized stream. */
766 conn
->state
!= AP_CONN_STATE_OPEN
&&
767 conn
->state
!= EXIT_CONN_STATE_OPEN
) {
768 return connection_edge_process_relay_cell_not_open(
769 &rh
, cell
, circ
, conn
, layer_hint
);
772 switch (rh
.command
) {
773 case RELAY_COMMAND_DROP
:
774 log_fn(LOG_INFO
,"Got a relay-level padding cell. Dropping.");
776 case RELAY_COMMAND_BEGIN
:
778 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
779 log_fn(LOG_WARN
,"relay begin request unsupported at AP. Dropping.");
783 log_fn(LOG_WARN
,"begin cell for known stream. Dropping.");
786 connection_exit_begin_conn(cell
, circ
);
788 case RELAY_COMMAND_DATA
:
789 ++stats_n_data_cells_received
;
790 if (( layer_hint
&& --layer_hint
->deliver_window
< 0) ||
791 (!layer_hint
&& --circ
->deliver_window
< 0)) {
792 log_fn(LOG_WARN
,"(relay data) circ deliver_window below 0. Killing.");
793 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
, conn
->cpath_layer
);
794 connection_mark_for_close(conn
);
797 log_fn(LOG_DEBUG
,"circ deliver_window now %d.", layer_hint
?
798 layer_hint
->deliver_window
: circ
->deliver_window
);
800 circuit_consider_sending_sendme(circ
, layer_hint
);
803 log_fn(LOG_INFO
,"data cell dropped, unknown stream.");
807 if (--conn
->deliver_window
< 0) { /* is it below 0 after decrement? */
808 log_fn(LOG_WARN
,"(relay data) conn deliver_window below 0. Killing.");
809 return -1; /* somebody's breaking protocol. kill the whole circuit. */
812 stats_n_data_bytes_received
+= rh
.length
;
813 if (conn
->type
== CONN_TYPE_AP
) {
814 conn
->stream_size
+= rh
.length
;
815 log_fn(LOG_DEBUG
,"%d: stream size now %d.", conn
->s
, (int)conn
->stream_size
);
817 connection_write_to_buf(cell
->payload
+ RELAY_HEADER_SIZE
,
819 connection_edge_consider_sending_sendme(conn
);
821 case RELAY_COMMAND_END
:
823 log_fn(LOG_INFO
,"end cell (%s) dropped, unknown stream.",
824 connection_edge_end_reason_str(cell
->payload
+RELAY_HEADER_SIZE
,
828 /* XXX add to this log_fn the exit node's nickname? */
829 log_fn(LOG_INFO
,"%d: end cell (%s) for stream %d. Removing stream. Size %d.",
831 connection_edge_end_reason_str(cell
->payload
+RELAY_HEADER_SIZE
,
833 conn
->stream_id
, (int)conn
->stream_size
);
834 if (conn
->socks_request
&& !conn
->socks_request
->has_finished
) {
835 socks5_reply_status_t status
;
837 log_fn(LOG_WARN
,"End cell arrived with length 0. Should be at least 1.");
838 status
= SOCKS5_GENERAL_ERROR
;
840 status
= connection_edge_end_reason_socks5_response(
841 *(uint8_t*)cell
->payload
+RELAY_HEADER_SIZE
);
843 connection_ap_handshake_socks_reply(conn
, NULL
, 0, status
);
846 conn
->done_sending
= 1;
847 shutdown(conn
->s
, 1); /* XXX check return; refactor NM */
848 if (conn
->done_receiving
) {
849 /* We just *got* an end; no reason to send one. */
850 conn
->has_sent_end
= 1;
851 connection_mark_for_close(conn
);
852 conn
->hold_open_until_flushed
= 1;
855 /* We just *got* an end; no reason to send one. */
856 conn
->has_sent_end
= 1;
857 if (!conn
->marked_for_close
) {
858 /* only mark it if not already marked. it's possible to
859 * get the 'end' right around when the client hangs up on us. */
860 connection_mark_for_close(conn
);
861 conn
->hold_open_until_flushed
= 1;
865 case RELAY_COMMAND_EXTEND
:
867 log_fn(LOG_WARN
,"'extend' for non-zero stream. Dropping.");
870 return circuit_extend(cell
, circ
);
871 case RELAY_COMMAND_EXTENDED
:
873 log_fn(LOG_WARN
,"'extended' unsupported at non-origin. Dropping.");
876 log_fn(LOG_DEBUG
,"Got an extended cell! Yay.");
877 if (circuit_finish_handshake(circ
, cell
->payload
+RELAY_HEADER_SIZE
) < 0) {
878 log_fn(LOG_WARN
,"circuit_finish_handshake failed.");
881 if (circuit_send_next_onion_skin(circ
)<0) {
882 log_fn(LOG_INFO
,"circuit_send_next_onion_skin() failed.");
886 case RELAY_COMMAND_TRUNCATE
:
888 log_fn(LOG_WARN
,"'truncate' unsupported at origin. Dropping.");
892 connection_send_destroy(circ
->n_circ_id
, circ
->n_conn
);
895 log_fn(LOG_DEBUG
, "Processed 'truncate', replying.");
896 connection_edge_send_command(NULL
, circ
, RELAY_COMMAND_TRUNCATED
,
899 case RELAY_COMMAND_TRUNCATED
:
901 log_fn(LOG_WARN
,"'truncated' unsupported at non-origin. Dropping.");
904 circuit_truncated(circ
, layer_hint
);
906 case RELAY_COMMAND_CONNECTED
:
908 log_fn(LOG_WARN
,"'connected' unsupported while open. Closing circ.");
911 log_fn(LOG_INFO
,"'connected' received, no conn attached anymore. Ignoring.");
913 case RELAY_COMMAND_SENDME
:
916 layer_hint
->package_window
+= CIRCWINDOW_INCREMENT
;
917 log_fn(LOG_DEBUG
,"circ-level sendme at origin, packagewindow %d.",
918 layer_hint
->package_window
);
919 circuit_resume_edge_reading(circ
, layer_hint
);
921 circ
->package_window
+= CIRCWINDOW_INCREMENT
;
922 log_fn(LOG_DEBUG
,"circ-level sendme at non-origin, packagewindow %d.",
923 circ
->package_window
);
924 circuit_resume_edge_reading(circ
, layer_hint
);
928 conn
->package_window
+= STREAMWINDOW_INCREMENT
;
929 log_fn(LOG_DEBUG
,"stream-level sendme, packagewindow now %d.", conn
->package_window
);
930 connection_start_reading(conn
);
931 /* handle whatever might still be on the inbuf */
932 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
933 /* (We already sent an end cell if possible) */
934 connection_mark_for_close(conn
);
938 case RELAY_COMMAND_RESOLVE
:
940 log_fn(LOG_WARN
,"resolve request unsupported at AP; dropping.");
943 log_fn(LOG_WARN
, "resolve request for known stream; dropping.");
945 } else if (circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
946 log_fn(LOG_WARN
, "resolve request on circ with purpose %d; dropping",
950 connection_exit_begin_resolve(cell
, circ
);
952 case RELAY_COMMAND_RESOLVED
:
954 log_fn(LOG_WARN
,"'resolved' unsupported while open. Closing circ.");
957 log_fn(LOG_INFO
,"'resolved' received, no conn attached anymore. Ignoring.");
959 case RELAY_COMMAND_ESTABLISH_INTRO
:
960 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS
:
961 case RELAY_COMMAND_INTRODUCE1
:
962 case RELAY_COMMAND_INTRODUCE2
:
963 case RELAY_COMMAND_INTRODUCE_ACK
:
964 case RELAY_COMMAND_RENDEZVOUS1
:
965 case RELAY_COMMAND_RENDEZVOUS2
:
966 case RELAY_COMMAND_INTRO_ESTABLISHED
:
967 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED
:
968 rend_process_relay_cell(circ
, rh
.command
, rh
.length
,
969 cell
->payload
+RELAY_HEADER_SIZE
);
972 log_fn(LOG_WARN
,"unknown relay command %d.",rh
.command
);
976 uint64_t stats_n_data_cells_packaged
= 0;
977 uint64_t stats_n_data_bytes_packaged
= 0;
978 uint64_t stats_n_data_cells_received
= 0;
979 uint64_t stats_n_data_bytes_received
= 0;
981 /** While conn->inbuf has an entire relay payload of bytes on it,
982 * and the appropriate package windows aren't empty, grab a cell
983 * and send it down the circuit.
985 * Return -1 (and send a RELAY_END cell if necessary) if conn should
986 * be marked for close, else return 0.
988 int connection_edge_package_raw_inbuf(connection_t
*conn
, int package_partial
) {
989 size_t amount_to_process
, length
;
990 char payload
[CELL_PAYLOAD_SIZE
];
994 tor_assert(!connection_speaks_cells(conn
));
995 if (conn
->marked_for_close
) {
996 log_fn(LOG_WARN
,"Bug: called on conn that's already marked for close at %s:%d.",
997 conn
->marked_for_close_file
, conn
->marked_for_close
);
1001 repeat_connection_edge_package_raw_inbuf
:
1003 circ
= circuit_get_by_conn(conn
);
1005 log_fn(LOG_INFO
,"conn has no circuit! Closing.");
1009 if (circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
))
1012 if (conn
->package_window
<= 0) {
1013 log_fn(LOG_INFO
,"called with package_window %d. Skipping.", conn
->package_window
);
1014 connection_stop_reading(conn
);
1018 amount_to_process
= buf_datalen(conn
->inbuf
);
1020 if (!amount_to_process
)
1023 if (!package_partial
&& amount_to_process
< RELAY_PAYLOAD_SIZE
)
1026 if (amount_to_process
> RELAY_PAYLOAD_SIZE
) {
1027 length
= RELAY_PAYLOAD_SIZE
;
1029 length
= amount_to_process
;
1031 stats_n_data_bytes_packaged
+= length
;
1032 stats_n_data_cells_packaged
+= 1;
1034 connection_fetch_from_buf(payload
, length
, conn
);
1036 log_fn(LOG_DEBUG
,"(%d) Packaging %d bytes (%d waiting).", conn
->s
,
1037 (int)length
, (int)buf_datalen(conn
->inbuf
));
1038 if (conn
->type
== CONN_TYPE_EXIT
) {
1039 conn
->stream_size
+= length
;
1040 log_fn(LOG_DEBUG
,"%d: Stream size now %d.", conn
->s
, (int)conn
->stream_size
);
1043 if (connection_edge_send_command(conn
, circ
, RELAY_COMMAND_DATA
,
1044 payload
, length
, conn
->cpath_layer
) < 0)
1045 /* circuit got marked for close, don't continue, don't need to mark conn */
1048 if (!conn
->cpath_layer
) { /* non-rendezvous exit */
1049 tor_assert(circ
->package_window
> 0);
1050 circ
->package_window
--;
1051 } else { /* we're an AP, or an exit on a rendezvous circ */
1052 tor_assert(conn
->cpath_layer
->package_window
> 0);
1053 conn
->cpath_layer
->package_window
--;
1056 if (--conn
->package_window
<= 0) { /* is it 0 after decrement? */
1057 connection_stop_reading(conn
);
1058 log_fn(LOG_DEBUG
,"conn->package_window reached 0.");
1059 circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
);
1060 return 0; /* don't process the inbuf any more */
1062 log_fn(LOG_DEBUG
,"conn->package_window is now %d",conn
->package_window
);
1064 /* handle more if there's more, or return 0 if there isn't */
1065 goto repeat_connection_edge_package_raw_inbuf
;
1068 /** Called when we've just received a relay data cell, or when
1069 * we've just finished flushing all bytes to stream <b>conn</b>.
1071 * If conn->outbuf is not too full, and our deliver window is
1072 * low, send back a suitable number of stream-level sendme cells.
1074 void connection_edge_consider_sending_sendme(connection_t
*conn
) {
1077 if (connection_outbuf_too_full(conn
))
1080 circ
= circuit_get_by_conn(conn
);
1082 /* this can legitimately happen if the destroy has already
1083 * arrived and torn down the circuit */
1084 log_fn(LOG_INFO
,"No circuit associated with conn. Skipping.");
1088 while (conn
->deliver_window
< STREAMWINDOW_START
- STREAMWINDOW_INCREMENT
) {
1089 log_fn(LOG_DEBUG
,"Outbuf %d, Queueing stream sendme.", (int)conn
->outbuf_flushlen
);
1090 conn
->deliver_window
+= STREAMWINDOW_INCREMENT
;
1091 if (connection_edge_send_command(conn
, circ
, RELAY_COMMAND_SENDME
,
1092 NULL
, 0, conn
->cpath_layer
) < 0) {
1093 log_fn(LOG_WARN
,"connection_edge_send_command failed. Returning.");
1094 return; /* the circuit's closed, don't continue */
1099 /** The circuit <b>circ</b> has received a circuit-level sendme
1100 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1101 * attached streams and let them resume reading and packaging, if
1102 * their stream windows allow it.
1105 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1108 log_fn(LOG_DEBUG
,"resuming");
1110 /* have to check both n_streams and p_streams, to handle rendezvous */
1111 if (circuit_resume_edge_reading_helper(circ
->n_streams
, circ
, layer_hint
) >= 0)
1112 circuit_resume_edge_reading_helper(circ
->p_streams
, circ
, layer_hint
);
1115 /** A helper function for circuit_resume_edge_reading() above.
1116 * The arguments are the same, except that <b>conn</b> is the head
1117 * of a linked list of edge streams that should each be considered.
1120 circuit_resume_edge_reading_helper(connection_t
*conn
,
1122 crypt_path_t
*layer_hint
) {
1124 for ( ; conn
; conn
=conn
->next_stream
) {
1125 if (conn
->marked_for_close
)
1127 if ((!layer_hint
&& conn
->package_window
> 0) ||
1128 (layer_hint
&& conn
->package_window
> 0 && conn
->cpath_layer
== layer_hint
)) {
1129 connection_start_reading(conn
);
1130 /* handle whatever might still be on the inbuf */
1131 if (connection_edge_package_raw_inbuf(conn
, 1)<0) {
1132 /* (We already sent an end cell if possible) */
1133 connection_mark_for_close(conn
);
1137 /* If the circuit won't accept any more data, return without looking
1138 * at any more of the streams. Any connections that should be stopped
1139 * have already been stopped by connection_edge_package_raw_inbuf. */
1140 if (circuit_consider_stop_edge_reading(circ
, layer_hint
))
1147 /** Check if the package window for <b>circ</b> is empty (at
1148 * hop <b>layer_hint</b> if it's defined).
1150 * If yes, tell edge streams to stop reading and return 1.
1154 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1156 connection_t
*conn
= NULL
;
1159 log_fn(LOG_DEBUG
,"considering circ->package_window %d", circ
->package_window
);
1160 if (circ
->package_window
<= 0) {
1161 log_fn(LOG_DEBUG
,"yes, not-at-origin. stopped.");
1162 for (conn
= circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1163 connection_stop_reading(conn
);
1168 /* else, layer hint is defined, use it */
1169 log_fn(LOG_DEBUG
,"considering layer_hint->package_window %d", layer_hint
->package_window
);
1170 if (layer_hint
->package_window
<= 0) {
1171 log_fn(LOG_DEBUG
,"yes, at-origin. stopped.");
1172 for (conn
= circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1173 if (conn
->cpath_layer
== layer_hint
)
1174 connection_stop_reading(conn
);
1175 for (conn
= circ
->p_streams
; conn
; conn
=conn
->next_stream
)
1176 if (conn
->cpath_layer
== layer_hint
)
1177 connection_stop_reading(conn
);
1183 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1184 * <b>layer_hint</b> if it's defined) is low enough that we should
1185 * send a circuit-level sendme back down the circuit. If so, send
1186 * enough sendmes that the window would be overfull if we sent any
1190 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1192 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1193 // layer_hint ? "defined" : "null");
1194 while ((layer_hint
? layer_hint
->deliver_window
: circ
->deliver_window
) <
1195 CIRCWINDOW_START
- CIRCWINDOW_INCREMENT
) {
1196 log_fn(LOG_DEBUG
,"Queueing circuit sendme.");
1198 layer_hint
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1200 circ
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1201 if (connection_edge_send_command(NULL
, circ
, RELAY_COMMAND_SENDME
,
1202 NULL
, 0, layer_hint
) < 0) {
1203 log_fn(LOG_WARN
,"connection_edge_send_command failed. Circuit's closed.");
1204 return; /* the circuit's closed, don't continue */