Fix relay_command_to_string(); solve 12700.
[tor.git] / src / or / relay.c
blobfffd45d52206f60d3ba1bded027a3a45906206d0
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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file relay.c
9 * \brief Handle relay cell encryption/decryption, plus packaging and
10 * receiving from circuits, plus queuing on circuits.
11 **/
13 #define RELAY_PRIVATE
14 #include "or.h"
15 #include "addressmap.h"
16 #include "buffers.h"
17 #include "channel.h"
18 #include "circuitbuild.h"
19 #include "circuitlist.h"
20 #include "circuituse.h"
21 #include "config.h"
22 #include "connection.h"
23 #include "connection_edge.h"
24 #include "connection_or.h"
25 #include "control.h"
26 #include "geoip.h"
27 #include "main.h"
28 #include "mempool.h"
29 #include "networkstatus.h"
30 #include "nodelist.h"
31 #include "onion.h"
32 #include "policies.h"
33 #include "reasons.h"
34 #include "relay.h"
35 #include "rendcommon.h"
36 #include "router.h"
37 #include "routerlist.h"
38 #include "routerparse.h"
40 static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
41 cell_direction_t cell_direction,
42 crypt_path_t *layer_hint);
44 static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
45 edge_connection_t *conn,
46 crypt_path_t *layer_hint);
47 static void circuit_consider_sending_sendme(circuit_t *circ,
48 crypt_path_t *layer_hint);
49 static void circuit_resume_edge_reading(circuit_t *circ,
50 crypt_path_t *layer_hint);
51 static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
52 circuit_t *circ,
53 crypt_path_t *layer_hint);
54 static int circuit_consider_stop_edge_reading(circuit_t *circ,
55 crypt_path_t *layer_hint);
56 static int circuit_queue_streams_are_blocked(circuit_t *circ);
57 static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
58 entry_connection_t *conn,
59 node_t *node,
60 const tor_addr_t *addr);
62 /** Stop reading on edge connections when we have this many cells
63 * waiting on the appropriate queue. */
64 #define CELL_QUEUE_HIGHWATER_SIZE 256
65 /** Start reading from edge connections again when we get down to this many
66 * cells. */
67 #define CELL_QUEUE_LOWWATER_SIZE 64
69 /** Stats: how many relay cells have originated at this hop, or have
70 * been relayed onward (not recognized at this hop)?
72 uint64_t stats_n_relay_cells_relayed = 0;
73 /** Stats: how many relay cells have been delivered to streams at this
74 * hop?
76 uint64_t stats_n_relay_cells_delivered = 0;
78 /** Used to tell which stream to read from first on a circuit. */
79 static tor_weak_rng_t stream_choice_rng = TOR_WEAK_RNG_INIT;
81 /** Update digest from the payload of cell. Assign integrity part to
82 * cell.
84 static void
85 relay_set_digest(crypto_digest_t *digest, cell_t *cell)
87 char integrity[4];
88 relay_header_t rh;
90 crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
91 crypto_digest_get_digest(digest, integrity, 4);
92 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
93 // integrity[0], integrity[1], integrity[2], integrity[3]);
94 relay_header_unpack(&rh, cell->payload);
95 memcpy(rh.integrity, integrity, 4);
96 relay_header_pack(cell->payload, &rh);
99 /** Does the digest for this circuit indicate that this cell is for us?
101 * Update digest from the payload of cell (with the integrity part set
102 * to 0). If the integrity part is valid, return 1, else restore digest
103 * and cell to their original state and return 0.
105 static int
106 relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
108 char received_integrity[4], calculated_integrity[4];
109 relay_header_t rh;
110 crypto_digest_t *backup_digest=NULL;
112 backup_digest = crypto_digest_dup(digest);
114 relay_header_unpack(&rh, cell->payload);
115 memcpy(received_integrity, rh.integrity, 4);
116 memset(rh.integrity, 0, 4);
117 relay_header_pack(cell->payload, &rh);
119 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
120 // received_integrity[0], received_integrity[1],
121 // received_integrity[2], received_integrity[3]);
123 crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
124 crypto_digest_get_digest(digest, calculated_integrity, 4);
126 if (tor_memneq(received_integrity, calculated_integrity, 4)) {
127 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
128 // (%d vs %d).", received_integrity, calculated_integrity);
129 /* restore digest to its old form */
130 crypto_digest_assign(digest, backup_digest);
131 /* restore the relay header */
132 memcpy(rh.integrity, received_integrity, 4);
133 relay_header_pack(cell->payload, &rh);
134 crypto_digest_free(backup_digest);
135 return 0;
137 crypto_digest_free(backup_digest);
138 return 1;
141 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
142 * (in place).
144 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
146 * Return -1 if the crypto fails, else return 0.
148 static int
149 relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
150 int encrypt_mode)
152 int r;
153 (void)encrypt_mode;
154 r = crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
156 if (r) {
157 log_warn(LD_BUG,"Error during relay encryption");
158 return -1;
160 return 0;
163 /** Receive a relay cell:
164 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
165 * origin; decrypt if we're headed toward the exit).
166 * - Check if recognized (if exitward).
167 * - If recognized and the digest checks out, then find if there's a stream
168 * that the cell is intended for, and deliver it to the right
169 * connection_edge.
170 * - If not recognized, then we need to relay it: append it to the appropriate
171 * cell_queue on <b>circ</b>.
173 * Return -<b>reason</b> on failure.
176 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
177 cell_direction_t cell_direction)
179 channel_t *chan = NULL;
180 crypt_path_t *layer_hint=NULL;
181 char recognized=0;
182 int reason;
184 tor_assert(cell);
185 tor_assert(circ);
186 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
187 cell_direction == CELL_DIRECTION_IN);
188 if (circ->marked_for_close)
189 return 0;
191 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
192 log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
193 return -END_CIRC_REASON_INTERNAL;
196 if (recognized) {
197 edge_connection_t *conn = NULL;
199 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
200 pathbias_check_probe_response(circ, cell);
202 /* We need to drop this cell no matter what to avoid code that expects
203 * a certain purpose (such as the hidserv code). */
204 return 0;
207 conn = relay_lookup_conn(circ, cell, cell_direction,
208 layer_hint);
209 if (cell_direction == CELL_DIRECTION_OUT) {
210 ++stats_n_relay_cells_delivered;
211 log_debug(LD_OR,"Sending away from origin.");
212 if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
213 < 0) {
214 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
215 "connection_edge_process_relay_cell (away from origin) "
216 "failed.");
217 return reason;
220 if (cell_direction == CELL_DIRECTION_IN) {
221 ++stats_n_relay_cells_delivered;
222 log_debug(LD_OR,"Sending to origin.");
223 if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
224 layer_hint)) < 0) {
225 log_warn(LD_OR,
226 "connection_edge_process_relay_cell (at origin) failed.");
227 return reason;
230 return 0;
233 /* not recognized. pass it on. */
234 if (cell_direction == CELL_DIRECTION_OUT) {
235 cell->circ_id = circ->n_circ_id; /* switch it */
236 chan = circ->n_chan;
237 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
238 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
239 chan = TO_OR_CIRCUIT(circ)->p_chan;
240 } else {
241 log_fn(LOG_PROTOCOL_WARN, LD_OR,
242 "Dropping unrecognized inbound cell on origin circuit.");
243 /* If we see unrecognized cells on path bias testing circs,
244 * it's bad mojo. Those circuits need to die.
245 * XXX: Shouldn't they always die? */
246 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
247 TO_ORIGIN_CIRCUIT(circ)->path_state = PATH_STATE_USE_FAILED;
248 return -END_CIRC_REASON_TORPROTOCOL;
249 } else {
250 return 0;
254 if (!chan) {
255 // XXXX Can this splice stuff be done more cleanly?
256 if (! CIRCUIT_IS_ORIGIN(circ) &&
257 TO_OR_CIRCUIT(circ)->rend_splice &&
258 cell_direction == CELL_DIRECTION_OUT) {
259 or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
260 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
261 tor_assert(splice->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
262 cell->circ_id = splice->p_circ_id;
263 cell->command = CELL_RELAY; /* can't be relay_early anyway */
264 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
265 CELL_DIRECTION_IN)) < 0) {
266 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
267 "circuits");
268 /* XXXX Do this here, or just return -1? */
269 circuit_mark_for_close(circ, -reason);
270 return reason;
272 return 0;
274 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
275 "Didn't recognize cell, but circ stops here! Closing circ.");
276 return -END_CIRC_REASON_TORPROTOCOL;
279 log_debug(LD_OR,"Passing on unrecognized cell.");
281 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
282 * we might kill the circ before we relay
283 * the cells. */
285 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
286 return 0;
289 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
290 * <b>circ</b> in direction <b>cell_direction</b>.
292 * If cell_direction == CELL_DIRECTION_IN:
293 * - If we're at the origin (we're the OP), for hops 1..N,
294 * decrypt cell. If recognized, stop.
295 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
297 * If cell_direction == CELL_DIRECTION_OUT:
298 * - decrypt one hop. Check if recognized.
300 * If cell is recognized, set *recognized to 1, and set
301 * *layer_hint to the hop that recognized it.
303 * Return -1 to indicate that we should mark the circuit for close,
304 * else return 0.
307 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
308 crypt_path_t **layer_hint, char *recognized)
310 relay_header_t rh;
312 tor_assert(circ);
313 tor_assert(cell);
314 tor_assert(recognized);
315 tor_assert(cell_direction == CELL_DIRECTION_IN ||
316 cell_direction == CELL_DIRECTION_OUT);
318 if (cell_direction == CELL_DIRECTION_IN) {
319 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
320 * We'll want to do layered decrypts. */
321 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
322 thishop = cpath;
323 if (thishop->state != CPATH_STATE_OPEN) {
324 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
325 "Relay cell before first created cell? Closing.");
326 return -1;
328 do { /* Remember: cpath is in forward order, that is, first hop first. */
329 tor_assert(thishop);
331 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
332 return -1;
334 relay_header_unpack(&rh, cell->payload);
335 if (rh.recognized == 0) {
336 /* it's possibly recognized. have to check digest to be sure. */
337 if (relay_digest_matches(thishop->b_digest, cell)) {
338 *recognized = 1;
339 *layer_hint = thishop;
340 return 0;
344 thishop = thishop->next;
345 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
346 log_fn(LOG_PROTOCOL_WARN, LD_OR,
347 "Incoming cell at client not recognized. Closing.");
348 return -1;
349 } else { /* we're in the middle. Just one crypt. */
350 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
351 cell->payload, 1) < 0)
352 return -1;
353 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
354 // "the client.");
356 } else /* cell_direction == CELL_DIRECTION_OUT */ {
357 /* we're in the middle. Just one crypt. */
359 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
360 cell->payload, 0) < 0)
361 return -1;
363 relay_header_unpack(&rh, cell->payload);
364 if (rh.recognized == 0) {
365 /* it's possibly recognized. have to check digest to be sure. */
366 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
367 *recognized = 1;
368 return 0;
372 return 0;
375 /** Package a relay cell from an edge:
376 * - Encrypt it to the right layer
377 * - Append it to the appropriate cell_queue on <b>circ</b>.
379 static int
380 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
381 cell_direction_t cell_direction,
382 crypt_path_t *layer_hint, streamid_t on_stream,
383 const char *filename, int lineno)
385 channel_t *chan; /* where to send the cell */
387 if (cell_direction == CELL_DIRECTION_OUT) {
388 crypt_path_t *thishop; /* counter for repeated crypts */
389 chan = circ->n_chan;
390 if (!chan) {
391 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d has n_chan==NULL."
392 " Dropping.", filename, lineno);
393 return 0; /* just drop it */
395 if (!CIRCUIT_IS_ORIGIN(circ)) {
396 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d on non-origin "
397 "circ. Dropping.", filename, lineno);
398 return 0; /* just drop it */
401 relay_set_digest(layer_hint->f_digest, cell);
403 thishop = layer_hint;
404 /* moving from farthest to nearest hop */
405 do {
406 tor_assert(thishop);
407 /* XXXX RD This is a bug, right? */
408 log_debug(LD_OR,"crypting a layer of the relay cell.");
409 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
410 return -1;
413 thishop = thishop->prev;
414 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
416 } else { /* incoming cell */
417 or_circuit_t *or_circ;
418 if (CIRCUIT_IS_ORIGIN(circ)) {
419 /* We should never package an _incoming_ cell from the circuit
420 * origin; that means we messed up somewhere. */
421 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
422 assert_circuit_ok(circ);
423 return 0; /* just drop it */
425 or_circ = TO_OR_CIRCUIT(circ);
426 chan = or_circ->p_chan;
427 relay_set_digest(or_circ->p_digest, cell);
428 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
429 return -1;
431 ++stats_n_relay_cells_relayed;
433 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
434 return 0;
437 /** If cell's stream_id matches the stream_id of any conn that's
438 * attached to circ, return that conn, else return NULL.
440 static edge_connection_t *
441 relay_lookup_conn(circuit_t *circ, cell_t *cell,
442 cell_direction_t cell_direction, crypt_path_t *layer_hint)
444 edge_connection_t *tmpconn;
445 relay_header_t rh;
447 relay_header_unpack(&rh, cell->payload);
449 if (!rh.stream_id)
450 return NULL;
452 /* IN or OUT cells could have come from either direction, now
453 * that we allow rendezvous *to* an OP.
456 if (CIRCUIT_IS_ORIGIN(circ)) {
457 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
458 tmpconn=tmpconn->next_stream) {
459 if (rh.stream_id == tmpconn->stream_id &&
460 !tmpconn->base_.marked_for_close &&
461 tmpconn->cpath_layer == layer_hint) {
462 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
463 return tmpconn;
466 } else {
467 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
468 tmpconn=tmpconn->next_stream) {
469 if (rh.stream_id == tmpconn->stream_id &&
470 !tmpconn->base_.marked_for_close) {
471 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
472 if (cell_direction == CELL_DIRECTION_OUT ||
473 connection_edge_is_rendezvous_stream(tmpconn))
474 return tmpconn;
477 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
478 tmpconn=tmpconn->next_stream) {
479 if (rh.stream_id == tmpconn->stream_id &&
480 !tmpconn->base_.marked_for_close) {
481 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
482 return tmpconn;
486 return NULL; /* probably a begin relay cell */
489 /** Pack the relay_header_t host-order structure <b>src</b> into
490 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
491 * about the wire format.
493 void
494 relay_header_pack(uint8_t *dest, const relay_header_t *src)
496 set_uint8(dest, src->command);
497 set_uint16(dest+1, htons(src->recognized));
498 set_uint16(dest+3, htons(src->stream_id));
499 memcpy(dest+5, src->integrity, 4);
500 set_uint16(dest+9, htons(src->length));
503 /** Unpack the network-order buffer <b>src</b> into a host-order
504 * relay_header_t structure <b>dest</b>.
506 void
507 relay_header_unpack(relay_header_t *dest, const uint8_t *src)
509 dest->command = get_uint8(src);
510 dest->recognized = ntohs(get_uint16(src+1));
511 dest->stream_id = ntohs(get_uint16(src+3));
512 memcpy(dest->integrity, src+5, 4);
513 dest->length = ntohs(get_uint16(src+9));
516 /** Convert the relay <b>command</b> into a human-readable string. */
517 static const char *
518 relay_command_to_string(uint8_t command)
520 static char buf[64];
521 switch (command) {
522 case RELAY_COMMAND_BEGIN: return "BEGIN";
523 case RELAY_COMMAND_DATA: return "DATA";
524 case RELAY_COMMAND_END: return "END";
525 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
526 case RELAY_COMMAND_SENDME: return "SENDME";
527 case RELAY_COMMAND_EXTEND: return "EXTEND";
528 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
529 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
530 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
531 case RELAY_COMMAND_DROP: return "DROP";
532 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
533 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
534 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
535 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
536 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
537 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
538 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
539 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
540 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
541 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
542 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
543 return "RENDEZVOUS_ESTABLISHED";
544 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
545 case RELAY_COMMAND_EXTEND2: return "EXTEND2";
546 case RELAY_COMMAND_EXTENDED2: return "EXTENDED2";
547 default:
548 tor_snprintf(buf, sizeof(buf), "Unrecognized relay command %u",
549 (unsigned)command);
550 return buf;
554 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
555 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
556 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
557 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
558 * destination hop for OP->OR cells.
560 * If you can't send the cell, mark the circuit for close and return -1. Else
561 * return 0.
564 relay_send_command_from_edge_(streamid_t stream_id, circuit_t *circ,
565 uint8_t relay_command, const char *payload,
566 size_t payload_len, crypt_path_t *cpath_layer,
567 const char *filename, int lineno)
569 cell_t cell;
570 relay_header_t rh;
571 cell_direction_t cell_direction;
572 /* XXXX NM Split this function into a separate versions per circuit type? */
574 tor_assert(circ);
575 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
577 memset(&cell, 0, sizeof(cell_t));
578 cell.command = CELL_RELAY;
579 if (cpath_layer) {
580 cell.circ_id = circ->n_circ_id;
581 cell_direction = CELL_DIRECTION_OUT;
582 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
583 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
584 cell_direction = CELL_DIRECTION_IN;
585 } else {
586 return -1;
589 memset(&rh, 0, sizeof(rh));
590 rh.command = relay_command;
591 rh.stream_id = stream_id;
592 rh.length = payload_len;
593 relay_header_pack(cell.payload, &rh);
594 if (payload_len)
595 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
597 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
598 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
600 /* If we are sending an END cell and this circuit is used for a tunneled
601 * directory request, advance its state. */
602 if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
603 geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
604 DIRREQ_END_CELL_SENT);
606 if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
607 /* if we're using relaybandwidthrate, this conn wants priority */
608 channel_timestamp_client(circ->n_chan);
611 if (cell_direction == CELL_DIRECTION_OUT) {
612 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
613 if (origin_circ->remaining_relay_early_cells > 0 &&
614 (relay_command == RELAY_COMMAND_EXTEND ||
615 relay_command == RELAY_COMMAND_EXTEND2 ||
616 cpath_layer != origin_circ->cpath)) {
617 /* If we've got any relay_early cells left and (we're sending
618 * an extend cell or we're not talking to the first hop), use
619 * one of them. Don't worry about the conn protocol version:
620 * append_cell_to_circuit_queue will fix it up. */
621 cell.command = CELL_RELAY_EARLY;
622 --origin_circ->remaining_relay_early_cells;
623 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
624 (int)origin_circ->remaining_relay_early_cells);
625 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
626 * task 878. */
627 origin_circ->relay_early_commands[
628 origin_circ->relay_early_cells_sent++] = relay_command;
629 } else if (relay_command == RELAY_COMMAND_EXTEND ||
630 relay_command == RELAY_COMMAND_EXTEND2) {
631 /* If no RELAY_EARLY cells can be sent over this circuit, log which
632 * commands have been sent as RELAY_EARLY cells before; helps debug
633 * task 878. */
634 smartlist_t *commands_list = smartlist_new();
635 int i = 0;
636 char *commands = NULL;
637 for (; i < origin_circ->relay_early_cells_sent; i++)
638 smartlist_add(commands_list, (char *)
639 relay_command_to_string(origin_circ->relay_early_commands[i]));
640 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
641 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
642 "but we have run out of RELAY_EARLY cells on that circuit. "
643 "Commands sent before: %s", commands);
644 tor_free(commands);
645 smartlist_free(commands_list);
649 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
650 stream_id, filename, lineno) < 0) {
651 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
652 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
653 return -1;
655 return 0;
658 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
659 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
660 * that's sending the relay cell, or NULL if it's a control cell.
661 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
662 * for OP->OR cells.
664 * If you can't send the cell, mark the circuit for close and
665 * return -1. Else return 0.
668 connection_edge_send_command(edge_connection_t *fromconn,
669 uint8_t relay_command, const char *payload,
670 size_t payload_len)
672 /* XXXX NM Split this function into a separate versions per circuit type? */
673 circuit_t *circ;
674 crypt_path_t *cpath_layer = fromconn->cpath_layer;
675 tor_assert(fromconn);
676 circ = fromconn->on_circuit;
678 if (fromconn->base_.marked_for_close) {
679 log_warn(LD_BUG,
680 "called on conn that's already marked for close at %s:%d.",
681 fromconn->base_.marked_for_close_file,
682 fromconn->base_.marked_for_close);
683 return 0;
686 if (!circ) {
687 if (fromconn->base_.type == CONN_TYPE_AP) {
688 log_info(LD_APP,"no circ. Closing conn.");
689 connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
690 END_STREAM_REASON_INTERNAL);
691 } else {
692 log_info(LD_EXIT,"no circ. Closing conn.");
693 fromconn->edge_has_sent_end = 1; /* no circ to send to */
694 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
695 connection_mark_for_close(TO_CONN(fromconn));
697 return -1;
700 return relay_send_command_from_edge(fromconn->stream_id, circ,
701 relay_command, payload,
702 payload_len, cpath_layer);
705 /** How many times will I retry a stream that fails due to DNS
706 * resolve failure or misc error?
708 #define MAX_RESOLVE_FAILURES 3
710 /** Return 1 if reason is something that you should retry if you
711 * get the end cell before you've connected; else return 0. */
712 static int
713 edge_reason_is_retriable(int reason)
715 return reason == END_STREAM_REASON_HIBERNATING ||
716 reason == END_STREAM_REASON_RESOURCELIMIT ||
717 reason == END_STREAM_REASON_EXITPOLICY ||
718 reason == END_STREAM_REASON_RESOLVEFAILED ||
719 reason == END_STREAM_REASON_MISC ||
720 reason == END_STREAM_REASON_NOROUTE;
723 /** Called when we receive an END cell on a stream that isn't open yet,
724 * from the client side.
725 * Arguments are as for connection_edge_process_relay_cell().
727 static int
728 connection_ap_process_end_not_open(
729 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
730 entry_connection_t *conn, crypt_path_t *layer_hint)
732 node_t *exitrouter;
733 int reason = *(cell->payload+RELAY_HEADER_SIZE);
734 int control_reason;
735 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
736 (void) layer_hint; /* unused */
738 if (rh->length > 0) {
739 if (reason == END_STREAM_REASON_TORPROTOCOL ||
740 reason == END_STREAM_REASON_DESTROY) {
741 /* Both of these reasons could mean a failed tag
742 * hit the exit and it complained. Do not probe.
743 * Fail the circuit. */
744 circ->path_state = PATH_STATE_USE_FAILED;
745 return -END_CIRC_REASON_TORPROTOCOL;
746 } else if (reason == END_STREAM_REASON_INTERNAL) {
747 /* We can't infer success or failure, since older Tors report
748 * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
749 } else {
750 /* Path bias: If we get a valid reason code from the exit,
751 * it wasn't due to tagging.
753 * We rely on recognized+digest being strong enough to make
754 * tags unlikely to allow us to get tagged, yet 'recognized'
755 * reason codes here. */
756 pathbias_mark_use_success(circ);
760 if (rh->length == 0) {
761 reason = END_STREAM_REASON_MISC;
764 control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
766 if (edge_reason_is_retriable(reason) &&
767 /* avoid retry if rend */
768 !connection_edge_is_rendezvous_stream(edge_conn)) {
769 const char *chosen_exit_digest =
770 circ->build_state->chosen_exit->identity_digest;
771 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
772 safe_str(conn->socks_request->address),
773 stream_end_reason_to_string(reason));
774 exitrouter = node_get_mutable_by_id(chosen_exit_digest);
775 switch (reason) {
776 case END_STREAM_REASON_EXITPOLICY: {
777 tor_addr_t addr;
778 tor_addr_make_unspec(&addr);
779 if (rh->length >= 5) {
780 int ttl = -1;
781 tor_addr_make_unspec(&addr);
782 if (rh->length == 5 || rh->length == 9) {
783 tor_addr_from_ipv4n(&addr,
784 get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
785 if (rh->length == 9)
786 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
787 } else if (rh->length == 17 || rh->length == 21) {
788 tor_addr_from_ipv6_bytes(&addr,
789 (char*)(cell->payload+RELAY_HEADER_SIZE+1));
790 if (rh->length == 21)
791 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
793 if (tor_addr_is_null(&addr)) {
794 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
795 safe_str(conn->socks_request->address));
796 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
797 return 0;
800 if ((tor_addr_family(&addr) == AF_INET && !conn->ipv4_traffic_ok) ||
801 (tor_addr_family(&addr) == AF_INET6 && !conn->ipv6_traffic_ok)) {
802 log_fn(LOG_PROTOCOL_WARN, LD_APP,
803 "Got an EXITPOLICY failure on a connection with a "
804 "mismatched family. Closing.");
805 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
806 return 0;
808 if (get_options()->ClientDNSRejectInternalAddresses &&
809 tor_addr_is_internal(&addr, 0)) {
810 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
811 safe_str(conn->socks_request->address));
812 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
813 return 0;
816 client_dns_set_addressmap(conn,
817 conn->socks_request->address, &addr,
818 conn->chosen_exit_name, ttl);
821 char new_addr[TOR_ADDR_BUF_LEN];
822 tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
823 if (strcmp(conn->socks_request->address, new_addr)) {
824 strlcpy(conn->socks_request->address, new_addr,
825 sizeof(conn->socks_request->address));
826 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
830 /* check if he *ought* to have allowed it */
832 adjust_exit_policy_from_exitpolicy_failure(circ,
833 conn,
834 exitrouter,
835 &addr);
837 if (conn->chosen_exit_optional ||
838 conn->chosen_exit_retries) {
839 /* stop wanting a specific exit */
840 conn->chosen_exit_optional = 0;
841 /* A non-zero chosen_exit_retries can happen if we set a
842 * TrackHostExits for this address under a port that the exit
843 * relay allows, but then try the same address with a different
844 * port that it doesn't allow to exit. We shouldn't unregister
845 * the mapping, since it is probably still wanted on the
846 * original port. But now we give away to the exit relay that
847 * we probably have a TrackHostExits on it. So be it. */
848 conn->chosen_exit_retries = 0;
849 tor_free(conn->chosen_exit_name); /* clears it */
851 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
852 return 0;
853 /* else, conn will get closed below */
854 break;
856 case END_STREAM_REASON_CONNECTREFUSED:
857 if (!conn->chosen_exit_optional)
858 break; /* break means it'll close, below */
859 /* Else fall through: expire this circuit, clear the
860 * chosen_exit_name field, and try again. */
861 case END_STREAM_REASON_RESOLVEFAILED:
862 case END_STREAM_REASON_TIMEOUT:
863 case END_STREAM_REASON_MISC:
864 case END_STREAM_REASON_NOROUTE:
865 if (client_dns_incr_failures(conn->socks_request->address)
866 < MAX_RESOLVE_FAILURES) {
867 /* We haven't retried too many times; reattach the connection. */
868 circuit_log_path(LOG_INFO,LD_APP,circ);
869 /* Mark this circuit "unusable for new streams". */
870 mark_circuit_unusable_for_new_conns(circ);
872 if (conn->chosen_exit_optional) {
873 /* stop wanting a specific exit */
874 conn->chosen_exit_optional = 0;
875 tor_free(conn->chosen_exit_name); /* clears it */
877 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
878 return 0;
879 /* else, conn will get closed below */
880 } else {
881 log_notice(LD_APP,
882 "Have tried resolving or connecting to address '%s' "
883 "at %d different places. Giving up.",
884 safe_str(conn->socks_request->address),
885 MAX_RESOLVE_FAILURES);
886 /* clear the failures, so it will have a full try next time */
887 client_dns_clear_failures(conn->socks_request->address);
889 break;
890 case END_STREAM_REASON_HIBERNATING:
891 case END_STREAM_REASON_RESOURCELIMIT:
892 if (exitrouter) {
893 policies_set_node_exitpolicy_to_reject_all(exitrouter);
895 if (conn->chosen_exit_optional) {
896 /* stop wanting a specific exit */
897 conn->chosen_exit_optional = 0;
898 tor_free(conn->chosen_exit_name); /* clears it */
900 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
901 return 0;
902 /* else, will close below */
903 break;
904 } /* end switch */
905 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
908 log_info(LD_APP,
909 "Edge got end (%s) before we're connected. Marking for close.",
910 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
911 circuit_log_path(LOG_INFO,LD_APP,circ);
912 /* need to test because of detach_retriable */
913 if (!ENTRY_TO_CONN(conn)->marked_for_close)
914 connection_mark_unattached_ap(conn, control_reason);
915 return 0;
918 /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
919 * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
920 * told us which address it rejected, then <b>addr</b> is that address;
921 * otherwise it is AF_UNSPEC.
923 * If we are sure the node should have allowed this address, mark the node as
924 * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
925 * for this particular address.
927 static void
928 adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
929 entry_connection_t *conn,
930 node_t *node,
931 const tor_addr_t *addr)
933 int make_reject_all = 0;
934 const sa_family_t family = tor_addr_family(addr);
936 if (node) {
937 tor_addr_t tmp;
938 int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
939 if (family == AF_UNSPEC) {
940 make_reject_all = 1;
941 } else if (node_exit_policy_is_exact(node, family) &&
942 asked_for_family != -1 && !conn->chosen_exit_name) {
943 make_reject_all = 1;
946 if (make_reject_all) {
947 log_info(LD_APP,
948 "Exitrouter %s seems to be more restrictive than its exit "
949 "policy. Not using this router as exit for now.",
950 node_describe(node));
951 policies_set_node_exitpolicy_to_reject_all(node);
955 if (family != AF_UNSPEC)
956 addr_policy_append_reject_addr(&circ->prepend_policy, addr);
959 /** Helper: change the socks_request-&gt;address field on conn to the
960 * dotted-quad representation of <b>new_addr</b>,
961 * and send an appropriate REMAP event. */
962 static void
963 remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
965 tor_addr_to_str(conn->socks_request->address, new_addr,
966 sizeof(conn->socks_request->address),
968 control_event_stream_status(conn, STREAM_EVENT_REMAP,
969 REMAP_STREAM_SOURCE_EXIT);
972 /** Extract the contents of a connected cell in <b>cell</b>, whose relay
973 * header has already been parsed into <b>rh</b>. On success, set
974 * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
975 * the ttl of that address, in seconds, and return 0. On failure, return
976 * -1. */
978 connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
979 tor_addr_t *addr_out, int *ttl_out)
981 uint32_t bytes;
982 const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
984 tor_addr_make_unspec(addr_out);
985 *ttl_out = -1;
986 if (rh->length == 0)
987 return 0;
988 if (rh->length < 4)
989 return -1;
990 bytes = ntohl(get_uint32(payload));
992 /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
993 if (bytes != 0) {
994 /* v4 address */
995 tor_addr_from_ipv4h(addr_out, bytes);
996 if (rh->length >= 8) {
997 bytes = ntohl(get_uint32(payload + 4));
998 if (bytes <= INT32_MAX)
999 *ttl_out = bytes;
1001 } else {
1002 if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
1003 return -1;
1004 if (get_uint8(payload + 4) != 6)
1005 return -1;
1006 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
1007 bytes = ntohl(get_uint32(payload + 21));
1008 if (bytes <= INT32_MAX)
1009 *ttl_out = (int) bytes;
1011 return 0;
1014 /** An incoming relay cell has arrived from circuit <b>circ</b> to
1015 * stream <b>conn</b>.
1017 * The arguments here are the same as in
1018 * connection_edge_process_relay_cell() below; this function is called
1019 * from there when <b>conn</b> is defined and not in an open state.
1021 static int
1022 connection_edge_process_relay_cell_not_open(
1023 relay_header_t *rh, cell_t *cell, circuit_t *circ,
1024 edge_connection_t *conn, crypt_path_t *layer_hint)
1026 if (rh->command == RELAY_COMMAND_END) {
1027 if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
1028 return connection_ap_process_end_not_open(rh, cell,
1029 TO_ORIGIN_CIRCUIT(circ),
1030 EDGE_TO_ENTRY_CONN(conn),
1031 layer_hint);
1032 } else {
1033 /* we just got an 'end', don't need to send one */
1034 conn->edge_has_sent_end = 1;
1035 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
1036 END_STREAM_REASON_FLAG_REMOTE;
1037 connection_mark_for_close(TO_CONN(conn));
1038 return 0;
1042 if (conn->base_.type == CONN_TYPE_AP &&
1043 rh->command == RELAY_COMMAND_CONNECTED) {
1044 tor_addr_t addr;
1045 int ttl;
1046 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1047 tor_assert(CIRCUIT_IS_ORIGIN(circ));
1048 if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
1049 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1050 "Got 'connected' while not in state connect_wait. Dropping.");
1051 return 0;
1053 conn->base_.state = AP_CONN_STATE_OPEN;
1054 log_info(LD_APP,"'connected' received after %d seconds.",
1055 (int)(time(NULL) - conn->base_.timestamp_lastread));
1056 if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
1057 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1058 "Got a badly formatted connected cell. Closing.");
1059 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1060 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1062 if (tor_addr_family(&addr) != AF_UNSPEC) {
1063 const sa_family_t family = tor_addr_family(&addr);
1064 if (tor_addr_is_null(&addr) ||
1065 (get_options()->ClientDNSRejectInternalAddresses &&
1066 tor_addr_is_internal(&addr, 0))) {
1067 log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
1068 fmt_addr(&addr));
1069 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1070 connection_mark_unattached_ap(entry_conn,
1071 END_STREAM_REASON_TORPROTOCOL);
1072 return 0;
1075 if ((family == AF_INET && ! entry_conn->ipv4_traffic_ok) ||
1076 (family == AF_INET6 && ! entry_conn->ipv6_traffic_ok)) {
1077 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1078 "Got a connected cell to %s with unsupported address family."
1079 " Closing.", fmt_addr(&addr));
1080 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1081 connection_mark_unattached_ap(entry_conn,
1082 END_STREAM_REASON_TORPROTOCOL);
1083 return 0;
1086 client_dns_set_addressmap(entry_conn,
1087 entry_conn->socks_request->address, &addr,
1088 entry_conn->chosen_exit_name, ttl);
1090 remap_event_helper(entry_conn, &addr);
1092 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
1093 /* don't send a socks reply to transparent conns */
1094 tor_assert(entry_conn->socks_request != NULL);
1095 if (!entry_conn->socks_request->has_finished)
1096 connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
1098 /* Was it a linked dir conn? If so, a dir request just started to
1099 * fetch something; this could be a bootstrap status milestone. */
1100 log_debug(LD_APP, "considering");
1101 if (TO_CONN(conn)->linked_conn &&
1102 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
1103 connection_t *dirconn = TO_CONN(conn)->linked_conn;
1104 log_debug(LD_APP, "it is! %d", dirconn->purpose);
1105 switch (dirconn->purpose) {
1106 case DIR_PURPOSE_FETCH_CERTIFICATE:
1107 if (consensus_is_waiting_for_certs())
1108 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
1109 break;
1110 case DIR_PURPOSE_FETCH_CONSENSUS:
1111 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
1112 break;
1113 case DIR_PURPOSE_FETCH_SERVERDESC:
1114 case DIR_PURPOSE_FETCH_MICRODESC:
1115 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
1116 count_loading_descriptors_progress());
1117 break;
1120 /* This is definitely a success, so forget about any pending data we
1121 * had sent. */
1122 if (entry_conn->pending_optimistic_data) {
1123 generic_buffer_free(entry_conn->pending_optimistic_data);
1124 entry_conn->pending_optimistic_data = NULL;
1127 /* handle anything that might have queued */
1128 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1129 /* (We already sent an end cell if possible) */
1130 connection_mark_for_close(TO_CONN(conn));
1131 return 0;
1133 return 0;
1135 if (conn->base_.type == CONN_TYPE_AP &&
1136 rh->command == RELAY_COMMAND_RESOLVED) {
1137 int ttl;
1138 int answer_len;
1139 uint8_t answer_type;
1140 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1141 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
1142 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
1143 "not in state resolve_wait. Dropping.");
1144 return 0;
1146 tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
1147 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
1148 if (rh->length < 2 || answer_len+2>rh->length) {
1149 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1150 "Dropping malformed 'resolved' cell");
1151 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1152 return 0;
1154 answer_type = cell->payload[RELAY_HEADER_SIZE];
1155 if (rh->length >= answer_len+6)
1156 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
1157 2+answer_len));
1158 else
1159 ttl = -1;
1160 if (answer_type == RESOLVED_TYPE_IPV4 ||
1161 answer_type == RESOLVED_TYPE_IPV6) {
1162 tor_addr_t addr;
1163 if (decode_address_from_payload(&addr, cell->payload+RELAY_HEADER_SIZE,
1164 rh->length) &&
1165 tor_addr_is_internal(&addr, 0) &&
1166 get_options()->ClientDNSRejectInternalAddresses) {
1167 log_info(LD_APP,"Got a resolve with answer %s. Rejecting.",
1168 fmt_addr(&addr));
1169 connection_ap_handshake_socks_resolved(entry_conn,
1170 RESOLVED_TYPE_ERROR_TRANSIENT,
1171 0, NULL, 0, TIME_MAX);
1172 connection_mark_unattached_ap(entry_conn,
1173 END_STREAM_REASON_TORPROTOCOL);
1174 return 0;
1177 connection_ap_handshake_socks_resolved(entry_conn,
1178 answer_type,
1179 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
1180 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
1181 ttl,
1182 -1);
1183 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1184 tor_addr_t addr;
1185 tor_addr_from_ipv4n(&addr,
1186 get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
1187 remap_event_helper(entry_conn, &addr);
1188 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
1189 tor_addr_t addr;
1190 tor_addr_from_ipv6_bytes(&addr,
1191 (char*)(cell->payload+RELAY_HEADER_SIZE+2));
1192 remap_event_helper(entry_conn, &addr);
1194 connection_mark_unattached_ap(entry_conn,
1195 END_STREAM_REASON_DONE |
1196 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1197 return 0;
1200 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1201 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
1202 rh->command, conn->base_.state,
1203 conn_state_to_string(conn->base_.type, conn->base_.state));
1204 return 0; /* for forward compatibility, don't kill the circuit */
1205 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1206 // connection_mark_for_close(conn);
1207 // return -1;
1210 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
1211 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
1212 * destined for <b>conn</b>.
1214 * If <b>layer_hint</b> is defined, then we're the origin of the
1215 * circuit, and it specifies the hop that packaged <b>cell</b>.
1217 * Return -reason if you want to warn and tear down the circuit, else 0.
1219 static int
1220 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
1221 edge_connection_t *conn,
1222 crypt_path_t *layer_hint)
1224 static int num_seen=0;
1225 relay_header_t rh;
1226 unsigned domain = layer_hint?LD_APP:LD_EXIT;
1227 int reason;
1228 int optimistic_data = 0; /* Set to 1 if we receive data on a stream
1229 * that's in the EXIT_CONN_STATE_RESOLVING
1230 * or EXIT_CONN_STATE_CONNECTING states. */
1232 tor_assert(cell);
1233 tor_assert(circ);
1235 relay_header_unpack(&rh, cell->payload);
1236 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1237 num_seen++;
1238 log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
1239 num_seen, rh.command, rh.stream_id);
1241 if (rh.length > RELAY_PAYLOAD_SIZE) {
1242 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1243 "Relay cell length field too long. Closing circuit.");
1244 return - END_CIRC_REASON_TORPROTOCOL;
1247 if (rh.stream_id == 0) {
1248 switch (rh.command) {
1249 case RELAY_COMMAND_BEGIN:
1250 case RELAY_COMMAND_CONNECTED:
1251 case RELAY_COMMAND_DATA:
1252 case RELAY_COMMAND_END:
1253 case RELAY_COMMAND_RESOLVE:
1254 case RELAY_COMMAND_RESOLVED:
1255 case RELAY_COMMAND_BEGIN_DIR:
1256 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
1257 "stream_id. Dropping.", (int)rh.command);
1258 return 0;
1259 default:
1264 /* either conn is NULL, in which case we've got a control cell, or else
1265 * conn points to the recognized stream. */
1267 if (conn && !connection_state_is_open(TO_CONN(conn))) {
1268 if (conn->base_.type == CONN_TYPE_EXIT &&
1269 (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
1270 conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
1271 rh.command == RELAY_COMMAND_DATA) {
1272 /* Allow DATA cells to be delivered to an exit node in state
1273 * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
1274 * This speeds up HTTP, for example. */
1275 optimistic_data = 1;
1276 } else {
1277 return connection_edge_process_relay_cell_not_open(
1278 &rh, cell, circ, conn, layer_hint);
1282 switch (rh.command) {
1283 case RELAY_COMMAND_DROP:
1284 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1285 return 0;
1286 case RELAY_COMMAND_BEGIN:
1287 case RELAY_COMMAND_BEGIN_DIR:
1288 if (layer_hint &&
1289 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1290 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1291 "Relay begin request unsupported at AP. Dropping.");
1292 return 0;
1294 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1295 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1296 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1297 "Relay begin request to Hidden Service "
1298 "from intermediary node. Dropping.");
1299 return 0;
1301 if (conn) {
1302 log_fn(LOG_PROTOCOL_WARN, domain,
1303 "Begin cell for known stream. Dropping.");
1304 return 0;
1306 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
1307 /* Assign this circuit and its app-ward OR connection a unique ID,
1308 * so that we can measure download times. The local edge and dir
1309 * connection will be assigned the same ID when they are created
1310 * and linked. */
1311 static uint64_t next_id = 0;
1312 circ->dirreq_id = ++next_id;
1313 TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
1316 return connection_exit_begin_conn(cell, circ);
1317 case RELAY_COMMAND_DATA:
1318 ++stats_n_data_cells_received;
1319 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1320 (!layer_hint && --circ->deliver_window < 0)) {
1321 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1322 "(relay data) circ deliver_window below 0. Killing.");
1323 if (conn) {
1324 /* XXXX Do we actually need to do this? Will killing the circuit
1325 * not send an END and mark the stream for close as appropriate? */
1326 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1327 connection_mark_for_close(TO_CONN(conn));
1329 return -END_CIRC_REASON_TORPROTOCOL;
1331 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1332 layer_hint->deliver_window : circ->deliver_window);
1334 circuit_consider_sending_sendme(circ, layer_hint);
1336 if (!conn) {
1337 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1338 rh.stream_id);
1339 return 0;
1342 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1343 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1344 "(relay data) conn deliver_window below 0. Killing.");
1345 return -END_CIRC_REASON_TORPROTOCOL;
1348 stats_n_data_bytes_received += rh.length;
1349 connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
1350 rh.length, TO_CONN(conn));
1352 if (!optimistic_data) {
1353 /* Only send a SENDME if we're not getting optimistic data; otherwise
1354 * a SENDME could arrive before the CONNECTED.
1356 connection_edge_consider_sending_sendme(conn);
1359 return 0;
1360 case RELAY_COMMAND_END:
1361 reason = rh.length > 0 ?
1362 get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1363 if (!conn) {
1364 log_info(domain,"end cell (%s) dropped, unknown stream.",
1365 stream_end_reason_to_string(reason));
1366 return 0;
1368 /* XXX add to this log_fn the exit node's nickname? */
1369 log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
1370 "Removing stream.",
1371 conn->base_.s,
1372 stream_end_reason_to_string(reason),
1373 conn->stream_id);
1374 if (conn->base_.type == CONN_TYPE_AP) {
1375 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1376 if (entry_conn->socks_request &&
1377 !entry_conn->socks_request->has_finished)
1378 log_warn(LD_BUG,
1379 "open stream hasn't sent socks answer yet? Closing.");
1381 /* We just *got* an end; no reason to send one. */
1382 conn->edge_has_sent_end = 1;
1383 if (!conn->end_reason)
1384 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1385 if (!conn->base_.marked_for_close) {
1386 /* only mark it if not already marked. it's possible to
1387 * get the 'end' right around when the client hangs up on us. */
1388 connection_mark_and_flush(TO_CONN(conn));
1390 return 0;
1391 case RELAY_COMMAND_EXTEND:
1392 case RELAY_COMMAND_EXTEND2: {
1393 static uint64_t total_n_extend=0, total_nonearly=0;
1394 total_n_extend++;
1395 if (rh.stream_id) {
1396 log_fn(LOG_PROTOCOL_WARN, domain,
1397 "'extend' cell received for non-zero stream. Dropping.");
1398 return 0;
1400 if (cell->command != CELL_RELAY_EARLY &&
1401 !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
1402 #define EARLY_WARNING_INTERVAL 3600
1403 static ratelim_t early_warning_limit =
1404 RATELIM_INIT(EARLY_WARNING_INTERVAL);
1405 char *m;
1406 if (cell->command == CELL_RELAY) {
1407 ++total_nonearly;
1408 if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
1409 double percentage = ((double)total_nonearly)/total_n_extend;
1410 percentage *= 100;
1411 log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
1412 "but not via RELAY_EARLY. Dropping.%s", m);
1413 log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
1414 "all EXTEND cells for this reason)", percentage);
1415 tor_free(m);
1417 } else {
1418 log_fn(LOG_WARN, domain,
1419 "EXTEND cell received, in a cell with type %d! Dropping.",
1420 cell->command);
1422 return 0;
1424 return circuit_extend(cell, circ);
1426 case RELAY_COMMAND_EXTENDED:
1427 case RELAY_COMMAND_EXTENDED2:
1428 if (!layer_hint) {
1429 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1430 "'extended' unsupported at non-origin. Dropping.");
1431 return 0;
1433 log_debug(domain,"Got an extended cell! Yay.");
1435 extended_cell_t extended_cell;
1436 if (extended_cell_parse(&extended_cell, rh.command,
1437 (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
1438 rh.length)<0) {
1439 log_warn(LD_PROTOCOL,
1440 "Can't parse EXTENDED cell; killing circuit.");
1441 return -END_CIRC_REASON_TORPROTOCOL;
1443 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1444 &extended_cell.created_cell)) < 0) {
1445 log_warn(domain,"circuit_finish_handshake failed.");
1446 return reason;
1449 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1450 log_info(domain,"circuit_send_next_onion_skin() failed.");
1451 return reason;
1453 return 0;
1454 case RELAY_COMMAND_TRUNCATE:
1455 if (layer_hint) {
1456 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1457 "'truncate' unsupported at origin. Dropping.");
1458 return 0;
1460 if (circ->n_hop) {
1461 if (circ->n_chan)
1462 log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
1463 extend_info_free(circ->n_hop);
1464 circ->n_hop = NULL;
1465 tor_free(circ->n_chan_create_cell);
1466 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
1468 if (circ->n_chan) {
1469 uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
1470 circuit_clear_cell_queue(circ, circ->n_chan);
1471 channel_send_destroy(circ->n_circ_id, circ->n_chan,
1472 trunc_reason);
1473 circuit_set_n_circid_chan(circ, 0, NULL);
1475 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1477 char payload[1];
1478 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1479 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1480 payload, sizeof(payload), NULL);
1482 return 0;
1483 case RELAY_COMMAND_TRUNCATED:
1484 if (!layer_hint) {
1485 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1486 "'truncated' unsupported at non-origin. Dropping.");
1487 return 0;
1489 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
1490 get_uint8(cell->payload + RELAY_HEADER_SIZE));
1491 return 0;
1492 case RELAY_COMMAND_CONNECTED:
1493 if (conn) {
1494 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1495 "'connected' unsupported while open. Closing circ.");
1496 return -END_CIRC_REASON_TORPROTOCOL;
1498 log_info(domain,
1499 "'connected' received, no conn attached anymore. Ignoring.");
1500 return 0;
1501 case RELAY_COMMAND_SENDME:
1502 if (!rh.stream_id) {
1503 if (layer_hint) {
1504 if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
1505 CIRCWINDOW_START_MAX) {
1506 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1507 "Unexpected sendme cell from exit relay. "
1508 "Closing circ.");
1509 return -END_CIRC_REASON_TORPROTOCOL;
1511 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1512 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1513 layer_hint->package_window);
1514 circuit_resume_edge_reading(circ, layer_hint);
1515 } else {
1516 if (circ->package_window + CIRCWINDOW_INCREMENT >
1517 CIRCWINDOW_START_MAX) {
1518 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1519 "Unexpected sendme cell from client. "
1520 "Closing circ (window %d).",
1521 circ->package_window);
1522 return -END_CIRC_REASON_TORPROTOCOL;
1524 circ->package_window += CIRCWINDOW_INCREMENT;
1525 log_debug(LD_APP,
1526 "circ-level sendme at non-origin, packagewindow %d.",
1527 circ->package_window);
1528 circuit_resume_edge_reading(circ, layer_hint);
1530 return 0;
1532 if (!conn) {
1533 log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
1534 rh.stream_id);
1535 return 0;
1537 conn->package_window += STREAMWINDOW_INCREMENT;
1538 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1539 conn->package_window);
1540 if (circuit_queue_streams_are_blocked(circ)) {
1541 /* Still waiting for queue to flush; don't touch conn */
1542 return 0;
1544 connection_start_reading(TO_CONN(conn));
1545 /* handle whatever might still be on the inbuf */
1546 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1547 /* (We already sent an end cell if possible) */
1548 connection_mark_for_close(TO_CONN(conn));
1549 return 0;
1551 return 0;
1552 case RELAY_COMMAND_RESOLVE:
1553 if (layer_hint) {
1554 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1555 "resolve request unsupported at AP; dropping.");
1556 return 0;
1557 } else if (conn) {
1558 log_fn(LOG_PROTOCOL_WARN, domain,
1559 "resolve request for known stream; dropping.");
1560 return 0;
1561 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1562 log_fn(LOG_PROTOCOL_WARN, domain,
1563 "resolve request on circ with purpose %d; dropping",
1564 circ->purpose);
1565 return 0;
1567 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1568 return 0;
1569 case RELAY_COMMAND_RESOLVED:
1570 if (conn) {
1571 log_fn(LOG_PROTOCOL_WARN, domain,
1572 "'resolved' unsupported while open. Closing circ.");
1573 return -END_CIRC_REASON_TORPROTOCOL;
1575 log_info(domain,
1576 "'resolved' received, no conn attached anymore. Ignoring.");
1577 return 0;
1578 case RELAY_COMMAND_ESTABLISH_INTRO:
1579 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1580 case RELAY_COMMAND_INTRODUCE1:
1581 case RELAY_COMMAND_INTRODUCE2:
1582 case RELAY_COMMAND_INTRODUCE_ACK:
1583 case RELAY_COMMAND_RENDEZVOUS1:
1584 case RELAY_COMMAND_RENDEZVOUS2:
1585 case RELAY_COMMAND_INTRO_ESTABLISHED:
1586 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1587 rend_process_relay_cell(circ, layer_hint,
1588 rh.command, rh.length,
1589 cell->payload+RELAY_HEADER_SIZE);
1590 return 0;
1592 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1593 "Received unknown relay command %d. Perhaps the other side is using "
1594 "a newer version of Tor? Dropping.",
1595 rh.command);
1596 return 0; /* for forward compatibility, don't kill the circuit */
1599 /** How many relay_data cells have we built, ever? */
1600 uint64_t stats_n_data_cells_packaged = 0;
1601 /** How many bytes of data have we put in relay_data cells have we built,
1602 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1603 * every relay cell we ever sent were completely full of data. */
1604 uint64_t stats_n_data_bytes_packaged = 0;
1605 /** How many relay_data cells have we received, ever? */
1606 uint64_t stats_n_data_cells_received = 0;
1607 /** How many bytes of data have we received relay_data cells, ever? This would
1608 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1609 * ever received were completely full of data. */
1610 uint64_t stats_n_data_bytes_received = 0;
1612 /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
1613 * <b>package_partial</b> is true), and the appropriate package windows aren't
1614 * empty, grab a cell and send it down the circuit.
1616 * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
1617 * *<b>max_cells</b> by the number of cells packaged.
1619 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1620 * be marked for close, else return 0.
1623 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
1624 int *max_cells)
1626 size_t bytes_to_process, length;
1627 char payload[CELL_PAYLOAD_SIZE];
1628 circuit_t *circ;
1629 const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
1630 int sending_from_optimistic = 0;
1631 entry_connection_t *entry_conn =
1632 conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
1633 const int sending_optimistically =
1634 entry_conn &&
1635 conn->base_.type == CONN_TYPE_AP &&
1636 conn->base_.state != AP_CONN_STATE_OPEN;
1637 crypt_path_t *cpath_layer = conn->cpath_layer;
1639 tor_assert(conn);
1641 if (conn->base_.marked_for_close) {
1642 log_warn(LD_BUG,
1643 "called on conn that's already marked for close at %s:%d.",
1644 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
1645 return 0;
1648 if (max_cells && *max_cells <= 0)
1649 return 0;
1651 repeat_connection_edge_package_raw_inbuf:
1653 circ = circuit_get_by_edge_conn(conn);
1654 if (!circ) {
1655 log_info(domain,"conn has no circuit! Closing.");
1656 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1657 return -1;
1660 if (circuit_consider_stop_edge_reading(circ, cpath_layer))
1661 return 0;
1663 if (conn->package_window <= 0) {
1664 log_info(domain,"called with package_window %d. Skipping.",
1665 conn->package_window);
1666 connection_stop_reading(TO_CONN(conn));
1667 return 0;
1670 sending_from_optimistic = entry_conn &&
1671 entry_conn->sending_optimistic_data != NULL;
1673 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
1674 bytes_to_process = generic_buffer_len(entry_conn->sending_optimistic_data);
1675 if (PREDICT_UNLIKELY(!bytes_to_process)) {
1676 log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
1677 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
1678 sending_from_optimistic = 0;
1680 } else {
1681 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
1684 if (!bytes_to_process)
1685 return 0;
1687 if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
1688 return 0;
1690 if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
1691 length = RELAY_PAYLOAD_SIZE;
1692 } else {
1693 length = bytes_to_process;
1695 stats_n_data_bytes_packaged += length;
1696 stats_n_data_cells_packaged += 1;
1698 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
1699 /* XXXX We could be more efficient here by sometimes packing
1700 * previously-sent optimistic data in the same cell with data
1701 * from the inbuf. */
1702 generic_buffer_get(entry_conn->sending_optimistic_data, payload, length);
1703 if (!generic_buffer_len(entry_conn->sending_optimistic_data)) {
1704 generic_buffer_free(entry_conn->sending_optimistic_data);
1705 entry_conn->sending_optimistic_data = NULL;
1707 } else {
1708 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1711 log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
1712 conn->base_.s,
1713 (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
1715 if (sending_optimistically && !sending_from_optimistic) {
1716 /* This is new optimistic data; remember it in case we need to detach and
1717 retry */
1718 if (!entry_conn->pending_optimistic_data)
1719 entry_conn->pending_optimistic_data = generic_buffer_new();
1720 generic_buffer_add(entry_conn->pending_optimistic_data, payload, length);
1723 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1724 payload, length) < 0 )
1725 /* circuit got marked for close, don't continue, don't need to mark conn */
1726 return 0;
1728 if (!cpath_layer) { /* non-rendezvous exit */
1729 tor_assert(circ->package_window > 0);
1730 circ->package_window--;
1731 } else { /* we're an AP, or an exit on a rendezvous circ */
1732 tor_assert(cpath_layer->package_window > 0);
1733 cpath_layer->package_window--;
1736 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1737 connection_stop_reading(TO_CONN(conn));
1738 log_debug(domain,"conn->package_window reached 0.");
1739 circuit_consider_stop_edge_reading(circ, cpath_layer);
1740 return 0; /* don't process the inbuf any more */
1742 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1744 if (max_cells) {
1745 *max_cells -= 1;
1746 if (*max_cells <= 0)
1747 return 0;
1750 /* handle more if there's more, or return 0 if there isn't */
1751 goto repeat_connection_edge_package_raw_inbuf;
1754 /** Called when we've just received a relay data cell, when
1755 * we've just finished flushing all bytes to stream <b>conn</b>,
1756 * or when we've flushed *some* bytes to the stream <b>conn</b>.
1758 * If conn->outbuf is not too full, and our deliver window is
1759 * low, send back a suitable number of stream-level sendme cells.
1761 void
1762 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1764 circuit_t *circ;
1766 if (connection_outbuf_too_full(TO_CONN(conn)))
1767 return;
1769 circ = circuit_get_by_edge_conn(conn);
1770 if (!circ) {
1771 /* this can legitimately happen if the destroy has already
1772 * arrived and torn down the circuit */
1773 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1774 return;
1777 while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1778 log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
1779 "Outbuf %d, Queuing stream sendme.",
1780 (int)conn->base_.outbuf_flushlen);
1781 conn->deliver_window += STREAMWINDOW_INCREMENT;
1782 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
1783 NULL, 0) < 0) {
1784 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
1785 return; /* the circuit's closed, don't continue */
1790 /** The circuit <b>circ</b> has received a circuit-level sendme
1791 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1792 * attached streams and let them resume reading and packaging, if
1793 * their stream windows allow it.
1795 static void
1796 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1798 if (circuit_queue_streams_are_blocked(circ)) {
1799 log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
1800 return;
1802 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1804 if (CIRCUIT_IS_ORIGIN(circ))
1805 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
1806 circ, layer_hint);
1807 else
1808 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
1809 circ, layer_hint);
1812 void
1813 stream_choice_seed_weak_rng(void)
1815 crypto_seed_weak_rng(&stream_choice_rng);
1818 /** A helper function for circuit_resume_edge_reading() above.
1819 * The arguments are the same, except that <b>conn</b> is the head
1820 * of a linked list of edge streams that should each be considered.
1822 static int
1823 circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
1824 circuit_t *circ,
1825 crypt_path_t *layer_hint)
1827 edge_connection_t *conn;
1828 int n_packaging_streams, n_streams_left;
1829 int packaged_this_round;
1830 int cells_on_queue;
1831 int cells_per_conn;
1832 edge_connection_t *chosen_stream = NULL;
1833 int max_to_package;
1835 if (first_conn == NULL) {
1836 /* Don't bother to try to do the rest of this if there are no connections
1837 * to resume. */
1838 return 0;
1841 /* How many cells do we have space for? It will be the minimum of
1842 * the number needed to exhaust the package window, and the minimum
1843 * needed to fill the cell queue. */
1844 max_to_package = circ->package_window;
1845 if (CIRCUIT_IS_ORIGIN(circ)) {
1846 cells_on_queue = circ->n_chan_cells.n;
1847 } else {
1848 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1849 cells_on_queue = or_circ->p_chan_cells.n;
1851 if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
1852 max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
1854 /* Once we used to start listening on the streams in the order they
1855 * appeared in the linked list. That leads to starvation on the
1856 * streams that appeared later on the list, since the first streams
1857 * would always get to read first. Instead, we just pick a random
1858 * stream on the list, and enable reading for streams starting at that
1859 * point (and wrapping around as if the list were circular). It would
1860 * probably be better to actually remember which streams we've
1861 * serviced in the past, but this is simple and effective. */
1863 /* Select a stream uniformly at random from the linked list. We
1864 * don't need cryptographic randomness here. */
1866 int num_streams = 0;
1867 for (conn = first_conn; conn; conn = conn->next_stream) {
1868 num_streams++;
1869 if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
1870 chosen_stream = conn;
1872 /* Invariant: chosen_stream has been chosen uniformly at random from
1873 * among the first num_streams streams on first_conn.
1875 * (Note that we iterate over every stream on the circuit, so that after
1876 * we've considered the first stream, we've chosen it with P=1; and
1877 * after we consider the second stream, we've switched to it with P=1/2
1878 * and stayed with the first stream with P=1/2; and after we've
1879 * considered the third stream, we've switched to it with P=1/3 and
1880 * remained with one of the first two streams with P=(2/3), giving each
1881 * one P=(1/2)(2/3) )=(1/3).) */
1885 /* Count how many non-marked streams there are that have anything on
1886 * their inbuf, and enable reading on all of the connections. */
1887 n_packaging_streams = 0;
1888 /* Activate reading starting from the chosen stream */
1889 for (conn=chosen_stream; conn; conn = conn->next_stream) {
1890 /* Start reading for the streams starting from here */
1891 if (conn->base_.marked_for_close || conn->package_window <= 0)
1892 continue;
1893 if (!layer_hint || conn->cpath_layer == layer_hint) {
1894 connection_start_reading(TO_CONN(conn));
1896 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
1897 ++n_packaging_streams;
1900 /* Go back and do the ones we skipped, circular-style */
1901 for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
1902 if (conn->base_.marked_for_close || conn->package_window <= 0)
1903 continue;
1904 if (!layer_hint || conn->cpath_layer == layer_hint) {
1905 connection_start_reading(TO_CONN(conn));
1907 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
1908 ++n_packaging_streams;
1912 if (n_packaging_streams == 0) /* avoid divide-by-zero */
1913 return 0;
1915 again:
1917 cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
1919 packaged_this_round = 0;
1920 n_streams_left = 0;
1922 /* Iterate over all connections. Package up to cells_per_conn cells on
1923 * each. Update packaged_this_round with the total number of cells
1924 * packaged, and n_streams_left with the number that still have data to
1925 * package.
1927 for (conn=first_conn; conn; conn=conn->next_stream) {
1928 if (conn->base_.marked_for_close || conn->package_window <= 0)
1929 continue;
1930 if (!layer_hint || conn->cpath_layer == layer_hint) {
1931 int n = cells_per_conn, r;
1932 /* handle whatever might still be on the inbuf */
1933 r = connection_edge_package_raw_inbuf(conn, 1, &n);
1935 /* Note how many we packaged */
1936 packaged_this_round += (cells_per_conn-n);
1938 if (r<0) {
1939 /* Problem while packaging. (We already sent an end cell if
1940 * possible) */
1941 connection_mark_for_close(TO_CONN(conn));
1942 continue;
1945 /* If there's still data to read, we'll be coming back to this stream. */
1946 if (connection_get_inbuf_len(TO_CONN(conn)))
1947 ++n_streams_left;
1949 /* If the circuit won't accept any more data, return without looking
1950 * at any more of the streams. Any connections that should be stopped
1951 * have already been stopped by connection_edge_package_raw_inbuf. */
1952 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1953 return -1;
1954 /* XXXX should we also stop immediately if we fill up the cell queue?
1955 * Probably. */
1959 /* If we made progress, and we are willing to package more, and there are
1960 * any streams left that want to package stuff... try again!
1962 if (packaged_this_round && packaged_this_round < max_to_package &&
1963 n_streams_left) {
1964 max_to_package -= packaged_this_round;
1965 n_packaging_streams = n_streams_left;
1966 goto again;
1969 return 0;
1972 /** Check if the package window for <b>circ</b> is empty (at
1973 * hop <b>layer_hint</b> if it's defined).
1975 * If yes, tell edge streams to stop reading and return 1.
1976 * Else return 0.
1978 static int
1979 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1981 edge_connection_t *conn = NULL;
1982 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1984 if (!layer_hint) {
1985 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1986 log_debug(domain,"considering circ->package_window %d",
1987 circ->package_window);
1988 if (circ->package_window <= 0) {
1989 log_debug(domain,"yes, not-at-origin. stopped.");
1990 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
1991 connection_stop_reading(TO_CONN(conn));
1992 return 1;
1994 return 0;
1996 /* else, layer hint is defined, use it */
1997 log_debug(domain,"considering layer_hint->package_window %d",
1998 layer_hint->package_window);
1999 if (layer_hint->package_window <= 0) {
2000 log_debug(domain,"yes, at-origin. stopped.");
2001 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
2002 conn=conn->next_stream) {
2003 if (conn->cpath_layer == layer_hint)
2004 connection_stop_reading(TO_CONN(conn));
2006 return 1;
2008 return 0;
2011 /** Check if the deliver_window for circuit <b>circ</b> (at hop
2012 * <b>layer_hint</b> if it's defined) is low enough that we should
2013 * send a circuit-level sendme back down the circuit. If so, send
2014 * enough sendmes that the window would be overfull if we sent any
2015 * more.
2017 static void
2018 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
2020 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
2021 // layer_hint ? "defined" : "null");
2022 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
2023 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
2024 log_debug(LD_CIRC,"Queuing circuit sendme.");
2025 if (layer_hint)
2026 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
2027 else
2028 circ->deliver_window += CIRCWINDOW_INCREMENT;
2029 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
2030 NULL, 0, layer_hint) < 0) {
2031 log_warn(LD_CIRC,
2032 "relay_send_command_from_edge failed. Circuit's closed.");
2033 return; /* the circuit's closed, don't continue */
2038 #ifdef ACTIVE_CIRCUITS_PARANOIA
2039 #define assert_cmux_ok_paranoid(chan) \
2040 assert_circuit_mux_okay(chan)
2041 #else
2042 #define assert_cmux_ok_paranoid(chan)
2043 #endif
2045 /** The total number of cells we have allocated from the memory pool. */
2046 static size_t total_cells_allocated = 0;
2048 /** A memory pool to allocate packed_cell_t objects. */
2049 static mp_pool_t *cell_pool = NULL;
2051 /** Allocate structures to hold cells. */
2052 void
2053 init_cell_pool(void)
2055 tor_assert(!cell_pool);
2056 cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
2059 /** Free all storage used to hold cells (and insertion times if we measure
2060 * cell statistics). */
2061 void
2062 free_cell_pool(void)
2064 /* Maybe we haven't called init_cell_pool yet; need to check for it. */
2065 if (cell_pool) {
2066 mp_pool_destroy(cell_pool);
2067 cell_pool = NULL;
2071 /** Free excess storage in cell pool. */
2072 void
2073 clean_cell_pool(void)
2075 tor_assert(cell_pool);
2076 mp_pool_clean(cell_pool, 0, 1);
2079 /** Release storage held by <b>cell</b>. */
2080 static INLINE void
2081 packed_cell_free_unchecked(packed_cell_t *cell)
2083 --total_cells_allocated;
2084 mp_pool_release(cell);
2087 /** Allocate and return a new packed_cell_t. */
2088 static INLINE packed_cell_t *
2089 packed_cell_new(void)
2091 ++total_cells_allocated;
2092 return mp_pool_get(cell_pool);
2095 /** Return a packed cell used outside by channel_t lower layer */
2096 void
2097 packed_cell_free(packed_cell_t *cell)
2099 packed_cell_free_unchecked(cell);
2102 /** Log current statistics for cell pool allocation at log level
2103 * <b>severity</b>. */
2104 void
2105 dump_cell_pool_usage(int severity)
2107 circuit_t *c;
2108 int n_circs = 0;
2109 int n_cells = 0;
2110 for (c = circuit_get_global_list_(); c; c = c->next) {
2111 n_cells += c->n_chan_cells.n;
2112 if (!CIRCUIT_IS_ORIGIN(c))
2113 n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
2114 ++n_circs;
2116 tor_log(severity, LD_MM,
2117 "%d cells allocated on %d circuits. %d cells leaked.",
2118 n_cells, n_circs, (int)total_cells_allocated - n_cells);
2119 mp_pool_log_status(cell_pool, severity);
2122 /** Allocate a new copy of packed <b>cell</b>. */
2123 static INLINE packed_cell_t *
2124 packed_cell_copy(const cell_t *cell, int wide_circ_ids)
2126 packed_cell_t *c = packed_cell_new();
2127 cell_pack(c, cell, wide_circ_ids);
2128 c->next = NULL;
2129 return c;
2132 /** Append <b>cell</b> to the end of <b>queue</b>. */
2133 void
2134 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
2136 if (queue->tail) {
2137 tor_assert(!queue->tail->next);
2138 queue->tail->next = cell;
2139 } else {
2140 queue->head = cell;
2142 queue->tail = cell;
2143 cell->next = NULL;
2144 ++queue->n;
2147 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
2148 void
2149 cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell,
2150 int wide_circ_ids)
2152 struct timeval now;
2153 packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
2154 tor_gettimeofday_cached(&now);
2155 copy->inserted_time = (uint32_t)tv_to_msec(&now);
2157 cell_queue_append(queue, copy);
2160 /** Remove and free every cell in <b>queue</b>. */
2161 void
2162 cell_queue_clear(cell_queue_t *queue)
2164 packed_cell_t *cell, *next;
2165 cell = queue->head;
2166 while (cell) {
2167 next = cell->next;
2168 packed_cell_free_unchecked(cell);
2169 cell = next;
2171 queue->head = queue->tail = NULL;
2172 queue->n = 0;
2175 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
2176 * <b>queue</b> is empty. */
2177 static INLINE packed_cell_t *
2178 cell_queue_pop(cell_queue_t *queue)
2180 packed_cell_t *cell = queue->head;
2181 if (!cell)
2182 return NULL;
2183 queue->head = cell->next;
2184 if (cell == queue->tail) {
2185 tor_assert(!queue->head);
2186 queue->tail = NULL;
2188 --queue->n;
2189 return cell;
2192 /** Return the total number of bytes used for each packed_cell in a queue.
2193 * Approximate. */
2194 size_t
2195 packed_cell_mem_cost(void)
2197 return sizeof(packed_cell_t) + MP_POOL_ITEM_OVERHEAD;
2200 /** Check whether we've got too much space used for cells. If so,
2201 * call the OOM handler and return 1. Otherwise, return 0. */
2202 static int
2203 cell_queues_check_size(void)
2205 size_t alloc = total_cells_allocated * packed_cell_mem_cost();
2206 if (alloc >= get_options()->MaxMemInCellQueues) {
2207 circuits_handle_oom(alloc);
2208 return 1;
2210 return 0;
2214 * Update the number of cells available on the circuit's n_chan or p_chan's
2215 * circuit mux.
2217 void
2218 update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
2219 const char *file, int lineno)
2221 channel_t *chan = NULL;
2222 or_circuit_t *or_circ = NULL;
2223 circuitmux_t *cmux = NULL;
2225 tor_assert(circ);
2227 /* Okay, get the channel */
2228 if (direction == CELL_DIRECTION_OUT) {
2229 chan = circ->n_chan;
2230 } else {
2231 or_circ = TO_OR_CIRCUIT(circ);
2232 chan = or_circ->p_chan;
2235 tor_assert(chan);
2236 tor_assert(chan->cmux);
2238 /* Now get the cmux */
2239 cmux = chan->cmux;
2241 /* Cmux sanity check */
2242 if (! circuitmux_is_circuit_attached(cmux, circ)) {
2243 log_warn(LD_BUG, "called on non-attachd circuit from %s:%d",
2244 file, lineno);
2245 return;
2247 tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
2249 assert_cmux_ok_paranoid(chan);
2251 /* Update the number of cells we have for the circuit mux */
2252 if (direction == CELL_DIRECTION_OUT) {
2253 circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
2254 } else {
2255 circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
2258 assert_cmux_ok_paranoid(chan);
2261 /** Remove all circuits from the cmux on <b>chan</b>. */
2262 void
2263 channel_unlink_all_circuits(channel_t *chan)
2265 tor_assert(chan);
2266 tor_assert(chan->cmux);
2268 circuitmux_detach_all_circuits(chan->cmux);
2269 chan->num_n_circuits = 0;
2270 chan->num_p_circuits = 0;
2273 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
2274 * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
2275 * and start or stop reading as appropriate.
2277 * If <b>stream_id</b> is nonzero, block only the edge connection whose
2278 * stream_id matches it.
2280 * Returns the number of streams whose status we changed.
2282 static int
2283 set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
2284 int block, streamid_t stream_id)
2286 edge_connection_t *edge = NULL;
2287 int n = 0;
2288 if (circ->n_chan == chan) {
2289 circ->streams_blocked_on_n_chan = block;
2290 if (CIRCUIT_IS_ORIGIN(circ))
2291 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
2292 } else {
2293 circ->streams_blocked_on_p_chan = block;
2294 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
2295 edge = TO_OR_CIRCUIT(circ)->n_streams;
2298 for (; edge; edge = edge->next_stream) {
2299 connection_t *conn = TO_CONN(edge);
2300 if (stream_id && edge->stream_id != stream_id)
2301 continue;
2303 if (edge->edge_blocked_on_circ != block) {
2304 ++n;
2305 edge->edge_blocked_on_circ = block;
2308 if (!conn->read_event && !HAS_BUFFEREVENT(conn)) {
2309 /* This connection is a placeholder for something; probably a DNS
2310 * request. It can't actually stop or start reading.*/
2311 continue;
2314 if (block) {
2315 if (connection_is_reading(conn))
2316 connection_stop_reading(conn);
2317 } else {
2318 /* Is this right? */
2319 if (!connection_is_reading(conn))
2320 connection_start_reading(conn);
2324 return n;
2327 /** Pull as many cells as possible (but no more than <b>max</b>) from the
2328 * queue of the first active circuit on <b>chan</b>, and write them to
2329 * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
2330 * the active circuit pointer to the next active circuit in the ring. */
2332 channel_flush_from_first_active_circuit(channel_t *chan, int max)
2334 circuitmux_t *cmux = NULL;
2335 int n_flushed = 0;
2336 cell_queue_t *queue;
2337 circuit_t *circ;
2338 or_circuit_t *or_circ;
2339 int streams_blocked;
2340 packed_cell_t *cell;
2342 /* Get the cmux */
2343 tor_assert(chan);
2344 tor_assert(chan->cmux);
2345 cmux = chan->cmux;
2347 /* Main loop: pick a circuit, send a cell, update the cmux */
2348 while (n_flushed < max) {
2349 circ = circuitmux_get_first_active_circuit(cmux);
2350 /* If it returns NULL, no cells left to send */
2351 if (!circ) break;
2352 assert_cmux_ok_paranoid(chan);
2354 if (circ->n_chan == chan) {
2355 queue = &circ->n_chan_cells;
2356 streams_blocked = circ->streams_blocked_on_n_chan;
2357 } else {
2358 or_circ = TO_OR_CIRCUIT(circ);
2359 tor_assert(or_circ->p_chan == chan);
2360 queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
2361 streams_blocked = circ->streams_blocked_on_p_chan;
2364 /* Circuitmux told us this was active, so it should have cells */
2365 tor_assert(queue->n > 0);
2368 * Get just one cell here; once we've sent it, that can change the circuit
2369 * selection, so we have to loop around for another even if this circuit
2370 * has more than one.
2372 cell = cell_queue_pop(queue);
2374 /* Calculate the exact time that this cell has spent in the queue. */
2375 if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
2376 uint32_t msec_waiting;
2377 struct timeval tvnow;
2378 or_circ = TO_OR_CIRCUIT(circ);
2379 tor_gettimeofday_cached(&tvnow);
2380 msec_waiting = ((uint32_t)tv_to_msec(&tvnow)) - cell->inserted_time;
2382 or_circ->total_cell_waiting_time += msec_waiting;
2383 or_circ->processed_cells++;
2386 /* If we just flushed our queue and this circuit is used for a
2387 * tunneled directory request, possibly advance its state. */
2388 if (queue->n == 0 && chan->dirreq_id)
2389 geoip_change_dirreq_state(chan->dirreq_id,
2390 DIRREQ_TUNNELED,
2391 DIRREQ_CIRC_QUEUE_FLUSHED);
2393 /* Now send the cell */
2394 channel_write_packed_cell(chan, cell);
2395 cell = NULL;
2398 * Don't packed_cell_free_unchecked(cell) here because the channel will
2399 * do so when it gets out of the channel queue (probably already did, in
2400 * which case that was an immediate double-free bug).
2403 /* Update the counter */
2404 ++n_flushed;
2407 * Now update the cmux; tell it we've just sent a cell, and how many
2408 * we have left.
2410 circuitmux_notify_xmit_cells(cmux, circ, 1);
2411 circuitmux_set_num_cells(cmux, circ, queue->n);
2412 if (queue->n == 0)
2413 log_debug(LD_GENERAL, "Made a circuit inactive.");
2415 /* Is the cell queue low enough to unblock all the streams that are waiting
2416 * to write to this circuit? */
2417 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
2418 set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
2420 /* If n_flushed < max still, loop around and pick another circuit */
2423 /* Okay, we're done sending now */
2424 assert_cmux_ok_paranoid(chan);
2426 return n_flushed;
2429 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
2430 * transmitting in <b>direction</b>. */
2431 void
2432 append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
2433 cell_t *cell, cell_direction_t direction,
2434 streamid_t fromstream)
2436 or_circuit_t *orcirc = NULL;
2437 cell_queue_t *queue;
2438 int streams_blocked;
2440 if (circ->marked_for_close)
2441 return;
2443 if (direction == CELL_DIRECTION_OUT) {
2444 queue = &circ->n_chan_cells;
2445 streams_blocked = circ->streams_blocked_on_n_chan;
2446 } else {
2447 orcirc = TO_OR_CIRCUIT(circ);
2448 queue = &orcirc->p_chan_cells;
2449 streams_blocked = circ->streams_blocked_on_p_chan;
2453 * Disabling this for now because of a possible guard discovery attack
2455 #if 0
2456 /* Are we a middle circuit about to exceed ORCIRC_MAX_MIDDLE_CELLS? */
2457 if ((circ->n_chan != NULL) && CIRCUIT_IS_ORCIRC(circ)) {
2458 orcirc = TO_OR_CIRCUIT(circ);
2459 if (orcirc->p_chan) {
2460 if (queue->n + 1 >= ORCIRC_MAX_MIDDLE_CELLS) {
2461 /* Queueing this cell would put queue over the cap */
2462 log_warn(LD_CIRC,
2463 "Got a cell exceeding the cap of %u in the %s direction "
2464 "on middle circ ID %u on chan ID " U64_FORMAT
2465 "; killing the circuit.",
2466 ORCIRC_MAX_MIDDLE_CELLS,
2467 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2468 (direction == CELL_DIRECTION_OUT) ?
2469 circ->n_circ_id : orcirc->p_circ_id,
2470 U64_PRINTF_ARG(
2471 (direction == CELL_DIRECTION_OUT) ?
2472 circ->n_chan->global_identifier :
2473 orcirc->p_chan->global_identifier));
2474 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2475 return;
2479 #endif
2481 cell_queue_append_packed_copy(queue, cell, chan->wide_circ_ids);
2483 if (PREDICT_UNLIKELY(cell_queues_check_size())) {
2484 /* We ran the OOM handler */
2485 if (circ->marked_for_close)
2486 return;
2489 /* If we have too many cells on the circuit, we should stop reading from
2490 * the edge streams for a while. */
2491 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
2492 set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
2494 if (streams_blocked && fromstream) {
2495 /* This edge connection is apparently not blocked; block it. */
2496 set_streams_blocked_on_circ(circ, chan, 1, fromstream);
2499 update_circuit_on_cmux(circ, direction);
2500 if (queue->n == 1) {
2501 /* This was the first cell added to the queue. We just made this
2502 * circuit active. */
2503 log_debug(LD_GENERAL, "Made a circuit active.");
2506 if (!channel_has_queued_writes(chan)) {
2507 /* There is no data at all waiting to be sent on the outbuf. Add a
2508 * cell, so that we can notice when it gets flushed, flushed_some can
2509 * get called, and we can start putting more data onto the buffer then.
2511 log_debug(LD_GENERAL, "Primed a buffer.");
2512 channel_flush_from_first_active_circuit(chan, 1);
2516 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
2517 * have at least 18 bytes of free space. The encoding is, as specified in
2518 * tor-spec.txt:
2519 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
2520 * LENGTH [1 byte]
2521 * ADDRESS [length bytes]
2522 * Return the number of bytes added, or -1 on error */
2524 append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
2526 uint32_t a;
2527 switch (tor_addr_family(addr)) {
2528 case AF_INET:
2529 payload_out[0] = RESOLVED_TYPE_IPV4;
2530 payload_out[1] = 4;
2531 a = tor_addr_to_ipv4n(addr);
2532 memcpy(payload_out+2, &a, 4);
2533 return 6;
2534 case AF_INET6:
2535 payload_out[0] = RESOLVED_TYPE_IPV6;
2536 payload_out[1] = 16;
2537 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
2538 return 18;
2539 case AF_UNSPEC:
2540 default:
2541 return -1;
2545 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
2546 * encoded as by append_address_to_payload(), try to decode the address into
2547 * *<b>addr_out</b>. Return the next byte in the payload after the address on
2548 * success, or NULL on failure. */
2549 const uint8_t *
2550 decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
2551 int payload_len)
2553 if (payload_len < 2)
2554 return NULL;
2555 if (payload_len < 2+payload[1])
2556 return NULL;
2558 switch (payload[0]) {
2559 case RESOLVED_TYPE_IPV4:
2560 if (payload[1] != 4)
2561 return NULL;
2562 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
2563 break;
2564 case RESOLVED_TYPE_IPV6:
2565 if (payload[1] != 16)
2566 return NULL;
2567 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
2568 break;
2569 default:
2570 tor_addr_make_unspec(addr_out);
2571 break;
2573 return payload + 2 + payload[1];
2576 /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
2577 void
2578 circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
2580 cell_queue_t *queue;
2581 cell_direction_t direction;
2583 if (circ->n_chan == chan) {
2584 queue = &circ->n_chan_cells;
2585 direction = CELL_DIRECTION_OUT;
2586 } else {
2587 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
2588 tor_assert(orcirc->p_chan == chan);
2589 queue = &orcirc->p_chan_cells;
2590 direction = CELL_DIRECTION_IN;
2593 /* Clear the queue */
2594 cell_queue_clear(queue);
2596 /* Update the cell counter in the cmux */
2597 if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
2598 update_circuit_on_cmux(circ, direction);
2601 /** Fail with an assert if the circuit mux on chan is corrupt
2603 void
2604 assert_circuit_mux_okay(channel_t *chan)
2606 tor_assert(chan);
2607 tor_assert(chan->cmux);
2609 circuitmux_assert_okay(chan->cmux);
2612 /** Return 1 if we shouldn't restart reading on this circuit, even if
2613 * we get a SENDME. Else return 0.
2615 static int
2616 circuit_queue_streams_are_blocked(circuit_t *circ)
2618 if (CIRCUIT_IS_ORIGIN(circ)) {
2619 return circ->streams_blocked_on_n_chan;
2620 } else {
2621 return circ->streams_blocked_on_p_chan;