rearrange our assert so we don't possibly overflow rh.length before
[tor.git] / src / or / relay.c
blobdd999e9eb0699739db3c3e3b94a68549089dd2d2
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char relay_c_id[] =
8 "$Id$";
10 /**
11 * \file relay.c
12 * \brief Handle relay cell encryption/decryption, plus packaging and
13 * receiving from circuits, plus queueing on circuits.
14 **/
16 #include "or.h"
17 #include "mempool.h"
19 static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
20 crypt_path_t **layer_hint, char *recognized);
21 static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
22 int cell_direction,
23 crypt_path_t *layer_hint);
25 static int
26 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
27 edge_connection_t *conn,
28 crypt_path_t *layer_hint);
29 static void
30 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
31 static void
32 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
33 static int
34 circuit_resume_edge_reading_helper(edge_connection_t *conn,
35 circuit_t *circ,
36 crypt_path_t *layer_hint);
37 static int
38 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
40 /** Stats: how many relay cells have originated at this hop, or have
41 * been relayed onward (not recognized at this hop)?
43 uint64_t stats_n_relay_cells_relayed = 0;
44 /** Stats: how many relay cells have been delivered to streams at this
45 * hop?
47 uint64_t stats_n_relay_cells_delivered = 0;
49 /** Update digest from the payload of cell. Assign integrity part to
50 * cell.
52 static void
53 relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
55 char integrity[4];
56 relay_header_t rh;
58 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
59 crypto_digest_get_digest(digest, integrity, 4);
60 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
61 // integrity[0], integrity[1], integrity[2], integrity[3]);
62 relay_header_unpack(&rh, cell->payload);
63 memcpy(rh.integrity, integrity, 4);
64 relay_header_pack(cell->payload, &rh);
67 /** Does the digest for this circuit indicate that this cell is for us?
69 * Update digest from the payload of cell (with the integrity part set
70 * to 0). If the integrity part is valid, return 1, else restore digest
71 * and cell to their original state and return 0.
73 static int
74 relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
76 char received_integrity[4], calculated_integrity[4];
77 relay_header_t rh;
78 crypto_digest_env_t *backup_digest=NULL;
80 backup_digest = crypto_digest_dup(digest);
82 relay_header_unpack(&rh, cell->payload);
83 memcpy(received_integrity, rh.integrity, 4);
84 memset(rh.integrity, 0, 4);
85 relay_header_pack(cell->payload, &rh);
87 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
88 // received_integrity[0], received_integrity[1],
89 // received_integrity[2], received_integrity[3]);
91 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
92 crypto_digest_get_digest(digest, calculated_integrity, 4);
94 if (memcmp(received_integrity, calculated_integrity, 4)) {
95 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
96 // (%d vs %d).", received_integrity, calculated_integrity);
97 /* restore digest to its old form */
98 crypto_digest_assign(digest, backup_digest);
99 /* restore the relay header */
100 memcpy(rh.integrity, received_integrity, 4);
101 relay_header_pack(cell->payload, &rh);
102 crypto_free_digest_env(backup_digest);
103 return 0;
105 crypto_free_digest_env(backup_digest);
106 return 1;
109 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
110 * (in place).
112 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
114 * Return -1 if the crypto fails, else return 0.
116 static int
117 relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
118 int encrypt_mode)
120 int r;
121 (void)encrypt_mode;
122 r = crypto_cipher_crypt_inplace(cipher, in, CELL_PAYLOAD_SIZE);
124 if (r) {
125 log_warn(LD_BUG,"Error during relay encryption");
126 return -1;
128 return 0;
131 /** Receive a relay cell:
132 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
133 * origin; decrypt if we're headed toward the exit).
134 * - Check if recognized (if exitward).
135 * - If recognized and the digest checks out, then find if there's a stream
136 * that the cell is intended for, and deliver it to the right
137 * connection_edge.
138 * - If not recognized, then we need to relay it: append it to the appropriate
139 * cell_queue on <b>circ</b>.
141 * Return -<b>reason</b> on failure.
144 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ, int cell_direction)
146 or_connection_t *or_conn=NULL;
147 crypt_path_t *layer_hint=NULL;
148 char recognized=0;
149 int reason;
151 tor_assert(cell);
152 tor_assert(circ);
153 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
154 cell_direction == CELL_DIRECTION_IN);
155 if (circ->marked_for_close)
156 return 0;
158 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
159 log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
160 return -END_CIRC_REASON_INTERNAL;
163 if (recognized) {
164 edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
165 layer_hint);
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 or_conn = circ->n_conn;
194 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
195 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
196 or_conn = TO_OR_CIRCUIT(circ)->p_conn;
197 } else {
198 log_fn(LOG_PROTOCOL_WARN, LD_OR,
199 "Dropping unrecognized inbound cell on origin circuit.");
200 return 0;
203 if (!or_conn) {
204 // XXXX Can this splice stuff be done more cleanly?
205 if (! CIRCUIT_IS_ORIGIN(circ) &&
206 TO_OR_CIRCUIT(circ)->rend_splice &&
207 cell_direction == CELL_DIRECTION_OUT) {
208 or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
209 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
210 tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
211 cell->circ_id = splice->p_circ_id;
212 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
213 CELL_DIRECTION_IN)) < 0) {
214 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
215 "circuits");
216 /* XXXX Do this here, or just return -1? */
217 circuit_mark_for_close(circ, -reason);
218 return reason;
220 return 0;
222 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
223 "Didn't recognize cell, but circ stops here! Closing circ.");
224 return -END_CIRC_REASON_TORPROTOCOL;
227 log_debug(LD_OR,"Passing on unrecognized cell.");
229 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
230 * we might kill the circ before we relay
231 * the cells. */
233 append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
234 return 0;
237 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
238 * <b>circ</b> in direction <b>cell_direction</b>.
240 * If cell_direction == CELL_DIRECTION_IN:
241 * - If we're at the origin (we're the OP), for hops 1..N,
242 * decrypt cell. If recognized, stop.
243 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
245 * If cell_direction == CELL_DIRECTION_OUT:
246 * - decrypt one hop. Check if recognized.
248 * If cell is recognized, set *recognized to 1, and set
249 * *layer_hint to the hop that recognized it.
251 * Return -1 to indicate that we should mark the circuit for close,
252 * else return 0.
254 static int
255 relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
256 crypt_path_t **layer_hint, char *recognized)
258 relay_header_t rh;
260 tor_assert(circ);
261 tor_assert(cell);
262 tor_assert(recognized);
263 tor_assert(cell_direction == CELL_DIRECTION_IN ||
264 cell_direction == CELL_DIRECTION_OUT);
266 if (cell_direction == CELL_DIRECTION_IN) {
267 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
268 * We'll want to do layered decrypts. */
269 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
270 thishop = cpath;
271 if (thishop->state != CPATH_STATE_OPEN) {
272 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
273 "Relay cell before first created cell? Closing.");
274 return -1;
276 do { /* Remember: cpath is in forward order, that is, first hop first. */
277 tor_assert(thishop);
279 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
280 return -1;
282 relay_header_unpack(&rh, cell->payload);
283 if (rh.recognized == 0) {
284 /* it's possibly recognized. have to check digest to be sure. */
285 if (relay_digest_matches(thishop->b_digest, cell)) {
286 *recognized = 1;
287 *layer_hint = thishop;
288 return 0;
292 thishop = thishop->next;
293 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
294 log_fn(LOG_PROTOCOL_WARN, LD_OR,
295 "Incoming cell at client not recognized. Closing.");
296 return -1;
297 } else { /* we're in the middle. Just one crypt. */
298 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
299 cell->payload, 1) < 0)
300 return -1;
301 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
302 // "the client.");
304 } else /* cell_direction == CELL_DIRECTION_OUT */ {
305 /* we're in the middle. Just one crypt. */
307 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
308 cell->payload, 0) < 0)
309 return -1;
311 relay_header_unpack(&rh, cell->payload);
312 if (rh.recognized == 0) {
313 /* it's possibly recognized. have to check digest to be sure. */
314 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
315 *recognized = 1;
316 return 0;
320 return 0;
323 /** Package a relay cell from an edge:
324 * - Encrypt it to the right layer
325 * - Append it to the appropriate cell_queue on <b>circ</b>.
327 static int
328 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
329 int cell_direction,
330 crypt_path_t *layer_hint)
332 or_connection_t *conn; /* where to send the cell */
334 if (cell_direction == CELL_DIRECTION_OUT) {
335 crypt_path_t *thishop; /* counter for repeated crypts */
336 conn = circ->n_conn;
337 if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
338 log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
339 return 0; /* just drop it */
341 relay_set_digest(layer_hint->f_digest, cell);
343 thishop = layer_hint;
344 /* moving from farthest to nearest hop */
345 do {
346 tor_assert(thishop);
347 /* XXXX RD This is a bug, right? */
348 log_debug(LD_OR,"crypting a layer of the relay cell.");
349 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
350 return -1;
353 thishop = thishop->prev;
354 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
356 } else { /* incoming cell */
357 or_circuit_t *or_circ;
358 if (CIRCUIT_IS_ORIGIN(circ)) {
359 /* We should never package an _incoming_ cell from the circuit
360 * origin; that means we messed up somewhere. */
361 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
362 assert_circuit_ok(circ);
363 return 0; /* just drop it */
365 or_circ = TO_OR_CIRCUIT(circ);
366 conn = or_circ->p_conn;
367 relay_set_digest(or_circ->p_digest, cell);
368 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
369 return -1;
371 ++stats_n_relay_cells_relayed;
373 append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
374 return 0;
377 /** If cell's stream_id matches the stream_id of any conn that's
378 * attached to circ, return that conn, else return NULL.
380 static edge_connection_t *
381 relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction,
382 crypt_path_t *layer_hint)
384 edge_connection_t *tmpconn;
385 relay_header_t rh;
387 relay_header_unpack(&rh, cell->payload);
389 if (!rh.stream_id)
390 return NULL;
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 tmpconn->cpath_layer == layer_hint) {
402 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
403 return tmpconn;
406 } else {
407 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
408 tmpconn=tmpconn->next_stream) {
409 if (rh.stream_id == tmpconn->stream_id &&
410 !tmpconn->_base.marked_for_close) {
411 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
412 if (cell_direction == CELL_DIRECTION_OUT ||
413 connection_edge_is_rendezvous_stream(tmpconn))
414 return tmpconn;
417 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
418 tmpconn=tmpconn->next_stream) {
419 if (rh.stream_id == tmpconn->stream_id &&
420 !tmpconn->_base.marked_for_close) {
421 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
422 return tmpconn;
426 return NULL; /* probably a begin relay cell */
429 /** Pack the relay_header_t host-order structure <b>src</b> into
430 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
431 * about the wire format.
433 void
434 relay_header_pack(char *dest, const relay_header_t *src)
436 *(uint8_t*)(dest) = src->command;
438 set_uint16(dest+1, htons(src->recognized));
439 set_uint16(dest+3, htons(src->stream_id));
440 memcpy(dest+5, src->integrity, 4);
441 set_uint16(dest+9, htons(src->length));
444 /** Unpack the network-order buffer <b>src</b> into a host-order
445 * relay_header_t structure <b>dest</b>.
447 void
448 relay_header_unpack(relay_header_t *dest, const char *src)
450 dest->command = *(uint8_t*)(src);
452 dest->recognized = ntohs(get_uint16(src+1));
453 dest->stream_id = ntohs(get_uint16(src+3));
454 memcpy(dest->integrity, src+5, 4);
455 dest->length = ntohs(get_uint16(src+9));
458 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
459 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
460 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
461 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
462 * destination hop for OP->OR cells.
464 * If you can't send the cell, mark the circuit for close and return -1. Else
465 * return 0.
468 relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
469 int relay_command, const char *payload,
470 size_t payload_len, crypt_path_t *cpath_layer)
472 cell_t cell;
473 relay_header_t rh;
474 int cell_direction;
475 /* XXXX NM Split this function into a separate versions per circuit type? */
477 tor_assert(circ);
478 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
480 memset(&cell, 0, sizeof(cell_t));
481 cell.command = CELL_RELAY;
482 if (cpath_layer) {
483 cell.circ_id = circ->n_circ_id;
484 cell_direction = CELL_DIRECTION_OUT;
485 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
486 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
487 cell_direction = CELL_DIRECTION_IN;
488 } else {
489 return -1;
492 memset(&rh, 0, sizeof(rh));
493 rh.command = relay_command;
494 rh.stream_id = stream_id;
495 rh.length = payload_len;
496 relay_header_pack(cell.payload, &rh);
497 if (payload_len)
498 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 (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
504 /* if we're using relaybandwidthrate, this conn wants priority */
505 /* XXXX021 the call to time() seems little too frequent */
506 circ->n_conn->client_used = time(NULL);
509 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
510 < 0) {
511 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
512 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
513 return -1;
515 return 0;
518 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
519 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
520 * that's sending the relay cell, or NULL if it's a control cell.
521 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
522 * for OP->OR cells.
524 * If you can't send the cell, mark the circuit for close and
525 * return -1. Else return 0.
528 connection_edge_send_command(edge_connection_t *fromconn,
529 int relay_command, const char *payload,
530 size_t payload_len)
532 /* XXXX NM Split this function into a separate versions per circuit type? */
533 circuit_t *circ;
534 tor_assert(fromconn);
535 circ = fromconn->on_circuit;
537 if (fromconn->_base.marked_for_close) {
538 log_warn(LD_BUG,
539 "called on conn that's already marked for close at %s:%d.",
540 fromconn->_base.marked_for_close_file,
541 fromconn->_base.marked_for_close);
542 return 0;
545 if (!circ) {
546 if (fromconn->_base.type == CONN_TYPE_AP) {
547 log_info(LD_APP,"no circ. Closing conn.");
548 connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
549 } else {
550 log_info(LD_EXIT,"no circ. Closing conn.");
551 fromconn->_base.edge_has_sent_end = 1; /* no circ to send to */
552 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
553 connection_mark_for_close(TO_CONN(fromconn));
555 return -1;
558 return relay_send_command_from_edge(fromconn->stream_id, circ,
559 relay_command, payload,
560 payload_len, fromconn->cpath_layer);
563 /** Translate <b>reason</b>, which came from a relay 'end' cell,
564 * into a static const string describing why the stream is closing.
565 * <b>reason</b> is -1 if no reason was provided.
567 static const char *
568 connection_edge_end_reason_str(int reason)
570 switch (reason) {
571 case -1:
572 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
573 "End cell arrived with length 0. Should be at least 1.");
574 return "MALFORMED";
575 case END_STREAM_REASON_MISC: return "misc error";
576 case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
577 case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
578 case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
579 case END_STREAM_REASON_DESTROY: return "destroyed";
580 case END_STREAM_REASON_DONE: return "closed normally";
581 case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
582 case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
583 case END_STREAM_REASON_INTERNAL: return "internal error at server";
584 case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
585 case END_STREAM_REASON_CONNRESET: return "connection reset";
586 case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
587 case END_STREAM_REASON_NOTDIRECTORY: return "not a directory";
588 default:
589 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
590 "Reason for ending (%d) not recognized.",reason);
591 return "unknown";
595 /** Translate <b>reason</b> (as from a relay 'end' cell) into an
596 * appropriate SOCKS5 reply code.
598 * A reason of 0 means that we're not actually expecting to send
599 * this code back to the socks client; we just call it 'succeeded'
600 * to keep things simple.
602 socks5_reply_status_t
603 connection_edge_end_reason_socks5_response(int reason)
605 switch (reason & END_STREAM_REASON_MASK) {
606 case 0:
607 return SOCKS5_SUCCEEDED;
608 case END_STREAM_REASON_MISC:
609 return SOCKS5_GENERAL_ERROR;
610 case END_STREAM_REASON_RESOLVEFAILED:
611 return SOCKS5_HOST_UNREACHABLE;
612 case END_STREAM_REASON_CONNECTREFUSED:
613 return SOCKS5_CONNECTION_REFUSED;
614 case END_STREAM_REASON_ENTRYPOLICY:
615 return SOCKS5_NOT_ALLOWED;
616 case END_STREAM_REASON_EXITPOLICY:
617 return SOCKS5_NOT_ALLOWED;
618 case END_STREAM_REASON_DESTROY:
619 return SOCKS5_GENERAL_ERROR;
620 case END_STREAM_REASON_DONE:
621 return SOCKS5_SUCCEEDED;
622 case END_STREAM_REASON_TIMEOUT:
623 return SOCKS5_TTL_EXPIRED;
624 case END_STREAM_REASON_RESOURCELIMIT:
625 return SOCKS5_GENERAL_ERROR;
626 case END_STREAM_REASON_HIBERNATING:
627 return SOCKS5_GENERAL_ERROR;
628 case END_STREAM_REASON_INTERNAL:
629 return SOCKS5_GENERAL_ERROR;
630 case END_STREAM_REASON_CONNRESET:
631 return SOCKS5_CONNECTION_REFUSED;
632 case END_STREAM_REASON_TORPROTOCOL:
633 return SOCKS5_GENERAL_ERROR;
635 case END_STREAM_REASON_CANT_ATTACH:
636 return SOCKS5_GENERAL_ERROR;
637 case END_STREAM_REASON_NET_UNREACHABLE:
638 return SOCKS5_NET_UNREACHABLE;
639 case END_STREAM_REASON_SOCKSPROTOCOL:
640 return SOCKS5_GENERAL_ERROR;
641 default:
642 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
643 "Reason for ending (%d) not recognized; "
644 "sending generic socks error.", reason);
645 return SOCKS5_GENERAL_ERROR;
649 /* We need to use a few macros to deal with the fact that Windows
650 * decided that their sockets interface should be a permakludge.
651 * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
652 * version, and S_CASE is for errors where windows has only a WSAEFOO
653 * version. (The E is for 'error', the S is for 'socket'). */
654 #ifdef MS_WINDOWS
655 #define E_CASE(s) case s: case WSA ## s
656 #define S_CASE(s) case WSA ## s
657 #else
658 #define E_CASE(s) case s
659 #define S_CASE(s) case s
660 #endif
662 /** Given an errno from a failed exit connection, return a reason code
663 * appropriate for use in a RELAY END cell.
666 errno_to_end_reason(int e)
668 switch (e) {
669 case EPIPE:
670 return END_STREAM_REASON_DONE;
671 E_CASE(EBADF):
672 E_CASE(EFAULT):
673 E_CASE(EINVAL):
674 S_CASE(EISCONN):
675 S_CASE(ENOTSOCK):
676 S_CASE(EPROTONOSUPPORT):
677 S_CASE(EAFNOSUPPORT):
678 E_CASE(EACCES):
679 S_CASE(ENOTCONN):
680 S_CASE(ENETUNREACH):
681 return END_STREAM_REASON_INTERNAL;
682 S_CASE(ECONNREFUSED):
683 return END_STREAM_REASON_CONNECTREFUSED;
684 S_CASE(ECONNRESET):
685 return END_STREAM_REASON_CONNRESET;
686 S_CASE(ETIMEDOUT):
687 return END_STREAM_REASON_TIMEOUT;
688 S_CASE(ENOBUFS):
689 case ENOMEM:
690 case ENFILE:
691 E_CASE(EMFILE):
692 return END_STREAM_REASON_RESOURCELIMIT;
693 default:
694 log_info(LD_EXIT, "Didn't recognize errno %d (%s); telling the client "
695 "that we are ending a stream for 'misc' reason.",
696 e, tor_socket_strerror(e));
697 return END_STREAM_REASON_MISC;
701 /** How many times will I retry a stream that fails due to DNS
702 * resolve failure or misc error?
704 #define MAX_RESOLVE_FAILURES 3
706 /** Return 1 if reason is something that you should retry if you
707 * get the end cell before you've connected; else return 0. */
708 static int
709 edge_reason_is_retriable(int reason)
711 return reason == END_STREAM_REASON_HIBERNATING ||
712 reason == END_STREAM_REASON_RESOURCELIMIT ||
713 reason == END_STREAM_REASON_EXITPOLICY ||
714 reason == END_STREAM_REASON_RESOLVEFAILED ||
715 reason == END_STREAM_REASON_MISC;
718 /** Called when we receive an END cell on a stream that isn't open yet.
719 * Arguments are as for connection_edge_process_relay_cell().
721 static int
722 connection_edge_process_end_not_open(
723 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
724 edge_connection_t *conn, crypt_path_t *layer_hint)
726 struct in_addr in;
727 routerinfo_t *exitrouter;
728 int reason = *(cell->payload+RELAY_HEADER_SIZE);
729 int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
730 (void) layer_hint; /* unused */
732 if (rh->length > 0 && edge_reason_is_retriable(reason) &&
733 conn->_base.type == CONN_TYPE_AP) {
734 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
735 safe_str(conn->socks_request->address),
736 connection_edge_end_reason_str(reason));
737 exitrouter =
738 router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
739 switch (reason) {
740 case END_STREAM_REASON_EXITPOLICY:
741 if (rh->length >= 5) {
742 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
743 int ttl;
744 if (!addr) {
745 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
746 safe_str(conn->socks_request->address));
747 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
748 return 0;
750 if (rh->length >= 9)
751 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
752 else
753 ttl = -1;
754 client_dns_set_addressmap(conn->socks_request->address, addr,
755 conn->chosen_exit_name, ttl);
757 /* check if he *ought* to have allowed it */
758 if (exitrouter &&
759 (rh->length < 5 ||
760 (tor_inet_aton(conn->socks_request->address, &in) &&
761 !conn->chosen_exit_name))) {
762 log_notice(LD_APP,
763 "Exitrouter '%s' seems to be more restrictive than its exit "
764 "policy. Not using this router as exit for now.",
765 exitrouter->nickname);
766 policies_set_router_exitpolicy_to_reject_all(exitrouter);
768 /* rewrite it to an IP if we learned one. */
769 if (addressmap_rewrite(conn->socks_request->address,
770 sizeof(conn->socks_request->address),
771 NULL)) {
772 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
774 if (conn->_base.chosen_exit_optional) {
775 /* stop wanting a specific exit */
776 conn->_base.chosen_exit_optional = 0;
777 tor_free(conn->chosen_exit_name); /* clears it */
779 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
780 return 0;
781 /* else, conn will get closed below */
782 break;
783 case END_STREAM_REASON_CONNECTREFUSED:
784 if (!conn->_base.chosen_exit_optional)
785 break; /* break means it'll close, below */
786 /* Else fall through: expire this circuit, clear the
787 * chosen_exit_name field, and try again. */
788 case END_STREAM_REASON_RESOLVEFAILED:
789 case END_STREAM_REASON_TIMEOUT:
790 case END_STREAM_REASON_MISC:
791 if (client_dns_incr_failures(conn->socks_request->address)
792 < MAX_RESOLVE_FAILURES) {
793 /* We haven't retried too many times; reattach the connection. */
794 circuit_log_path(LOG_INFO,LD_APP,circ);
795 tor_assert(circ->_base.timestamp_dirty);
796 circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
798 if (conn->_base.chosen_exit_optional) {
799 /* stop wanting a specific exit */
800 conn->_base.chosen_exit_optional = 0;
801 tor_free(conn->chosen_exit_name); /* clears it */
803 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
804 return 0;
805 /* else, conn will get closed below */
806 } else {
807 log_notice(LD_APP,
808 "Have tried resolving or connecting to address '%s' "
809 "at %d different places. Giving up.",
810 safe_str(conn->socks_request->address),
811 MAX_RESOLVE_FAILURES);
812 /* clear the failures, so it will have a full try next time */
813 client_dns_clear_failures(conn->socks_request->address);
815 break;
816 case END_STREAM_REASON_HIBERNATING:
817 case END_STREAM_REASON_RESOURCELIMIT:
818 if (exitrouter) {
819 policies_set_router_exitpolicy_to_reject_all(exitrouter);
821 if (conn->_base.chosen_exit_optional) {
822 /* stop wanting a specific exit */
823 conn->_base.chosen_exit_optional = 0;
824 tor_free(conn->chosen_exit_name); /* clears it */
826 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
827 return 0;
828 /* else, will close below */
829 break;
830 } /* end switch */
831 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
834 log_info(LD_APP,
835 "Edge got end (%s) before we're connected. Marking for close.",
836 connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
837 if (conn->_base.type == CONN_TYPE_AP) {
838 circuit_log_path(LOG_INFO,LD_APP,circ);
839 connection_mark_unattached_ap(conn, control_reason);
840 } else {
841 /* we just got an 'end', don't need to send one */
842 conn->_base.edge_has_sent_end = 1;
843 conn->end_reason = control_reason;
844 connection_mark_for_close(TO_CONN(conn));
846 return 0;
849 /** Helper: change the socks_request-&gt;address field on conn to the
850 * dotted-quad representation of <b>new_addr</b> (given in host order),
851 * and send an appropriate REMAP event. */
852 static void
853 remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
855 struct in_addr in;
857 in.s_addr = htonl(new_addr);
858 tor_inet_ntoa(&in, conn->socks_request->address,
859 sizeof(conn->socks_request->address));
860 control_event_stream_status(conn, STREAM_EVENT_REMAP,
861 REMAP_STREAM_SOURCE_EXIT);
864 /** An incoming relay cell has arrived from circuit <b>circ</b> to
865 * stream <b>conn</b>.
867 * The arguments here are the same as in
868 * connection_edge_process_relay_cell() below; this function is called
869 * from there when <b>conn</b> is defined and not in an open state.
871 static int
872 connection_edge_process_relay_cell_not_open(
873 relay_header_t *rh, cell_t *cell, circuit_t *circ,
874 edge_connection_t *conn, crypt_path_t *layer_hint)
876 if (rh->command == RELAY_COMMAND_END) {
877 if (CIRCUIT_IS_ORIGIN(circ))
878 return connection_edge_process_end_not_open(rh, cell,
879 TO_ORIGIN_CIRCUIT(circ), conn,
880 layer_hint);
881 else
882 return 0;
885 if (conn->_base.type == CONN_TYPE_AP &&
886 rh->command == RELAY_COMMAND_CONNECTED) {
887 tor_assert(CIRCUIT_IS_ORIGIN(circ));
888 if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
889 log_fn(LOG_PROTOCOL_WARN, LD_APP,
890 "Got 'connected' while not in state connect_wait. Dropping.");
891 return 0;
893 conn->_base.state = AP_CONN_STATE_OPEN;
894 log_info(LD_APP,"'connected' received after %d seconds.",
895 (int)(time(NULL) - conn->_base.timestamp_lastread));
896 if (rh->length >= 4) {
897 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
898 int ttl;
899 if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
900 is_internal_IP(addr, 0))) {
901 char buf[INET_NTOA_BUF_LEN];
902 struct in_addr a;
903 a.s_addr = htonl(addr);
904 tor_inet_ntoa(&a, buf, sizeof(buf));
905 log_info(LD_APP,
906 "...but it claims the IP address was %s. Closing.", buf);
907 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
908 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
909 return 0;
911 if (rh->length >= 8)
912 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
913 else
914 ttl = -1;
915 client_dns_set_addressmap(conn->socks_request->address, addr,
916 conn->chosen_exit_name, ttl);
918 remap_event_helper(conn, addr);
920 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
921 /* don't send a socks reply to transparent conns */
922 if (!conn->socks_request->has_finished)
923 connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
924 /* handle anything that might have queued */
925 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
926 /* (We already sent an end cell if possible) */
927 connection_mark_for_close(TO_CONN(conn));
928 return 0;
930 return 0;
932 if (conn->_base.type == CONN_TYPE_AP &&
933 rh->command == RELAY_COMMAND_RESOLVED) {
934 int ttl;
935 int answer_len;
936 uint8_t answer_type;
937 if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
938 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
939 "not in state resolve_wait. Dropping.");
940 return 0;
942 tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
943 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
944 if (rh->length < 2 || answer_len+2>rh->length) {
945 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
946 "Dropping malformed 'resolved' cell");
947 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
948 return 0;
950 answer_type = cell->payload[RELAY_HEADER_SIZE];
951 if (rh->length >= answer_len+6)
952 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
953 2+answer_len));
954 else
955 ttl = -1;
956 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
957 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
958 if (get_options()->ClientDNSRejectInternalAddresses &&
959 is_internal_IP(addr, 0)) {
960 char buf[INET_NTOA_BUF_LEN];
961 struct in_addr a;
962 a.s_addr = htonl(addr);
963 tor_inet_ntoa(&a, buf, sizeof(buf));
964 log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
965 connection_ap_handshake_socks_resolved(conn,
966 RESOLVED_TYPE_ERROR_TRANSIENT,
967 0, NULL, 0, TIME_MAX);
968 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
969 return 0;
972 connection_ap_handshake_socks_resolved(conn,
973 answer_type,
974 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
975 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
976 ttl,
977 -1);
978 if (answer_type == RESOLVED_TYPE_IPV4) {
979 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
980 remap_event_helper(conn, addr);
982 connection_mark_unattached_ap(conn,
983 END_STREAM_REASON_DONE |
984 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
985 return 0;
988 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
989 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
990 rh->command, conn->_base.state,
991 conn_state_to_string(conn->_base.type, conn->_base.state));
992 return 0; /* for forward compatibility, don't kill the circuit */
993 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
994 // connection_mark_for_close(conn);
995 // return -1;
998 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
999 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
1000 * destined for <b>conn</b>.
1002 * If <b>layer_hint</b> is defined, then we're the origin of the
1003 * circuit, and it specifies the hop that packaged <b>cell</b>.
1005 * Return -reason if you want to warn and tear down the circuit, else 0.
1007 static int
1008 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
1009 edge_connection_t *conn,
1010 crypt_path_t *layer_hint)
1012 static int num_seen=0;
1013 relay_header_t rh;
1014 unsigned domain = layer_hint?LD_APP:LD_EXIT;
1015 int reason;
1017 tor_assert(cell);
1018 tor_assert(circ);
1020 relay_header_unpack(&rh, cell->payload);
1021 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1022 num_seen++;
1023 log_debug(domain, "Now seen %d relay cells here.", num_seen);
1025 if (rh.length > RELAY_PAYLOAD_SIZE) {
1026 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1027 "Relay cell length field too long. Closing circuit.");
1028 return - END_CIRC_REASON_TORPROTOCOL;
1031 /* either conn is NULL, in which case we've got a control cell, or else
1032 * conn points to the recognized stream. */
1034 if (conn && !connection_state_is_open(TO_CONN(conn)))
1035 return connection_edge_process_relay_cell_not_open(
1036 &rh, cell, circ, conn, layer_hint);
1038 switch (rh.command) {
1039 case RELAY_COMMAND_DROP:
1040 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1041 return 0;
1042 case RELAY_COMMAND_BEGIN:
1043 case RELAY_COMMAND_BEGIN_DIR:
1044 if (layer_hint &&
1045 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1046 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1047 "Relay begin request unsupported at AP. Dropping.");
1048 return 0;
1050 if (conn) {
1051 log_fn(LOG_PROTOCOL_WARN, domain,
1052 "Begin cell for known stream. Dropping.");
1053 return 0;
1055 return connection_exit_begin_conn(cell, circ);
1056 case RELAY_COMMAND_DATA:
1057 ++stats_n_data_cells_received;
1058 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1059 (!layer_hint && --circ->deliver_window < 0)) {
1060 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1061 "(relay data) circ deliver_window below 0. Killing.");
1062 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1063 connection_mark_for_close(TO_CONN(conn));
1064 return -END_CIRC_REASON_TORPROTOCOL;
1066 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1067 layer_hint->deliver_window : circ->deliver_window);
1069 circuit_consider_sending_sendme(circ, layer_hint);
1071 if (!conn) {
1072 log_info(domain,"data cell dropped, unknown stream.");
1073 return 0;
1076 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1077 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1078 "(relay data) conn deliver_window below 0. Killing.");
1079 return -END_CIRC_REASON_TORPROTOCOL;
1082 stats_n_data_bytes_received += rh.length;
1083 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
1084 rh.length, TO_CONN(conn));
1085 connection_edge_consider_sending_sendme(conn);
1086 return 0;
1087 case RELAY_COMMAND_END:
1088 reason = rh.length > 0 ?
1089 *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1090 if (!conn) {
1091 log_info(domain,"end cell (%s) dropped, unknown stream.",
1092 connection_edge_end_reason_str(reason));
1093 return 0;
1095 /* XXX add to this log_fn the exit node's nickname? */
1096 log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
1097 conn->_base.s,
1098 connection_edge_end_reason_str(reason),
1099 conn->stream_id);
1100 if (conn->socks_request && !conn->socks_request->has_finished)
1101 log_warn(LD_BUG,
1102 "open stream hasn't sent socks answer yet? Closing.");
1103 /* We just *got* an end; no reason to send one. */
1104 conn->_base.edge_has_sent_end = 1;
1105 if (!conn->end_reason)
1106 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1107 if (!conn->_base.marked_for_close) {
1108 /* only mark it if not already marked. it's possible to
1109 * get the 'end' right around when the client hangs up on us. */
1110 connection_mark_for_close(TO_CONN(conn));
1111 conn->_base.hold_open_until_flushed = 1;
1113 return 0;
1114 case RELAY_COMMAND_EXTEND:
1115 if (conn) {
1116 log_fn(LOG_PROTOCOL_WARN, domain,
1117 "'extend' cell received for non-zero stream. Dropping.");
1118 return 0;
1120 return circuit_extend(cell, circ);
1121 case RELAY_COMMAND_EXTENDED:
1122 if (!layer_hint) {
1123 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1124 "'extended' unsupported at non-origin. Dropping.");
1125 return 0;
1127 log_debug(domain,"Got an extended cell! Yay.");
1128 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1129 CELL_CREATED,
1130 cell->payload+RELAY_HEADER_SIZE)) < 0) {
1131 log_warn(domain,"circuit_finish_handshake failed.");
1132 return reason;
1134 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1135 log_info(domain,"circuit_send_next_onion_skin() failed.");
1136 return reason;
1138 return 0;
1139 case RELAY_COMMAND_TRUNCATE:
1140 if (layer_hint) {
1141 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1142 "'truncate' unsupported at origin. Dropping.");
1143 return 0;
1145 if (circ->n_conn) {
1146 uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
1147 connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
1148 trunc_reason);
1149 circuit_set_n_circid_orconn(circ, 0, NULL);
1151 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1153 char payload[1];
1154 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1155 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1156 payload, sizeof(payload), NULL);
1158 return 0;
1159 case RELAY_COMMAND_TRUNCATED:
1160 if (!layer_hint) {
1161 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1162 "'truncated' unsupported at non-origin. Dropping.");
1163 return 0;
1165 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
1166 return 0;
1167 case RELAY_COMMAND_CONNECTED:
1168 if (conn) {
1169 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1170 "'connected' unsupported while open. Closing circ.");
1171 return -END_CIRC_REASON_TORPROTOCOL;
1173 log_info(domain,
1174 "'connected' received, no conn attached anymore. Ignoring.");
1175 return 0;
1176 case RELAY_COMMAND_SENDME:
1177 if (!conn) {
1178 if (layer_hint) {
1179 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1180 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1181 layer_hint->package_window);
1182 circuit_resume_edge_reading(circ, layer_hint);
1183 } else {
1184 circ->package_window += CIRCWINDOW_INCREMENT;
1185 log_debug(LD_APP,
1186 "circ-level sendme at non-origin, packagewindow %d.",
1187 circ->package_window);
1188 circuit_resume_edge_reading(circ, layer_hint);
1190 return 0;
1192 conn->package_window += STREAMWINDOW_INCREMENT;
1193 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1194 conn->package_window);
1195 connection_start_reading(TO_CONN(conn));
1196 /* handle whatever might still be on the inbuf */
1197 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
1198 /* (We already sent an end cell if possible) */
1199 connection_mark_for_close(TO_CONN(conn));
1200 return 0;
1202 return 0;
1203 case RELAY_COMMAND_RESOLVE:
1204 if (layer_hint) {
1205 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1206 "resolve request unsupported at AP; dropping.");
1207 return 0;
1208 } else if (conn) {
1209 log_fn(LOG_PROTOCOL_WARN, domain,
1210 "resolve request for known stream; dropping.");
1211 return 0;
1212 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1213 log_fn(LOG_PROTOCOL_WARN, domain,
1214 "resolve request on circ with purpose %d; dropping",
1215 circ->purpose);
1216 return 0;
1218 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1219 return 0;
1220 case RELAY_COMMAND_RESOLVED:
1221 if (conn) {
1222 log_fn(LOG_PROTOCOL_WARN, domain,
1223 "'resolved' unsupported while open. Closing circ.");
1224 return -END_CIRC_REASON_TORPROTOCOL;
1226 log_info(domain,
1227 "'resolved' received, no conn attached anymore. Ignoring.");
1228 return 0;
1229 case RELAY_COMMAND_ESTABLISH_INTRO:
1230 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1231 case RELAY_COMMAND_INTRODUCE1:
1232 case RELAY_COMMAND_INTRODUCE2:
1233 case RELAY_COMMAND_INTRODUCE_ACK:
1234 case RELAY_COMMAND_RENDEZVOUS1:
1235 case RELAY_COMMAND_RENDEZVOUS2:
1236 case RELAY_COMMAND_INTRO_ESTABLISHED:
1237 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1238 rend_process_relay_cell(circ, rh.command, rh.length,
1239 cell->payload+RELAY_HEADER_SIZE);
1240 return 0;
1242 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1243 "Received unknown relay command %d. Perhaps the other side is using "
1244 "a newer version of Tor? Dropping.",
1245 rh.command);
1246 return 0; /* for forward compatibility, don't kill the circuit */
1249 uint64_t stats_n_data_cells_packaged = 0;
1250 uint64_t stats_n_data_bytes_packaged = 0;
1251 uint64_t stats_n_data_cells_received = 0;
1252 uint64_t stats_n_data_bytes_received = 0;
1254 /** While conn->inbuf has an entire relay payload of bytes on it,
1255 * and the appropriate package windows aren't empty, grab a cell
1256 * and send it down the circuit.
1258 * Return -1 (and send a RELAY_END cell if necessary) if conn should
1259 * be marked for close, else return 0.
1262 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
1264 size_t amount_to_process, length;
1265 char payload[CELL_PAYLOAD_SIZE];
1266 circuit_t *circ;
1267 unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
1269 tor_assert(conn);
1271 if (conn->_base.marked_for_close) {
1272 log_warn(LD_BUG,
1273 "called on conn that's already marked for close at %s:%d.",
1274 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
1275 return 0;
1278 repeat_connection_edge_package_raw_inbuf:
1280 circ = circuit_get_by_edge_conn(conn);
1281 if (!circ) {
1282 log_info(domain,"conn has no circuit! Closing.");
1283 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1284 return -1;
1287 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
1288 return 0;
1290 if (conn->package_window <= 0) {
1291 log_info(domain,"called with package_window %d. Skipping.",
1292 conn->package_window);
1293 connection_stop_reading(TO_CONN(conn));
1294 return 0;
1297 amount_to_process = buf_datalen(conn->_base.inbuf);
1299 if (!amount_to_process)
1300 return 0;
1302 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
1303 return 0;
1305 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
1306 length = RELAY_PAYLOAD_SIZE;
1307 } else {
1308 length = amount_to_process;
1310 stats_n_data_bytes_packaged += length;
1311 stats_n_data_cells_packaged += 1;
1313 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1315 log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
1316 (int)length, (int)buf_datalen(conn->_base.inbuf));
1318 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1319 payload, length) < 0 )
1320 /* circuit got marked for close, don't continue, don't need to mark conn */
1321 return 0;
1323 if (!conn->cpath_layer) { /* non-rendezvous exit */
1324 tor_assert(circ->package_window > 0);
1325 circ->package_window--;
1326 } else { /* we're an AP, or an exit on a rendezvous circ */
1327 tor_assert(conn->cpath_layer->package_window > 0);
1328 conn->cpath_layer->package_window--;
1331 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1332 connection_stop_reading(TO_CONN(conn));
1333 log_debug(domain,"conn->package_window reached 0.");
1334 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
1335 return 0; /* don't process the inbuf any more */
1337 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1339 /* handle more if there's more, or return 0 if there isn't */
1340 goto repeat_connection_edge_package_raw_inbuf;
1343 /** Called when we've just received a relay data cell, or when
1344 * we've just finished flushing all bytes to stream <b>conn</b>.
1346 * If conn->outbuf is not too full, and our deliver window is
1347 * low, send back a suitable number of stream-level sendme cells.
1349 void
1350 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1352 circuit_t *circ;
1354 if (connection_outbuf_too_full(TO_CONN(conn)))
1355 return;
1357 circ = circuit_get_by_edge_conn(conn);
1358 if (!circ) {
1359 /* this can legitimately happen if the destroy has already
1360 * arrived and torn down the circuit */
1361 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1362 return;
1365 while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1366 log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
1367 "Outbuf %d, Queueing stream sendme.",
1368 (int)conn->_base.outbuf_flushlen);
1369 conn->deliver_window += STREAMWINDOW_INCREMENT;
1370 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
1371 NULL, 0) < 0) {
1372 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
1373 return; /* the circuit's closed, don't continue */
1378 /** The circuit <b>circ</b> has received a circuit-level sendme
1379 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1380 * attached streams and let them resume reading and packaging, if
1381 * their stream windows allow it.
1383 static void
1384 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1387 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1389 if (CIRCUIT_IS_ORIGIN(circ))
1390 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
1391 circ, layer_hint);
1392 else
1393 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
1394 circ, layer_hint);
1397 /** A helper function for circuit_resume_edge_reading() above.
1398 * The arguments are the same, except that <b>conn</b> is the head
1399 * of a linked list of edge streams that should each be considered.
1401 static int
1402 circuit_resume_edge_reading_helper(edge_connection_t *conn,
1403 circuit_t *circ,
1404 crypt_path_t *layer_hint)
1406 for ( ; conn; conn=conn->next_stream) {
1407 if (conn->_base.marked_for_close)
1408 continue;
1409 if ((!layer_hint && conn->package_window > 0) ||
1410 (layer_hint && conn->package_window > 0 &&
1411 conn->cpath_layer == layer_hint)) {
1412 connection_start_reading(TO_CONN(conn));
1413 /* handle whatever might still be on the inbuf */
1414 if (connection_edge_package_raw_inbuf(conn, 1)<0) {
1415 /* (We already sent an end cell if possible) */
1416 connection_mark_for_close(TO_CONN(conn));
1417 continue;
1420 /* If the circuit won't accept any more data, return without looking
1421 * at any more of the streams. Any connections that should be stopped
1422 * have already been stopped by connection_edge_package_raw_inbuf. */
1423 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1424 return -1;
1427 return 0;
1430 /** Check if the package window for <b>circ</b> is empty (at
1431 * hop <b>layer_hint</b> if it's defined).
1433 * If yes, tell edge streams to stop reading and return 1.
1434 * Else return 0.
1436 static int
1437 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1439 edge_connection_t *conn = NULL;
1440 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1442 if (!layer_hint) {
1443 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1444 log_debug(domain,"considering circ->package_window %d",
1445 circ->package_window);
1446 if (circ->package_window <= 0) {
1447 log_debug(domain,"yes, not-at-origin. stopped.");
1448 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
1449 connection_stop_reading(TO_CONN(conn));
1450 return 1;
1452 return 0;
1454 /* else, layer hint is defined, use it */
1455 log_debug(domain,"considering layer_hint->package_window %d",
1456 layer_hint->package_window);
1457 if (layer_hint->package_window <= 0) {
1458 log_debug(domain,"yes, at-origin. stopped.");
1459 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
1460 conn=conn->next_stream)
1461 if (conn->cpath_layer == layer_hint)
1462 connection_stop_reading(TO_CONN(conn));
1463 return 1;
1465 return 0;
1468 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1469 * <b>layer_hint</b> if it's defined) is low enough that we should
1470 * send a circuit-level sendme back down the circuit. If so, send
1471 * enough sendmes that the window would be overfull if we sent any
1472 * more.
1474 static void
1475 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1477 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1478 // layer_hint ? "defined" : "null");
1479 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
1480 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1481 log_debug(LD_CIRC,"Queueing circuit sendme.");
1482 if (layer_hint)
1483 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1484 else
1485 circ->deliver_window += CIRCWINDOW_INCREMENT;
1486 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
1487 NULL, 0, layer_hint) < 0) {
1488 log_warn(LD_CIRC,
1489 "connection_edge_send_command failed. Circuit's closed.");
1490 return; /* the circuit's closed, don't continue */
1495 /** Stop reading on edge connections when we have this many cells
1496 * waiting on the appropriate queue. */
1497 #define CELL_QUEUE_HIGHWATER_SIZE 256
1498 /** Start reading from edge connections again when we get down to this many
1499 * cells. */
1500 #define CELL_QUEUE_LOWWATER_SIZE 64
1502 #ifdef ACTIVE_CIRCUITS_PARANOIA
1503 #define assert_active_circuits_ok_paranoid(conn) \
1504 assert_active_circuits_ok(conn)
1505 #else
1506 #define assert_active_circuits_ok_paranoid(conn)
1507 #endif
1509 /** The total number of cells we have allocated from the memory pool. */
1510 static int total_cells_allocated = 0;
1512 #ifdef ENABLE_CELL_POOL /* Defined in ./configure. True by default. */
1513 /* XXX021 make cell pools the only option once we know they work and improve
1514 * matters? -RD */
1515 static mp_pool_t *cell_pool = NULL;
1516 /** Allocate structures to hold cells. */
1517 void
1518 init_cell_pool(void)
1520 tor_assert(!cell_pool);
1521 cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
1524 /** Free all storage used to hold cells. */
1525 void
1526 free_cell_pool(void)
1528 /* Maybe we haven't called init_cell_pool yet; need to check for it. */
1529 if (cell_pool) {
1530 mp_pool_destroy(cell_pool);
1531 cell_pool = NULL;
1535 /** Free excess storage in cell pool. */
1536 void
1537 clean_cell_pool(void)
1539 tor_assert(cell_pool);
1540 mp_pool_clean(cell_pool, 0, 1);
1543 /** Release storage held by <b>cell</b>. */
1544 static INLINE void
1545 packed_cell_free(packed_cell_t *cell)
1547 --total_cells_allocated;
1548 mp_pool_release(cell);
1551 /** Allocate and return a new packed_cell_t. */
1552 static INLINE packed_cell_t *
1553 packed_cell_alloc(void)
1555 ++total_cells_allocated;
1556 return mp_pool_get(cell_pool);
1558 void
1559 dump_cell_pool_usage(int severity)
1561 circuit_t *c;
1562 int n_circs = 0;
1563 int n_cells = 0;
1564 for (c = _circuit_get_global_list(); c; c = c->next) {
1565 n_cells += c->n_conn_cells.n;
1566 if (!CIRCUIT_IS_ORIGIN(c))
1567 n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
1568 ++n_circs;
1570 log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
1571 n_cells, n_circs, total_cells_allocated - n_cells);
1572 mp_pool_log_status(cell_pool, severity);
1574 #else
1575 /* ENABLE_CELL_POOL isn't defined: here are some stubs to use tor_malloc()
1576 * and tor_free() instead. */
1577 void
1578 init_cell_pool(void)
1582 void
1583 free_cell_pool(void)
1587 void
1588 clean_cell_pool(void)
1592 static INLINE void
1593 packed_cell_free(packed_cell_t *cell)
1595 --total_cells_allocated;
1596 tor_free(cell);
1599 static INLINE packed_cell_t *
1600 packed_cell_alloc(void)
1602 ++total_cells_allocated;
1603 return tor_malloc(sizeof(packed_cell_t));
1605 void
1606 dump_cell_pool_usage(int severity)
1608 (void) severity;
1610 #endif
1612 /** Allocate a new copy of packed <b>cell</b>. */
1613 static INLINE packed_cell_t *
1614 packed_cell_copy(const cell_t *cell)
1616 packed_cell_t *c = packed_cell_alloc();
1617 cell_pack(c, cell);
1618 c->next = NULL;
1619 return c;
1622 /** Append <b>cell</b> to the end of <b>queue</b>. */
1623 void
1624 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
1626 if (queue->tail) {
1627 tor_assert(!queue->tail->next);
1628 queue->tail->next = cell;
1629 } else {
1630 queue->head = cell;
1632 queue->tail = cell;
1633 cell->next = NULL;
1634 ++queue->n;
1637 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
1638 void
1639 cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
1641 cell_queue_append(queue, packed_cell_copy(cell));
1644 /** Remove and free every cell in <b>queue</b>. */
1645 void
1646 cell_queue_clear(cell_queue_t *queue)
1648 packed_cell_t *cell, *next;
1649 cell = queue->head;
1650 while (cell) {
1651 next = cell->next;
1652 packed_cell_free(cell);
1653 cell = next;
1655 queue->head = queue->tail = NULL;
1656 queue->n = 0;
1659 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
1660 * <b>queue</b> is empty. */
1661 static INLINE packed_cell_t *
1662 cell_queue_pop(cell_queue_t *queue)
1664 packed_cell_t *cell = queue->head;
1665 if (!cell)
1666 return NULL;
1667 queue->head = cell->next;
1668 if (cell == queue->tail) {
1669 tor_assert(!queue->head);
1670 queue->tail = NULL;
1672 --queue->n;
1673 return cell;
1676 /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
1677 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1678 static INLINE circuit_t **
1679 next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1681 tor_assert(circ);
1682 tor_assert(conn);
1683 if (conn == circ->n_conn) {
1684 return &circ->next_active_on_n_conn;
1685 } else {
1686 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1687 tor_assert(conn == orcirc->p_conn);
1688 return &orcirc->next_active_on_p_conn;
1692 /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
1693 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1694 static INLINE circuit_t **
1695 prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1697 tor_assert(circ);
1698 tor_assert(conn);
1699 if (conn == circ->n_conn) {
1700 return &circ->prev_active_on_n_conn;
1701 } else {
1702 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1703 tor_assert(conn == orcirc->p_conn);
1704 return &orcirc->prev_active_on_p_conn;
1708 /** Add <b>circ</b> to the list of circuits with pending cells on
1709 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1710 void
1711 make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
1713 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1714 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1716 if (*nextp && *prevp) {
1717 /* Already active. */
1718 return;
1721 if (! conn->active_circuits) {
1722 conn->active_circuits = circ;
1723 *prevp = *nextp = circ;
1724 } else {
1725 circuit_t *head = conn->active_circuits;
1726 circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
1727 *next_circ_on_conn_p(old_tail, conn) = circ;
1728 *nextp = head;
1729 *prev_circ_on_conn_p(head, conn) = circ;
1730 *prevp = old_tail;
1732 assert_active_circuits_ok_paranoid(conn);
1735 /** Remove <b>circ</b> to the list of circuits with pending cells on
1736 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1737 void
1738 make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
1740 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1741 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1742 circuit_t *next = *nextp, *prev = *prevp;
1744 if (!next && !prev) {
1745 /* Already inactive. */
1746 return;
1749 tor_assert(next && prev);
1750 tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
1751 tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
1753 if (next == circ) {
1754 conn->active_circuits = NULL;
1755 } else {
1756 *prev_circ_on_conn_p(next, conn) = prev;
1757 *next_circ_on_conn_p(prev, conn) = next;
1758 if (conn->active_circuits == circ)
1759 conn->active_circuits = next;
1761 *prevp = *nextp = NULL;
1762 assert_active_circuits_ok_paranoid(conn);
1765 /** Remove all circuits from the list of circuits with pending cells on
1766 * <b>conn</b>. */
1767 void
1768 connection_or_unlink_all_active_circs(or_connection_t *orconn)
1770 circuit_t *head = orconn->active_circuits;
1771 circuit_t *cur = head;
1772 if (! head)
1773 return;
1774 do {
1775 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1776 *prev_circ_on_conn_p(cur, orconn) = NULL;
1777 *next_circ_on_conn_p(cur, orconn) = NULL;
1778 cur = next;
1779 } while (cur != head);
1780 orconn->active_circuits = NULL;
1783 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
1784 * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
1785 * and start or stop reading as appropriate. */
1786 static void
1787 set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
1788 int block)
1790 edge_connection_t *edge = NULL;
1791 if (circ->n_conn == orconn) {
1792 circ->streams_blocked_on_n_conn = block;
1793 if (CIRCUIT_IS_ORIGIN(circ))
1794 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
1795 } else {
1796 circ->streams_blocked_on_p_conn = block;
1797 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1798 edge = TO_OR_CIRCUIT(circ)->n_streams;
1801 for (; edge; edge = edge->next_stream) {
1802 connection_t *conn = TO_CONN(edge);
1803 conn->edge_blocked_on_circ = block;
1805 if (block) {
1806 if (connection_is_reading(conn))
1807 connection_stop_reading(conn);
1808 } else {
1809 /* Is this right? */
1810 if (!connection_is_reading(conn))
1811 connection_start_reading(conn);
1816 /** Pull as many cells as possible (but no more than <b>max</b>) from the
1817 * queue of the first active circuit on <b>conn</b>, and write then to
1818 * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
1819 * the active circuit pointer to the next active circuit in the ring. */
1821 connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max)
1823 int n_flushed;
1824 cell_queue_t *queue;
1825 circuit_t *circ;
1826 int streams_blocked;
1827 circ = conn->active_circuits;
1828 if (!circ) return 0;
1829 assert_active_circuits_ok_paranoid(conn);
1830 if (circ->n_conn == conn) {
1831 queue = &circ->n_conn_cells;
1832 streams_blocked = circ->streams_blocked_on_n_conn;
1833 } else {
1834 queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
1835 streams_blocked = circ->streams_blocked_on_p_conn;
1837 tor_assert(*next_circ_on_conn_p(circ,conn));
1839 for (n_flushed = 0; n_flushed < max && queue->head; ) {
1840 packed_cell_t *cell = cell_queue_pop(queue);
1841 tor_assert(*next_circ_on_conn_p(circ,conn));
1843 connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
1845 packed_cell_free(cell);
1846 ++n_flushed;
1847 if (circ != conn->active_circuits) {
1848 /* If this happens, the current circuit just got made inactive by
1849 * a call in connection_write_to_buf(). That's nothing to worry about:
1850 * circuit_make_inactive_on_conn() already advanced conn->active_circuits
1851 * for us.
1853 assert_active_circuits_ok_paranoid(conn);
1854 return n_flushed;
1857 tor_assert(*next_circ_on_conn_p(circ,conn));
1858 assert_active_circuits_ok_paranoid(conn);
1859 conn->active_circuits = *next_circ_on_conn_p(circ, conn);
1861 /* Is the cell queue low enough to unblock all the streams that are waiting
1862 * to write to this circuit? */
1863 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
1864 set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
1866 /* Did we just ran out of cells on this queue? */
1867 if (queue->n == 0) {
1868 log_debug(LD_GENERAL, "Made a circuit inactive.");
1869 make_circuit_inactive_on_conn(circ, conn);
1871 return n_flushed;
1874 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
1875 * transmitting in <b>direction</b>. */
1876 void
1877 append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
1878 cell_t *cell, int direction)
1880 cell_queue_t *queue;
1881 int streams_blocked;
1882 if (direction == CELL_DIRECTION_OUT) {
1883 queue = &circ->n_conn_cells;
1884 streams_blocked = circ->streams_blocked_on_n_conn;
1885 } else {
1886 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1887 queue = &orcirc->p_conn_cells;
1888 streams_blocked = circ->streams_blocked_on_p_conn;
1890 if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
1891 /* V1 connections don't understand RELAY_EARLY. */
1892 cell->command = CELL_RELAY;
1895 cell_queue_append_packed_copy(queue, cell);
1897 /* If we have too many cells on the circuit, we should stop reading from
1898 * the edge streams for a while. */
1899 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
1900 set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
1902 if (queue->n == 1) {
1903 /* This was the first cell added to the queue. We need to make this
1904 * circuit active. */
1905 log_debug(LD_GENERAL, "Made a circuit active.");
1906 make_circuit_active_on_conn(circ, orconn);
1909 if (! buf_datalen(orconn->_base.outbuf)) {
1910 /* There is no data at all waiting to be sent on the outbuf. Add a
1911 * cell, so that we can notice when it gets flushed, flushed_some can
1912 * get called, and we can start putting more data onto the buffer then.
1914 log_debug(LD_GENERAL, "Primed a buffer.");
1915 connection_or_flush_from_first_active_circuit(orconn, 1);
1919 /** Fail with an assert if the active circuits ring on <b>orconn</b> is
1920 * corrupt. */
1921 void
1922 assert_active_circuits_ok(or_connection_t *orconn)
1924 circuit_t *head = orconn->active_circuits;
1925 circuit_t *cur = head;
1926 if (! head)
1927 return;
1928 do {
1929 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1930 circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
1931 tor_assert(next);
1932 tor_assert(prev);
1933 tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
1934 tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
1935 cur = next;
1936 } while (cur != head);