Merge branch 'bug8185_025' into bug8185_031
[tor.git] / src / or / relay.c
blob81942af1e8bd29d1c2c97c39f8b6323f500456de
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-2017, 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.
12 * This is a core modules that makes Tor work. It's responsible for
13 * dealing with RELAY cells (the ones that travel more than one hop along a
14 * circuit), by:
15 * <ul>
16 * <li>constructing relays cells,
17 * <li>encrypting relay cells,
18 * <li>decrypting relay cells,
19 * <li>demultiplexing relay cells as they arrive on a connection,
20 * <li>queueing relay cells for retransmission,
21 * <li>or handling relay cells that are for us to receive (as an exit or a
22 * client).
23 * </ul>
25 * RELAY cells are generated throughout the code at the client or relay side,
26 * using relay_send_command_from_edge() or one of the functions like
27 * connection_edge_send_command() that calls it. Of particular interest is
28 * connection_edge_package_raw_inbuf(), which takes information that has
29 * arrived on an edge connection socket, and packages it as a RELAY_DATA cell
30 * -- this is how information is actually sent across the Tor network. The
31 * cryptography for these functions is handled deep in
32 * circuit_package_relay_cell(), which either adds a single layer of
33 * encryption (if we're an exit), or multiple layers (if we're the origin of
34 * the circuit). After construction and encryption, the RELAY cells are
35 * passed to append_cell_to_circuit_queue(), which queues them for
36 * transmission and tells the circuitmux (see circuitmux.c) that the circuit
37 * is waiting to send something.
39 * Incoming RELAY cells arrive at circuit_receive_relay_cell(), called from
40 * command.c. There they are decrypted and, if they are for us, are passed to
41 * connection_edge_process_relay_cell(). If they're not for us, they're
42 * re-queued for retransmission again with append_cell_to_circuit_queue().
44 * The connection_edge_process_relay_cell() function handles all the different
45 * types of relay cells, launching requests or transmitting data as needed.
46 **/
48 #define RELAY_PRIVATE
49 #include "or.h"
50 #include "addressmap.h"
51 #include "backtrace.h"
52 #include "buffers.h"
53 #include "channel.h"
54 #include "circpathbias.h"
55 #include "circuitbuild.h"
56 #include "circuitlist.h"
57 #include "circuituse.h"
58 #include "compress.h"
59 #include "config.h"
60 #include "connection.h"
61 #include "connection_edge.h"
62 #include "connection_or.h"
63 #include "control.h"
64 #include "geoip.h"
65 #include "hs_cache.h"
66 #include "main.h"
67 #include "networkstatus.h"
68 #include "nodelist.h"
69 #include "onion.h"
70 #include "policies.h"
71 #include "reasons.h"
72 #include "relay.h"
73 #include "rendcache.h"
74 #include "rendcommon.h"
75 #include "router.h"
76 #include "routerlist.h"
77 #include "routerparse.h"
78 #include "scheduler.h"
79 #include "rephist.h"
81 static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
82 cell_direction_t cell_direction,
83 crypt_path_t *layer_hint);
85 static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
86 edge_connection_t *conn,
87 crypt_path_t *layer_hint);
88 static void circuit_consider_sending_sendme(circuit_t *circ,
89 crypt_path_t *layer_hint);
90 static void circuit_resume_edge_reading(circuit_t *circ,
91 crypt_path_t *layer_hint);
92 static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
93 circuit_t *circ,
94 crypt_path_t *layer_hint);
95 static int circuit_consider_stop_edge_reading(circuit_t *circ,
96 crypt_path_t *layer_hint);
97 static int circuit_queue_streams_are_blocked(circuit_t *circ);
98 static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
99 entry_connection_t *conn,
100 node_t *node,
101 const tor_addr_t *addr);
102 #if 0
103 static int get_max_middle_cells(void);
104 #endif
106 /** Stop reading on edge connections when we have this many cells
107 * waiting on the appropriate queue. */
108 #define CELL_QUEUE_HIGHWATER_SIZE 256
109 /** Start reading from edge connections again when we get down to this many
110 * cells. */
111 #define CELL_QUEUE_LOWWATER_SIZE 64
113 /** Stats: how many relay cells have originated at this hop, or have
114 * been relayed onward (not recognized at this hop)?
116 uint64_t stats_n_relay_cells_relayed = 0;
117 /** Stats: how many relay cells have been delivered to streams at this
118 * hop?
120 uint64_t stats_n_relay_cells_delivered = 0;
122 /** Used to tell which stream to read from first on a circuit. */
123 static tor_weak_rng_t stream_choice_rng = TOR_WEAK_RNG_INIT;
125 /** Update digest from the payload of cell. Assign integrity part to
126 * cell.
128 static void
129 relay_set_digest(crypto_digest_t *digest, cell_t *cell)
131 char integrity[4];
132 relay_header_t rh;
134 crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
135 crypto_digest_get_digest(digest, integrity, 4);
136 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
137 // integrity[0], integrity[1], integrity[2], integrity[3]);
138 relay_header_unpack(&rh, cell->payload);
139 memcpy(rh.integrity, integrity, 4);
140 relay_header_pack(cell->payload, &rh);
143 /** Does the digest for this circuit indicate that this cell is for us?
145 * Update digest from the payload of cell (with the integrity part set
146 * to 0). If the integrity part is valid, return 1, else restore digest
147 * and cell to their original state and return 0.
149 static int
150 relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
152 uint32_t received_integrity, calculated_integrity;
153 relay_header_t rh;
154 crypto_digest_t *backup_digest=NULL;
156 backup_digest = crypto_digest_dup(digest);
158 relay_header_unpack(&rh, cell->payload);
159 memcpy(&received_integrity, rh.integrity, 4);
160 memset(rh.integrity, 0, 4);
161 relay_header_pack(cell->payload, &rh);
163 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
164 // received_integrity[0], received_integrity[1],
165 // received_integrity[2], received_integrity[3]);
167 crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
168 crypto_digest_get_digest(digest, (char*) &calculated_integrity, 4);
170 if (calculated_integrity != received_integrity) {
171 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
172 // (%d vs %d).", received_integrity, calculated_integrity);
173 /* restore digest to its old form */
174 crypto_digest_assign(digest, backup_digest);
175 /* restore the relay header */
176 memcpy(rh.integrity, &received_integrity, 4);
177 relay_header_pack(cell->payload, &rh);
178 crypto_digest_free(backup_digest);
179 return 0;
181 crypto_digest_free(backup_digest);
182 return 1;
185 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
186 * (in place).
188 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
190 * Returns 0.
192 static int
193 relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
194 int encrypt_mode)
196 (void)encrypt_mode;
197 crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
199 return 0;
203 * Update channel usage state based on the type of relay cell and
204 * circuit properties.
206 * This is needed to determine if a client channel is being
207 * used for application traffic, and if a relay channel is being
208 * used for multihop circuits and application traffic. The decision
209 * to pad in channelpadding.c depends upon this info (as well as
210 * consensus parameters) to decide what channels to pad.
212 static void
213 circuit_update_channel_usage(circuit_t *circ, cell_t *cell)
215 if (CIRCUIT_IS_ORIGIN(circ)) {
217 * The client state was first set much earlier in
218 * circuit_send_next_onion_skin(), so we can start padding as early as
219 * possible.
221 * However, if padding turns out to be expensive, we may want to not do
222 * it until actual application traffic starts flowing (which is controlled
223 * via consensus param nf_pad_before_usage).
225 * So: If we're an origin circuit and we've created a full length circuit,
226 * then any CELL_RELAY cell means application data. Increase the usage
227 * state of the channel to indicate this.
229 * We want to wait for CELL_RELAY specifically here, so we know that
230 * the channel was definitely being used for data and not for extends.
231 * By default, we pad as soon as a channel has been used for *any*
232 * circuits, so this state is irrelevant to the padding decision in
233 * the default case. However, if padding turns out to be expensive,
234 * we would like the ability to avoid padding until we're absolutely
235 * sure that a channel is used for enough application data to be worth
236 * padding.
238 * (So it does not matter that CELL_RELAY_EARLY can actually contain
239 * application data. This is only a load reducing option and that edge
240 * case does not matter if we're desperately trying to reduce overhead
241 * anyway. See also consensus parameter nf_pad_before_usage).
243 if (BUG(!circ->n_chan))
244 return;
246 if (circ->n_chan->channel_usage == CHANNEL_USED_FOR_FULL_CIRCS &&
247 cell->command == CELL_RELAY) {
248 circ->n_chan->channel_usage = CHANNEL_USED_FOR_USER_TRAFFIC;
250 } else {
251 /* If we're a relay circuit, the question is more complicated. Basically:
252 * we only want to pad connections that carry multihop (anonymous)
253 * circuits.
255 * We assume we're more than one hop if either the previous hop
256 * is not a client, or if the previous hop is a client and there's
257 * a next hop. Then, circuit traffic starts at RELAY_EARLY, and
258 * user application traffic starts when we see RELAY cells.
260 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
262 if (BUG(!or_circ->p_chan))
263 return;
265 if (!channel_is_client(or_circ->p_chan) ||
266 (channel_is_client(or_circ->p_chan) && circ->n_chan)) {
267 if (cell->command == CELL_RELAY_EARLY) {
268 if (or_circ->p_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS) {
269 or_circ->p_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
271 } else if (cell->command == CELL_RELAY) {
272 or_circ->p_chan->channel_usage = CHANNEL_USED_FOR_USER_TRAFFIC;
278 /** Receive a relay cell:
279 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
280 * origin; decrypt if we're headed toward the exit).
281 * - Check if recognized (if exitward).
282 * - If recognized and the digest checks out, then find if there's a stream
283 * that the cell is intended for, and deliver it to the right
284 * connection_edge.
285 * - If not recognized, then we need to relay it: append it to the appropriate
286 * cell_queue on <b>circ</b>.
288 * Return -<b>reason</b> on failure.
291 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
292 cell_direction_t cell_direction)
294 channel_t *chan = NULL;
295 crypt_path_t *layer_hint=NULL;
296 char recognized=0;
297 int reason;
299 tor_assert(cell);
300 tor_assert(circ);
301 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
302 cell_direction == CELL_DIRECTION_IN);
303 if (circ->marked_for_close)
304 return 0;
306 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
307 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
308 "relay crypt failed. Dropping connection.");
309 return -END_CIRC_REASON_INTERNAL;
312 circuit_update_channel_usage(circ, cell);
314 if (recognized) {
315 edge_connection_t *conn = NULL;
317 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
318 pathbias_check_probe_response(circ, cell);
320 /* We need to drop this cell no matter what to avoid code that expects
321 * a certain purpose (such as the hidserv code). */
322 return 0;
325 conn = relay_lookup_conn(circ, cell, cell_direction, layer_hint);
326 if (cell_direction == CELL_DIRECTION_OUT) {
327 ++stats_n_relay_cells_delivered;
328 log_debug(LD_OR,"Sending away from origin.");
329 if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
330 < 0) {
331 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
332 "connection_edge_process_relay_cell (away from origin) "
333 "failed.");
334 return reason;
337 if (cell_direction == CELL_DIRECTION_IN) {
338 ++stats_n_relay_cells_delivered;
339 log_debug(LD_OR,"Sending to origin.");
340 if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
341 layer_hint)) < 0) {
342 /* If a client is trying to connect to unknown hidden service port,
343 * END_CIRC_AT_ORIGIN is sent back so we can then close the circuit.
344 * Do not log warn as this is an expected behavior for a service. */
345 if (reason != END_CIRC_AT_ORIGIN) {
346 log_warn(LD_OR,
347 "connection_edge_process_relay_cell (at origin) failed.");
349 return reason;
352 return 0;
355 /* not recognized. pass it on. */
356 if (cell_direction == CELL_DIRECTION_OUT) {
357 cell->circ_id = circ->n_circ_id; /* switch it */
358 chan = circ->n_chan;
359 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
360 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
361 chan = TO_OR_CIRCUIT(circ)->p_chan;
362 } else {
363 log_fn(LOG_PROTOCOL_WARN, LD_OR,
364 "Dropping unrecognized inbound cell on origin circuit.");
365 /* If we see unrecognized cells on path bias testing circs,
366 * it's bad mojo. Those circuits need to die.
367 * XXX: Shouldn't they always die? */
368 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
369 TO_ORIGIN_CIRCUIT(circ)->path_state = PATH_STATE_USE_FAILED;
370 return -END_CIRC_REASON_TORPROTOCOL;
371 } else {
372 return 0;
376 if (!chan) {
377 // XXXX Can this splice stuff be done more cleanly?
378 if (! CIRCUIT_IS_ORIGIN(circ) &&
379 TO_OR_CIRCUIT(circ)->rend_splice &&
380 cell_direction == CELL_DIRECTION_OUT) {
381 or_circuit_t *splice_ = TO_OR_CIRCUIT(circ)->rend_splice;
382 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
383 tor_assert(splice_->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
384 cell->circ_id = splice_->p_circ_id;
385 cell->command = CELL_RELAY; /* can't be relay_early anyway */
386 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice_),
387 CELL_DIRECTION_IN)) < 0) {
388 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
389 "circuits");
390 /* XXXX Do this here, or just return -1? */
391 circuit_mark_for_close(circ, -reason);
392 return reason;
394 return 0;
396 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
397 "Didn't recognize cell, but circ stops here! Closing circ.");
398 return -END_CIRC_REASON_TORPROTOCOL;
401 log_debug(LD_OR,"Passing on unrecognized cell.");
403 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
404 * we might kill the circ before we relay
405 * the cells. */
407 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
408 return 0;
411 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
412 * <b>circ</b> in direction <b>cell_direction</b>.
414 * If cell_direction == CELL_DIRECTION_IN:
415 * - If we're at the origin (we're the OP), for hops 1..N,
416 * decrypt cell. If recognized, stop.
417 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
419 * If cell_direction == CELL_DIRECTION_OUT:
420 * - decrypt one hop. Check if recognized.
422 * If cell is recognized, set *recognized to 1, and set
423 * *layer_hint to the hop that recognized it.
425 * Return -1 to indicate that we should mark the circuit for close,
426 * else return 0.
429 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
430 crypt_path_t **layer_hint, char *recognized)
432 relay_header_t rh;
434 tor_assert(circ);
435 tor_assert(cell);
436 tor_assert(recognized);
437 tor_assert(cell_direction == CELL_DIRECTION_IN ||
438 cell_direction == CELL_DIRECTION_OUT);
440 if (cell_direction == CELL_DIRECTION_IN) {
441 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
442 * We'll want to do layered decrypts. */
443 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
444 thishop = cpath;
445 if (thishop->state != CPATH_STATE_OPEN) {
446 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
447 "Relay cell before first created cell? Closing.");
448 return -1;
450 do { /* Remember: cpath is in forward order, that is, first hop first. */
451 tor_assert(thishop);
453 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
454 return -1;
456 relay_header_unpack(&rh, cell->payload);
457 if (rh.recognized == 0) {
458 /* it's possibly recognized. have to check digest to be sure. */
459 if (relay_digest_matches(thishop->b_digest, cell)) {
460 *recognized = 1;
461 *layer_hint = thishop;
462 return 0;
466 thishop = thishop->next;
467 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
468 log_fn(LOG_PROTOCOL_WARN, LD_OR,
469 "Incoming cell at client not recognized. Closing.");
470 return -1;
471 } else { /* we're in the middle. Just one crypt. */
472 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
473 cell->payload, 1) < 0)
474 return -1;
475 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
476 // "the client.");
478 } else /* cell_direction == CELL_DIRECTION_OUT */ {
479 /* we're in the middle. Just one crypt. */
481 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
482 cell->payload, 0) < 0)
483 return -1;
485 relay_header_unpack(&rh, cell->payload);
486 if (rh.recognized == 0) {
487 /* it's possibly recognized. have to check digest to be sure. */
488 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
489 *recognized = 1;
490 return 0;
494 return 0;
497 /** Package a relay cell from an edge:
498 * - Encrypt it to the right layer
499 * - Append it to the appropriate cell_queue on <b>circ</b>.
501 static int
502 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
503 cell_direction_t cell_direction,
504 crypt_path_t *layer_hint, streamid_t on_stream,
505 const char *filename, int lineno)
507 channel_t *chan; /* where to send the cell */
509 if (circ->marked_for_close) {
510 /* Circuit is marked; send nothing. */
511 return 0;
514 if (cell_direction == CELL_DIRECTION_OUT) {
515 crypt_path_t *thishop; /* counter for repeated crypts */
516 chan = circ->n_chan;
517 if (!chan) {
518 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d has n_chan==NULL."
519 " Dropping.", filename, lineno);
520 log_backtrace(LOG_WARN,LD_BUG,"");
521 return 0; /* just drop it */
523 if (!CIRCUIT_IS_ORIGIN(circ)) {
524 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d on non-origin "
525 "circ. Dropping.", filename, lineno);
526 log_backtrace(LOG_WARN,LD_BUG,"");
527 return 0; /* just drop it */
530 relay_set_digest(layer_hint->f_digest, cell);
532 thishop = layer_hint;
533 /* moving from farthest to nearest hop */
534 do {
535 tor_assert(thishop);
536 /* XXXX RD This is a bug, right? */
537 log_debug(LD_OR,"crypting a layer of the relay cell.");
538 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
539 return -1;
542 thishop = thishop->prev;
543 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
545 } else { /* incoming cell */
546 or_circuit_t *or_circ;
547 if (CIRCUIT_IS_ORIGIN(circ)) {
548 /* We should never package an _incoming_ cell from the circuit
549 * origin; that means we messed up somewhere. */
550 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
551 assert_circuit_ok(circ);
552 return 0; /* just drop it */
554 or_circ = TO_OR_CIRCUIT(circ);
555 chan = or_circ->p_chan;
556 relay_set_digest(or_circ->p_digest, cell);
557 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
558 return -1;
560 ++stats_n_relay_cells_relayed;
562 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
563 return 0;
566 /** If cell's stream_id matches the stream_id of any conn that's
567 * attached to circ, return that conn, else return NULL.
569 static edge_connection_t *
570 relay_lookup_conn(circuit_t *circ, cell_t *cell,
571 cell_direction_t cell_direction, crypt_path_t *layer_hint)
573 edge_connection_t *tmpconn;
574 relay_header_t rh;
576 relay_header_unpack(&rh, cell->payload);
578 if (!rh.stream_id)
579 return NULL;
581 /* IN or OUT cells could have come from either direction, now
582 * that we allow rendezvous *to* an OP.
585 if (CIRCUIT_IS_ORIGIN(circ)) {
586 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
587 tmpconn=tmpconn->next_stream) {
588 if (rh.stream_id == tmpconn->stream_id &&
589 !tmpconn->base_.marked_for_close &&
590 tmpconn->cpath_layer == layer_hint) {
591 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
592 return tmpconn;
595 } else {
596 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
597 tmpconn=tmpconn->next_stream) {
598 if (rh.stream_id == tmpconn->stream_id &&
599 !tmpconn->base_.marked_for_close) {
600 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
601 if (cell_direction == CELL_DIRECTION_OUT ||
602 connection_edge_is_rendezvous_stream(tmpconn))
603 return tmpconn;
606 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
607 tmpconn=tmpconn->next_stream) {
608 if (rh.stream_id == tmpconn->stream_id &&
609 !tmpconn->base_.marked_for_close) {
610 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
611 return tmpconn;
615 return NULL; /* probably a begin relay cell */
618 /** Pack the relay_header_t host-order structure <b>src</b> into
619 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
620 * about the wire format.
622 void
623 relay_header_pack(uint8_t *dest, const relay_header_t *src)
625 set_uint8(dest, src->command);
626 set_uint16(dest+1, htons(src->recognized));
627 set_uint16(dest+3, htons(src->stream_id));
628 memcpy(dest+5, src->integrity, 4);
629 set_uint16(dest+9, htons(src->length));
632 /** Unpack the network-order buffer <b>src</b> into a host-order
633 * relay_header_t structure <b>dest</b>.
635 void
636 relay_header_unpack(relay_header_t *dest, const uint8_t *src)
638 dest->command = get_uint8(src);
639 dest->recognized = ntohs(get_uint16(src+1));
640 dest->stream_id = ntohs(get_uint16(src+3));
641 memcpy(dest->integrity, src+5, 4);
642 dest->length = ntohs(get_uint16(src+9));
645 /** Convert the relay <b>command</b> into a human-readable string. */
646 static const char *
647 relay_command_to_string(uint8_t command)
649 static char buf[64];
650 switch (command) {
651 case RELAY_COMMAND_BEGIN: return "BEGIN";
652 case RELAY_COMMAND_DATA: return "DATA";
653 case RELAY_COMMAND_END: return "END";
654 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
655 case RELAY_COMMAND_SENDME: return "SENDME";
656 case RELAY_COMMAND_EXTEND: return "EXTEND";
657 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
658 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
659 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
660 case RELAY_COMMAND_DROP: return "DROP";
661 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
662 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
663 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
664 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
665 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
666 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
667 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
668 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
669 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
670 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
671 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
672 return "RENDEZVOUS_ESTABLISHED";
673 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
674 case RELAY_COMMAND_EXTEND2: return "EXTEND2";
675 case RELAY_COMMAND_EXTENDED2: return "EXTENDED2";
676 default:
677 tor_snprintf(buf, sizeof(buf), "Unrecognized relay command %u",
678 (unsigned)command);
679 return buf;
683 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
684 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
685 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
686 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
687 * destination hop for OP->OR cells.
689 * If you can't send the cell, mark the circuit for close and return -1. Else
690 * return 0.
692 MOCK_IMPL(int,
693 relay_send_command_from_edge_,(streamid_t stream_id, circuit_t *circ,
694 uint8_t relay_command, const char *payload,
695 size_t payload_len, crypt_path_t *cpath_layer,
696 const char *filename, int lineno))
698 cell_t cell;
699 relay_header_t rh;
700 cell_direction_t cell_direction;
701 /* XXXX NM Split this function into a separate versions per circuit type? */
703 tor_assert(circ);
704 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
706 memset(&cell, 0, sizeof(cell_t));
707 cell.command = CELL_RELAY;
708 if (CIRCUIT_IS_ORIGIN(circ)) {
709 tor_assert(cpath_layer);
710 cell.circ_id = circ->n_circ_id;
711 cell_direction = CELL_DIRECTION_OUT;
712 } else {
713 tor_assert(! cpath_layer);
714 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
715 cell_direction = CELL_DIRECTION_IN;
718 memset(&rh, 0, sizeof(rh));
719 rh.command = relay_command;
720 rh.stream_id = stream_id;
721 rh.length = payload_len;
722 relay_header_pack(cell.payload, &rh);
723 if (payload_len)
724 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
726 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
727 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
729 if (relay_command == RELAY_COMMAND_DROP)
730 rep_hist_padding_count_write(PADDING_TYPE_DROP);
732 /* If we are sending an END cell and this circuit is used for a tunneled
733 * directory request, advance its state. */
734 if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
735 geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
736 DIRREQ_END_CELL_SENT);
738 if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
739 /* if we're using relaybandwidthrate, this conn wants priority */
740 channel_timestamp_client(circ->n_chan);
743 if (cell_direction == CELL_DIRECTION_OUT) {
744 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
745 if (origin_circ->remaining_relay_early_cells > 0 &&
746 (relay_command == RELAY_COMMAND_EXTEND ||
747 relay_command == RELAY_COMMAND_EXTEND2 ||
748 cpath_layer != origin_circ->cpath)) {
749 /* If we've got any relay_early cells left and (we're sending
750 * an extend cell or we're not talking to the first hop), use
751 * one of them. Don't worry about the conn protocol version:
752 * append_cell_to_circuit_queue will fix it up. */
753 cell.command = CELL_RELAY_EARLY;
754 --origin_circ->remaining_relay_early_cells;
755 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
756 (int)origin_circ->remaining_relay_early_cells);
757 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
758 * task 878. */
759 origin_circ->relay_early_commands[
760 origin_circ->relay_early_cells_sent++] = relay_command;
761 } else if (relay_command == RELAY_COMMAND_EXTEND ||
762 relay_command == RELAY_COMMAND_EXTEND2) {
763 /* If no RELAY_EARLY cells can be sent over this circuit, log which
764 * commands have been sent as RELAY_EARLY cells before; helps debug
765 * task 878. */
766 smartlist_t *commands_list = smartlist_new();
767 int i = 0;
768 char *commands = NULL;
769 for (; i < origin_circ->relay_early_cells_sent; i++)
770 smartlist_add(commands_list, (char *)
771 relay_command_to_string(origin_circ->relay_early_commands[i]));
772 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
773 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
774 "but we have run out of RELAY_EARLY cells on that circuit. "
775 "Commands sent before: %s", commands);
776 tor_free(commands);
777 smartlist_free(commands_list);
781 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
782 stream_id, filename, lineno) < 0) {
783 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
784 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
785 return -1;
787 return 0;
790 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
791 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
792 * that's sending the relay cell, or NULL if it's a control cell.
793 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
794 * for OP->OR cells.
796 * If you can't send the cell, mark the circuit for close and
797 * return -1. Else return 0.
800 connection_edge_send_command(edge_connection_t *fromconn,
801 uint8_t relay_command, const char *payload,
802 size_t payload_len)
804 /* XXXX NM Split this function into a separate versions per circuit type? */
805 circuit_t *circ;
806 crypt_path_t *cpath_layer = fromconn->cpath_layer;
807 tor_assert(fromconn);
808 circ = fromconn->on_circuit;
810 if (fromconn->base_.marked_for_close) {
811 log_warn(LD_BUG,
812 "called on conn that's already marked for close at %s:%d.",
813 fromconn->base_.marked_for_close_file,
814 fromconn->base_.marked_for_close);
815 return 0;
818 if (!circ) {
819 if (fromconn->base_.type == CONN_TYPE_AP) {
820 log_info(LD_APP,"no circ. Closing conn.");
821 connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
822 END_STREAM_REASON_INTERNAL);
823 } else {
824 log_info(LD_EXIT,"no circ. Closing conn.");
825 fromconn->edge_has_sent_end = 1; /* no circ to send to */
826 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
827 connection_mark_for_close(TO_CONN(fromconn));
829 return -1;
832 if (circ->marked_for_close) {
833 /* The circuit has been marked, but not freed yet. When it's freed, it
834 * will mark this connection for close. */
835 return -1;
838 #ifdef MEASUREMENTS_21206
839 /* Keep track of the number of RELAY_DATA cells sent for directory
840 * connections. */
841 connection_t *linked_conn = TO_CONN(fromconn)->linked_conn;
843 if (linked_conn && linked_conn->type == CONN_TYPE_DIR) {
844 ++(TO_DIR_CONN(linked_conn)->data_cells_sent);
846 #endif
848 return relay_send_command_from_edge(fromconn->stream_id, circ,
849 relay_command, payload,
850 payload_len, cpath_layer);
853 /** How many times will I retry a stream that fails due to DNS
854 * resolve failure or misc error?
856 #define MAX_RESOLVE_FAILURES 3
858 /** Return 1 if reason is something that you should retry if you
859 * get the end cell before you've connected; else return 0. */
860 static int
861 edge_reason_is_retriable(int reason)
863 return reason == END_STREAM_REASON_HIBERNATING ||
864 reason == END_STREAM_REASON_RESOURCELIMIT ||
865 reason == END_STREAM_REASON_EXITPOLICY ||
866 reason == END_STREAM_REASON_RESOLVEFAILED ||
867 reason == END_STREAM_REASON_MISC ||
868 reason == END_STREAM_REASON_NOROUTE;
871 /** Called when we receive an END cell on a stream that isn't open yet,
872 * from the client side.
873 * Arguments are as for connection_edge_process_relay_cell().
875 static int
876 connection_ap_process_end_not_open(
877 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
878 entry_connection_t *conn, crypt_path_t *layer_hint)
880 node_t *exitrouter;
881 int reason = *(cell->payload+RELAY_HEADER_SIZE);
882 int control_reason;
883 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
884 (void) layer_hint; /* unused */
886 if (rh->length > 0) {
887 if (reason == END_STREAM_REASON_TORPROTOCOL ||
888 reason == END_STREAM_REASON_DESTROY) {
889 /* Both of these reasons could mean a failed tag
890 * hit the exit and it complained. Do not probe.
891 * Fail the circuit. */
892 circ->path_state = PATH_STATE_USE_FAILED;
893 return -END_CIRC_REASON_TORPROTOCOL;
894 } else if (reason == END_STREAM_REASON_INTERNAL) {
895 /* We can't infer success or failure, since older Tors report
896 * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
897 } else {
898 /* Path bias: If we get a valid reason code from the exit,
899 * it wasn't due to tagging.
901 * We rely on recognized+digest being strong enough to make
902 * tags unlikely to allow us to get tagged, yet 'recognized'
903 * reason codes here. */
904 pathbias_mark_use_success(circ);
908 if (rh->length == 0) {
909 reason = END_STREAM_REASON_MISC;
912 control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
914 if (edge_reason_is_retriable(reason) &&
915 /* avoid retry if rend */
916 !connection_edge_is_rendezvous_stream(edge_conn)) {
917 const char *chosen_exit_digest =
918 circ->build_state->chosen_exit->identity_digest;
919 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
920 safe_str(conn->socks_request->address),
921 stream_end_reason_to_string(reason));
922 exitrouter = node_get_mutable_by_id(chosen_exit_digest);
923 switch (reason) {
924 case END_STREAM_REASON_EXITPOLICY: {
925 tor_addr_t addr;
926 tor_addr_make_unspec(&addr);
927 if (rh->length >= 5) {
928 int ttl = -1;
929 tor_addr_make_unspec(&addr);
930 if (rh->length == 5 || rh->length == 9) {
931 tor_addr_from_ipv4n(&addr,
932 get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
933 if (rh->length == 9)
934 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
935 } else if (rh->length == 17 || rh->length == 21) {
936 tor_addr_from_ipv6_bytes(&addr,
937 (char*)(cell->payload+RELAY_HEADER_SIZE+1));
938 if (rh->length == 21)
939 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
941 if (tor_addr_is_null(&addr)) {
942 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
943 safe_str(conn->socks_request->address));
944 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
945 return 0;
948 if ((tor_addr_family(&addr) == AF_INET &&
949 !conn->entry_cfg.ipv4_traffic) ||
950 (tor_addr_family(&addr) == AF_INET6 &&
951 !conn->entry_cfg.ipv6_traffic)) {
952 log_fn(LOG_PROTOCOL_WARN, LD_APP,
953 "Got an EXITPOLICY failure on a connection with a "
954 "mismatched family. Closing.");
955 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
956 return 0;
958 if (get_options()->ClientDNSRejectInternalAddresses &&
959 tor_addr_is_internal(&addr, 0)) {
960 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
961 safe_str(conn->socks_request->address));
962 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
963 return 0;
966 client_dns_set_addressmap(conn,
967 conn->socks_request->address, &addr,
968 conn->chosen_exit_name, ttl);
971 char new_addr[TOR_ADDR_BUF_LEN];
972 tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
973 if (strcmp(conn->socks_request->address, new_addr)) {
974 strlcpy(conn->socks_request->address, new_addr,
975 sizeof(conn->socks_request->address));
976 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
980 /* check if the exit *ought* to have allowed it */
982 adjust_exit_policy_from_exitpolicy_failure(circ,
983 conn,
984 exitrouter,
985 &addr);
987 if (conn->chosen_exit_optional ||
988 conn->chosen_exit_retries) {
989 /* stop wanting a specific exit */
990 conn->chosen_exit_optional = 0;
991 /* A non-zero chosen_exit_retries can happen if we set a
992 * TrackHostExits for this address under a port that the exit
993 * relay allows, but then try the same address with a different
994 * port that it doesn't allow to exit. We shouldn't unregister
995 * the mapping, since it is probably still wanted on the
996 * original port. But now we give away to the exit relay that
997 * we probably have a TrackHostExits on it. So be it. */
998 conn->chosen_exit_retries = 0;
999 tor_free(conn->chosen_exit_name); /* clears it */
1001 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
1002 return 0;
1003 /* else, conn will get closed below */
1004 break;
1006 case END_STREAM_REASON_CONNECTREFUSED:
1007 if (!conn->chosen_exit_optional)
1008 break; /* break means it'll close, below */
1009 /* Else fall through: expire this circuit, clear the
1010 * chosen_exit_name field, and try again. */
1011 /* Falls through. */
1012 case END_STREAM_REASON_RESOLVEFAILED:
1013 case END_STREAM_REASON_TIMEOUT:
1014 case END_STREAM_REASON_MISC:
1015 case END_STREAM_REASON_NOROUTE:
1016 if (client_dns_incr_failures(conn->socks_request->address)
1017 < MAX_RESOLVE_FAILURES) {
1018 /* We haven't retried too many times; reattach the connection. */
1019 circuit_log_path(LOG_INFO,LD_APP,circ);
1020 /* Mark this circuit "unusable for new streams". */
1021 mark_circuit_unusable_for_new_conns(circ);
1023 if (conn->chosen_exit_optional) {
1024 /* stop wanting a specific exit */
1025 conn->chosen_exit_optional = 0;
1026 tor_free(conn->chosen_exit_name); /* clears it */
1028 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
1029 return 0;
1030 /* else, conn will get closed below */
1031 } else {
1032 log_notice(LD_APP,
1033 "Have tried resolving or connecting to address '%s' "
1034 "at %d different places. Giving up.",
1035 safe_str(conn->socks_request->address),
1036 MAX_RESOLVE_FAILURES);
1037 /* clear the failures, so it will have a full try next time */
1038 client_dns_clear_failures(conn->socks_request->address);
1040 break;
1041 case END_STREAM_REASON_HIBERNATING:
1042 case END_STREAM_REASON_RESOURCELIMIT:
1043 if (exitrouter) {
1044 policies_set_node_exitpolicy_to_reject_all(exitrouter);
1046 if (conn->chosen_exit_optional) {
1047 /* stop wanting a specific exit */
1048 conn->chosen_exit_optional = 0;
1049 tor_free(conn->chosen_exit_name); /* clears it */
1051 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
1052 return 0;
1053 /* else, will close below */
1054 break;
1055 } /* end switch */
1056 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
1059 log_info(LD_APP,
1060 "Edge got end (%s) before we're connected. Marking for close.",
1061 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
1062 circuit_log_path(LOG_INFO,LD_APP,circ);
1063 /* need to test because of detach_retriable */
1064 if (!ENTRY_TO_CONN(conn)->marked_for_close)
1065 connection_mark_unattached_ap(conn, control_reason);
1066 return 0;
1069 /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
1070 * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
1071 * told us which address it rejected, then <b>addr</b> is that address;
1072 * otherwise it is AF_UNSPEC.
1074 * If we are sure the node should have allowed this address, mark the node as
1075 * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
1076 * for this particular address.
1078 static void
1079 adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
1080 entry_connection_t *conn,
1081 node_t *node,
1082 const tor_addr_t *addr)
1084 int make_reject_all = 0;
1085 const sa_family_t family = tor_addr_family(addr);
1087 if (node) {
1088 tor_addr_t tmp;
1089 int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
1090 if (family == AF_UNSPEC) {
1091 make_reject_all = 1;
1092 } else if (node_exit_policy_is_exact(node, family) &&
1093 asked_for_family != -1 && !conn->chosen_exit_name) {
1094 make_reject_all = 1;
1097 if (make_reject_all) {
1098 log_info(LD_APP,
1099 "Exitrouter %s seems to be more restrictive than its exit "
1100 "policy. Not using this router as exit for now.",
1101 node_describe(node));
1102 policies_set_node_exitpolicy_to_reject_all(node);
1106 if (family != AF_UNSPEC)
1107 addr_policy_append_reject_addr(&circ->prepend_policy, addr);
1110 /** Helper: change the socks_request-&gt;address field on conn to the
1111 * dotted-quad representation of <b>new_addr</b>,
1112 * and send an appropriate REMAP event. */
1113 static void
1114 remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
1116 tor_addr_to_str(conn->socks_request->address, new_addr,
1117 sizeof(conn->socks_request->address),
1119 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1120 REMAP_STREAM_SOURCE_EXIT);
1123 /** Extract the contents of a connected cell in <b>cell</b>, whose relay
1124 * header has already been parsed into <b>rh</b>. On success, set
1125 * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
1126 * the ttl of that address, in seconds, and return 0. On failure, return
1127 * -1. */
1128 STATIC int
1129 connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
1130 tor_addr_t *addr_out, int *ttl_out)
1132 uint32_t bytes;
1133 const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
1135 tor_addr_make_unspec(addr_out);
1136 *ttl_out = -1;
1137 if (rh->length == 0)
1138 return 0;
1139 if (rh->length < 4)
1140 return -1;
1141 bytes = ntohl(get_uint32(payload));
1143 /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
1144 if (bytes != 0) {
1145 /* v4 address */
1146 tor_addr_from_ipv4h(addr_out, bytes);
1147 if (rh->length >= 8) {
1148 bytes = ntohl(get_uint32(payload + 4));
1149 if (bytes <= INT32_MAX)
1150 *ttl_out = bytes;
1152 } else {
1153 if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
1154 return -1;
1155 if (get_uint8(payload + 4) != 6)
1156 return -1;
1157 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
1158 bytes = ntohl(get_uint32(payload + 21));
1159 if (bytes <= INT32_MAX)
1160 *ttl_out = (int) bytes;
1162 return 0;
1165 /** Drop all storage held by <b>addr</b>. */
1166 STATIC void
1167 address_ttl_free(address_ttl_t *addr)
1169 if (!addr)
1170 return;
1171 tor_free(addr->hostname);
1172 tor_free(addr);
1175 /** Parse a resolved cell in <b>cell</b>, with parsed header in <b>rh</b>.
1176 * Return -1 on parse error. On success, add one or more newly allocated
1177 * address_ttl_t to <b>addresses_out</b>; set *<b>errcode_out</b> to
1178 * one of 0, RESOLVED_TYPE_ERROR, or RESOLVED_TYPE_ERROR_TRANSIENT, and
1179 * return 0. */
1180 STATIC int
1181 resolved_cell_parse(const cell_t *cell, const relay_header_t *rh,
1182 smartlist_t *addresses_out, int *errcode_out)
1184 const uint8_t *cp;
1185 uint8_t answer_type;
1186 size_t answer_len;
1187 address_ttl_t *addr;
1188 size_t remaining;
1189 int errcode = 0;
1190 smartlist_t *addrs;
1192 tor_assert(cell);
1193 tor_assert(rh);
1194 tor_assert(addresses_out);
1195 tor_assert(errcode_out);
1197 *errcode_out = 0;
1199 if (rh->length > RELAY_PAYLOAD_SIZE)
1200 return -1;
1202 addrs = smartlist_new();
1204 cp = cell->payload + RELAY_HEADER_SIZE;
1206 remaining = rh->length;
1207 while (remaining) {
1208 const uint8_t *cp_orig = cp;
1209 if (remaining < 2)
1210 goto err;
1211 answer_type = *cp++;
1212 answer_len = *cp++;
1213 if (remaining < 2 + answer_len + 4) {
1214 goto err;
1216 if (answer_type == RESOLVED_TYPE_IPV4) {
1217 if (answer_len != 4) {
1218 goto err;
1220 addr = tor_malloc_zero(sizeof(*addr));
1221 tor_addr_from_ipv4n(&addr->addr, get_uint32(cp));
1222 cp += 4;
1223 addr->ttl = ntohl(get_uint32(cp));
1224 cp += 4;
1225 smartlist_add(addrs, addr);
1226 } else if (answer_type == RESOLVED_TYPE_IPV6) {
1227 if (answer_len != 16)
1228 goto err;
1229 addr = tor_malloc_zero(sizeof(*addr));
1230 tor_addr_from_ipv6_bytes(&addr->addr, (const char*) cp);
1231 cp += 16;
1232 addr->ttl = ntohl(get_uint32(cp));
1233 cp += 4;
1234 smartlist_add(addrs, addr);
1235 } else if (answer_type == RESOLVED_TYPE_HOSTNAME) {
1236 if (answer_len == 0) {
1237 goto err;
1239 addr = tor_malloc_zero(sizeof(*addr));
1240 addr->hostname = tor_memdup_nulterm(cp, answer_len);
1241 cp += answer_len;
1242 addr->ttl = ntohl(get_uint32(cp));
1243 cp += 4;
1244 smartlist_add(addrs, addr);
1245 } else if (answer_type == RESOLVED_TYPE_ERROR_TRANSIENT ||
1246 answer_type == RESOLVED_TYPE_ERROR) {
1247 errcode = answer_type;
1248 /* Ignore the error contents */
1249 cp += answer_len + 4;
1250 } else {
1251 cp += answer_len + 4;
1253 tor_assert(((ssize_t)remaining) >= (cp - cp_orig));
1254 remaining -= (cp - cp_orig);
1257 if (errcode && smartlist_len(addrs) == 0) {
1258 /* Report an error only if there were no results. */
1259 *errcode_out = errcode;
1262 smartlist_add_all(addresses_out, addrs);
1263 smartlist_free(addrs);
1265 return 0;
1267 err:
1268 /* On parse error, don't report any results */
1269 SMARTLIST_FOREACH(addrs, address_ttl_t *, a, address_ttl_free(a));
1270 smartlist_free(addrs);
1271 return -1;
1274 /** Helper for connection_edge_process_resolved_cell: given an error code,
1275 * an entry_connection, and a list of address_ttl_t *, report the best answer
1276 * to the entry_connection. */
1277 static void
1278 connection_ap_handshake_socks_got_resolved_cell(entry_connection_t *conn,
1279 int error_code,
1280 smartlist_t *results)
1282 address_ttl_t *addr_ipv4 = NULL;
1283 address_ttl_t *addr_ipv6 = NULL;
1284 address_ttl_t *addr_hostname = NULL;
1285 address_ttl_t *addr_best = NULL;
1287 /* If it's an error code, that's easy. */
1288 if (error_code) {
1289 tor_assert(error_code == RESOLVED_TYPE_ERROR ||
1290 error_code == RESOLVED_TYPE_ERROR_TRANSIENT);
1291 connection_ap_handshake_socks_resolved(conn,
1292 error_code,0,NULL,-1,-1);
1293 return;
1296 /* Get the first answer of each type. */
1297 SMARTLIST_FOREACH_BEGIN(results, address_ttl_t *, addr) {
1298 if (addr->hostname) {
1299 if (!addr_hostname) {
1300 addr_hostname = addr;
1302 } else if (tor_addr_family(&addr->addr) == AF_INET) {
1303 if (!addr_ipv4 && conn->entry_cfg.ipv4_traffic) {
1304 addr_ipv4 = addr;
1306 } else if (tor_addr_family(&addr->addr) == AF_INET6) {
1307 if (!addr_ipv6 && conn->entry_cfg.ipv6_traffic) {
1308 addr_ipv6 = addr;
1311 } SMARTLIST_FOREACH_END(addr);
1313 /* Now figure out which type we wanted to deliver. */
1314 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR) {
1315 if (addr_hostname) {
1316 connection_ap_handshake_socks_resolved(conn,
1317 RESOLVED_TYPE_HOSTNAME,
1318 strlen(addr_hostname->hostname),
1319 (uint8_t*)addr_hostname->hostname,
1320 addr_hostname->ttl,-1);
1321 } else {
1322 connection_ap_handshake_socks_resolved(conn,
1323 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1325 return;
1328 if (conn->entry_cfg.prefer_ipv6) {
1329 addr_best = addr_ipv6 ? addr_ipv6 : addr_ipv4;
1330 } else {
1331 addr_best = addr_ipv4 ? addr_ipv4 : addr_ipv6;
1334 /* Now convert it to the ugly old interface */
1335 if (! addr_best) {
1336 connection_ap_handshake_socks_resolved(conn,
1337 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1338 return;
1341 connection_ap_handshake_socks_resolved_addr(conn,
1342 &addr_best->addr,
1343 addr_best->ttl,
1344 -1);
1346 remap_event_helper(conn, &addr_best->addr);
1349 /** Handle a RELAY_COMMAND_RESOLVED cell that we received on a non-open AP
1350 * stream. */
1351 STATIC int
1352 connection_edge_process_resolved_cell(edge_connection_t *conn,
1353 const cell_t *cell,
1354 const relay_header_t *rh)
1356 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1357 smartlist_t *resolved_addresses = NULL;
1358 int errcode = 0;
1360 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
1361 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
1362 "not in state resolve_wait. Dropping.");
1363 return 0;
1365 tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
1367 resolved_addresses = smartlist_new();
1368 if (resolved_cell_parse(cell, rh, resolved_addresses, &errcode)) {
1369 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1370 "Dropping malformed 'resolved' cell");
1371 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1372 goto done;
1375 if (get_options()->ClientDNSRejectInternalAddresses) {
1376 int orig_len = smartlist_len(resolved_addresses);
1377 SMARTLIST_FOREACH_BEGIN(resolved_addresses, address_ttl_t *, addr) {
1378 if (addr->hostname == NULL && tor_addr_is_internal(&addr->addr, 0)) {
1379 log_info(LD_APP, "Got a resolved cell with answer %s; dropping that "
1380 "answer.",
1381 safe_str_client(fmt_addr(&addr->addr)));
1382 address_ttl_free(addr);
1383 SMARTLIST_DEL_CURRENT(resolved_addresses, addr);
1385 } SMARTLIST_FOREACH_END(addr);
1386 if (orig_len && smartlist_len(resolved_addresses) == 0) {
1387 log_info(LD_APP, "Got a resolved cell with only private addresses; "
1388 "dropping it.");
1389 connection_ap_handshake_socks_resolved(entry_conn,
1390 RESOLVED_TYPE_ERROR_TRANSIENT,
1391 0, NULL, 0, TIME_MAX);
1392 connection_mark_unattached_ap(entry_conn,
1393 END_STREAM_REASON_TORPROTOCOL);
1394 goto done;
1398 connection_ap_handshake_socks_got_resolved_cell(entry_conn,
1399 errcode,
1400 resolved_addresses);
1402 connection_mark_unattached_ap(entry_conn,
1403 END_STREAM_REASON_DONE |
1404 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1406 done:
1407 SMARTLIST_FOREACH(resolved_addresses, address_ttl_t *, addr,
1408 address_ttl_free(addr));
1409 smartlist_free(resolved_addresses);
1410 return 0;
1413 /** An incoming relay cell has arrived from circuit <b>circ</b> to
1414 * stream <b>conn</b>.
1416 * The arguments here are the same as in
1417 * connection_edge_process_relay_cell() below; this function is called
1418 * from there when <b>conn</b> is defined and not in an open state.
1420 static int
1421 connection_edge_process_relay_cell_not_open(
1422 relay_header_t *rh, cell_t *cell, circuit_t *circ,
1423 edge_connection_t *conn, crypt_path_t *layer_hint)
1425 if (rh->command == RELAY_COMMAND_END) {
1426 if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
1427 return connection_ap_process_end_not_open(rh, cell,
1428 TO_ORIGIN_CIRCUIT(circ),
1429 EDGE_TO_ENTRY_CONN(conn),
1430 layer_hint);
1431 } else {
1432 /* we just got an 'end', don't need to send one */
1433 conn->edge_has_sent_end = 1;
1434 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
1435 END_STREAM_REASON_FLAG_REMOTE;
1436 connection_mark_for_close(TO_CONN(conn));
1437 return 0;
1441 if (conn->base_.type == CONN_TYPE_AP &&
1442 rh->command == RELAY_COMMAND_CONNECTED) {
1443 tor_addr_t addr;
1444 int ttl;
1445 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1446 tor_assert(CIRCUIT_IS_ORIGIN(circ));
1447 if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
1448 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1449 "Got 'connected' while not in state connect_wait. Dropping.");
1450 return 0;
1452 CONNECTION_AP_EXPECT_NONPENDING(entry_conn);
1453 conn->base_.state = AP_CONN_STATE_OPEN;
1454 log_info(LD_APP,"'connected' received for circid %u streamid %d "
1455 "after %d seconds.",
1456 (unsigned)circ->n_circ_id,
1457 rh->stream_id,
1458 (int)(time(NULL) - conn->base_.timestamp_lastread));
1459 if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
1460 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1461 "Got a badly formatted connected cell. Closing.");
1462 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1463 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1465 if (tor_addr_family(&addr) != AF_UNSPEC) {
1466 const sa_family_t family = tor_addr_family(&addr);
1467 if (tor_addr_is_null(&addr) ||
1468 (get_options()->ClientDNSRejectInternalAddresses &&
1469 tor_addr_is_internal(&addr, 0))) {
1470 log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
1471 fmt_addr(&addr));
1472 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1473 connection_mark_unattached_ap(entry_conn,
1474 END_STREAM_REASON_TORPROTOCOL);
1475 return 0;
1478 if ((family == AF_INET && ! entry_conn->entry_cfg.ipv4_traffic) ||
1479 (family == AF_INET6 && ! entry_conn->entry_cfg.ipv6_traffic)) {
1480 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1481 "Got a connected cell to %s with unsupported address family."
1482 " Closing.", fmt_addr(&addr));
1483 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1484 connection_mark_unattached_ap(entry_conn,
1485 END_STREAM_REASON_TORPROTOCOL);
1486 return 0;
1489 client_dns_set_addressmap(entry_conn,
1490 entry_conn->socks_request->address, &addr,
1491 entry_conn->chosen_exit_name, ttl);
1493 remap_event_helper(entry_conn, &addr);
1495 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
1496 /* don't send a socks reply to transparent conns */
1497 tor_assert(entry_conn->socks_request != NULL);
1498 if (!entry_conn->socks_request->has_finished)
1499 connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
1501 /* Was it a linked dir conn? If so, a dir request just started to
1502 * fetch something; this could be a bootstrap status milestone. */
1503 log_debug(LD_APP, "considering");
1504 if (TO_CONN(conn)->linked_conn &&
1505 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
1506 connection_t *dirconn = TO_CONN(conn)->linked_conn;
1507 log_debug(LD_APP, "it is! %d", dirconn->purpose);
1508 switch (dirconn->purpose) {
1509 case DIR_PURPOSE_FETCH_CERTIFICATE:
1510 if (consensus_is_waiting_for_certs())
1511 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
1512 break;
1513 case DIR_PURPOSE_FETCH_CONSENSUS:
1514 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
1515 break;
1516 case DIR_PURPOSE_FETCH_SERVERDESC:
1517 case DIR_PURPOSE_FETCH_MICRODESC:
1518 if (TO_DIR_CONN(dirconn)->router_purpose == ROUTER_PURPOSE_GENERAL)
1519 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
1520 count_loading_descriptors_progress());
1521 break;
1524 /* This is definitely a success, so forget about any pending data we
1525 * had sent. */
1526 if (entry_conn->pending_optimistic_data) {
1527 buf_free(entry_conn->pending_optimistic_data);
1528 entry_conn->pending_optimistic_data = NULL;
1531 /* handle anything that might have queued */
1532 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1533 /* (We already sent an end cell if possible) */
1534 connection_mark_for_close(TO_CONN(conn));
1535 return 0;
1537 return 0;
1539 if (conn->base_.type == CONN_TYPE_AP &&
1540 rh->command == RELAY_COMMAND_RESOLVED) {
1541 return connection_edge_process_resolved_cell(conn, cell, rh);
1544 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1545 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
1546 rh->command, conn->base_.state,
1547 conn_state_to_string(conn->base_.type, conn->base_.state));
1548 return 0; /* for forward compatibility, don't kill the circuit */
1549 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1550 // connection_mark_for_close(conn);
1551 // return -1;
1554 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
1555 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
1556 * destined for <b>conn</b>.
1558 * If <b>layer_hint</b> is defined, then we're the origin of the
1559 * circuit, and it specifies the hop that packaged <b>cell</b>.
1561 * Return -reason if you want to warn and tear down the circuit, else 0.
1563 static int
1564 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
1565 edge_connection_t *conn,
1566 crypt_path_t *layer_hint)
1568 static int num_seen=0;
1569 relay_header_t rh;
1570 unsigned domain = layer_hint?LD_APP:LD_EXIT;
1571 int reason;
1572 int optimistic_data = 0; /* Set to 1 if we receive data on a stream
1573 * that's in the EXIT_CONN_STATE_RESOLVING
1574 * or EXIT_CONN_STATE_CONNECTING states. */
1576 tor_assert(cell);
1577 tor_assert(circ);
1579 relay_header_unpack(&rh, cell->payload);
1580 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1581 num_seen++;
1582 log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
1583 num_seen, rh.command, rh.stream_id);
1585 if (rh.length > RELAY_PAYLOAD_SIZE) {
1586 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1587 "Relay cell length field too long. Closing circuit.");
1588 return - END_CIRC_REASON_TORPROTOCOL;
1591 if (rh.stream_id == 0) {
1592 switch (rh.command) {
1593 case RELAY_COMMAND_BEGIN:
1594 case RELAY_COMMAND_CONNECTED:
1595 case RELAY_COMMAND_END:
1596 case RELAY_COMMAND_RESOLVE:
1597 case RELAY_COMMAND_RESOLVED:
1598 case RELAY_COMMAND_BEGIN_DIR:
1599 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
1600 "stream_id. Dropping.", (int)rh.command);
1601 return 0;
1602 default:
1607 /* either conn is NULL, in which case we've got a control cell, or else
1608 * conn points to the recognized stream. */
1610 if (conn && !connection_state_is_open(TO_CONN(conn))) {
1611 if (conn->base_.type == CONN_TYPE_EXIT &&
1612 (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
1613 conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
1614 rh.command == RELAY_COMMAND_DATA) {
1615 /* Allow DATA cells to be delivered to an exit node in state
1616 * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
1617 * This speeds up HTTP, for example. */
1618 optimistic_data = 1;
1619 } else if (rh.stream_id == 0 && rh.command == RELAY_COMMAND_DATA) {
1620 log_warn(LD_BUG, "Somehow I had a connection that matched a "
1621 "data cell with stream ID 0.");
1622 } else {
1623 return connection_edge_process_relay_cell_not_open(
1624 &rh, cell, circ, conn, layer_hint);
1628 switch (rh.command) {
1629 case RELAY_COMMAND_DROP:
1630 rep_hist_padding_count_read(PADDING_TYPE_DROP);
1631 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1632 return 0;
1633 case RELAY_COMMAND_BEGIN:
1634 case RELAY_COMMAND_BEGIN_DIR:
1635 if (layer_hint &&
1636 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1637 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1638 "Relay begin request unsupported at AP. Dropping.");
1639 return 0;
1641 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1642 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1643 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1644 "Relay begin request to Hidden Service "
1645 "from intermediary node. Dropping.");
1646 return 0;
1648 if (conn) {
1649 log_fn(LOG_PROTOCOL_WARN, domain,
1650 "Begin cell for known stream. Dropping.");
1651 return 0;
1653 if (rh.command == RELAY_COMMAND_BEGIN_DIR &&
1654 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1655 /* Assign this circuit and its app-ward OR connection a unique ID,
1656 * so that we can measure download times. The local edge and dir
1657 * connection will be assigned the same ID when they are created
1658 * and linked. */
1659 static uint64_t next_id = 0;
1660 circ->dirreq_id = ++next_id;
1661 TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
1664 return connection_exit_begin_conn(cell, circ);
1665 case RELAY_COMMAND_DATA:
1666 ++stats_n_data_cells_received;
1667 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1668 (!layer_hint && --circ->deliver_window < 0)) {
1669 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1670 "(relay data) circ deliver_window below 0. Killing.");
1671 if (conn) {
1672 /* XXXX Do we actually need to do this? Will killing the circuit
1673 * not send an END and mark the stream for close as appropriate? */
1674 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1675 connection_mark_for_close(TO_CONN(conn));
1677 return -END_CIRC_REASON_TORPROTOCOL;
1679 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1680 layer_hint->deliver_window : circ->deliver_window);
1682 circuit_consider_sending_sendme(circ, layer_hint);
1684 if (rh.stream_id == 0) {
1685 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay data cell with zero "
1686 "stream_id. Dropping.");
1687 return 0;
1688 } else if (!conn) {
1689 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1690 rh.stream_id);
1691 return 0;
1694 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1695 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1696 "(relay data) conn deliver_window below 0. Killing.");
1697 return -END_CIRC_REASON_TORPROTOCOL;
1700 stats_n_data_bytes_received += rh.length;
1701 connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
1702 rh.length, TO_CONN(conn));
1704 #ifdef MEASUREMENTS_21206
1705 /* Count number of RELAY_DATA cells received on a linked directory
1706 * connection. */
1707 connection_t *linked_conn = TO_CONN(conn)->linked_conn;
1709 if (linked_conn && linked_conn->type == CONN_TYPE_DIR) {
1710 ++(TO_DIR_CONN(linked_conn)->data_cells_received);
1712 #endif
1714 if (!optimistic_data) {
1715 /* Only send a SENDME if we're not getting optimistic data; otherwise
1716 * a SENDME could arrive before the CONNECTED.
1718 connection_edge_consider_sending_sendme(conn);
1721 return 0;
1722 case RELAY_COMMAND_END:
1723 reason = rh.length > 0 ?
1724 get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1725 if (!conn) {
1726 log_info(domain,"end cell (%s) dropped, unknown stream.",
1727 stream_end_reason_to_string(reason));
1728 return 0;
1730 /* XXX add to this log_fn the exit node's nickname? */
1731 log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
1732 "Removing stream.",
1733 conn->base_.s,
1734 stream_end_reason_to_string(reason),
1735 conn->stream_id);
1736 if (conn->base_.type == CONN_TYPE_AP) {
1737 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1738 if (entry_conn->socks_request &&
1739 !entry_conn->socks_request->has_finished)
1740 log_warn(LD_BUG,
1741 "open stream hasn't sent socks answer yet? Closing.");
1743 /* We just *got* an end; no reason to send one. */
1744 conn->edge_has_sent_end = 1;
1745 if (!conn->end_reason)
1746 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1747 if (!conn->base_.marked_for_close) {
1748 /* only mark it if not already marked. it's possible to
1749 * get the 'end' right around when the client hangs up on us. */
1750 connection_mark_and_flush(TO_CONN(conn));
1752 return 0;
1753 case RELAY_COMMAND_EXTEND:
1754 case RELAY_COMMAND_EXTEND2: {
1755 static uint64_t total_n_extend=0, total_nonearly=0;
1756 total_n_extend++;
1757 if (rh.stream_id) {
1758 log_fn(LOG_PROTOCOL_WARN, domain,
1759 "'extend' cell received for non-zero stream. Dropping.");
1760 return 0;
1762 if (cell->command != CELL_RELAY_EARLY &&
1763 !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
1764 #define EARLY_WARNING_INTERVAL 3600
1765 static ratelim_t early_warning_limit =
1766 RATELIM_INIT(EARLY_WARNING_INTERVAL);
1767 char *m;
1768 if (cell->command == CELL_RELAY) {
1769 ++total_nonearly;
1770 if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
1771 double percentage = ((double)total_nonearly)/total_n_extend;
1772 percentage *= 100;
1773 log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
1774 "but not via RELAY_EARLY. Dropping.%s", m);
1775 log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
1776 "all EXTEND cells for this reason)", percentage);
1777 tor_free(m);
1779 } else {
1780 log_fn(LOG_WARN, domain,
1781 "EXTEND cell received, in a cell with type %d! Dropping.",
1782 cell->command);
1784 return 0;
1786 return circuit_extend(cell, circ);
1788 case RELAY_COMMAND_EXTENDED:
1789 case RELAY_COMMAND_EXTENDED2:
1790 if (!layer_hint) {
1791 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1792 "'extended' unsupported at non-origin. Dropping.");
1793 return 0;
1795 log_debug(domain,"Got an extended cell! Yay.");
1797 extended_cell_t extended_cell;
1798 if (extended_cell_parse(&extended_cell, rh.command,
1799 (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
1800 rh.length)<0) {
1801 log_warn(LD_PROTOCOL,
1802 "Can't parse EXTENDED cell; killing circuit.");
1803 return -END_CIRC_REASON_TORPROTOCOL;
1805 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1806 &extended_cell.created_cell)) < 0) {
1807 circuit_mark_for_close(circ, -reason);
1808 return 0; /* We don't want to cause a warning, so we mark the circuit
1809 * here. */
1812 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1813 log_info(domain,"circuit_send_next_onion_skin() failed.");
1814 return reason;
1816 return 0;
1817 case RELAY_COMMAND_TRUNCATE:
1818 if (layer_hint) {
1819 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1820 "'truncate' unsupported at origin. Dropping.");
1821 return 0;
1823 if (circ->n_hop) {
1824 if (circ->n_chan)
1825 log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
1826 extend_info_free(circ->n_hop);
1827 circ->n_hop = NULL;
1828 tor_free(circ->n_chan_create_cell);
1829 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
1831 if (circ->n_chan) {
1832 uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
1833 circuit_clear_cell_queue(circ, circ->n_chan);
1834 channel_send_destroy(circ->n_circ_id, circ->n_chan,
1835 trunc_reason);
1836 circuit_set_n_circid_chan(circ, 0, NULL);
1838 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1840 char payload[1];
1841 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1842 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1843 payload, sizeof(payload), NULL);
1845 return 0;
1846 case RELAY_COMMAND_TRUNCATED:
1847 if (!layer_hint) {
1848 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1849 "'truncated' unsupported at non-origin. Dropping.");
1850 return 0;
1852 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
1853 get_uint8(cell->payload + RELAY_HEADER_SIZE));
1854 return 0;
1855 case RELAY_COMMAND_CONNECTED:
1856 if (conn) {
1857 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1858 "'connected' unsupported while open. Closing circ.");
1859 return -END_CIRC_REASON_TORPROTOCOL;
1861 log_info(domain,
1862 "'connected' received on circid %u for streamid %d, "
1863 "no conn attached anymore. Ignoring.",
1864 (unsigned)circ->n_circ_id, rh.stream_id);
1865 return 0;
1866 case RELAY_COMMAND_SENDME:
1867 if (!rh.stream_id) {
1868 if (layer_hint) {
1869 if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
1870 CIRCWINDOW_START_MAX) {
1871 static struct ratelim_t exit_warn_ratelim = RATELIM_INIT(600);
1872 log_fn_ratelim(&exit_warn_ratelim, LOG_WARN, LD_PROTOCOL,
1873 "Unexpected sendme cell from exit relay. "
1874 "Closing circ.");
1875 return -END_CIRC_REASON_TORPROTOCOL;
1877 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1878 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1879 layer_hint->package_window);
1880 circuit_resume_edge_reading(circ, layer_hint);
1881 } else {
1882 if (circ->package_window + CIRCWINDOW_INCREMENT >
1883 CIRCWINDOW_START_MAX) {
1884 static struct ratelim_t client_warn_ratelim = RATELIM_INIT(600);
1885 log_fn_ratelim(&client_warn_ratelim,LOG_PROTOCOL_WARN, LD_PROTOCOL,
1886 "Unexpected sendme cell from client. "
1887 "Closing circ (window %d).",
1888 circ->package_window);
1889 return -END_CIRC_REASON_TORPROTOCOL;
1891 circ->package_window += CIRCWINDOW_INCREMENT;
1892 log_debug(LD_APP,
1893 "circ-level sendme at non-origin, packagewindow %d.",
1894 circ->package_window);
1895 circuit_resume_edge_reading(circ, layer_hint);
1897 return 0;
1899 if (!conn) {
1900 log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
1901 rh.stream_id);
1902 return 0;
1904 conn->package_window += STREAMWINDOW_INCREMENT;
1905 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1906 conn->package_window);
1907 if (circuit_queue_streams_are_blocked(circ)) {
1908 /* Still waiting for queue to flush; don't touch conn */
1909 return 0;
1911 connection_start_reading(TO_CONN(conn));
1912 /* handle whatever might still be on the inbuf */
1913 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1914 /* (We already sent an end cell if possible) */
1915 connection_mark_for_close(TO_CONN(conn));
1916 return 0;
1918 return 0;
1919 case RELAY_COMMAND_RESOLVE:
1920 if (layer_hint) {
1921 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1922 "resolve request unsupported at AP; dropping.");
1923 return 0;
1924 } else if (conn) {
1925 log_fn(LOG_PROTOCOL_WARN, domain,
1926 "resolve request for known stream; dropping.");
1927 return 0;
1928 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1929 log_fn(LOG_PROTOCOL_WARN, domain,
1930 "resolve request on circ with purpose %d; dropping",
1931 circ->purpose);
1932 return 0;
1934 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1935 return 0;
1936 case RELAY_COMMAND_RESOLVED:
1937 if (conn) {
1938 log_fn(LOG_PROTOCOL_WARN, domain,
1939 "'resolved' unsupported while open. Closing circ.");
1940 return -END_CIRC_REASON_TORPROTOCOL;
1942 log_info(domain,
1943 "'resolved' received, no conn attached anymore. Ignoring.");
1944 return 0;
1945 case RELAY_COMMAND_ESTABLISH_INTRO:
1946 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1947 case RELAY_COMMAND_INTRODUCE1:
1948 case RELAY_COMMAND_INTRODUCE2:
1949 case RELAY_COMMAND_INTRODUCE_ACK:
1950 case RELAY_COMMAND_RENDEZVOUS1:
1951 case RELAY_COMMAND_RENDEZVOUS2:
1952 case RELAY_COMMAND_INTRO_ESTABLISHED:
1953 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1954 rend_process_relay_cell(circ, layer_hint,
1955 rh.command, rh.length,
1956 cell->payload+RELAY_HEADER_SIZE);
1957 return 0;
1959 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1960 "Received unknown relay command %d. Perhaps the other side is using "
1961 "a newer version of Tor? Dropping.",
1962 rh.command);
1963 return 0; /* for forward compatibility, don't kill the circuit */
1966 /** How many relay_data cells have we built, ever? */
1967 uint64_t stats_n_data_cells_packaged = 0;
1968 /** How many bytes of data have we put in relay_data cells have we built,
1969 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1970 * every relay cell we ever sent were completely full of data. */
1971 uint64_t stats_n_data_bytes_packaged = 0;
1972 /** How many relay_data cells have we received, ever? */
1973 uint64_t stats_n_data_cells_received = 0;
1974 /** How many bytes of data have we received relay_data cells, ever? This would
1975 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1976 * ever received were completely full of data. */
1977 uint64_t stats_n_data_bytes_received = 0;
1979 /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
1980 * <b>package_partial</b> is true), and the appropriate package windows aren't
1981 * empty, grab a cell and send it down the circuit.
1983 * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
1984 * *<b>max_cells</b> by the number of cells packaged.
1986 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1987 * be marked for close, else return 0.
1990 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
1991 int *max_cells)
1993 size_t bytes_to_process, length;
1994 char payload[CELL_PAYLOAD_SIZE];
1995 circuit_t *circ;
1996 const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
1997 int sending_from_optimistic = 0;
1998 entry_connection_t *entry_conn =
1999 conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
2000 const int sending_optimistically =
2001 entry_conn &&
2002 conn->base_.type == CONN_TYPE_AP &&
2003 conn->base_.state != AP_CONN_STATE_OPEN;
2004 crypt_path_t *cpath_layer = conn->cpath_layer;
2006 tor_assert(conn);
2008 if (conn->base_.marked_for_close) {
2009 log_warn(LD_BUG,
2010 "called on conn that's already marked for close at %s:%d.",
2011 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
2012 return 0;
2015 if (max_cells && *max_cells <= 0)
2016 return 0;
2018 repeat_connection_edge_package_raw_inbuf:
2020 circ = circuit_get_by_edge_conn(conn);
2021 if (!circ) {
2022 log_info(domain,"conn has no circuit! Closing.");
2023 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
2024 return -1;
2027 if (circuit_consider_stop_edge_reading(circ, cpath_layer))
2028 return 0;
2030 if (conn->package_window <= 0) {
2031 log_info(domain,"called with package_window %d. Skipping.",
2032 conn->package_window);
2033 connection_stop_reading(TO_CONN(conn));
2034 return 0;
2037 sending_from_optimistic = entry_conn &&
2038 entry_conn->sending_optimistic_data != NULL;
2040 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
2041 bytes_to_process = buf_datalen(entry_conn->sending_optimistic_data);
2042 if (PREDICT_UNLIKELY(!bytes_to_process)) {
2043 log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
2044 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
2045 sending_from_optimistic = 0;
2047 } else {
2048 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
2051 if (!bytes_to_process)
2052 return 0;
2054 if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
2055 return 0;
2057 if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
2058 length = RELAY_PAYLOAD_SIZE;
2059 } else {
2060 length = bytes_to_process;
2062 stats_n_data_bytes_packaged += length;
2063 stats_n_data_cells_packaged += 1;
2065 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
2066 /* XXXX We could be more efficient here by sometimes packing
2067 * previously-sent optimistic data in the same cell with data
2068 * from the inbuf. */
2069 fetch_from_buf(payload, length, entry_conn->sending_optimistic_data);
2070 if (!buf_datalen(entry_conn->sending_optimistic_data)) {
2071 buf_free(entry_conn->sending_optimistic_data);
2072 entry_conn->sending_optimistic_data = NULL;
2074 } else {
2075 connection_fetch_from_buf(payload, length, TO_CONN(conn));
2078 log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
2079 conn->base_.s,
2080 (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
2082 if (sending_optimistically && !sending_from_optimistic) {
2083 /* This is new optimistic data; remember it in case we need to detach and
2084 retry */
2085 if (!entry_conn->pending_optimistic_data)
2086 entry_conn->pending_optimistic_data = buf_new();
2087 write_to_buf(payload, length, entry_conn->pending_optimistic_data);
2090 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
2091 payload, length) < 0 )
2092 /* circuit got marked for close, don't continue, don't need to mark conn */
2093 return 0;
2095 if (!cpath_layer) { /* non-rendezvous exit */
2096 tor_assert(circ->package_window > 0);
2097 circ->package_window--;
2098 } else { /* we're an AP, or an exit on a rendezvous circ */
2099 tor_assert(cpath_layer->package_window > 0);
2100 cpath_layer->package_window--;
2103 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
2104 connection_stop_reading(TO_CONN(conn));
2105 log_debug(domain,"conn->package_window reached 0.");
2106 circuit_consider_stop_edge_reading(circ, cpath_layer);
2107 return 0; /* don't process the inbuf any more */
2109 log_debug(domain,"conn->package_window is now %d",conn->package_window);
2111 if (max_cells) {
2112 *max_cells -= 1;
2113 if (*max_cells <= 0)
2114 return 0;
2117 /* handle more if there's more, or return 0 if there isn't */
2118 goto repeat_connection_edge_package_raw_inbuf;
2121 /** Called when we've just received a relay data cell, when
2122 * we've just finished flushing all bytes to stream <b>conn</b>,
2123 * or when we've flushed *some* bytes to the stream <b>conn</b>.
2125 * If conn->outbuf is not too full, and our deliver window is
2126 * low, send back a suitable number of stream-level sendme cells.
2128 void
2129 connection_edge_consider_sending_sendme(edge_connection_t *conn)
2131 circuit_t *circ;
2133 if (connection_outbuf_too_full(TO_CONN(conn)))
2134 return;
2136 circ = circuit_get_by_edge_conn(conn);
2137 if (!circ) {
2138 /* this can legitimately happen if the destroy has already
2139 * arrived and torn down the circuit */
2140 log_info(LD_APP,"No circuit associated with conn. Skipping.");
2141 return;
2144 while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
2145 log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
2146 "Outbuf %d, Queuing stream sendme.",
2147 (int)conn->base_.outbuf_flushlen);
2148 conn->deliver_window += STREAMWINDOW_INCREMENT;
2149 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
2150 NULL, 0) < 0) {
2151 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
2152 return; /* the circuit's closed, don't continue */
2157 /** The circuit <b>circ</b> has received a circuit-level sendme
2158 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
2159 * attached streams and let them resume reading and packaging, if
2160 * their stream windows allow it.
2162 static void
2163 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
2165 if (circuit_queue_streams_are_blocked(circ)) {
2166 log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
2167 return;
2169 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
2171 if (CIRCUIT_IS_ORIGIN(circ))
2172 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
2173 circ, layer_hint);
2174 else
2175 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
2176 circ, layer_hint);
2179 void
2180 stream_choice_seed_weak_rng(void)
2182 crypto_seed_weak_rng(&stream_choice_rng);
2185 /** A helper function for circuit_resume_edge_reading() above.
2186 * The arguments are the same, except that <b>conn</b> is the head
2187 * of a linked list of edge streams that should each be considered.
2189 static int
2190 circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
2191 circuit_t *circ,
2192 crypt_path_t *layer_hint)
2194 edge_connection_t *conn;
2195 int n_packaging_streams, n_streams_left;
2196 int packaged_this_round;
2197 int cells_on_queue;
2198 int cells_per_conn;
2199 edge_connection_t *chosen_stream = NULL;
2200 int max_to_package;
2202 if (first_conn == NULL) {
2203 /* Don't bother to try to do the rest of this if there are no connections
2204 * to resume. */
2205 return 0;
2208 /* How many cells do we have space for? It will be the minimum of
2209 * the number needed to exhaust the package window, and the minimum
2210 * needed to fill the cell queue. */
2211 max_to_package = circ->package_window;
2212 if (CIRCUIT_IS_ORIGIN(circ)) {
2213 cells_on_queue = circ->n_chan_cells.n;
2214 } else {
2215 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2216 cells_on_queue = or_circ->p_chan_cells.n;
2218 if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
2219 max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
2221 /* Once we used to start listening on the streams in the order they
2222 * appeared in the linked list. That leads to starvation on the
2223 * streams that appeared later on the list, since the first streams
2224 * would always get to read first. Instead, we just pick a random
2225 * stream on the list, and enable reading for streams starting at that
2226 * point (and wrapping around as if the list were circular). It would
2227 * probably be better to actually remember which streams we've
2228 * serviced in the past, but this is simple and effective. */
2230 /* Select a stream uniformly at random from the linked list. We
2231 * don't need cryptographic randomness here. */
2233 int num_streams = 0;
2234 for (conn = first_conn; conn; conn = conn->next_stream) {
2235 num_streams++;
2236 if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
2237 chosen_stream = conn;
2239 /* Invariant: chosen_stream has been chosen uniformly at random from
2240 * among the first num_streams streams on first_conn.
2242 * (Note that we iterate over every stream on the circuit, so that after
2243 * we've considered the first stream, we've chosen it with P=1; and
2244 * after we consider the second stream, we've switched to it with P=1/2
2245 * and stayed with the first stream with P=1/2; and after we've
2246 * considered the third stream, we've switched to it with P=1/3 and
2247 * remained with one of the first two streams with P=(2/3), giving each
2248 * one P=(1/2)(2/3) )=(1/3).) */
2252 /* Count how many non-marked streams there are that have anything on
2253 * their inbuf, and enable reading on all of the connections. */
2254 n_packaging_streams = 0;
2255 /* Activate reading starting from the chosen stream */
2256 for (conn=chosen_stream; conn; conn = conn->next_stream) {
2257 /* Start reading for the streams starting from here */
2258 if (conn->base_.marked_for_close || conn->package_window <= 0)
2259 continue;
2260 if (!layer_hint || conn->cpath_layer == layer_hint) {
2261 connection_start_reading(TO_CONN(conn));
2263 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2264 ++n_packaging_streams;
2267 /* Go back and do the ones we skipped, circular-style */
2268 for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
2269 if (conn->base_.marked_for_close || conn->package_window <= 0)
2270 continue;
2271 if (!layer_hint || conn->cpath_layer == layer_hint) {
2272 connection_start_reading(TO_CONN(conn));
2274 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2275 ++n_packaging_streams;
2279 if (n_packaging_streams == 0) /* avoid divide-by-zero */
2280 return 0;
2282 again:
2284 cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
2286 packaged_this_round = 0;
2287 n_streams_left = 0;
2289 /* Iterate over all connections. Package up to cells_per_conn cells on
2290 * each. Update packaged_this_round with the total number of cells
2291 * packaged, and n_streams_left with the number that still have data to
2292 * package.
2294 for (conn=first_conn; conn; conn=conn->next_stream) {
2295 if (conn->base_.marked_for_close || conn->package_window <= 0)
2296 continue;
2297 if (!layer_hint || conn->cpath_layer == layer_hint) {
2298 int n = cells_per_conn, r;
2299 /* handle whatever might still be on the inbuf */
2300 r = connection_edge_package_raw_inbuf(conn, 1, &n);
2302 /* Note how many we packaged */
2303 packaged_this_round += (cells_per_conn-n);
2305 if (r<0) {
2306 /* Problem while packaging. (We already sent an end cell if
2307 * possible) */
2308 connection_mark_for_close(TO_CONN(conn));
2309 continue;
2312 /* If there's still data to read, we'll be coming back to this stream. */
2313 if (connection_get_inbuf_len(TO_CONN(conn)))
2314 ++n_streams_left;
2316 /* If the circuit won't accept any more data, return without looking
2317 * at any more of the streams. Any connections that should be stopped
2318 * have already been stopped by connection_edge_package_raw_inbuf. */
2319 if (circuit_consider_stop_edge_reading(circ, layer_hint))
2320 return -1;
2321 /* XXXX should we also stop immediately if we fill up the cell queue?
2322 * Probably. */
2326 /* If we made progress, and we are willing to package more, and there are
2327 * any streams left that want to package stuff... try again!
2329 if (packaged_this_round && packaged_this_round < max_to_package &&
2330 n_streams_left) {
2331 max_to_package -= packaged_this_round;
2332 n_packaging_streams = n_streams_left;
2333 goto again;
2336 return 0;
2339 /** Check if the package window for <b>circ</b> is empty (at
2340 * hop <b>layer_hint</b> if it's defined).
2342 * If yes, tell edge streams to stop reading and return 1.
2343 * Else return 0.
2345 static int
2346 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
2348 edge_connection_t *conn = NULL;
2349 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
2351 if (!layer_hint) {
2352 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2353 log_debug(domain,"considering circ->package_window %d",
2354 circ->package_window);
2355 if (circ->package_window <= 0) {
2356 log_debug(domain,"yes, not-at-origin. stopped.");
2357 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
2358 connection_stop_reading(TO_CONN(conn));
2359 return 1;
2361 return 0;
2363 /* else, layer hint is defined, use it */
2364 log_debug(domain,"considering layer_hint->package_window %d",
2365 layer_hint->package_window);
2366 if (layer_hint->package_window <= 0) {
2367 log_debug(domain,"yes, at-origin. stopped.");
2368 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
2369 conn=conn->next_stream) {
2370 if (conn->cpath_layer == layer_hint)
2371 connection_stop_reading(TO_CONN(conn));
2373 return 1;
2375 return 0;
2378 /** Check if the deliver_window for circuit <b>circ</b> (at hop
2379 * <b>layer_hint</b> if it's defined) is low enough that we should
2380 * send a circuit-level sendme back down the circuit. If so, send
2381 * enough sendmes that the window would be overfull if we sent any
2382 * more.
2384 static void
2385 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
2387 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
2388 // layer_hint ? "defined" : "null");
2389 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
2390 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
2391 log_debug(LD_CIRC,"Queuing circuit sendme.");
2392 if (layer_hint)
2393 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
2394 else
2395 circ->deliver_window += CIRCWINDOW_INCREMENT;
2396 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
2397 NULL, 0, layer_hint) < 0) {
2398 log_warn(LD_CIRC,
2399 "relay_send_command_from_edge failed. Circuit's closed.");
2400 return; /* the circuit's closed, don't continue */
2405 #ifdef ACTIVE_CIRCUITS_PARANOIA
2406 #define assert_cmux_ok_paranoid(chan) \
2407 assert_circuit_mux_okay(chan)
2408 #else
2409 #define assert_cmux_ok_paranoid(chan)
2410 #endif
2412 /** The total number of cells we have allocated. */
2413 static size_t total_cells_allocated = 0;
2415 /** Release storage held by <b>cell</b>. */
2416 static inline void
2417 packed_cell_free_unchecked(packed_cell_t *cell)
2419 --total_cells_allocated;
2420 tor_free(cell);
2423 /** Allocate and return a new packed_cell_t. */
2424 STATIC packed_cell_t *
2425 packed_cell_new(void)
2427 ++total_cells_allocated;
2428 return tor_malloc_zero(sizeof(packed_cell_t));
2431 /** Return a packed cell used outside by channel_t lower layer */
2432 void
2433 packed_cell_free(packed_cell_t *cell)
2435 if (!cell)
2436 return;
2437 packed_cell_free_unchecked(cell);
2440 /** Log current statistics for cell pool allocation at log level
2441 * <b>severity</b>. */
2442 void
2443 dump_cell_pool_usage(int severity)
2445 int n_circs = 0;
2446 int n_cells = 0;
2447 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
2448 n_cells += c->n_chan_cells.n;
2449 if (!CIRCUIT_IS_ORIGIN(c))
2450 n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
2451 ++n_circs;
2453 SMARTLIST_FOREACH_END(c);
2454 tor_log(severity, LD_MM,
2455 "%d cells allocated on %d circuits. %d cells leaked.",
2456 n_cells, n_circs, (int)total_cells_allocated - n_cells);
2459 /** Allocate a new copy of packed <b>cell</b>. */
2460 static inline packed_cell_t *
2461 packed_cell_copy(const cell_t *cell, int wide_circ_ids)
2463 packed_cell_t *c = packed_cell_new();
2464 cell_pack(c, cell, wide_circ_ids);
2465 return c;
2468 /** Append <b>cell</b> to the end of <b>queue</b>. */
2469 void
2470 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
2472 TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
2473 ++queue->n;
2476 /** Append a newly allocated copy of <b>cell</b> to the end of the
2477 * <b>exitward</b> (or app-ward) <b>queue</b> of <b>circ</b>. If
2478 * <b>use_stats</b> is true, record statistics about the cell.
2480 void
2481 cell_queue_append_packed_copy(circuit_t *circ, cell_queue_t *queue,
2482 int exitward, const cell_t *cell,
2483 int wide_circ_ids, int use_stats)
2485 packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
2486 (void)circ;
2487 (void)exitward;
2488 (void)use_stats;
2490 copy->inserted_time = (uint32_t) monotime_coarse_absolute_msec();
2492 cell_queue_append(queue, copy);
2495 /** Initialize <b>queue</b> as an empty cell queue. */
2496 void
2497 cell_queue_init(cell_queue_t *queue)
2499 memset(queue, 0, sizeof(cell_queue_t));
2500 TOR_SIMPLEQ_INIT(&queue->head);
2503 /** Remove and free every cell in <b>queue</b>. */
2504 void
2505 cell_queue_clear(cell_queue_t *queue)
2507 packed_cell_t *cell;
2508 while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
2509 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2510 packed_cell_free_unchecked(cell);
2512 TOR_SIMPLEQ_INIT(&queue->head);
2513 queue->n = 0;
2516 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
2517 * <b>queue</b> is empty. */
2518 STATIC packed_cell_t *
2519 cell_queue_pop(cell_queue_t *queue)
2521 packed_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
2522 if (!cell)
2523 return NULL;
2524 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2525 --queue->n;
2526 return cell;
2529 /** Return the total number of bytes used for each packed_cell in a queue.
2530 * Approximate. */
2531 size_t
2532 packed_cell_mem_cost(void)
2534 return sizeof(packed_cell_t);
2537 /* DOCDOC */
2538 STATIC size_t
2539 cell_queues_get_total_allocation(void)
2541 return total_cells_allocated * packed_cell_mem_cost();
2544 /** How long after we've been low on memory should we try to conserve it? */
2545 #define MEMORY_PRESSURE_INTERVAL (30*60)
2547 /** The time at which we were last low on memory. */
2548 static time_t last_time_under_memory_pressure = 0;
2550 /** Check whether we've got too much space used for cells. If so,
2551 * call the OOM handler and return 1. Otherwise, return 0. */
2552 STATIC int
2553 cell_queues_check_size(void)
2555 size_t alloc = cell_queues_get_total_allocation();
2556 alloc += buf_get_total_allocation();
2557 alloc += tor_compress_get_total_allocation();
2558 const size_t rend_cache_total = rend_cache_get_total_allocation();
2559 alloc += rend_cache_total;
2560 if (alloc >= get_options()->MaxMemInQueues_low_threshold) {
2561 last_time_under_memory_pressure = approx_time();
2562 if (alloc >= get_options()->MaxMemInQueues) {
2563 /* If we're spending over 20% of the memory limit on hidden service
2564 * descriptors, free them until we're down to 10%.
2566 if (rend_cache_total > get_options()->MaxMemInQueues / 5) {
2567 const size_t bytes_to_remove =
2568 rend_cache_total - (size_t)(get_options()->MaxMemInQueues / 10);
2569 alloc -= hs_cache_handle_oom(time(NULL), bytes_to_remove);
2571 circuits_handle_oom(alloc);
2572 return 1;
2575 return 0;
2578 /** Return true if we've been under memory pressure in the last
2579 * MEMORY_PRESSURE_INTERVAL seconds. */
2581 have_been_under_memory_pressure(void)
2583 return last_time_under_memory_pressure + MEMORY_PRESSURE_INTERVAL
2584 < approx_time();
2588 * Update the number of cells available on the circuit's n_chan or p_chan's
2589 * circuit mux.
2591 void
2592 update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
2593 const char *file, int lineno)
2595 channel_t *chan = NULL;
2596 or_circuit_t *or_circ = NULL;
2597 circuitmux_t *cmux = NULL;
2599 tor_assert(circ);
2601 /* Okay, get the channel */
2602 if (direction == CELL_DIRECTION_OUT) {
2603 chan = circ->n_chan;
2604 } else {
2605 or_circ = TO_OR_CIRCUIT(circ);
2606 chan = or_circ->p_chan;
2609 tor_assert(chan);
2610 tor_assert(chan->cmux);
2612 /* Now get the cmux */
2613 cmux = chan->cmux;
2615 /* Cmux sanity check */
2616 if (! circuitmux_is_circuit_attached(cmux, circ)) {
2617 log_warn(LD_BUG, "called on non-attached circuit from %s:%d",
2618 file, lineno);
2619 return;
2621 tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
2623 assert_cmux_ok_paranoid(chan);
2625 /* Update the number of cells we have for the circuit mux */
2626 if (direction == CELL_DIRECTION_OUT) {
2627 circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
2628 } else {
2629 circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
2632 assert_cmux_ok_paranoid(chan);
2635 /** Remove all circuits from the cmux on <b>chan</b>.
2637 * If <b>circuits_out</b> is non-NULL, add all detached circuits to
2638 * <b>circuits_out</b>.
2640 void
2641 channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
2643 tor_assert(chan);
2644 tor_assert(chan->cmux);
2646 circuitmux_detach_all_circuits(chan->cmux, circuits_out);
2647 chan->num_n_circuits = 0;
2648 chan->num_p_circuits = 0;
2651 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
2652 * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
2653 * and start or stop reading as appropriate.
2655 * If <b>stream_id</b> is nonzero, block only the edge connection whose
2656 * stream_id matches it.
2658 * Returns the number of streams whose status we changed.
2660 static int
2661 set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
2662 int block, streamid_t stream_id)
2664 edge_connection_t *edge = NULL;
2665 int n = 0;
2666 if (circ->n_chan == chan) {
2667 circ->streams_blocked_on_n_chan = block;
2668 if (CIRCUIT_IS_ORIGIN(circ))
2669 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
2670 } else {
2671 circ->streams_blocked_on_p_chan = block;
2672 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
2673 edge = TO_OR_CIRCUIT(circ)->n_streams;
2676 for (; edge; edge = edge->next_stream) {
2677 connection_t *conn = TO_CONN(edge);
2678 if (stream_id && edge->stream_id != stream_id)
2679 continue;
2681 if (edge->edge_blocked_on_circ != block) {
2682 ++n;
2683 edge->edge_blocked_on_circ = block;
2686 if (!conn->read_event) {
2687 /* This connection is a placeholder for something; probably a DNS
2688 * request. It can't actually stop or start reading.*/
2689 continue;
2692 if (block) {
2693 if (connection_is_reading(conn))
2694 connection_stop_reading(conn);
2695 } else {
2696 /* Is this right? */
2697 if (!connection_is_reading(conn))
2698 connection_start_reading(conn);
2702 return n;
2705 /** Extract the command from a packed cell. */
2706 static uint8_t
2707 packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
2709 if (wide_circ_ids) {
2710 return get_uint8(cell->body+4);
2711 } else {
2712 return get_uint8(cell->body+2);
2716 /** Extract the circuit ID from a packed cell. */
2717 circid_t
2718 packed_cell_get_circid(const packed_cell_t *cell, int wide_circ_ids)
2720 if (wide_circ_ids) {
2721 return ntohl(get_uint32(cell->body));
2722 } else {
2723 return ntohs(get_uint16(cell->body));
2727 /** Pull as many cells as possible (but no more than <b>max</b>) from the
2728 * queue of the first active circuit on <b>chan</b>, and write them to
2729 * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
2730 * the active circuit pointer to the next active circuit in the ring. */
2731 MOCK_IMPL(int,
2732 channel_flush_from_first_active_circuit, (channel_t *chan, int max))
2734 circuitmux_t *cmux = NULL;
2735 int n_flushed = 0;
2736 cell_queue_t *queue, *destroy_queue=NULL;
2737 circuit_t *circ;
2738 or_circuit_t *or_circ;
2739 int streams_blocked;
2740 packed_cell_t *cell;
2742 /* Get the cmux */
2743 tor_assert(chan);
2744 tor_assert(chan->cmux);
2745 cmux = chan->cmux;
2747 /* Main loop: pick a circuit, send a cell, update the cmux */
2748 while (n_flushed < max) {
2749 circ = circuitmux_get_first_active_circuit(cmux, &destroy_queue);
2750 if (destroy_queue) {
2751 /* this code is duplicated from some of the logic below. Ugly! XXXX */
2752 tor_assert(destroy_queue->n > 0);
2753 cell = cell_queue_pop(destroy_queue);
2754 channel_write_packed_cell(chan, cell);
2755 /* Update the cmux destroy counter */
2756 circuitmux_notify_xmit_destroy(cmux);
2757 cell = NULL;
2758 ++n_flushed;
2759 continue;
2761 /* If it returns NULL, no cells left to send */
2762 if (!circ) break;
2763 assert_cmux_ok_paranoid(chan);
2765 if (circ->n_chan == chan) {
2766 queue = &circ->n_chan_cells;
2767 streams_blocked = circ->streams_blocked_on_n_chan;
2768 } else {
2769 or_circ = TO_OR_CIRCUIT(circ);
2770 tor_assert(or_circ->p_chan == chan);
2771 queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
2772 streams_blocked = circ->streams_blocked_on_p_chan;
2775 /* Circuitmux told us this was active, so it should have cells */
2776 if (/*BUG(*/ queue->n == 0 /*)*/) {
2777 log_warn(LD_BUG, "Found a supposedly active circuit with no cells "
2778 "to send. Trying to recover.");
2779 circuitmux_set_num_cells(cmux, circ, 0);
2780 if (! circ->marked_for_close)
2781 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
2782 continue;
2785 tor_assert(queue->n > 0);
2788 * Get just one cell here; once we've sent it, that can change the circuit
2789 * selection, so we have to loop around for another even if this circuit
2790 * has more than one.
2792 cell = cell_queue_pop(queue);
2794 /* Calculate the exact time that this cell has spent in the queue. */
2795 if (get_options()->CellStatistics ||
2796 get_options()->TestingEnableCellStatsEvent) {
2797 uint32_t msec_waiting;
2798 uint32_t msec_now = (uint32_t)monotime_coarse_absolute_msec();
2799 msec_waiting = msec_now - cell->inserted_time;
2801 if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
2802 or_circ = TO_OR_CIRCUIT(circ);
2803 or_circ->total_cell_waiting_time += msec_waiting;
2804 or_circ->processed_cells++;
2807 if (get_options()->TestingEnableCellStatsEvent) {
2808 uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
2810 testing_cell_stats_entry_t *ent =
2811 tor_malloc_zero(sizeof(testing_cell_stats_entry_t));
2812 ent->command = command;
2813 ent->waiting_time = msec_waiting / 10;
2814 ent->removed = 1;
2815 if (circ->n_chan == chan)
2816 ent->exitward = 1;
2817 if (!circ->testing_cell_stats)
2818 circ->testing_cell_stats = smartlist_new();
2819 smartlist_add(circ->testing_cell_stats, ent);
2823 /* If we just flushed our queue and this circuit is used for a
2824 * tunneled directory request, possibly advance its state. */
2825 if (queue->n == 0 && chan->dirreq_id)
2826 geoip_change_dirreq_state(chan->dirreq_id,
2827 DIRREQ_TUNNELED,
2828 DIRREQ_CIRC_QUEUE_FLUSHED);
2830 /* Now send the cell */
2831 channel_write_packed_cell(chan, cell);
2832 cell = NULL;
2835 * Don't packed_cell_free_unchecked(cell) here because the channel will
2836 * do so when it gets out of the channel queue (probably already did, in
2837 * which case that was an immediate double-free bug).
2840 /* Update the counter */
2841 ++n_flushed;
2844 * Now update the cmux; tell it we've just sent a cell, and how many
2845 * we have left.
2847 circuitmux_notify_xmit_cells(cmux, circ, 1);
2848 circuitmux_set_num_cells(cmux, circ, queue->n);
2849 if (queue->n == 0)
2850 log_debug(LD_GENERAL, "Made a circuit inactive.");
2852 /* Is the cell queue low enough to unblock all the streams that are waiting
2853 * to write to this circuit? */
2854 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
2855 set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
2857 /* If n_flushed < max still, loop around and pick another circuit */
2860 /* Okay, we're done sending now */
2861 assert_cmux_ok_paranoid(chan);
2863 return n_flushed;
2866 #if 0
2867 /** Indicate the current preferred cap for middle circuits; zero disables
2868 * the cap. Right now it's just a constant, ORCIRC_MAX_MIDDLE_CELLS, but
2869 * the logic in append_cell_to_circuit_queue() is written to be correct
2870 * if we want to base it on a consensus param or something that might change
2871 * in the future.
2873 static int
2874 get_max_middle_cells(void)
2876 return ORCIRC_MAX_MIDDLE_CELLS;
2878 #endif
2880 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
2881 * transmitting in <b>direction</b>. */
2882 void
2883 append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
2884 cell_t *cell, cell_direction_t direction,
2885 streamid_t fromstream)
2887 or_circuit_t *orcirc = NULL;
2888 cell_queue_t *queue;
2889 int streams_blocked;
2890 #if 0
2891 uint32_t tgt_max_middle_cells, p_len, n_len, tmp, hard_max_middle_cells;
2892 #endif
2894 int exitward;
2895 if (circ->marked_for_close)
2896 return;
2898 exitward = (direction == CELL_DIRECTION_OUT);
2899 if (exitward) {
2900 queue = &circ->n_chan_cells;
2901 streams_blocked = circ->streams_blocked_on_n_chan;
2902 } else {
2903 orcirc = TO_OR_CIRCUIT(circ);
2904 queue = &orcirc->p_chan_cells;
2905 streams_blocked = circ->streams_blocked_on_p_chan;
2909 * Disabling this for now because of a possible guard discovery attack
2911 #if 0
2912 /* Are we a middle circuit about to exceed ORCIRC_MAX_MIDDLE_CELLS? */
2913 if ((circ->n_chan != NULL) && CIRCUIT_IS_ORCIRC(circ)) {
2914 orcirc = TO_OR_CIRCUIT(circ);
2915 if (orcirc->p_chan) {
2916 /* We are a middle circuit if we have both n_chan and p_chan */
2917 /* We'll need to know the current preferred maximum */
2918 tgt_max_middle_cells = get_max_middle_cells();
2919 if (tgt_max_middle_cells > 0) {
2920 /* Do we need to initialize middle_max_cells? */
2921 if (orcirc->max_middle_cells == 0) {
2922 orcirc->max_middle_cells = tgt_max_middle_cells;
2923 } else {
2924 if (tgt_max_middle_cells > orcirc->max_middle_cells) {
2925 /* If we want to increase the cap, we can do so right away */
2926 orcirc->max_middle_cells = tgt_max_middle_cells;
2927 } else if (tgt_max_middle_cells < orcirc->max_middle_cells) {
2929 * If we're shrinking the cap, we can't shrink past either queue;
2930 * compare tgt_max_middle_cells rather than tgt_max_middle_cells *
2931 * ORCIRC_MAX_MIDDLE_KILL_THRESH so the queues don't shrink enough
2932 * to generate spurious warnings, either.
2934 n_len = circ->n_chan_cells.n;
2935 p_len = orcirc->p_chan_cells.n;
2936 tmp = tgt_max_middle_cells;
2937 if (tmp < n_len) tmp = n_len;
2938 if (tmp < p_len) tmp = p_len;
2939 orcirc->max_middle_cells = tmp;
2941 /* else no change */
2943 } else {
2944 /* tgt_max_middle_cells == 0 indicates we should disable the cap */
2945 orcirc->max_middle_cells = 0;
2948 /* Now we know orcirc->max_middle_cells is set correctly */
2949 if (orcirc->max_middle_cells > 0) {
2950 hard_max_middle_cells =
2951 (uint32_t)(((double)orcirc->max_middle_cells) *
2952 ORCIRC_MAX_MIDDLE_KILL_THRESH);
2954 if ((unsigned)queue->n + 1 >= hard_max_middle_cells) {
2955 /* Queueing this cell would put queue over the kill theshold */
2956 log_warn(LD_CIRC,
2957 "Got a cell exceeding the hard cap of %u in the "
2958 "%s direction on middle circ ID %u on chan ID "
2959 U64_FORMAT "; killing the circuit.",
2960 hard_max_middle_cells,
2961 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2962 (direction == CELL_DIRECTION_OUT) ?
2963 circ->n_circ_id : orcirc->p_circ_id,
2964 U64_PRINTF_ARG(
2965 (direction == CELL_DIRECTION_OUT) ?
2966 circ->n_chan->global_identifier :
2967 orcirc->p_chan->global_identifier));
2968 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2969 return;
2970 } else if ((unsigned)queue->n + 1 == orcirc->max_middle_cells) {
2971 /* Only use ==, not >= for this test so we don't spam the log */
2972 log_warn(LD_CIRC,
2973 "While trying to queue a cell, reached the soft cap of %u "
2974 "in the %s direction on middle circ ID %u "
2975 "on chan ID " U64_FORMAT ".",
2976 orcirc->max_middle_cells,
2977 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2978 (direction == CELL_DIRECTION_OUT) ?
2979 circ->n_circ_id : orcirc->p_circ_id,
2980 U64_PRINTF_ARG(
2981 (direction == CELL_DIRECTION_OUT) ?
2982 circ->n_chan->global_identifier :
2983 orcirc->p_chan->global_identifier));
2988 #endif
2990 cell_queue_append_packed_copy(circ, queue, exitward, cell,
2991 chan->wide_circ_ids, 1);
2993 if (PREDICT_UNLIKELY(cell_queues_check_size())) {
2994 /* We ran the OOM handler */
2995 if (circ->marked_for_close)
2996 return;
2999 /* If we have too many cells on the circuit, we should stop reading from
3000 * the edge streams for a while. */
3001 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
3002 set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
3004 if (streams_blocked && fromstream) {
3005 /* This edge connection is apparently not blocked; block it. */
3006 set_streams_blocked_on_circ(circ, chan, 1, fromstream);
3009 update_circuit_on_cmux(circ, direction);
3010 if (queue->n == 1) {
3011 /* This was the first cell added to the queue. We just made this
3012 * circuit active. */
3013 log_debug(LD_GENERAL, "Made a circuit active.");
3016 /* New way: mark this as having waiting cells for the scheduler */
3017 scheduler_channel_has_waiting_cells(chan);
3020 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
3021 * have at least 18 bytes of free space. The encoding is, as specified in
3022 * tor-spec.txt:
3023 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
3024 * LENGTH [1 byte]
3025 * ADDRESS [length bytes]
3026 * Return the number of bytes added, or -1 on error */
3028 append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
3030 uint32_t a;
3031 switch (tor_addr_family(addr)) {
3032 case AF_INET:
3033 payload_out[0] = RESOLVED_TYPE_IPV4;
3034 payload_out[1] = 4;
3035 a = tor_addr_to_ipv4n(addr);
3036 memcpy(payload_out+2, &a, 4);
3037 return 6;
3038 case AF_INET6:
3039 payload_out[0] = RESOLVED_TYPE_IPV6;
3040 payload_out[1] = 16;
3041 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
3042 return 18;
3043 case AF_UNSPEC:
3044 default:
3045 return -1;
3049 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
3050 * encoded as by append_address_to_payload(), try to decode the address into
3051 * *<b>addr_out</b>. Return the next byte in the payload after the address on
3052 * success, or NULL on failure. */
3053 const uint8_t *
3054 decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
3055 int payload_len)
3057 if (payload_len < 2)
3058 return NULL;
3059 if (payload_len < 2+payload[1])
3060 return NULL;
3062 switch (payload[0]) {
3063 case RESOLVED_TYPE_IPV4:
3064 if (payload[1] != 4)
3065 return NULL;
3066 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
3067 break;
3068 case RESOLVED_TYPE_IPV6:
3069 if (payload[1] != 16)
3070 return NULL;
3071 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
3072 break;
3073 default:
3074 tor_addr_make_unspec(addr_out);
3075 break;
3077 return payload + 2 + payload[1];
3080 /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
3081 void
3082 circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
3084 cell_queue_t *queue;
3085 cell_direction_t direction;
3087 if (circ->n_chan == chan) {
3088 queue = &circ->n_chan_cells;
3089 direction = CELL_DIRECTION_OUT;
3090 } else {
3091 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
3092 tor_assert(orcirc->p_chan == chan);
3093 queue = &orcirc->p_chan_cells;
3094 direction = CELL_DIRECTION_IN;
3097 /* Clear the queue */
3098 cell_queue_clear(queue);
3100 /* Update the cell counter in the cmux */
3101 if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
3102 update_circuit_on_cmux(circ, direction);
3105 /** Fail with an assert if the circuit mux on chan is corrupt
3107 void
3108 assert_circuit_mux_okay(channel_t *chan)
3110 tor_assert(chan);
3111 tor_assert(chan->cmux);
3113 circuitmux_assert_okay(chan->cmux);
3116 /** Return 1 if we shouldn't restart reading on this circuit, even if
3117 * we get a SENDME. Else return 0.
3119 static int
3120 circuit_queue_streams_are_blocked(circuit_t *circ)
3122 if (CIRCUIT_IS_ORIGIN(circ)) {
3123 return circ->streams_blocked_on_n_chan;
3124 } else {
3125 return circ->streams_blocked_on_p_chan;