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