1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char relay_c_id
[] =
11 * \brief Handle relay cell encryption/decryption, plus packaging and
12 * receiving from circuits, plus queueing on circuits.
16 #include "../common/mempool.h"
18 static int relay_crypt(circuit_t
*circ
, cell_t
*cell
, int cell_direction
,
19 crypt_path_t
**layer_hint
, char *recognized
);
20 static edge_connection_t
*relay_lookup_conn(circuit_t
*circ
, cell_t
*cell
,
24 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
25 edge_connection_t
*conn
,
26 crypt_path_t
*layer_hint
);
28 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
);
30 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
);
32 circuit_resume_edge_reading_helper(edge_connection_t
*conn
,
34 crypt_path_t
*layer_hint
);
36 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
);
38 /** Stats: how many relay cells have originated at this hop, or have
39 * been relayed onward (not recognized at this hop)?
41 uint64_t stats_n_relay_cells_relayed
= 0;
42 /** Stats: how many relay cells have been delivered to streams at this
45 uint64_t stats_n_relay_cells_delivered
= 0;
47 /** Update digest from the payload of cell. Assign integrity part to
51 relay_set_digest(crypto_digest_env_t
*digest
, cell_t
*cell
)
56 crypto_digest_add_bytes(digest
, cell
->payload
, CELL_PAYLOAD_SIZE
);
57 crypto_digest_get_digest(digest
, integrity
, 4);
58 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
59 // integrity[0], integrity[1], integrity[2], integrity[3]);
60 relay_header_unpack(&rh
, cell
->payload
);
61 memcpy(rh
.integrity
, integrity
, 4);
62 relay_header_pack(cell
->payload
, &rh
);
65 /** Does the digest for this circuit indicate that this cell is for us?
67 * Update digest from the payload of cell (with the integrity part set
68 * to 0). If the integrity part is valid, return 1, else restore digest
69 * and cell to their original state and return 0.
72 relay_digest_matches(crypto_digest_env_t
*digest
, cell_t
*cell
)
74 char received_integrity
[4], calculated_integrity
[4];
76 crypto_digest_env_t
*backup_digest
=NULL
;
78 backup_digest
= crypto_digest_dup(digest
);
80 relay_header_unpack(&rh
, cell
->payload
);
81 memcpy(received_integrity
, rh
.integrity
, 4);
82 memset(rh
.integrity
, 0, 4);
83 relay_header_pack(cell
->payload
, &rh
);
85 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
86 // received_integrity[0], received_integrity[1],
87 // received_integrity[2], received_integrity[3]);
89 crypto_digest_add_bytes(digest
, cell
->payload
, CELL_PAYLOAD_SIZE
);
90 crypto_digest_get_digest(digest
, calculated_integrity
, 4);
92 if (memcmp(received_integrity
, calculated_integrity
, 4)) {
93 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
94 // (%d vs %d).", received_integrity, calculated_integrity);
95 /* restore digest to its old form */
96 crypto_digest_assign(digest
, backup_digest
);
97 /* restore the relay header */
98 memcpy(rh
.integrity
, received_integrity
, 4);
99 relay_header_pack(cell
->payload
, &rh
);
100 crypto_free_digest_env(backup_digest
);
103 crypto_free_digest_env(backup_digest
);
107 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
110 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
112 * Return -1 if the crypto fails, else return 0.
115 relay_crypt_one_payload(crypto_cipher_env_t
*cipher
, char *in
,
118 char out
[CELL_PAYLOAD_SIZE
]; /* 'in' must be this size too */
122 r
= crypto_cipher_encrypt(cipher
, out
, in
, CELL_PAYLOAD_SIZE
);
124 r
= crypto_cipher_decrypt(cipher
, out
, in
, CELL_PAYLOAD_SIZE
);
127 log_warn(LD_BUG
,"Error during relay encryption");
130 memcpy(in
,out
,CELL_PAYLOAD_SIZE
);
134 /** Receive a relay cell:
135 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
136 * origin; decrypt if we're headed toward the exit).
137 * - Check if recognized (if exitward).
138 * - If recognized and the digest checks out, then find if there's a stream
139 * that the cell is intended for, and deliver it to the right
141 * - If not recognized, then we need to relay it: append it to the appropriate
142 * cell_queue on <b>circ</b>.
144 * Return -<b>reason</b> on failure.
147 circuit_receive_relay_cell(cell_t
*cell
, circuit_t
*circ
, int cell_direction
)
149 or_connection_t
*or_conn
=NULL
;
150 crypt_path_t
*layer_hint
=NULL
;
156 tor_assert(cell_direction
== CELL_DIRECTION_OUT
||
157 cell_direction
== CELL_DIRECTION_IN
);
158 if (circ
->marked_for_close
)
161 if (relay_crypt(circ
, cell
, cell_direction
, &layer_hint
, &recognized
) < 0) {
162 log_warn(LD_BUG
,"relay crypt failed. Dropping connection.");
163 return -END_CIRC_REASON_INTERNAL
;
167 edge_connection_t
*conn
= relay_lookup_conn(circ
, cell
, cell_direction
);
168 if (cell_direction
== CELL_DIRECTION_OUT
) {
169 ++stats_n_relay_cells_delivered
;
170 log_debug(LD_OR
,"Sending away from origin.");
171 if ((reason
=connection_edge_process_relay_cell(cell
, circ
, conn
, NULL
))
173 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
174 "connection_edge_process_relay_cell (away from origin) "
179 if (cell_direction
== CELL_DIRECTION_IN
) {
180 ++stats_n_relay_cells_delivered
;
181 log_debug(LD_OR
,"Sending to origin.");
182 if ((reason
= connection_edge_process_relay_cell(cell
, circ
, conn
,
185 "connection_edge_process_relay_cell (at origin) failed.");
192 /* not recognized. pass it on. */
193 if (cell_direction
== CELL_DIRECTION_OUT
) {
194 cell
->circ_id
= circ
->n_circ_id
; /* switch it */
195 or_conn
= circ
->n_conn
;
196 } else if (! CIRCUIT_IS_ORIGIN(circ
)) {
197 cell
->circ_id
= TO_OR_CIRCUIT(circ
)->p_circ_id
; /* switch it */
198 or_conn
= TO_OR_CIRCUIT(circ
)->p_conn
;
200 log_fn(LOG_PROTOCOL_WARN
, LD_OR
,
201 "Dropping unrecognized inbound cell on origin circuit.");
206 // XXXX Can this splice stuff be done more cleanly?
207 if (! CIRCUIT_IS_ORIGIN(circ
) &&
208 TO_OR_CIRCUIT(circ
)->rend_splice
&&
209 cell_direction
== CELL_DIRECTION_OUT
) {
210 or_circuit_t
*splice
= TO_OR_CIRCUIT(circ
)->rend_splice
;
211 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_REND_ESTABLISHED
);
212 tor_assert(splice
->_base
.purpose
== CIRCUIT_PURPOSE_REND_ESTABLISHED
);
213 cell
->circ_id
= splice
->p_circ_id
;
214 if ((reason
= circuit_receive_relay_cell(cell
, TO_CIRCUIT(splice
),
215 CELL_DIRECTION_IN
)) < 0) {
216 log_warn(LD_REND
, "Error relaying cell across rendezvous; closing "
218 /* XXXX Do this here, or just return -1? */
219 circuit_mark_for_close(circ
, -reason
);
224 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
225 "Didn't recognize cell, but circ stops here! Closing circ.");
226 return -END_CIRC_REASON_TORPROTOCOL
;
229 log_debug(LD_OR
,"Passing on unrecognized cell.");
231 ++stats_n_relay_cells_relayed
; /* XXXX no longer quite accurate {cells}
232 * we might kill the circ before we relay
235 append_cell_to_circuit_queue(circ
, or_conn
, cell
, cell_direction
);
239 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
240 * <b>circ</b> in direction <b>cell_direction</b>.
242 * If cell_direction == CELL_DIRECTION_IN:
243 * - If we're at the origin (we're the OP), for hops 1..N,
244 * decrypt cell. If recognized, stop.
245 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
247 * If cell_direction == CELL_DIRECTION_OUT:
248 * - decrypt one hop. Check if recognized.
250 * If cell is recognized, set *recognized to 1, and set
251 * *layer_hint to the hop that recognized it.
253 * Return -1 to indicate that we should mark the circuit for close,
257 relay_crypt(circuit_t
*circ
, cell_t
*cell
, int cell_direction
,
258 crypt_path_t
**layer_hint
, char *recognized
)
264 tor_assert(recognized
);
265 tor_assert(cell_direction
== CELL_DIRECTION_IN
||
266 cell_direction
== CELL_DIRECTION_OUT
);
268 if (cell_direction
== CELL_DIRECTION_IN
) {
269 if (CIRCUIT_IS_ORIGIN(circ
)) { /* We're at the beginning of the circuit.
270 * We'll want to do layered decrypts. */
271 crypt_path_t
*thishop
, *cpath
= TO_ORIGIN_CIRCUIT(circ
)->cpath
;
273 if (thishop
->state
!= CPATH_STATE_OPEN
) {
274 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
275 "Relay cell before first created cell? Closing.");
278 do { /* Remember: cpath is in forward order, that is, first hop first. */
281 if (relay_crypt_one_payload(thishop
->b_crypto
, cell
->payload
, 0) < 0)
284 relay_header_unpack(&rh
, cell
->payload
);
285 if (rh
.recognized
== 0) {
286 /* it's possibly recognized. have to check digest to be sure. */
287 if (relay_digest_matches(thishop
->b_digest
, cell
)) {
289 *layer_hint
= thishop
;
294 thishop
= thishop
->next
;
295 } while (thishop
!= cpath
&& thishop
->state
== CPATH_STATE_OPEN
);
296 log_fn(LOG_PROTOCOL_WARN
, LD_OR
,
297 "Incoming cell at client not recognized. Closing.");
299 } else { /* we're in the middle. Just one crypt. */
300 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ
)->p_crypto
,
301 cell
->payload
, 1) < 0)
303 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
306 } else /* cell_direction == CELL_DIRECTION_OUT */ {
307 /* we're in the middle. Just one crypt. */
309 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ
)->n_crypto
,
310 cell
->payload
, 0) < 0)
313 relay_header_unpack(&rh
, cell
->payload
);
314 if (rh
.recognized
== 0) {
315 /* it's possibly recognized. have to check digest to be sure. */
316 if (relay_digest_matches(TO_OR_CIRCUIT(circ
)->n_digest
, cell
)) {
325 /** Package a relay cell from an edge:
326 * - Encrypt it to the right layer
327 * - Append it to the appropriate cell_queue on <b>circ</b>.
330 circuit_package_relay_cell(cell_t
*cell
, circuit_t
*circ
,
332 crypt_path_t
*layer_hint
)
334 or_connection_t
*conn
; /* where to send the cell */
336 if (cell_direction
== CELL_DIRECTION_OUT
) {
337 crypt_path_t
*thishop
; /* counter for repeated crypts */
339 if (!CIRCUIT_IS_ORIGIN(circ
) || !conn
) {
340 log_warn(LD_BUG
,"outgoing relay cell has n_conn==NULL. Dropping.");
341 return 0; /* just drop it */
343 relay_set_digest(layer_hint
->f_digest
, cell
);
345 thishop
= layer_hint
;
346 /* moving from farthest to nearest hop */
349 /* XXXX RD This is a bug, right? */
350 log_debug(LD_OR
,"crypting a layer of the relay cell.");
351 if (relay_crypt_one_payload(thishop
->f_crypto
, cell
->payload
, 1) < 0) {
355 thishop
= thishop
->prev
;
356 } while (thishop
!= TO_ORIGIN_CIRCUIT(circ
)->cpath
->prev
);
358 } else { /* incoming cell */
359 or_circuit_t
*or_circ
;
360 if (CIRCUIT_IS_ORIGIN(circ
)) {
361 /* XXXX RD This is a bug, right? */
362 log_warn(LD_BUG
,"incoming relay cell at origin circuit. Dropping.");
363 assert_circuit_ok(circ
);
364 return 0; /* just drop it */
366 or_circ
= TO_OR_CIRCUIT(circ
);
367 conn
= or_circ
->p_conn
;
368 relay_set_digest(or_circ
->p_digest
, cell
);
369 if (relay_crypt_one_payload(or_circ
->p_crypto
, cell
->payload
, 1) < 0)
372 ++stats_n_relay_cells_relayed
;
374 append_cell_to_circuit_queue(circ
, conn
, cell
, cell_direction
);
378 /** If cell's stream_id matches the stream_id of any conn that's
379 * attached to circ, return that conn, else return NULL.
381 static edge_connection_t
*
382 relay_lookup_conn(circuit_t
*circ
, cell_t
*cell
, int cell_direction
)
384 edge_connection_t
*tmpconn
;
387 relay_header_unpack(&rh
, cell
->payload
);
392 /* IN or OUT cells could have come from either direction, now
393 * that we allow rendezvous *to* an OP.
396 if (CIRCUIT_IS_ORIGIN(circ
)) {
397 for (tmpconn
= TO_ORIGIN_CIRCUIT(circ
)->p_streams
; tmpconn
;
398 tmpconn
=tmpconn
->next_stream
) {
399 if (rh
.stream_id
== tmpconn
->stream_id
&&
400 !tmpconn
->_base
.marked_for_close
) {
401 log_debug(LD_APP
,"found conn for stream %d.", rh
.stream_id
);
406 for (tmpconn
= TO_OR_CIRCUIT(circ
)->n_streams
; tmpconn
;
407 tmpconn
=tmpconn
->next_stream
) {
408 if (rh
.stream_id
== tmpconn
->stream_id
&&
409 !tmpconn
->_base
.marked_for_close
) {
410 log_debug(LD_EXIT
,"found conn for stream %d.", rh
.stream_id
);
411 if (cell_direction
== CELL_DIRECTION_OUT
||
412 connection_edge_is_rendezvous_stream(tmpconn
))
416 for (tmpconn
= TO_OR_CIRCUIT(circ
)->resolving_streams
; tmpconn
;
417 tmpconn
=tmpconn
->next_stream
) {
418 if (rh
.stream_id
== tmpconn
->stream_id
&&
419 !tmpconn
->_base
.marked_for_close
) {
420 log_debug(LD_EXIT
,"found conn for stream %d.", rh
.stream_id
);
425 return NULL
; /* probably a begin relay cell */
428 /** Pack the relay_header_t host-order structure <b>src</b> into
429 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
430 * about the wire format.
433 relay_header_pack(char *dest
, const relay_header_t
*src
)
435 *(uint8_t*)(dest
) = src
->command
;
437 set_uint16(dest
+1, htons(src
->recognized
));
438 set_uint16(dest
+3, htons(src
->stream_id
));
439 memcpy(dest
+5, src
->integrity
, 4);
440 set_uint16(dest
+9, htons(src
->length
));
443 /** Unpack the network-order buffer <b>src</b> into a host-order
444 * relay_header_t structure <b>dest</b>.
447 relay_header_unpack(relay_header_t
*dest
, const char *src
)
449 dest
->command
= *(uint8_t*)(src
);
451 dest
->recognized
= ntohs(get_uint16(src
+1));
452 dest
->stream_id
= ntohs(get_uint16(src
+3));
453 memcpy(dest
->integrity
, src
+5, 4);
454 dest
->length
= ntohs(get_uint16(src
+9));
457 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
458 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
459 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
460 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
461 * destination hop for OP->OR cells.
463 * If you can't send the cell, mark the circuit for close and return -1. Else
467 relay_send_command_from_edge(uint16_t stream_id
, circuit_t
*circ
,
468 int relay_command
, const char *payload
,
469 size_t payload_len
, crypt_path_t
*cpath_layer
)
474 /* XXXX NM Split this function into a separate versions per circuit type? */
478 memset(&cell
, 0, sizeof(cell_t
));
479 cell
.command
= CELL_RELAY
;
481 cell
.circ_id
= circ
->n_circ_id
;
482 cell_direction
= CELL_DIRECTION_OUT
;
483 } else if (! CIRCUIT_IS_ORIGIN(circ
)) {
484 cell
.circ_id
= TO_OR_CIRCUIT(circ
)->p_circ_id
;
485 cell_direction
= CELL_DIRECTION_IN
;
490 memset(&rh
, 0, sizeof(rh
));
491 rh
.command
= relay_command
;
492 rh
.stream_id
= stream_id
;
493 rh
.length
= payload_len
;
494 relay_header_pack(cell
.payload
, &rh
);
496 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
497 memcpy(cell
.payload
+RELAY_HEADER_SIZE
, payload
, payload_len
);
500 log_debug(LD_OR
,"delivering %d cell %s.", relay_command
,
501 cell_direction
== CELL_DIRECTION_OUT
? "forward" : "backward");
503 if (circuit_package_relay_cell(&cell
, circ
, cell_direction
, cpath_layer
)
505 log_warn(LD_BUG
,"circuit_package_relay_cell failed. Closing.");
506 circuit_mark_for_close(circ
, END_CIRC_REASON_INTERNAL
);
512 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
513 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
514 * that's sending the relay cell, or NULL if it's a control cell.
515 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
518 * If you can't send the cell, mark the circuit for close and
519 * return -1. Else return 0.
522 connection_edge_send_command(edge_connection_t
*fromconn
,
523 int relay_command
, const char *payload
,
526 /* XXXX NM Split this function into a separate versions per circuit type? */
527 crypt_path_t
*cpath_layer
;
529 tor_assert(fromconn
);
530 cpath_layer
= fromconn
? fromconn
->cpath_layer
: NULL
;
531 circ
= fromconn
->on_circuit
;
533 if (fromconn
->_base
.marked_for_close
) {
535 "called on conn that's already marked for close at %s:%d.",
536 fromconn
->_base
.marked_for_close_file
,
537 fromconn
->_base
.marked_for_close
);
542 if (fromconn
->_base
.type
== CONN_TYPE_AP
) {
543 log_info(LD_APP
,"no circ. Closing conn.");
544 connection_mark_unattached_ap(fromconn
, END_STREAM_REASON_INTERNAL
);
546 log_info(LD_EXIT
,"no circ. Closing conn.");
547 fromconn
->_base
.edge_has_sent_end
= 1; /* no circ to send to */
548 fromconn
->end_reason
= END_STREAM_REASON_INTERNAL
;
549 connection_mark_for_close(TO_CONN(fromconn
));
554 return relay_send_command_from_edge(fromconn
->stream_id
, circ
,
555 relay_command
, payload
,
556 payload_len
, fromconn
->cpath_layer
);
559 /** Translate <b>reason</b>, which came from a relay 'end' cell,
560 * into a static const string describing why the stream is closing.
561 * <b>reason</b> is -1 if no reason was provided.
564 connection_edge_end_reason_str(int reason
)
568 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
569 "End cell arrived with length 0. Should be at least 1.");
571 case END_STREAM_REASON_MISC
: return "misc error";
572 case END_STREAM_REASON_RESOLVEFAILED
: return "resolve failed";
573 case END_STREAM_REASON_CONNECTREFUSED
: return "connection refused";
574 case END_STREAM_REASON_EXITPOLICY
: return "exit policy failed";
575 case END_STREAM_REASON_DESTROY
: return "destroyed";
576 case END_STREAM_REASON_DONE
: return "closed normally";
577 case END_STREAM_REASON_TIMEOUT
: return "gave up (timeout)";
578 case END_STREAM_REASON_HIBERNATING
: return "server is hibernating";
579 case END_STREAM_REASON_INTERNAL
: return "internal error at server";
580 case END_STREAM_REASON_RESOURCELIMIT
: return "server out of resources";
581 case END_STREAM_REASON_CONNRESET
: return "connection reset";
582 case END_STREAM_REASON_TORPROTOCOL
: return "Tor protocol error";
583 case END_STREAM_REASON_NOTDIRECTORY
: return "not a directory";
585 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
586 "Reason for ending (%d) not recognized.",reason
);
591 /** Translate <b>reason</b> (as from a relay 'end' cell) into an
592 * appropriate SOCKS5 reply code.
595 socks5_reply_status_t
596 connection_edge_end_reason_socks5_response(int reason
)
598 switch (reason
& END_STREAM_REASON_MASK
) {
600 return SOCKS5_SUCCEEDED
;
601 case END_STREAM_REASON_MISC
:
602 return SOCKS5_GENERAL_ERROR
;
603 case END_STREAM_REASON_RESOLVEFAILED
:
604 return SOCKS5_HOST_UNREACHABLE
;
605 case END_STREAM_REASON_CONNECTREFUSED
:
606 return SOCKS5_CONNECTION_REFUSED
;
607 case END_STREAM_REASON_EXITPOLICY
:
608 return SOCKS5_NOT_ALLOWED
;
609 case END_STREAM_REASON_DESTROY
:
610 return SOCKS5_GENERAL_ERROR
;
611 case END_STREAM_REASON_DONE
:
612 return SOCKS5_SUCCEEDED
;
613 case END_STREAM_REASON_TIMEOUT
:
614 return SOCKS5_TTL_EXPIRED
;
615 case END_STREAM_REASON_RESOURCELIMIT
:
616 return SOCKS5_GENERAL_ERROR
;
617 case END_STREAM_REASON_HIBERNATING
:
618 return SOCKS5_GENERAL_ERROR
;
619 case END_STREAM_REASON_INTERNAL
:
620 return SOCKS5_GENERAL_ERROR
;
621 case END_STREAM_REASON_CONNRESET
:
622 return SOCKS5_CONNECTION_REFUSED
;
623 case END_STREAM_REASON_TORPROTOCOL
:
624 return SOCKS5_GENERAL_ERROR
;
626 case END_STREAM_REASON_CANT_ATTACH
:
627 return SOCKS5_GENERAL_ERROR
;
628 case END_STREAM_REASON_NET_UNREACHABLE
:
629 return SOCKS5_NET_UNREACHABLE
;
630 case END_STREAM_REASON_SOCKSPROTOCOL
:
631 return SOCKS5_GENERAL_ERROR
;
633 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
634 "Reason for ending (%d) not recognized; "
635 "sending generic socks error.", reason
);
636 return SOCKS5_GENERAL_ERROR
;
640 /* We need to use a few macros to deal with the fact that Windows
641 * decided that their sockets interface should be a permakludge.
642 * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
643 * version, and S_CASE is for errors where windows has only a WSAEFOO
644 * version. (The E is for 'error', the S is for 'socket'). */
646 #define E_CASE(s) case s: case WSA ## s
647 #define S_CASE(s) case WSA ## s
649 #define E_CASE(s) case s
650 #define S_CASE(s) case s
653 /** Given an errno from a failed exit connection, return a reason code
654 * appropriate for use in a RELAY END cell.
657 errno_to_end_reason(int e
)
661 return END_STREAM_REASON_DONE
;
667 S_CASE(EPROTONOSUPPORT
):
668 S_CASE(EAFNOSUPPORT
):
672 return END_STREAM_REASON_INTERNAL
;
673 S_CASE(ECONNREFUSED
):
674 return END_STREAM_REASON_CONNECTREFUSED
;
676 return END_STREAM_REASON_CONNRESET
;
678 return END_STREAM_REASON_TIMEOUT
;
683 return END_STREAM_REASON_RESOURCELIMIT
;
685 log_info(LD_EXIT
, "Didn't recognize errno %d (%s); telling the client "
686 "that we are ending a stream for 'misc' reason.",
687 e
, tor_socket_strerror(e
));
688 return END_STREAM_REASON_MISC
;
692 /** How many times will I retry a stream that fails due to DNS
693 * resolve failure or misc error?
695 #define MAX_RESOLVE_FAILURES 3
697 /** Return 1 if reason is something that you should retry if you
698 * get the end cell before you've connected; else return 0. */
700 edge_reason_is_retriable(int reason
)
702 return reason
== END_STREAM_REASON_HIBERNATING
||
703 reason
== END_STREAM_REASON_RESOURCELIMIT
||
704 reason
== END_STREAM_REASON_EXITPOLICY
||
705 reason
== END_STREAM_REASON_RESOLVEFAILED
||
706 reason
== END_STREAM_REASON_MISC
;
709 /** Called when we receive an END cell on a stream that isn't open yet.
710 * Arguments are as for connection_edge_process_relay_cell().
713 connection_edge_process_end_not_open(
714 relay_header_t
*rh
, cell_t
*cell
, origin_circuit_t
*circ
,
715 edge_connection_t
*conn
, crypt_path_t
*layer_hint
)
718 routerinfo_t
*exitrouter
;
719 int reason
= *(cell
->payload
+RELAY_HEADER_SIZE
);
720 int control_reason
= reason
| END_STREAM_REASON_FLAG_REMOTE
;
721 (void) layer_hint
; /* unused */
723 if (rh
->length
> 0 && edge_reason_is_retriable(reason
) &&
724 conn
->_base
.type
== CONN_TYPE_AP
) {
725 log_info(LD_APP
,"Address '%s' refused due to '%s'. Considering retrying.",
726 safe_str(conn
->socks_request
->address
),
727 connection_edge_end_reason_str(reason
));
729 router_get_by_digest(circ
->build_state
->chosen_exit
->identity_digest
);
731 case END_STREAM_REASON_EXITPOLICY
:
732 if (rh
->length
>= 5) {
733 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+1));
736 log_info(LD_APP
,"Address '%s' resolved to 0.0.0.0. Closing,",
737 safe_str(conn
->socks_request
->address
));
738 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
742 ttl
= (int)ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+5));
745 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
746 conn
->chosen_exit_name
, ttl
);
748 /* check if he *ought* to have allowed it */
751 (tor_inet_aton(conn
->socks_request
->address
, &in
) &&
752 !conn
->chosen_exit_name
))) {
754 "Exitrouter '%s' seems to be more restrictive than its exit "
755 "policy. Not using this router as exit for now.",
756 exitrouter
->nickname
);
757 addr_policy_free(exitrouter
->exit_policy
);
758 exitrouter
->exit_policy
=
759 router_parse_addr_policy_from_string("reject *:*", -1);
761 /* rewrite it to an IP if we learned one. */
762 if (addressmap_rewrite(conn
->socks_request
->address
,
763 sizeof(conn
->socks_request
->address
))) {
764 control_event_stream_status(conn
, STREAM_EVENT_REMAP
, 0);
766 if (conn
->_base
.chosen_exit_optional
) {
767 /* stop wanting a specific exit */
768 conn
->_base
.chosen_exit_optional
= 0;
769 tor_free(conn
->chosen_exit_name
); /* clears it */
771 if (connection_ap_detach_retriable(conn
, circ
, control_reason
) >= 0)
773 /* else, conn will get closed below */
775 case END_STREAM_REASON_CONNECTREFUSED
:
776 if (!conn
->_base
.chosen_exit_optional
)
777 break; /* break means it'll close, below */
778 /* Else fall through: expire this circuit, clear the
779 * chosen_exit_name field, and try again. */
780 case END_STREAM_REASON_RESOLVEFAILED
:
781 case END_STREAM_REASON_TIMEOUT
:
782 case END_STREAM_REASON_MISC
:
783 if (client_dns_incr_failures(conn
->socks_request
->address
)
784 < MAX_RESOLVE_FAILURES
) {
785 /* We haven't retried too many times; reattach the connection. */
786 circuit_log_path(LOG_INFO
,LD_APP
,circ
);
787 tor_assert(circ
->_base
.timestamp_dirty
);
788 circ
->_base
.timestamp_dirty
-= get_options()->MaxCircuitDirtiness
;
790 if (conn
->_base
.chosen_exit_optional
) {
791 /* stop wanting a specific exit */
792 conn
->_base
.chosen_exit_optional
= 0;
793 tor_free(conn
->chosen_exit_name
); /* clears it */
795 if (connection_ap_detach_retriable(conn
, circ
, control_reason
) >= 0)
797 /* else, conn will get closed below */
800 "Have tried resolving or connecting to address '%s' "
801 "at %d different places. Giving up.",
802 safe_str(conn
->socks_request
->address
),
803 MAX_RESOLVE_FAILURES
);
804 /* clear the failures, so it will have a full try next time */
805 client_dns_clear_failures(conn
->socks_request
->address
);
808 case END_STREAM_REASON_HIBERNATING
:
809 case END_STREAM_REASON_RESOURCELIMIT
:
811 addr_policy_free(exitrouter
->exit_policy
);
812 exitrouter
->exit_policy
=
813 router_parse_addr_policy_from_string("reject *:*", -1);
815 if (conn
->_base
.chosen_exit_optional
) {
816 /* stop wanting a specific exit */
817 conn
->_base
.chosen_exit_optional
= 0;
818 tor_free(conn
->chosen_exit_name
); /* clears it */
820 if (connection_ap_detach_retriable(conn
, circ
, control_reason
) >= 0)
822 /* else, will close below */
825 log_info(LD_APP
,"Giving up on retrying; conn can't be handled.");
829 "Edge got end (%s) before we're connected. Marking for close.",
830 connection_edge_end_reason_str(rh
->length
> 0 ? reason
: -1));
831 if (conn
->_base
.type
== CONN_TYPE_AP
) {
832 circuit_log_path(LOG_INFO
,LD_APP
,circ
);
833 connection_mark_unattached_ap(conn
, control_reason
);
835 /* we just got an 'end', don't need to send one */
836 conn
->_base
.edge_has_sent_end
= 1;
837 conn
->end_reason
= control_reason
;
838 connection_mark_for_close(TO_CONN(conn
));
843 /** Helper: change the socks_request->address field on conn to the
844 * dotted-quad representation of <b>new_addr</b> (given in host order),
845 * and send an appropriate REMAP event. */
847 remap_event_helper(edge_connection_t
*conn
, uint32_t new_addr
)
851 in
.s_addr
= htonl(new_addr
);
852 tor_inet_ntoa(&in
, conn
->socks_request
->address
,
853 sizeof(conn
->socks_request
->address
));
854 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
855 REMAP_STREAM_SOURCE_EXIT
);
858 /** An incoming relay cell has arrived from circuit <b>circ</b> to
859 * stream <b>conn</b>.
861 * The arguments here are the same as in
862 * connection_edge_process_relay_cell() below; this function is called
863 * from there when <b>conn</b> is defined and not in an open state.
866 connection_edge_process_relay_cell_not_open(
867 relay_header_t
*rh
, cell_t
*cell
, circuit_t
*circ
,
868 edge_connection_t
*conn
, crypt_path_t
*layer_hint
)
870 if (rh
->command
== RELAY_COMMAND_END
) {
871 if (CIRCUIT_IS_ORIGIN(circ
))
872 return connection_edge_process_end_not_open(rh
, cell
,
873 TO_ORIGIN_CIRCUIT(circ
), conn
,
879 if (conn
->_base
.type
== CONN_TYPE_AP
&&
880 rh
->command
== RELAY_COMMAND_CONNECTED
) {
881 tor_assert(CIRCUIT_IS_ORIGIN(circ
));
882 if (conn
->_base
.state
!= AP_CONN_STATE_CONNECT_WAIT
) {
883 log_fn(LOG_PROTOCOL_WARN
, LD_APP
,
884 "Got 'connected' while not in state connect_wait. Dropping.");
887 conn
->_base
.state
= AP_CONN_STATE_OPEN
;
888 log_info(LD_APP
,"'connected' received after %d seconds.",
889 (int)(time(NULL
) - conn
->_base
.timestamp_lastread
));
890 if (rh
->length
>= 4) {
891 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
895 "...but it claims the IP address was 0.0.0.0. Closing.");
896 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
);
897 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
901 ttl
= (int)ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+4));
904 client_dns_set_addressmap(conn
->socks_request
->address
, addr
,
905 conn
->chosen_exit_name
, ttl
);
907 remap_event_helper(conn
, addr
);
909 circuit_log_path(LOG_INFO
,LD_APP
,TO_ORIGIN_CIRCUIT(circ
));
910 /* don't send a socks reply to transparent conns */
911 if (!conn
->socks_request
->has_finished
)
912 connection_ap_handshake_socks_reply(conn
, NULL
, 0, 0);
913 /* handle anything that might have queued */
914 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
915 /* (We already sent an end cell if possible) */
916 connection_mark_for_close(TO_CONN(conn
));
921 if (conn
->_base
.type
== CONN_TYPE_AP
&&
922 rh
->command
== RELAY_COMMAND_RESOLVED
) {
926 if (conn
->_base
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
927 log_fn(LOG_PROTOCOL_WARN
, LD_APP
, "Got a 'resolved' cell while "
928 "not in state resolve_wait. Dropping.");
931 tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
));
932 answer_len
= cell
->payload
[RELAY_HEADER_SIZE
+1];
933 if (rh
->length
< 2 || answer_len
+2>rh
->length
) {
934 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
935 "Dropping malformed 'resolved' cell");
936 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
939 if (rh
->length
>= answer_len
+6)
940 ttl
= (int)ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+
945 answer_type
= cell
->payload
[RELAY_HEADER_SIZE
];
946 connection_ap_handshake_socks_resolved(conn
,
948 cell
->payload
[RELAY_HEADER_SIZE
+1], /*answer_len*/
949 cell
->payload
+RELAY_HEADER_SIZE
+2, /*answer*/
951 if (answer_type
== RESOLVED_TYPE_IPV4
) {
952 uint32_t addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+2));
953 remap_event_helper(conn
, addr
);
955 connection_mark_unattached_ap(conn
,
956 END_STREAM_REASON_DONE
|
957 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
961 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
962 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
963 rh
->command
, conn
->_base
.state
,
964 conn_state_to_string(conn
->_base
.type
, conn
->_base
.state
));
965 return 0; /* for forward compatibility, don't kill the circuit */
966 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
967 // connection_mark_for_close(conn);
971 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
972 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
973 * destined for <b>conn</b>.
975 * If <b>layer_hint</b> is defined, then we're the origin of the
976 * circuit, and it specifies the hop that packaged <b>cell</b>.
978 * Return -reason if you want to warn and tear down the circuit, else 0.
981 connection_edge_process_relay_cell(cell_t
*cell
, circuit_t
*circ
,
982 edge_connection_t
*conn
,
983 crypt_path_t
*layer_hint
)
985 static int num_seen
=0;
987 unsigned domain
= layer_hint
?LD_APP
:LD_EXIT
;
993 relay_header_unpack(&rh
, cell
->payload
);
994 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
996 log_debug(domain
, "Now seen %d relay cells here.", num_seen
);
998 if (rh
.length
> RELAY_PAYLOAD_SIZE
) {
999 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
1000 "Relay cell length field too long. Closing circuit.");
1001 return - END_CIRC_REASON_TORPROTOCOL
;
1004 /* either conn is NULL, in which case we've got a control cell, or else
1005 * conn points to the recognized stream. */
1007 if (conn
&& !connection_state_is_open(TO_CONN(conn
)))
1008 return connection_edge_process_relay_cell_not_open(
1009 &rh
, cell
, circ
, conn
, layer_hint
);
1011 switch (rh
.command
) {
1012 case RELAY_COMMAND_DROP
:
1013 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1015 case RELAY_COMMAND_BEGIN
:
1016 case RELAY_COMMAND_BEGIN_DIR
:
1018 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
1019 log_fn(LOG_PROTOCOL_WARN
, LD_APP
,
1020 "Relay begin request unsupported at AP. Dropping.");
1024 log_fn(LOG_PROTOCOL_WARN
, domain
,
1025 "Begin cell for known stream. Dropping.");
1028 return connection_exit_begin_conn(cell
, circ
);
1029 case RELAY_COMMAND_DATA
:
1030 ++stats_n_data_cells_received
;
1031 if (( layer_hint
&& --layer_hint
->deliver_window
< 0) ||
1032 (!layer_hint
&& --circ
->deliver_window
< 0)) {
1033 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
1034 "(relay data) circ deliver_window below 0. Killing.");
1035 connection_edge_end(conn
, END_STREAM_REASON_TORPROTOCOL
);
1036 connection_mark_for_close(TO_CONN(conn
));
1037 return -END_CIRC_REASON_TORPROTOCOL
;
1039 log_debug(domain
,"circ deliver_window now %d.", layer_hint
?
1040 layer_hint
->deliver_window
: circ
->deliver_window
);
1042 circuit_consider_sending_sendme(circ
, layer_hint
);
1045 log_info(domain
,"data cell dropped, unknown stream.");
1049 if (--conn
->deliver_window
< 0) { /* is it below 0 after decrement? */
1050 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
1051 "(relay data) conn deliver_window below 0. Killing.");
1052 return -END_CIRC_REASON_TORPROTOCOL
;
1055 stats_n_data_bytes_received
+= rh
.length
;
1056 connection_write_to_buf(cell
->payload
+ RELAY_HEADER_SIZE
,
1057 rh
.length
, TO_CONN(conn
));
1058 connection_edge_consider_sending_sendme(conn
);
1060 case RELAY_COMMAND_END
:
1061 reason
= rh
.length
> 0 ?
1062 *(uint8_t *)(cell
->payload
+RELAY_HEADER_SIZE
) : END_STREAM_REASON_MISC
;
1064 log_info(domain
,"end cell (%s) dropped, unknown stream.",
1065 connection_edge_end_reason_str(reason
));
1068 /* XXX add to this log_fn the exit node's nickname? */
1069 log_info(domain
,"%d: end cell (%s) for stream %d. Removing stream.",
1071 connection_edge_end_reason_str(reason
),
1073 if (conn
->socks_request
&& !conn
->socks_request
->has_finished
)
1075 "open stream hasn't sent socks answer yet? Closing.");
1076 /* We just *got* an end; no reason to send one. */
1077 conn
->_base
.edge_has_sent_end
= 1;
1078 if (!conn
->end_reason
)
1079 conn
->end_reason
= reason
| END_STREAM_REASON_FLAG_REMOTE
;
1080 if (!conn
->_base
.marked_for_close
) {
1081 /* only mark it if not already marked. it's possible to
1082 * get the 'end' right around when the client hangs up on us. */
1083 connection_mark_for_close(TO_CONN(conn
));
1084 conn
->_base
.hold_open_until_flushed
= 1;
1087 case RELAY_COMMAND_EXTEND
:
1089 log_fn(LOG_PROTOCOL_WARN
, domain
,
1090 "'extend' cell received for non-zero stream. Dropping.");
1093 return circuit_extend(cell
, circ
);
1094 case RELAY_COMMAND_EXTENDED
:
1096 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
1097 "'extended' unsupported at non-origin. Dropping.");
1100 log_debug(domain
,"Got an extended cell! Yay.");
1101 if ((reason
= circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ
),
1103 cell
->payload
+RELAY_HEADER_SIZE
)) < 0) {
1104 log_warn(domain
,"circuit_finish_handshake failed.");
1107 if ((reason
=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
)))<0) {
1108 log_info(domain
,"circuit_send_next_onion_skin() failed.");
1112 case RELAY_COMMAND_TRUNCATE
:
1114 log_fn(LOG_PROTOCOL_WARN
, LD_APP
,
1115 "'truncate' unsupported at origin. Dropping.");
1119 uint8_t reason
= *(uint8_t*)(cell
->payload
+ RELAY_HEADER_SIZE
);
1120 connection_or_send_destroy(circ
->n_circ_id
, circ
->n_conn
, reason
);
1121 circuit_set_n_circid_orconn(circ
, 0, NULL
);
1123 log_debug(LD_EXIT
, "Processed 'truncate', replying.");
1126 payload
[0] = (char)END_CIRC_REASON_REQUESTED
;
1127 relay_send_command_from_edge(0, circ
, RELAY_COMMAND_TRUNCATED
,
1128 payload
, sizeof(payload
), NULL
);
1131 case RELAY_COMMAND_TRUNCATED
:
1133 log_fn(LOG_PROTOCOL_WARN
, LD_EXIT
,
1134 "'truncated' unsupported at non-origin. Dropping.");
1137 circuit_truncated(TO_ORIGIN_CIRCUIT(circ
), layer_hint
);
1139 case RELAY_COMMAND_CONNECTED
:
1141 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
1142 "'connected' unsupported while open. Closing circ.");
1143 return -END_CIRC_REASON_TORPROTOCOL
;
1146 "'connected' received, no conn attached anymore. Ignoring.");
1148 case RELAY_COMMAND_SENDME
:
1151 layer_hint
->package_window
+= CIRCWINDOW_INCREMENT
;
1152 log_debug(LD_APP
,"circ-level sendme at origin, packagewindow %d.",
1153 layer_hint
->package_window
);
1154 circuit_resume_edge_reading(circ
, layer_hint
);
1156 circ
->package_window
+= CIRCWINDOW_INCREMENT
;
1158 "circ-level sendme at non-origin, packagewindow %d.",
1159 circ
->package_window
);
1160 circuit_resume_edge_reading(circ
, layer_hint
);
1164 conn
->package_window
+= STREAMWINDOW_INCREMENT
;
1165 log_debug(domain
,"stream-level sendme, packagewindow now %d.",
1166 conn
->package_window
);
1167 connection_start_reading(TO_CONN(conn
));
1168 /* handle whatever might still be on the inbuf */
1169 if (connection_edge_package_raw_inbuf(conn
, 1) < 0) {
1170 /* (We already sent an end cell if possible) */
1171 connection_mark_for_close(TO_CONN(conn
));
1175 case RELAY_COMMAND_RESOLVE
:
1177 log_fn(LOG_PROTOCOL_WARN
, LD_APP
,
1178 "resolve request unsupported at AP; dropping.");
1181 log_fn(LOG_PROTOCOL_WARN
, domain
,
1182 "resolve request for known stream; dropping.");
1184 } else if (circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
1185 log_fn(LOG_PROTOCOL_WARN
, domain
,
1186 "resolve request on circ with purpose %d; dropping",
1190 connection_exit_begin_resolve(cell
, TO_OR_CIRCUIT(circ
));
1192 case RELAY_COMMAND_RESOLVED
:
1194 log_fn(LOG_PROTOCOL_WARN
, domain
,
1195 "'resolved' unsupported while open. Closing circ.");
1196 return -END_CIRC_REASON_TORPROTOCOL
;
1199 "'resolved' received, no conn attached anymore. Ignoring.");
1201 case RELAY_COMMAND_ESTABLISH_INTRO
:
1202 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS
:
1203 case RELAY_COMMAND_INTRODUCE1
:
1204 case RELAY_COMMAND_INTRODUCE2
:
1205 case RELAY_COMMAND_INTRODUCE_ACK
:
1206 case RELAY_COMMAND_RENDEZVOUS1
:
1207 case RELAY_COMMAND_RENDEZVOUS2
:
1208 case RELAY_COMMAND_INTRO_ESTABLISHED
:
1209 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED
:
1210 rend_process_relay_cell(circ
, rh
.command
, rh
.length
,
1211 cell
->payload
+RELAY_HEADER_SIZE
);
1214 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
1215 "Received unknown relay command %d. Perhaps the other side is using "
1216 "a newer version of Tor? Dropping.",
1218 return 0; /* for forward compatibility, don't kill the circuit */
1221 uint64_t stats_n_data_cells_packaged
= 0;
1222 uint64_t stats_n_data_bytes_packaged
= 0;
1223 uint64_t stats_n_data_cells_received
= 0;
1224 uint64_t stats_n_data_bytes_received
= 0;
1226 /** While conn->inbuf has an entire relay payload of bytes on it,
1227 * and the appropriate package windows aren't empty, grab a cell
1228 * and send it down the circuit.
1230 * Return -1 (and send a RELAY_END cell if necessary) if conn should
1231 * be marked for close, else return 0.
1234 connection_edge_package_raw_inbuf(edge_connection_t
*conn
, int package_partial
)
1236 size_t amount_to_process
, length
;
1237 char payload
[CELL_PAYLOAD_SIZE
];
1239 unsigned domain
= conn
->cpath_layer
? LD_APP
: LD_EXIT
;
1243 if (conn
->_base
.marked_for_close
) {
1245 "called on conn that's already marked for close at %s:%d.",
1246 conn
->_base
.marked_for_close_file
, conn
->_base
.marked_for_close
);
1250 repeat_connection_edge_package_raw_inbuf
:
1252 circ
= circuit_get_by_edge_conn(conn
);
1254 log_info(domain
,"conn has no circuit! Closing.");
1255 conn
->end_reason
= END_STREAM_REASON_CANT_ATTACH
;
1259 if (circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
))
1262 if (conn
->package_window
<= 0) {
1263 log_info(domain
,"called with package_window %d. Skipping.",
1264 conn
->package_window
);
1265 connection_stop_reading(TO_CONN(conn
));
1269 amount_to_process
= buf_datalen(conn
->_base
.inbuf
);
1271 if (!amount_to_process
)
1274 if (!package_partial
&& amount_to_process
< RELAY_PAYLOAD_SIZE
)
1277 if (amount_to_process
> RELAY_PAYLOAD_SIZE
) {
1278 length
= RELAY_PAYLOAD_SIZE
;
1280 length
= amount_to_process
;
1282 stats_n_data_bytes_packaged
+= length
;
1283 stats_n_data_cells_packaged
+= 1;
1285 connection_fetch_from_buf(payload
, length
, TO_CONN(conn
));
1287 log_debug(domain
,"(%d) Packaging %d bytes (%d waiting).", conn
->_base
.s
,
1288 (int)length
, (int)buf_datalen(conn
->_base
.inbuf
));
1290 if (connection_edge_send_command(conn
, RELAY_COMMAND_DATA
,
1291 payload
, length
) < 0 )
1292 /* circuit got marked for close, don't continue, don't need to mark conn */
1295 if (!conn
->cpath_layer
) { /* non-rendezvous exit */
1296 tor_assert(circ
->package_window
> 0);
1297 circ
->package_window
--;
1298 } else { /* we're an AP, or an exit on a rendezvous circ */
1299 tor_assert(conn
->cpath_layer
->package_window
> 0);
1300 conn
->cpath_layer
->package_window
--;
1303 if (--conn
->package_window
<= 0) { /* is it 0 after decrement? */
1304 connection_stop_reading(TO_CONN(conn
));
1305 log_debug(domain
,"conn->package_window reached 0.");
1306 circuit_consider_stop_edge_reading(circ
, conn
->cpath_layer
);
1307 return 0; /* don't process the inbuf any more */
1309 log_debug(domain
,"conn->package_window is now %d",conn
->package_window
);
1311 /* handle more if there's more, or return 0 if there isn't */
1312 goto repeat_connection_edge_package_raw_inbuf
;
1315 /** Called when we've just received a relay data cell, or when
1316 * we've just finished flushing all bytes to stream <b>conn</b>.
1318 * If conn->outbuf is not too full, and our deliver window is
1319 * low, send back a suitable number of stream-level sendme cells.
1322 connection_edge_consider_sending_sendme(edge_connection_t
*conn
)
1326 if (connection_outbuf_too_full(TO_CONN(conn
)))
1329 circ
= circuit_get_by_edge_conn(conn
);
1331 /* this can legitimately happen if the destroy has already
1332 * arrived and torn down the circuit */
1333 log_info(LD_APP
,"No circuit associated with conn. Skipping.");
1337 while (conn
->deliver_window
< STREAMWINDOW_START
- STREAMWINDOW_INCREMENT
) {
1338 log_debug(conn
->cpath_layer
?LD_APP
:LD_EXIT
,
1339 "Outbuf %d, Queueing stream sendme.",
1340 (int)conn
->_base
.outbuf_flushlen
);
1341 conn
->deliver_window
+= STREAMWINDOW_INCREMENT
;
1342 if (connection_edge_send_command(conn
, RELAY_COMMAND_SENDME
,
1344 log_warn(LD_APP
,"connection_edge_send_command failed. Returning.");
1345 return; /* the circuit's closed, don't continue */
1350 /** The circuit <b>circ</b> has received a circuit-level sendme
1351 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1352 * attached streams and let them resume reading and packaging, if
1353 * their stream windows allow it.
1356 circuit_resume_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1359 log_debug(layer_hint
?LD_APP
:LD_EXIT
,"resuming");
1361 if (CIRCUIT_IS_ORIGIN(circ
))
1362 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ
)->p_streams
,
1365 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ
)->n_streams
,
1369 /** A helper function for circuit_resume_edge_reading() above.
1370 * The arguments are the same, except that <b>conn</b> is the head
1371 * of a linked list of edge streams that should each be considered.
1374 circuit_resume_edge_reading_helper(edge_connection_t
*conn
,
1376 crypt_path_t
*layer_hint
)
1378 for ( ; conn
; conn
=conn
->next_stream
) {
1379 if (conn
->_base
.marked_for_close
)
1381 if ((!layer_hint
&& conn
->package_window
> 0) ||
1382 (layer_hint
&& conn
->package_window
> 0 &&
1383 conn
->cpath_layer
== layer_hint
)) {
1384 connection_start_reading(TO_CONN(conn
));
1385 /* handle whatever might still be on the inbuf */
1386 if (connection_edge_package_raw_inbuf(conn
, 1)<0) {
1387 /* (We already sent an end cell if possible) */
1388 connection_mark_for_close(TO_CONN(conn
));
1392 /* If the circuit won't accept any more data, return without looking
1393 * at any more of the streams. Any connections that should be stopped
1394 * have already been stopped by connection_edge_package_raw_inbuf. */
1395 if (circuit_consider_stop_edge_reading(circ
, layer_hint
))
1402 /** Check if the package window for <b>circ</b> is empty (at
1403 * hop <b>layer_hint</b> if it's defined).
1405 * If yes, tell edge streams to stop reading and return 1.
1409 circuit_consider_stop_edge_reading(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1411 edge_connection_t
*conn
= NULL
;
1412 unsigned domain
= layer_hint
? LD_APP
: LD_EXIT
;
1415 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
1416 log_debug(domain
,"considering circ->package_window %d",
1417 circ
->package_window
);
1418 if (circ
->package_window
<= 0) {
1419 log_debug(domain
,"yes, not-at-origin. stopped.");
1420 for (conn
= or_circ
->n_streams
; conn
; conn
=conn
->next_stream
)
1421 connection_stop_reading(TO_CONN(conn
));
1426 /* else, layer hint is defined, use it */
1427 log_debug(domain
,"considering layer_hint->package_window %d",
1428 layer_hint
->package_window
);
1429 if (layer_hint
->package_window
<= 0) {
1430 log_debug(domain
,"yes, at-origin. stopped.");
1431 for (conn
= TO_ORIGIN_CIRCUIT(circ
)->p_streams
; conn
;
1432 conn
=conn
->next_stream
)
1433 if (conn
->cpath_layer
== layer_hint
)
1434 connection_stop_reading(TO_CONN(conn
));
1440 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1441 * <b>layer_hint</b> if it's defined) is low enough that we should
1442 * send a circuit-level sendme back down the circuit. If so, send
1443 * enough sendmes that the window would be overfull if we sent any
1447 circuit_consider_sending_sendme(circuit_t
*circ
, crypt_path_t
*layer_hint
)
1449 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1450 // layer_hint ? "defined" : "null");
1451 while ((layer_hint
? layer_hint
->deliver_window
: circ
->deliver_window
) <
1452 CIRCWINDOW_START
- CIRCWINDOW_INCREMENT
) {
1453 log_debug(LD_CIRC
,"Queueing circuit sendme.");
1455 layer_hint
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1457 circ
->deliver_window
+= CIRCWINDOW_INCREMENT
;
1458 if (relay_send_command_from_edge(0, circ
, RELAY_COMMAND_SENDME
,
1459 NULL
, 0, layer_hint
) < 0) {
1461 "connection_edge_send_command failed. Circuit's closed.");
1462 return; /* the circuit's closed, don't continue */
1467 /** Stop reading on edge connections when we have this many cells
1468 * waiting on the appropriate queue. */
1469 #define CELL_QUEUE_HIGHWATER_SIZE 256
1470 /** Start reading from edge connections again when we get down to this many
1472 #define CELL_QUEUE_LOWWATER_SIZE 64
1474 #ifdef ACTIVE_CIRCUITS_PARANOIA
1475 #define assert_active_circuits_ok_paranoid(conn) \
1476 assert_active_circuits_ok(conn)
1478 #define assert_active_circuits_ok_paranoid(conn)
1481 #ifdef ENABLE_CELL_POOL
1482 static mp_pool_t
*cell_pool
= NULL
;
1483 /** Allocate structures to hold cells. */
1485 init_cell_pool(void)
1487 tor_assert(!cell_pool
);
1488 cell_pool
= mp_pool_new(sizeof(packed_cell_t
), 64);
1491 /** Free all storage used to hold cells. */
1493 free_cell_pool(void)
1495 tor_assert(cell_pool
);
1496 mp_pool_destroy(cell_pool
);
1500 /** Release storage held by <b>cell</b>. */
1502 packed_cell_free(packed_cell_t
*cell
)
1504 mp_pool_release(cell
);
1507 /** Allocate and return a new packed_cell_t. */
1508 static INLINE packed_cell_t
*
1509 packed_cell_alloc(void)
1511 return mp_pool_get(cell_pool
);
1514 /* ENABLE_CELL_POOL isn't defined: here are some stubs to use tor_malloc()
1515 * and tor_free() instead. */
1517 init_cell_pool(void)
1522 free_cell_pool(void)
1527 packed_cell_free(packed_cell_t
*cell
)
1532 static INLINE packed_cell_t
*
1533 packed_cell_alloc(void)
1535 return tor_malloc(sizeof(packed_cell_t
));
1539 /** Allocate a new copy of packed <b>cell</b>. */
1540 static INLINE packed_cell_t
*
1541 packed_cell_copy(const cell_t
*cell
)
1543 packed_cell_t
*c
= packed_cell_alloc();
1549 /** Append <b>cell</b> to the end of <b>queue</b>. */
1551 cell_queue_append(cell_queue_t
*queue
, packed_cell_t
*cell
)
1554 tor_assert(!queue
->tail
->next
);
1555 queue
->tail
->next
= cell
;
1564 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
1566 cell_queue_append_packed_copy(cell_queue_t
*queue
, const cell_t
*cell
)
1568 cell_queue_append(queue
, packed_cell_copy(cell
));
1571 /** Remove and free every cell in <b>queue</b>. */
1573 cell_queue_clear(cell_queue_t
*queue
)
1575 packed_cell_t
*cell
, *next
;
1579 packed_cell_free(cell
);
1582 queue
->head
= queue
->tail
= NULL
;
1586 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
1587 * <b>queue</b> is empty. */
1588 static INLINE packed_cell_t
*
1589 cell_queue_pop(cell_queue_t
*queue
)
1591 packed_cell_t
*cell
= queue
->head
;
1594 queue
->head
= cell
->next
;
1595 if (cell
== queue
->tail
) {
1596 tor_assert(!queue
->head
);
1603 /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
1604 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1605 static INLINE circuit_t
**
1606 next_circ_on_conn_p(circuit_t
*circ
, or_connection_t
*conn
)
1610 if (conn
== circ
->n_conn
) {
1611 return &circ
->next_active_on_n_conn
;
1613 or_circuit_t
*orcirc
= TO_OR_CIRCUIT(circ
);
1614 tor_assert(conn
== orcirc
->p_conn
);
1615 return &orcirc
->next_active_on_p_conn
;
1619 /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
1620 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1621 static INLINE circuit_t
**
1622 prev_circ_on_conn_p(circuit_t
*circ
, or_connection_t
*conn
)
1626 if (conn
== circ
->n_conn
) {
1627 return &circ
->prev_active_on_n_conn
;
1629 or_circuit_t
*orcirc
= TO_OR_CIRCUIT(circ
);
1630 tor_assert(conn
== orcirc
->p_conn
);
1631 return &orcirc
->prev_active_on_p_conn
;
1635 /** Add <b>circ</b> to the list of circuits with pending cells on
1636 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1638 make_circuit_active_on_conn(circuit_t
*circ
, or_connection_t
*conn
)
1640 circuit_t
**nextp
= next_circ_on_conn_p(circ
, conn
);
1641 circuit_t
**prevp
= prev_circ_on_conn_p(circ
, conn
);
1643 if (*nextp
&& *prevp
) {
1644 /* Already active. */
1648 if (! conn
->active_circuits
) {
1649 conn
->active_circuits
= circ
;
1650 *prevp
= *nextp
= circ
;
1652 circuit_t
*head
= conn
->active_circuits
;
1653 circuit_t
*old_tail
= *prev_circ_on_conn_p(head
, conn
);
1654 *next_circ_on_conn_p(old_tail
, conn
) = circ
;
1656 *prev_circ_on_conn_p(head
, conn
) = circ
;
1659 assert_active_circuits_ok_paranoid(conn
);
1662 /** Remove <b>circ</b> to the list of circuits with pending cells on
1663 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1665 make_circuit_inactive_on_conn(circuit_t
*circ
, or_connection_t
*conn
)
1667 circuit_t
**nextp
= next_circ_on_conn_p(circ
, conn
);
1668 circuit_t
**prevp
= prev_circ_on_conn_p(circ
, conn
);
1669 circuit_t
*next
= *nextp
, *prev
= *prevp
;
1671 if (!next
&& !prev
) {
1672 /* Already inactive. */
1676 tor_assert(next
&& prev
);
1677 tor_assert(*prev_circ_on_conn_p(next
, conn
) == circ
);
1678 tor_assert(*next_circ_on_conn_p(prev
, conn
) == circ
);
1681 conn
->active_circuits
= NULL
;
1683 *prev_circ_on_conn_p(next
, conn
) = prev
;
1684 *next_circ_on_conn_p(prev
, conn
) = next
;
1685 if (conn
->active_circuits
== circ
)
1686 conn
->active_circuits
= next
;
1688 *prevp
= *nextp
= NULL
;
1689 assert_active_circuits_ok_paranoid(conn
);
1692 /** Remove all circuits from the list of circuits with pending cells on
1695 connection_or_unlink_all_active_circs(or_connection_t
*orconn
)
1697 circuit_t
*head
= orconn
->active_circuits
;
1698 circuit_t
*cur
= head
;
1702 circuit_t
*next
= *next_circ_on_conn_p(cur
, orconn
);
1703 *prev_circ_on_conn_p(cur
, orconn
) = NULL
;
1704 *next_circ_on_conn_p(cur
, orconn
) = NULL
;
1706 } while (cur
!= head
);
1707 orconn
->active_circuits
= NULL
;
1710 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
1711 * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
1712 * and start or stop reading as appropriate. */
1714 set_streams_blocked_on_circ(circuit_t
*circ
, or_connection_t
*orconn
,
1717 edge_connection_t
*edge
= NULL
;
1718 if (circ
->n_conn
== orconn
) {
1719 circ
->streams_blocked_on_n_conn
= block
;
1720 if (CIRCUIT_IS_ORIGIN(circ
))
1721 edge
= TO_ORIGIN_CIRCUIT(circ
)->p_streams
;
1723 circ
->streams_blocked_on_p_conn
= block
;
1724 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1725 edge
= TO_OR_CIRCUIT(circ
)->n_streams
;
1728 for (; edge
; edge
= edge
->next_stream
) {
1729 connection_t
*conn
= TO_CONN(edge
);
1730 conn
->edge_blocked_on_circ
= block
;
1733 if (connection_is_reading(conn
))
1734 connection_stop_reading(conn
);
1736 /* Is this right? */
1737 if (!connection_is_reading(conn
))
1738 connection_start_reading(conn
);
1743 /** Pull as many cells as possible (but no more than <b>max</b>) from the
1744 * queue of the first active circuit on <b>conn</b>, and write then to
1745 * <b>conn</b>->outbuf. Return the number of cells written. Advance
1746 * the active circuit pointer to the next active circuit in the ring. */
1748 connection_or_flush_from_first_active_circuit(or_connection_t
*conn
, int max
)
1751 cell_queue_t
*queue
;
1753 int streams_blocked
;
1754 circ
= conn
->active_circuits
;
1755 if (!circ
) return 0;
1756 assert_active_circuits_ok_paranoid(conn
);
1757 if (circ
->n_conn
== conn
) {
1758 queue
= &circ
->n_conn_cells
;
1759 streams_blocked
= circ
->streams_blocked_on_n_conn
;
1761 queue
= &TO_OR_CIRCUIT(circ
)->p_conn_cells
;
1762 streams_blocked
= circ
->streams_blocked_on_p_conn
;
1764 tor_assert(*next_circ_on_conn_p(circ
,conn
));
1766 for (n_flushed
= 0; n_flushed
< max
&& queue
->head
; ++n_flushed
) {
1767 packed_cell_t
*cell
= cell_queue_pop(queue
);
1768 tor_assert(*next_circ_on_conn_p(circ
,conn
));
1770 connection_write_to_buf(cell
->body
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1772 packed_cell_free(cell
);
1774 if (circ
!= conn
->active_circuits
) {
1775 /* If this happens, the current circuit just got made inactive by
1776 * a call in connection_write_to_buf(). That's nothing to worry about:
1777 * circuit_make_inactive_on_conn() already advanced conn->active_circuits
1780 assert_active_circuits_ok_paranoid(conn
);
1784 tor_assert(*next_circ_on_conn_p(circ
,conn
));
1785 assert_active_circuits_ok_paranoid(conn
);
1786 conn
->active_circuits
= *next_circ_on_conn_p(circ
, conn
);
1788 /* Is the cell queue low enough to unblock all the streams that are waiting
1789 * to write to this circuit? */
1790 if (streams_blocked
&& queue
->n
<= CELL_QUEUE_LOWWATER_SIZE
)
1791 set_streams_blocked_on_circ(circ
, conn
, 0); /* unblock streams */
1793 /* Did we just ran out of cells on this queue? */
1794 if (queue
->n
== 0) {
1795 log_info(LD_GENERAL
, "Made a circuit inactive.");
1796 make_circuit_inactive_on_conn(circ
, conn
);
1801 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
1802 * transmitting in <b>direction</b>. */
1804 append_cell_to_circuit_queue(circuit_t
*circ
, or_connection_t
*orconn
,
1805 cell_t
*cell
, int direction
)
1807 cell_queue_t
*queue
;
1808 int streams_blocked
;
1809 if (direction
== CELL_DIRECTION_OUT
) {
1810 queue
= &circ
->n_conn_cells
;
1811 streams_blocked
= circ
->streams_blocked_on_n_conn
;
1813 or_circuit_t
*orcirc
= TO_OR_CIRCUIT(circ
);
1814 queue
= &orcirc
->p_conn_cells
;
1815 streams_blocked
= circ
->streams_blocked_on_p_conn
;
1818 cell_queue_append_packed_copy(queue
, cell
);
1820 /* If we have too many cells on the circuit, we should stop reading from
1821 * the edge streams for a while. */
1822 if (!streams_blocked
&& queue
->n
>= CELL_QUEUE_HIGHWATER_SIZE
)
1823 set_streams_blocked_on_circ(circ
, orconn
, 1); /* block streams */
1825 if (queue
->n
== 1) {
1826 /* This was the first cell added to the queue. We need to make this
1827 * circuit active. */
1828 log_info(LD_GENERAL
, "Made a circuit active.");
1829 make_circuit_active_on_conn(circ
, orconn
);
1832 if (! buf_datalen(orconn
->_base
.outbuf
)) {
1833 /* There is no data at all waiting to be sent on the outbuf. Add a
1834 * cell, so that we can notice when it gets flushed, flushed_some can
1835 * get called, and we can start putting more data onto the buffer then.
1837 log_info(LD_GENERAL
, "Primed a buffer.");
1838 connection_or_flush_from_first_active_circuit(orconn
, 1);
1842 /** Remove all the cells queued on <b>circ</b> for <b>orconn</b>. */
1844 circuit_clear_cell_queue(circuit_t
*circ
, or_connection_t
*orconn
)
1846 cell_queue_t
*queue
;
1847 int streams_blocked
;
1848 if (circ
->n_conn
== orconn
) {
1849 queue
= &circ
->n_conn_cells
;
1850 streams_blocked
= circ
->streams_blocked_on_n_conn
;
1852 or_circuit_t
*orcirc
= TO_OR_CIRCUIT(circ
);
1853 queue
= &orcirc
->p_conn_cells
;
1854 streams_blocked
= circ
->streams_blocked_on_p_conn
;
1858 make_circuit_inactive_on_conn(circ
,orconn
);
1860 cell_queue_clear(queue
);
1863 /** Fail with an assert if the active circuits ring on <b>orconn</b> is
1866 assert_active_circuits_ok(or_connection_t
*orconn
)
1868 circuit_t
*head
= orconn
->active_circuits
;
1869 circuit_t
*cur
= head
;
1873 circuit_t
*next
= *next_circ_on_conn_p(cur
, orconn
);
1874 circuit_t
*prev
= *prev_circ_on_conn_p(cur
, orconn
);
1877 tor_assert(*next_circ_on_conn_p(prev
, orconn
) == cur
);
1878 tor_assert(*prev_circ_on_conn_p(next
, orconn
) == cur
);
1880 } while (cur
!= head
);