Add some "to-be-safe" escaped() wrappers to log statements in rend*.c, though I am...
[tor.git] / src / or / relay.c
blob8dbe4acc12f66c78dee1092db56e6cd7ea715548
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char relay_c_id[] =
7 "$Id$";
9 /**
10 * \file relay.c
11 * \brief Handle relay cell encryption/decryption, plus packaging and
12 * receiving from circuits.
13 **/
15 #include "or.h"
17 static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
18 crypt_path_t **layer_hint, char *recognized);
19 static connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
20 int cell_direction);
22 static int
23 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
24 connection_t *conn,
25 crypt_path_t *layer_hint);
26 static void
27 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
28 static void
29 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
30 static int
31 circuit_resume_edge_reading_helper(connection_t *conn,
32 circuit_t *circ,
33 crypt_path_t *layer_hint);
34 static int
35 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
37 /** Stats: how many relay cells have originated at this hop, or have
38 * been relayed onward (not recognized at this hop)?
40 uint64_t stats_n_relay_cells_relayed = 0;
41 /** Stats: how many relay cells have been delivered to streams at this
42 * hop?
44 uint64_t stats_n_relay_cells_delivered = 0;
46 /** Update digest from the payload of cell. Assign integrity part to
47 * cell.
49 static void
50 relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
52 char integrity[4];
53 relay_header_t rh;
55 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
56 crypto_digest_get_digest(digest, integrity, 4);
57 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
58 // integrity[0], integrity[1], integrity[2], integrity[3]);
59 relay_header_unpack(&rh, cell->payload);
60 memcpy(rh.integrity, integrity, 4);
61 relay_header_pack(cell->payload, &rh);
64 /** Does the digest for this circuit indicate that this cell is for us?
66 * Update digest from the payload of cell (with the integrity part set
67 * to 0). If the integrity part is valid, return 1, else restore digest
68 * and cell to their original state and return 0.
70 static int
71 relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
73 char received_integrity[4], calculated_integrity[4];
74 relay_header_t rh;
75 crypto_digest_env_t *backup_digest=NULL;
77 backup_digest = crypto_digest_dup(digest);
79 relay_header_unpack(&rh, cell->payload);
80 memcpy(received_integrity, rh.integrity, 4);
81 memset(rh.integrity, 0, 4);
82 relay_header_pack(cell->payload, &rh);
84 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
85 // received_integrity[0], received_integrity[1],
86 // received_integrity[2], received_integrity[3]);
88 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
89 crypto_digest_get_digest(digest, calculated_integrity, 4);
91 if (memcmp(received_integrity, calculated_integrity, 4)) {
92 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
93 // (%d vs %d).", received_integrity, calculated_integrity);
94 /* restore digest to its old form */
95 crypto_digest_assign(digest, backup_digest);
96 /* restore the relay header */
97 memcpy(rh.integrity, received_integrity, 4);
98 relay_header_pack(cell->payload, &rh);
99 crypto_free_digest_env(backup_digest);
100 return 0;
102 crypto_free_digest_env(backup_digest);
103 return 1;
106 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
107 * (in place).
109 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
111 * Return -1 if the crypto fails, else return 0.
113 static int
114 relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
115 int encrypt_mode)
117 char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
118 int r;
120 if (encrypt_mode)
121 r = crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
122 else
123 r = crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
125 if (r) {
126 log_warn(LD_BUG,"Error during relay encryption");
127 return -1;
129 memcpy(in,out,CELL_PAYLOAD_SIZE);
130 return 0;
133 /** Receive a relay cell:
134 * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
135 * - Check if recognized (if exitward).
136 * - If recognized and the digest checks out, then find if there's
137 * a conn that the cell is intended for, and deliver it to
138 * connection_edge.
139 * - Else connection_or_write_cell_to_buf to the conn on the other
140 * side of the circuit.
142 * Return -reason on failure.
145 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ, int cell_direction)
147 connection_t *conn=NULL;
148 crypt_path_t *layer_hint=NULL;
149 char recognized=0;
150 int reason;
152 tor_assert(cell);
153 tor_assert(circ);
154 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
155 cell_direction == CELL_DIRECTION_IN);
156 if (circ->marked_for_close)
157 return 0;
159 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
160 log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
161 return -1;
164 if (recognized) {
165 conn = relay_lookup_conn(circ, cell, cell_direction);
166 if (cell_direction == CELL_DIRECTION_OUT) {
167 ++stats_n_relay_cells_delivered;
168 log_debug(LD_OR,"Sending away from origin.");
169 if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
170 < 0) {
171 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
172 "connection_edge_process_relay_cell (away from origin) "
173 "failed.");
174 return reason;
177 if (cell_direction == CELL_DIRECTION_IN) {
178 ++stats_n_relay_cells_delivered;
179 log_debug(LD_OR,"Sending to origin.");
180 if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
181 layer_hint)) < 0) {
182 log_warn(LD_OR,
183 "connection_edge_process_relay_cell (at origin) failed.");
184 return reason;
187 return 0;
190 /* not recognized. pass it on. */
191 if (cell_direction == CELL_DIRECTION_OUT) {
192 cell->circ_id = circ->n_circ_id; /* switch it */
193 conn = circ->n_conn;
194 } else {
195 cell->circ_id = circ->p_circ_id; /* switch it */
196 conn = circ->p_conn;
199 if (!conn) {
200 if (circ->rend_splice && cell_direction == CELL_DIRECTION_OUT) {
201 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
202 tor_assert(circ->rend_splice->purpose ==
203 CIRCUIT_PURPOSE_REND_ESTABLISHED);
204 cell->circ_id = circ->rend_splice->p_circ_id;
205 if ((reason = circuit_receive_relay_cell(cell, circ->rend_splice,
206 CELL_DIRECTION_IN)) < 0) {
207 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
208 "circuits");
209 /* XXXX Do this here, or just return -1? */
210 circuit_mark_for_close(circ, -reason);
211 return reason;
213 return 0;
215 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
216 "Didn't recognize cell, but circ stops here! Closing circ.");
217 return -END_CIRC_REASON_TORPROTOCOL;
220 log_debug(LD_OR,"Passing on unrecognized cell.");
221 ++stats_n_relay_cells_relayed;
222 connection_or_write_cell_to_buf(cell, conn);
223 return 0;
226 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
227 * <b>circ</b> in direction <b>cell_direction</b>.
229 * If cell_direction == CELL_DIRECTION_IN:
230 * - If we're at the origin (we're the OP), for hops 1..N,
231 * decrypt cell. If recognized, stop.
232 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
234 * If cell_direction == CELL_DIRECTION_OUT:
235 * - decrypt one hop. Check if recognized.
237 * If cell is recognized, set *recognized to 1, and set
238 * *layer_hint to the hop that recognized it.
240 * Return -1 to indicate that we should mark the circuit for close,
241 * else return 0.
243 /* wrap this into receive_relay_cell one day */
244 static int
245 relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
246 crypt_path_t **layer_hint, char *recognized)
248 crypt_path_t *thishop;
249 relay_header_t rh;
251 tor_assert(circ);
252 tor_assert(cell);
253 tor_assert(recognized);
254 tor_assert(cell_direction == CELL_DIRECTION_IN ||
255 cell_direction == CELL_DIRECTION_OUT);
257 if (cell_direction == CELL_DIRECTION_IN) {
258 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
259 * We'll want to do layered decrypts. */
260 tor_assert(circ->cpath);
261 thishop = circ->cpath;
262 if (thishop->state != CPATH_STATE_OPEN) {
263 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
264 "Relay cell before first created cell? Closing.");
265 return -1;
267 do { /* Remember: cpath is in forward order, that is, first hop first. */
268 tor_assert(thishop);
270 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
271 return -1;
273 relay_header_unpack(&rh, cell->payload);
274 if (rh.recognized == 0) {
275 /* it's possibly recognized. have to check digest to be sure. */
276 if (relay_digest_matches(thishop->b_digest, cell)) {
277 *recognized = 1;
278 *layer_hint = thishop;
279 return 0;
283 thishop = thishop->next;
284 } while (thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
285 log_warn(LD_OR,"in-cell at OP not recognized. Closing.");
286 return -1;
287 } else { /* we're in the middle. Just one crypt. */
288 if (relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
289 return -1;
290 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
291 // "the OP.");
293 } else /* cell_direction == CELL_DIRECTION_OUT */ {
294 /* we're in the middle. Just one crypt. */
296 if (relay_crypt_one_payload(circ->n_crypto, cell->payload, 0) < 0)
297 return -1;
299 relay_header_unpack(&rh, cell->payload);
300 if (rh.recognized == 0) {
301 /* it's possibly recognized. have to check digest to be sure. */
302 if (relay_digest_matches(circ->n_digest, cell)) {
303 *recognized = 1;
304 return 0;
308 return 0;
311 /** Package a relay cell:
312 * - Encrypt it to the right layer
313 * - connection_or_write_cell_to_buf to the right conn
315 static int
316 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
317 int cell_direction,
318 crypt_path_t *layer_hint)
320 connection_t *conn; /* where to send the cell */
321 crypt_path_t *thishop; /* counter for repeated crypts */
323 if (cell_direction == CELL_DIRECTION_OUT) {
324 conn = circ->n_conn;
325 if (!conn) {
326 log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
327 return 0; /* just drop it */
329 relay_set_digest(layer_hint->f_digest, cell);
331 thishop = layer_hint;
332 /* moving from farthest to nearest hop */
333 do {
334 tor_assert(thishop);
335 /* XXXX RD This is a bug, right? */
336 log_debug(LD_OR,"crypting a layer of the relay cell.");
337 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
338 return -1;
341 thishop = thishop->prev;
342 } while (thishop != circ->cpath->prev);
344 } else { /* incoming cell */
345 conn = circ->p_conn;
346 if (!conn) {
347 /* XXXX RD This is a bug, right? */
348 log_warn(LD_BUG,"incoming relay cell has p_conn==NULL. Dropping.");
349 assert_circuit_ok(circ);
350 return 0; /* just drop it */
352 relay_set_digest(circ->p_digest, cell);
353 if (relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
354 return -1;
356 ++stats_n_relay_cells_relayed;
357 connection_or_write_cell_to_buf(cell, conn);
358 return 0;
361 /** If cell's stream_id matches the stream_id of any conn that's
362 * attached to circ, return that conn, else return NULL.
364 static connection_t *
365 relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
367 connection_t *tmpconn;
368 relay_header_t rh;
370 relay_header_unpack(&rh, cell->payload);
372 if (!rh.stream_id)
373 return NULL;
375 /* IN or OUT cells could have come from either direction, now
376 * that we allow rendezvous *to* an OP.
379 for (tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
380 if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
381 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
382 if (cell_direction == CELL_DIRECTION_OUT ||
383 connection_edge_is_rendezvous_stream(tmpconn))
384 return tmpconn;
387 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
388 if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
389 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
390 return tmpconn;
393 for (tmpconn = circ->resolving_streams; tmpconn;
394 tmpconn=tmpconn->next_stream) {
395 if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
396 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
397 return tmpconn;
400 return NULL; /* probably a begin relay cell */
403 /** Pack the relay_header_t host-order structure <b>src</b> into
404 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
405 * about the wire format.
407 void
408 relay_header_pack(char *dest, const relay_header_t *src)
410 *(uint8_t*)(dest) = src->command;
412 set_uint16(dest+1, htons(src->recognized));
413 set_uint16(dest+3, htons(src->stream_id));
414 memcpy(dest+5, src->integrity, 4);
415 set_uint16(dest+9, htons(src->length));
418 /** Unpack the network-order buffer <b>src</b> into a host-order
419 * relay_header_t structure <b>dest</b>.
421 void
422 relay_header_unpack(relay_header_t *dest, const char *src)
424 dest->command = *(uint8_t*)(src);
426 dest->recognized = ntohs(get_uint16(src+1));
427 dest->stream_id = ntohs(get_uint16(src+3));
428 memcpy(dest->integrity, src+5, 4);
429 dest->length = ntohs(get_uint16(src+9));
432 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
433 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
434 * that's sending the relay cell, or NULL if it's a control cell.
435 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
436 * for OP->OR cells.
438 * If you can't send the cell, mark the circuit for close and
439 * return -1. Else return 0.
442 connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
443 int relay_command, const char *payload,
444 size_t payload_len, crypt_path_t *cpath_layer)
446 cell_t cell;
447 relay_header_t rh;
448 int cell_direction;
450 if (fromconn && fromconn->marked_for_close) {
451 log_warn(LD_BUG,
452 "Bug: called on conn that's already marked for close at %s:%d.",
453 fromconn->marked_for_close_file, fromconn->marked_for_close);
454 return 0;
457 if (!circ) {
458 tor_assert(fromconn);
459 if (fromconn->type == CONN_TYPE_AP) {
460 log_info(LD_APP,"no circ. Closing conn.");
461 connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
462 } else {
463 log_info(LD_EXIT,"no circ. Closing conn.");
464 fromconn->has_sent_end = 1; /* no circ to send to */
465 connection_mark_for_close(fromconn);
467 return -1;
470 memset(&cell, 0, sizeof(cell_t));
471 cell.command = CELL_RELAY;
472 if (cpath_layer) {
473 cell.circ_id = circ->n_circ_id;
474 cell_direction = CELL_DIRECTION_OUT;
475 } else {
476 cell.circ_id = circ->p_circ_id;
477 cell_direction = CELL_DIRECTION_IN;
480 memset(&rh, 0, sizeof(rh));
481 rh.command = relay_command;
482 if (fromconn)
483 rh.stream_id = fromconn->stream_id; /* else it's 0 */
484 rh.length = payload_len;
485 relay_header_pack(cell.payload, &rh);
486 if (payload_len) {
487 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
488 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
491 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
492 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
494 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
495 < 0) {
496 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
497 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
498 return -1;
500 return 0;
503 /** Translate <b>reason</b>, which came from a relay 'end' cell,
504 * into a static const string describing why the stream is closing.
505 * <b>reason</b> is -1 if no reason was provided.
507 static const char *
508 connection_edge_end_reason_str(int reason)
510 switch (reason) {
511 case -1:
512 log_warn(LD_PROTOCOL,
513 "End cell arrived with length 0. Should be at least 1.");
514 return "MALFORMED";
515 case END_STREAM_REASON_MISC: return "misc error";
516 case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
517 case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
518 case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
519 case END_STREAM_REASON_DESTROY: return "destroyed";
520 case END_STREAM_REASON_DONE: return "closed normally";
521 case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
522 case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
523 case END_STREAM_REASON_INTERNAL: return "internal error at server";
524 case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
525 case END_STREAM_REASON_CONNRESET: return "connection reset";
526 case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
527 default:
528 log_warn(LD_PROTOCOL,"Reason for ending (%d) not recognized.",reason);
529 return "unknown";
533 /** Translate <b>reason</b> (as from a relay 'end' cell) into an
534 * appropriate SOCKS5 reply code.
536 socks5_reply_status_t
537 connection_edge_end_reason_socks5_response(int reason)
539 switch (reason) {
540 case END_STREAM_REASON_MISC:
541 return SOCKS5_GENERAL_ERROR;
542 case END_STREAM_REASON_RESOLVEFAILED:
543 return SOCKS5_HOST_UNREACHABLE;
544 case END_STREAM_REASON_CONNECTREFUSED:
545 return SOCKS5_CONNECTION_REFUSED;
546 case END_STREAM_REASON_EXITPOLICY:
547 return SOCKS5_NOT_ALLOWED;
548 case END_STREAM_REASON_DESTROY:
549 return SOCKS5_GENERAL_ERROR;
550 case END_STREAM_REASON_DONE:
551 return SOCKS5_SUCCEEDED;
552 case END_STREAM_REASON_TIMEOUT:
553 return SOCKS5_TTL_EXPIRED;
554 case END_STREAM_REASON_RESOURCELIMIT:
555 return SOCKS5_GENERAL_ERROR;
556 case END_STREAM_REASON_HIBERNATING:
557 return SOCKS5_GENERAL_ERROR;
558 case END_STREAM_REASON_INTERNAL:
559 return SOCKS5_GENERAL_ERROR;
560 case END_STREAM_REASON_CONNRESET:
561 return SOCKS5_CONNECTION_REFUSED;
562 case END_STREAM_REASON_TORPROTOCOL:
563 return SOCKS5_GENERAL_ERROR;
565 case END_STREAM_REASON_ALREADY_SOCKS_REPLIED:
566 return SOCKS5_SUCCEEDED; /* never used */
567 case END_STREAM_REASON_CANT_ATTACH:
568 return SOCKS5_GENERAL_ERROR;
569 case END_STREAM_REASON_NET_UNREACHABLE:
570 return SOCKS5_NET_UNREACHABLE;
571 default:
572 log_warn(LD_PROTOCOL,"Reason for ending (%d) not recognized.",reason);
573 return SOCKS5_GENERAL_ERROR;
577 /* We need to use a few macros to deal with the fact that Windows
578 * decided that their sockets interface should be a permakludge.
579 * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
580 * version, and S_CASE is for errors where windows has only a WSAEFOO
581 * version. (The E is for 'error', the S is for 'socket'). */
582 #ifdef MS_WINDOWS
583 #define E_CASE(s) case s: case WSA ## s
584 #define S_CASE(s) case WSA ## s
585 #else
586 #define E_CASE(s) case s
587 #define S_CASE(s) case s
588 #endif
590 /** Given an errno from a failed exit connection, return a reason code
591 * appropriate for use in a RELAY END cell.
594 errno_to_end_reason(int e)
596 switch (e) {
597 case EPIPE:
598 return END_STREAM_REASON_DONE;
599 E_CASE(EBADF):
600 E_CASE(EFAULT):
601 E_CASE(EINVAL):
602 S_CASE(EISCONN):
603 S_CASE(ENOTSOCK):
604 S_CASE(EPROTONOSUPPORT):
605 S_CASE(EAFNOSUPPORT):
606 E_CASE(EACCES):
607 S_CASE(ENOTCONN):
608 S_CASE(ENETUNREACH):
609 return END_STREAM_REASON_INTERNAL;
610 S_CASE(ECONNREFUSED):
611 return END_STREAM_REASON_CONNECTREFUSED;
612 S_CASE(ECONNRESET):
613 return END_STREAM_REASON_CONNRESET;
614 S_CASE(ETIMEDOUT):
615 return END_STREAM_REASON_TIMEOUT;
616 S_CASE(ENOBUFS):
617 case ENOMEM:
618 case ENFILE:
619 E_CASE(EMFILE):
620 return END_STREAM_REASON_RESOURCELIMIT;
621 default:
622 log_info(LD_EXIT, "Didn't recognize errno %d (%s); telling the OP that "
623 "we are ending a stream for 'misc' reason.",
624 e, tor_socket_strerror(e));
625 return END_STREAM_REASON_MISC;
629 /** How many times will I retry a stream that fails due to DNS
630 * resolve failure or misc error?
632 #define MAX_RESOLVE_FAILURES 3
634 /** Return 1 if reason is something that you should retry if you
635 * get the end cell before you've connected; else return 0. */
636 static int
637 edge_reason_is_retriable(int reason)
639 return reason == END_STREAM_REASON_HIBERNATING ||
640 reason == END_STREAM_REASON_RESOURCELIMIT ||
641 reason == END_STREAM_REASON_EXITPOLICY ||
642 reason == END_STREAM_REASON_RESOLVEFAILED ||
643 reason == END_STREAM_REASON_MISC;
646 /** Called when we receive an END cell on a stream that isn't open yet.
647 * Arguments are as for connection_edge_process_relay_cell().
649 static int
650 connection_edge_process_end_not_open(
651 relay_header_t *rh, cell_t *cell, circuit_t *circ,
652 connection_t *conn, crypt_path_t *layer_hint)
654 struct in_addr in;
655 routerinfo_t *exitrouter;
656 int reason = *(cell->payload+RELAY_HEADER_SIZE);
658 if (rh->length > 0 && edge_reason_is_retriable(reason) &&
659 conn->type == CONN_TYPE_AP) {
660 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
661 safe_str(conn->socks_request->address),
662 connection_edge_end_reason_str(reason));
663 exitrouter =
664 router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
665 switch (reason) {
666 case END_STREAM_REASON_EXITPOLICY:
667 if (rh->length >= 5) {
668 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
669 int ttl;
670 if (!addr) {
671 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
672 safe_str(conn->socks_request->address));
673 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
674 return 0;
676 if (rh->length >= 9)
677 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
678 else
679 ttl = -1;
680 client_dns_set_addressmap(conn->socks_request->address, addr,
681 conn->chosen_exit_name, ttl);
683 /* check if he *ought* to have allowed it */
684 if (exitrouter &&
685 (rh->length < 5 ||
686 (tor_inet_aton(conn->socks_request->address, &in) &&
687 !conn->chosen_exit_name))) {
688 log_notice(LD_APP,
689 "Exitrouter '%s' seems to be more restrictive than its exit "
690 "policy. Not using this router as exit for now.",
691 exitrouter->nickname);
692 addr_policy_free(exitrouter->exit_policy);
693 exitrouter->exit_policy =
694 router_parse_addr_policy_from_string("reject *:*", -1);
696 /* rewrite it to an IP if we learned one. */
697 addressmap_rewrite(conn->socks_request->address,
698 sizeof(conn->socks_request->address));
699 if (connection_ap_detach_retriable(conn, circ) >= 0)
700 return 0;
701 /* else, conn will get closed below */
702 break;
703 case END_STREAM_REASON_RESOLVEFAILED:
704 case END_STREAM_REASON_MISC:
705 if (client_dns_incr_failures(conn->socks_request->address)
706 < MAX_RESOLVE_FAILURES) {
707 /* We haven't retried too many times; reattach the connection. */
708 circuit_log_path(LOG_INFO,LD_APP,circ);
709 tor_assert(circ->timestamp_dirty);
710 circ->timestamp_dirty -= get_options()->MaxCircuitDirtiness;
712 if (connection_ap_detach_retriable(conn, circ) >= 0)
713 return 0;
714 /* else, conn will get closed below */
715 } else {
716 log_notice(LD_APP,
717 "Have tried resolving or connecting to address '%s' "
718 "at %d different places. Giving up.",
719 safe_str(conn->socks_request->address),
720 MAX_RESOLVE_FAILURES);
721 /* clear the failures, so it will have a full try next time */
722 client_dns_clear_failures(conn->socks_request->address);
724 break;
725 case END_STREAM_REASON_HIBERNATING:
726 case END_STREAM_REASON_RESOURCELIMIT:
727 if (exitrouter) {
728 addr_policy_free(exitrouter->exit_policy);
729 exitrouter->exit_policy =
730 router_parse_addr_policy_from_string("reject *:*", -1);
732 if (connection_ap_detach_retriable(conn, circ) >= 0)
733 return 0;
734 /* else, will close below */
735 break;
736 } /* end switch */
737 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
740 log_info(LD_APP,
741 "Edge got end (%s) before we're connected. Marking for close.",
742 connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
743 if (conn->type == CONN_TYPE_AP) {
744 circuit_log_path(LOG_INFO,LD_APP,circ);
745 connection_mark_unattached_ap(conn, reason);
746 } else {
747 conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
748 connection_mark_for_close(conn);
750 return 0;
753 /** An incoming relay cell has arrived from circuit <b>circ</b> to
754 * stream <b>conn</b>.
756 * The arguments here are the same as in
757 * connection_edge_process_relay_cell() below; this function is called
758 * from there when <b>conn</b> is defined and not in an open state.
760 static int
761 connection_edge_process_relay_cell_not_open(
762 relay_header_t *rh, cell_t *cell, circuit_t *circ,
763 connection_t *conn, crypt_path_t *layer_hint)
765 if (rh->command == RELAY_COMMAND_END)
766 return connection_edge_process_end_not_open(rh, cell, circ, conn,
767 layer_hint);
769 if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
770 if (conn->state != AP_CONN_STATE_CONNECT_WAIT) {
771 log_warn(LD_APP,"Got 'connected' while not in state connect_wait. "
772 "Dropping.");
773 return 0;
775 // log_fn(LOG_INFO,"Connected! Notifying application.");
776 conn->state = AP_CONN_STATE_OPEN;
777 log_info(LD_APP,"'connected' received after %d seconds.",
778 (int)(time(NULL) - conn->timestamp_lastread));
779 if (rh->length >= 4) {
780 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
781 int ttl;
782 if (!addr) {
783 log_info(LD_APP,
784 "...but it claims the IP address was 0.0.0.0. Closing.");
785 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL,
786 conn->cpath_layer);
787 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
788 return 0;
790 if (rh->length >= 8)
791 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
792 else
793 ttl = -1;
794 client_dns_set_addressmap(conn->socks_request->address, addr,
795 conn->chosen_exit_name, ttl);
797 circuit_log_path(LOG_INFO,LD_APP,circ);
798 connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_SUCCEEDED);
799 /* handle anything that might have queued */
800 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
801 /* (We already sent an end cell if possible) */
802 connection_mark_for_close(conn);
803 return 0;
805 return 0;
807 if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_RESOLVED) {
808 int ttl;
809 int answer_len;
810 if (conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
811 log_warn(LD_APP,"Got a 'resolved' cell while not in state resolve_wait. "
812 "Dropping.");
813 return 0;
815 tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
816 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
817 if (rh->length < 2 || answer_len+2>rh->length) {
818 log_warn(LD_PROTOCOL, "Dropping malformed 'resolved' cell");
819 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
820 return 0;
822 if (rh->length >= answer_len+6)
823 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
824 2+answer_len));
825 else
826 ttl = -1;
827 connection_ap_handshake_socks_resolved(conn,
828 cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
829 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
830 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
831 ttl);
832 connection_mark_unattached_ap(conn,
833 END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
834 return 0;
837 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
838 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
839 rh->command, conn->state,
840 conn_state_to_string(conn->type, conn->state));
841 return 0; /* for forward compatibility, don't kill the circuit */
842 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL,
843 // conn->cpath_layer);
844 // connection_mark_for_close(conn);
845 // return -1;
848 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
849 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
850 * destined for <b>conn</b>.
852 * If <b>layer_hint</b> is defined, then we're the origin of the
853 * circuit, and it specifies the hop that packaged <b>cell</b>.
855 * Return -reason if you want to warn and tear down the circuit, else 0.
857 static int
858 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
859 connection_t *conn,
860 crypt_path_t *layer_hint)
862 static int num_seen=0;
863 relay_header_t rh;
864 unsigned domain = layer_hint?LD_APP:LD_EXIT;
865 int reason;
867 tor_assert(cell);
868 tor_assert(circ);
870 relay_header_unpack(&rh, cell->payload);
871 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
872 num_seen++;
873 log_debug(domain, "Now seen %d relay cells here.", num_seen);
875 if (rh.length > RELAY_PAYLOAD_SIZE) {
876 log_warn(LD_PROTOCOL,
877 "Relay cell length field too long. Closing circuit.");
878 return - END_CIRC_REASON_TORPROTOCOL;
881 /* either conn is NULL, in which case we've got a control cell, or else
882 * conn points to the recognized stream. */
884 if (conn && !connection_state_is_open(conn))
885 return connection_edge_process_relay_cell_not_open(
886 &rh, cell, circ, conn, layer_hint);
888 switch (rh.command) {
889 case RELAY_COMMAND_DROP:
890 log_info(domain,"Got a relay-level padding cell. Dropping.");
891 return 0;
892 case RELAY_COMMAND_BEGIN:
893 if (layer_hint &&
894 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
895 log_warn(LD_APP,"relay begin request unsupported at AP. Dropping.");
896 return 0;
898 if (conn) {
899 log_warn(domain,"begin cell for known stream. Dropping.");
900 return 0;
902 connection_exit_begin_conn(cell, circ);
903 return 0;
904 case RELAY_COMMAND_DATA:
905 ++stats_n_data_cells_received;
906 if (( layer_hint && --layer_hint->deliver_window < 0) ||
907 (!layer_hint && --circ->deliver_window < 0)) {
908 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
909 "(relay data) circ deliver_window below 0. Killing.");
910 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL,
911 conn->cpath_layer);
912 connection_mark_for_close(conn);
913 return -END_CIRC_REASON_TORPROTOCOL;
915 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
916 layer_hint->deliver_window : circ->deliver_window);
918 circuit_consider_sending_sendme(circ, layer_hint);
920 if (!conn) {
921 log_info(domain,"data cell dropped, unknown stream.");
922 return 0;
925 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
926 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
927 "(relay data) conn deliver_window below 0. Killing.");
928 return -END_CIRC_REASON_TORPROTOCOL;
931 stats_n_data_bytes_received += rh.length;
932 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
933 rh.length, conn);
934 connection_edge_consider_sending_sendme(conn);
935 return 0;
936 case RELAY_COMMAND_END:
937 if (!conn) {
938 log_info(domain,"end cell (%s) dropped, unknown stream.",
939 connection_edge_end_reason_str(rh.length > 0 ?
940 *(char *)(cell->payload+RELAY_HEADER_SIZE) : -1));
941 return 0;
943 /* XXX add to this log_fn the exit node's nickname? */
944 log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
945 conn->s,
946 connection_edge_end_reason_str(rh.length > 0 ?
947 *(char *)(cell->payload+RELAY_HEADER_SIZE) : -1),
948 conn->stream_id);
949 if (conn->socks_request && !conn->socks_request->has_finished)
950 log_warn(LD_BUG,
951 "Bug: open stream hasn't sent socks answer yet? Closing.");
952 #ifdef HALF_OPEN
953 conn->done_sending = 1;
954 shutdown(conn->s, 1); /* XXX check return; refactor NM */
955 if (conn->done_receiving) {
956 /* We just *got* an end; no reason to send one. */
957 conn->has_sent_end = 1;
958 connection_mark_for_close(conn);
959 conn->hold_open_until_flushed = 1;
961 #else
962 /* We just *got* an end; no reason to send one. */
963 conn->has_sent_end = 1;
964 if (!conn->marked_for_close) {
965 /* only mark it if not already marked. it's possible to
966 * get the 'end' right around when the client hangs up on us. */
967 connection_mark_for_close(conn);
968 conn->hold_open_until_flushed = 1;
970 #endif
971 return 0;
972 case RELAY_COMMAND_EXTEND:
973 if (conn) {
974 log_warn(domain,"'extend' for non-zero stream. Dropping.");
975 return 0;
977 return circuit_extend(cell, circ);
978 case RELAY_COMMAND_EXTENDED:
979 if (!layer_hint) {
980 log_warn(LD_PROTOCOL,
981 "'extended' unsupported at non-origin. Dropping.");
982 return 0;
984 log_debug(domain,"Got an extended cell! Yay.");
985 if ((reason = circuit_finish_handshake(circ, CELL_CREATED,
986 cell->payload+RELAY_HEADER_SIZE)) < 0) {
987 log_warn(domain,"circuit_finish_handshake failed.");
988 return reason;
990 if ((reason=circuit_send_next_onion_skin(circ))<0) {
991 log_info(domain,"circuit_send_next_onion_skin() failed.");
992 return reason;
994 return 0;
995 case RELAY_COMMAND_TRUNCATE:
996 if (layer_hint) {
997 log_warn(LD_APP,"'truncate' unsupported at origin. Dropping.");
998 return 0;
1000 if (circ->n_conn) {
1001 uint8_t reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
1002 connection_or_send_destroy(circ->n_circ_id, circ->n_conn, reason);
1003 circuit_set_circid_orconn(circ, 0, NULL, N_CONN_CHANGED);
1005 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1007 char payload[1];
1008 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1009 connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
1010 payload, sizeof(payload), NULL);
1012 return 0;
1013 case RELAY_COMMAND_TRUNCATED:
1014 if (!layer_hint) {
1015 log_warn(LD_EXIT,"'truncated' unsupported at non-origin. Dropping.");
1016 return 0;
1018 circuit_truncated(circ, layer_hint);
1019 return 0;
1020 case RELAY_COMMAND_CONNECTED:
1021 if (conn) {
1022 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1023 "'connected' unsupported while open. Closing circ.");
1024 return -END_CIRC_REASON_TORPROTOCOL;
1026 log_info(domain,
1027 "'connected' received, no conn attached anymore. Ignoring.");
1028 return 0;
1029 case RELAY_COMMAND_SENDME:
1030 if (!conn) {
1031 if (layer_hint) {
1032 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1033 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1034 layer_hint->package_window);
1035 circuit_resume_edge_reading(circ, layer_hint);
1036 } else {
1037 circ->package_window += CIRCWINDOW_INCREMENT;
1038 log_debug(LD_APP,
1039 "circ-level sendme at non-origin, packagewindow %d.",
1040 circ->package_window);
1041 circuit_resume_edge_reading(circ, layer_hint);
1043 return 0;
1045 conn->package_window += STREAMWINDOW_INCREMENT;
1046 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1047 conn->package_window);
1048 connection_start_reading(conn);
1049 /* handle whatever might still be on the inbuf */
1050 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
1051 /* (We already sent an end cell if possible) */
1052 connection_mark_for_close(conn);
1053 return 0;
1055 return 0;
1056 case RELAY_COMMAND_RESOLVE:
1057 if (layer_hint) {
1058 log_warn(LD_APP,"resolve request unsupported at AP; dropping.");
1059 return 0;
1060 } else if (conn) {
1061 log_warn(domain, "resolve request for known stream; dropping.");
1062 return 0;
1063 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1064 log_warn(domain, "resolve request on circ with purpose %d; dropping",
1065 circ->purpose);
1066 return 0;
1068 connection_exit_begin_resolve(cell, circ);
1069 return 0;
1070 case RELAY_COMMAND_RESOLVED:
1071 if (conn) {
1072 log_warn(domain,"'resolved' unsupported while open. Closing circ.");
1073 return -END_CIRC_REASON_TORPROTOCOL;
1075 log_info(domain,
1076 "'resolved' received, no conn attached anymore. Ignoring.");
1077 return 0;
1078 case RELAY_COMMAND_ESTABLISH_INTRO:
1079 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1080 case RELAY_COMMAND_INTRODUCE1:
1081 case RELAY_COMMAND_INTRODUCE2:
1082 case RELAY_COMMAND_INTRODUCE_ACK:
1083 case RELAY_COMMAND_RENDEZVOUS1:
1084 case RELAY_COMMAND_RENDEZVOUS2:
1085 case RELAY_COMMAND_INTRO_ESTABLISHED:
1086 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1087 rend_process_relay_cell(circ, rh.command, rh.length,
1088 cell->payload+RELAY_HEADER_SIZE);
1089 return 0;
1091 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1092 "Received unknown relay command %d. Perhaps the other side is using "
1093 "a newer version of Tor? Dropping.",
1094 rh.command);
1095 return 0; /* for forward compatibility, don't kill the circuit */
1098 uint64_t stats_n_data_cells_packaged = 0;
1099 uint64_t stats_n_data_bytes_packaged = 0;
1100 uint64_t stats_n_data_cells_received = 0;
1101 uint64_t stats_n_data_bytes_received = 0;
1103 /** While conn->inbuf has an entire relay payload of bytes on it,
1104 * and the appropriate package windows aren't empty, grab a cell
1105 * and send it down the circuit.
1107 * Return -1 (and send a RELAY_END cell if necessary) if conn should
1108 * be marked for close, else return 0.
1111 connection_edge_package_raw_inbuf(connection_t *conn, int package_partial)
1113 size_t amount_to_process, length;
1114 char payload[CELL_PAYLOAD_SIZE];
1115 circuit_t *circ;
1116 unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
1118 tor_assert(conn);
1119 tor_assert(!connection_speaks_cells(conn));
1120 if (conn->marked_for_close) {
1121 log_warn(LD_BUG,
1122 "Bug: called on conn that's already marked for close at %s:%d.",
1123 conn->marked_for_close_file, conn->marked_for_close);
1124 return 0;
1127 repeat_connection_edge_package_raw_inbuf:
1129 circ = circuit_get_by_edge_conn(conn);
1130 if (!circ) {
1131 log_info(domain,"conn has no circuit! Closing.");
1132 return -1;
1135 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
1136 return 0;
1138 if (conn->package_window <= 0) {
1139 log_info(domain,"called with package_window %d. Skipping.",
1140 conn->package_window);
1141 connection_stop_reading(conn);
1142 return 0;
1145 amount_to_process = buf_datalen(conn->inbuf);
1147 if (!amount_to_process)
1148 return 0;
1150 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
1151 return 0;
1153 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
1154 length = RELAY_PAYLOAD_SIZE;
1155 } else {
1156 length = amount_to_process;
1158 stats_n_data_bytes_packaged += length;
1159 stats_n_data_cells_packaged += 1;
1161 connection_fetch_from_buf(payload, length, conn);
1163 log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->s,
1164 (int)length, (int)buf_datalen(conn->inbuf));
1166 if (connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
1167 payload, length, conn->cpath_layer) < 0)
1168 /* circuit got marked for close, don't continue, don't need to mark conn */
1169 return 0;
1171 if (!conn->cpath_layer) { /* non-rendezvous exit */
1172 tor_assert(circ->package_window > 0);
1173 circ->package_window--;
1174 } else { /* we're an AP, or an exit on a rendezvous circ */
1175 tor_assert(conn->cpath_layer->package_window > 0);
1176 conn->cpath_layer->package_window--;
1179 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1180 connection_stop_reading(conn);
1181 log_debug(domain,"conn->package_window reached 0.");
1182 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
1183 return 0; /* don't process the inbuf any more */
1185 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1187 /* handle more if there's more, or return 0 if there isn't */
1188 goto repeat_connection_edge_package_raw_inbuf;
1191 /** Called when we've just received a relay data cell, or when
1192 * we've just finished flushing all bytes to stream <b>conn</b>.
1194 * If conn->outbuf is not too full, and our deliver window is
1195 * low, send back a suitable number of stream-level sendme cells.
1197 void
1198 connection_edge_consider_sending_sendme(connection_t *conn)
1200 circuit_t *circ;
1202 if (connection_outbuf_too_full(conn))
1203 return;
1205 circ = circuit_get_by_edge_conn(conn);
1206 if (!circ) {
1207 /* this can legitimately happen if the destroy has already
1208 * arrived and torn down the circuit */
1209 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1210 return;
1213 while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1214 log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
1215 "Outbuf %d, Queueing stream sendme.",
1216 (int)conn->outbuf_flushlen);
1217 conn->deliver_window += STREAMWINDOW_INCREMENT;
1218 if (connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
1219 NULL, 0, conn->cpath_layer) < 0) {
1220 log_warn(LD_APP,"connection_edge_send_command failed. Returning.");
1221 return; /* the circuit's closed, don't continue */
1226 /** The circuit <b>circ</b> has received a circuit-level sendme
1227 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1228 * attached streams and let them resume reading and packaging, if
1229 * their stream windows allow it.
1231 static void
1232 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1235 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1237 /* have to check both n_streams and p_streams, to handle rendezvous */
1238 if (circuit_resume_edge_reading_helper(circ->n_streams, circ, layer_hint)
1239 >= 0)
1240 circuit_resume_edge_reading_helper(circ->p_streams, circ, layer_hint);
1243 /** A helper function for circuit_resume_edge_reading() above.
1244 * The arguments are the same, except that <b>conn</b> is the head
1245 * of a linked list of edge streams that should each be considered.
1247 static int
1248 circuit_resume_edge_reading_helper(connection_t *conn,
1249 circuit_t *circ,
1250 crypt_path_t *layer_hint)
1252 for ( ; conn; conn=conn->next_stream) {
1253 if (conn->marked_for_close)
1254 continue;
1255 if ((!layer_hint && conn->package_window > 0) ||
1256 (layer_hint && conn->package_window > 0 &&
1257 conn->cpath_layer == layer_hint)) {
1258 connection_start_reading(conn);
1259 /* handle whatever might still be on the inbuf */
1260 if (connection_edge_package_raw_inbuf(conn, 1)<0) {
1261 /* (We already sent an end cell if possible) */
1262 connection_mark_for_close(conn);
1263 continue;
1266 /* If the circuit won't accept any more data, return without looking
1267 * at any more of the streams. Any connections that should be stopped
1268 * have already been stopped by connection_edge_package_raw_inbuf. */
1269 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1270 return -1;
1273 return 0;
1276 /** Check if the package window for <b>circ</b> is empty (at
1277 * hop <b>layer_hint</b> if it's defined).
1279 * If yes, tell edge streams to stop reading and return 1.
1280 * Else return 0.
1282 static int
1283 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1285 connection_t *conn = NULL;
1286 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1288 if (!layer_hint) {
1289 log_debug(domain,"considering circ->package_window %d",
1290 circ->package_window);
1291 if (circ->package_window <= 0) {
1292 log_debug(domain,"yes, not-at-origin. stopped.");
1293 for (conn = circ->n_streams; conn; conn=conn->next_stream)
1294 connection_stop_reading(conn);
1295 return 1;
1297 return 0;
1299 /* else, layer hint is defined, use it */
1300 log_debug(domain,"considering layer_hint->package_window %d",
1301 layer_hint->package_window);
1302 if (layer_hint->package_window <= 0) {
1303 log_debug(domain,"yes, at-origin. stopped.");
1304 for (conn = circ->n_streams; conn; conn=conn->next_stream)
1305 if (conn->cpath_layer == layer_hint)
1306 connection_stop_reading(conn);
1307 for (conn = circ->p_streams; conn; conn=conn->next_stream)
1308 if (conn->cpath_layer == layer_hint)
1309 connection_stop_reading(conn);
1310 return 1;
1312 return 0;
1315 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1316 * <b>layer_hint</b> if it's defined) is low enough that we should
1317 * send a circuit-level sendme back down the circuit. If so, send
1318 * enough sendmes that the window would be overfull if we sent any
1319 * more.
1321 static void
1322 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1324 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1325 // layer_hint ? "defined" : "null");
1326 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
1327 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1328 log_debug(LD_CIRC,"Queueing circuit sendme.");
1329 if (layer_hint)
1330 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1331 else
1332 circ->deliver_window += CIRCWINDOW_INCREMENT;
1333 if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
1334 NULL, 0, layer_hint) < 0) {
1335 log_warn(LD_CIRC,
1336 "connection_edge_send_command failed. Circuit's closed.");
1337 return; /* the circuit's closed, don't continue */