Merge branch 'maint-0.2.9' into maint-0.3.0
[tor/appveyor.git] / src / or / relay.c
blob9917dbb74e4612012dbca57285323e8ceae26be6
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-2016, 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 "buffers.h"
52 #include "channel.h"
53 #include "circpathbias.h"
54 #include "circuitbuild.h"
55 #include "circuitlist.h"
56 #include "circuituse.h"
57 #include "config.h"
58 #include "connection.h"
59 #include "connection_edge.h"
60 #include "connection_or.h"
61 #include "control.h"
62 #include "geoip.h"
63 #include "hs_cache.h"
64 #include "main.h"
65 #include "networkstatus.h"
66 #include "nodelist.h"
67 #include "onion.h"
68 #include "policies.h"
69 #include "reasons.h"
70 #include "relay.h"
71 #include "rendcache.h"
72 #include "rendcommon.h"
73 #include "router.h"
74 #include "routerlist.h"
75 #include "routerparse.h"
76 #include "scheduler.h"
78 static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
79 cell_direction_t cell_direction,
80 crypt_path_t *layer_hint);
82 static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
83 edge_connection_t *conn,
84 crypt_path_t *layer_hint);
85 static void circuit_consider_sending_sendme(circuit_t *circ,
86 crypt_path_t *layer_hint);
87 static void circuit_resume_edge_reading(circuit_t *circ,
88 crypt_path_t *layer_hint);
89 static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
90 circuit_t *circ,
91 crypt_path_t *layer_hint);
92 static int circuit_consider_stop_edge_reading(circuit_t *circ,
93 crypt_path_t *layer_hint);
94 static int circuit_queue_streams_are_blocked(circuit_t *circ);
95 static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
96 entry_connection_t *conn,
97 node_t *node,
98 const tor_addr_t *addr);
99 #if 0
100 static int get_max_middle_cells(void);
101 #endif
103 /** Stop reading on edge connections when we have this many cells
104 * waiting on the appropriate queue. */
105 #define CELL_QUEUE_HIGHWATER_SIZE 256
106 /** Start reading from edge connections again when we get down to this many
107 * cells. */
108 #define CELL_QUEUE_LOWWATER_SIZE 64
110 /** Stats: how many relay cells have originated at this hop, or have
111 * been relayed onward (not recognized at this hop)?
113 uint64_t stats_n_relay_cells_relayed = 0;
114 /** Stats: how many relay cells have been delivered to streams at this
115 * hop?
117 uint64_t stats_n_relay_cells_delivered = 0;
119 /** Used to tell which stream to read from first on a circuit. */
120 static tor_weak_rng_t stream_choice_rng = TOR_WEAK_RNG_INIT;
122 /** Update digest from the payload of cell. Assign integrity part to
123 * cell.
125 static void
126 relay_set_digest(crypto_digest_t *digest, cell_t *cell)
128 char integrity[4];
129 relay_header_t rh;
131 crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
132 crypto_digest_get_digest(digest, integrity, 4);
133 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
134 // integrity[0], integrity[1], integrity[2], integrity[3]);
135 relay_header_unpack(&rh, cell->payload);
136 memcpy(rh.integrity, integrity, 4);
137 relay_header_pack(cell->payload, &rh);
140 /** Does the digest for this circuit indicate that this cell is for us?
142 * Update digest from the payload of cell (with the integrity part set
143 * to 0). If the integrity part is valid, return 1, else restore digest
144 * and cell to their original state and return 0.
146 static int
147 relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
149 uint32_t received_integrity, calculated_integrity;
150 relay_header_t rh;
151 crypto_digest_t *backup_digest=NULL;
153 backup_digest = crypto_digest_dup(digest);
155 relay_header_unpack(&rh, cell->payload);
156 memcpy(&received_integrity, rh.integrity, 4);
157 memset(rh.integrity, 0, 4);
158 relay_header_pack(cell->payload, &rh);
160 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
161 // received_integrity[0], received_integrity[1],
162 // received_integrity[2], received_integrity[3]);
164 crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
165 crypto_digest_get_digest(digest, (char*) &calculated_integrity, 4);
167 if (calculated_integrity != received_integrity) {
168 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
169 // (%d vs %d).", received_integrity, calculated_integrity);
170 /* restore digest to its old form */
171 crypto_digest_assign(digest, backup_digest);
172 /* restore the relay header */
173 memcpy(rh.integrity, &received_integrity, 4);
174 relay_header_pack(cell->payload, &rh);
175 crypto_digest_free(backup_digest);
176 return 0;
178 crypto_digest_free(backup_digest);
179 return 1;
182 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
183 * (in place).
185 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
187 * Returns 0.
189 static int
190 relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
191 int encrypt_mode)
193 (void)encrypt_mode;
194 crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
196 return 0;
199 /** Receive a relay cell:
200 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
201 * origin; decrypt if we're headed toward the exit).
202 * - Check if recognized (if exitward).
203 * - If recognized and the digest checks out, then find if there's a stream
204 * that the cell is intended for, and deliver it to the right
205 * connection_edge.
206 * - If not recognized, then we need to relay it: append it to the appropriate
207 * cell_queue on <b>circ</b>.
209 * Return -<b>reason</b> on failure.
212 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
213 cell_direction_t cell_direction)
215 channel_t *chan = NULL;
216 crypt_path_t *layer_hint=NULL;
217 char recognized=0;
218 int reason;
220 tor_assert(cell);
221 tor_assert(circ);
222 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
223 cell_direction == CELL_DIRECTION_IN);
224 if (circ->marked_for_close)
225 return 0;
227 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
228 log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
229 return -END_CIRC_REASON_INTERNAL;
232 if (recognized) {
233 edge_connection_t *conn = NULL;
235 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
236 pathbias_check_probe_response(circ, cell);
238 /* We need to drop this cell no matter what to avoid code that expects
239 * a certain purpose (such as the hidserv code). */
240 return 0;
243 conn = relay_lookup_conn(circ, cell, cell_direction, layer_hint);
244 if (cell_direction == CELL_DIRECTION_OUT) {
245 ++stats_n_relay_cells_delivered;
246 log_debug(LD_OR,"Sending away from origin.");
247 if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
248 < 0) {
249 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
250 "connection_edge_process_relay_cell (away from origin) "
251 "failed.");
252 return reason;
255 if (cell_direction == CELL_DIRECTION_IN) {
256 ++stats_n_relay_cells_delivered;
257 log_debug(LD_OR,"Sending to origin.");
258 if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
259 layer_hint)) < 0) {
260 log_warn(LD_OR,
261 "connection_edge_process_relay_cell (at origin) failed.");
262 return reason;
265 return 0;
268 /* not recognized. pass it on. */
269 if (cell_direction == CELL_DIRECTION_OUT) {
270 cell->circ_id = circ->n_circ_id; /* switch it */
271 chan = circ->n_chan;
272 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
273 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
274 chan = TO_OR_CIRCUIT(circ)->p_chan;
275 } else {
276 log_fn(LOG_PROTOCOL_WARN, LD_OR,
277 "Dropping unrecognized inbound cell on origin circuit.");
278 /* If we see unrecognized cells on path bias testing circs,
279 * it's bad mojo. Those circuits need to die.
280 * XXX: Shouldn't they always die? */
281 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
282 TO_ORIGIN_CIRCUIT(circ)->path_state = PATH_STATE_USE_FAILED;
283 return -END_CIRC_REASON_TORPROTOCOL;
284 } else {
285 return 0;
289 if (!chan) {
290 // XXXX Can this splice stuff be done more cleanly?
291 if (! CIRCUIT_IS_ORIGIN(circ) &&
292 TO_OR_CIRCUIT(circ)->rend_splice &&
293 cell_direction == CELL_DIRECTION_OUT) {
294 or_circuit_t *splice_ = TO_OR_CIRCUIT(circ)->rend_splice;
295 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
296 tor_assert(splice_->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
297 cell->circ_id = splice_->p_circ_id;
298 cell->command = CELL_RELAY; /* can't be relay_early anyway */
299 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice_),
300 CELL_DIRECTION_IN)) < 0) {
301 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
302 "circuits");
303 /* XXXX Do this here, or just return -1? */
304 circuit_mark_for_close(circ, -reason);
305 return reason;
307 return 0;
309 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
310 "Didn't recognize cell, but circ stops here! Closing circ.");
311 return -END_CIRC_REASON_TORPROTOCOL;
314 log_debug(LD_OR,"Passing on unrecognized cell.");
316 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
317 * we might kill the circ before we relay
318 * the cells. */
320 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
321 return 0;
324 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
325 * <b>circ</b> in direction <b>cell_direction</b>.
327 * If cell_direction == CELL_DIRECTION_IN:
328 * - If we're at the origin (we're the OP), for hops 1..N,
329 * decrypt cell. If recognized, stop.
330 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
332 * If cell_direction == CELL_DIRECTION_OUT:
333 * - decrypt one hop. Check if recognized.
335 * If cell is recognized, set *recognized to 1, and set
336 * *layer_hint to the hop that recognized it.
338 * Return -1 to indicate that we should mark the circuit for close,
339 * else return 0.
342 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
343 crypt_path_t **layer_hint, char *recognized)
345 relay_header_t rh;
347 tor_assert(circ);
348 tor_assert(cell);
349 tor_assert(recognized);
350 tor_assert(cell_direction == CELL_DIRECTION_IN ||
351 cell_direction == CELL_DIRECTION_OUT);
353 if (cell_direction == CELL_DIRECTION_IN) {
354 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
355 * We'll want to do layered decrypts. */
356 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
357 thishop = cpath;
358 if (thishop->state != CPATH_STATE_OPEN) {
359 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
360 "Relay cell before first created cell? Closing.");
361 return -1;
363 do { /* Remember: cpath is in forward order, that is, first hop first. */
364 tor_assert(thishop);
366 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
367 return -1;
369 relay_header_unpack(&rh, cell->payload);
370 if (rh.recognized == 0) {
371 /* it's possibly recognized. have to check digest to be sure. */
372 if (relay_digest_matches(thishop->b_digest, cell)) {
373 *recognized = 1;
374 *layer_hint = thishop;
375 return 0;
379 thishop = thishop->next;
380 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
381 log_fn(LOG_PROTOCOL_WARN, LD_OR,
382 "Incoming cell at client not recognized. Closing.");
383 return -1;
384 } else { /* we're in the middle. Just one crypt. */
385 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
386 cell->payload, 1) < 0)
387 return -1;
388 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
389 // "the client.");
391 } else /* cell_direction == CELL_DIRECTION_OUT */ {
392 /* we're in the middle. Just one crypt. */
394 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
395 cell->payload, 0) < 0)
396 return -1;
398 relay_header_unpack(&rh, cell->payload);
399 if (rh.recognized == 0) {
400 /* it's possibly recognized. have to check digest to be sure. */
401 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
402 *recognized = 1;
403 return 0;
407 return 0;
410 /** Package a relay cell from an edge:
411 * - Encrypt it to the right layer
412 * - Append it to the appropriate cell_queue on <b>circ</b>.
414 static int
415 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
416 cell_direction_t cell_direction,
417 crypt_path_t *layer_hint, streamid_t on_stream,
418 const char *filename, int lineno)
420 channel_t *chan; /* where to send the cell */
422 if (cell_direction == CELL_DIRECTION_OUT) {
423 crypt_path_t *thishop; /* counter for repeated crypts */
424 chan = circ->n_chan;
425 if (!chan) {
426 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d has n_chan==NULL."
427 " Dropping.", filename, lineno);
428 return 0; /* just drop it */
430 if (!CIRCUIT_IS_ORIGIN(circ)) {
431 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d on non-origin "
432 "circ. Dropping.", filename, lineno);
433 return 0; /* just drop it */
436 relay_set_digest(layer_hint->f_digest, cell);
438 thishop = layer_hint;
439 /* moving from farthest to nearest hop */
440 do {
441 tor_assert(thishop);
442 /* XXXX RD This is a bug, right? */
443 log_debug(LD_OR,"crypting a layer of the relay cell.");
444 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
445 return -1;
448 thishop = thishop->prev;
449 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
451 } else { /* incoming cell */
452 or_circuit_t *or_circ;
453 if (CIRCUIT_IS_ORIGIN(circ)) {
454 /* We should never package an _incoming_ cell from the circuit
455 * origin; that means we messed up somewhere. */
456 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
457 assert_circuit_ok(circ);
458 return 0; /* just drop it */
460 or_circ = TO_OR_CIRCUIT(circ);
461 chan = or_circ->p_chan;
462 relay_set_digest(or_circ->p_digest, cell);
463 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
464 return -1;
466 ++stats_n_relay_cells_relayed;
468 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
469 return 0;
472 /** If cell's stream_id matches the stream_id of any conn that's
473 * attached to circ, return that conn, else return NULL.
475 static edge_connection_t *
476 relay_lookup_conn(circuit_t *circ, cell_t *cell,
477 cell_direction_t cell_direction, crypt_path_t *layer_hint)
479 edge_connection_t *tmpconn;
480 relay_header_t rh;
482 relay_header_unpack(&rh, cell->payload);
484 if (!rh.stream_id)
485 return NULL;
487 /* IN or OUT cells could have come from either direction, now
488 * that we allow rendezvous *to* an OP.
491 if (CIRCUIT_IS_ORIGIN(circ)) {
492 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
493 tmpconn=tmpconn->next_stream) {
494 if (rh.stream_id == tmpconn->stream_id &&
495 !tmpconn->base_.marked_for_close &&
496 tmpconn->cpath_layer == layer_hint) {
497 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
498 return tmpconn;
501 } else {
502 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
503 tmpconn=tmpconn->next_stream) {
504 if (rh.stream_id == tmpconn->stream_id &&
505 !tmpconn->base_.marked_for_close) {
506 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
507 if (cell_direction == CELL_DIRECTION_OUT ||
508 connection_edge_is_rendezvous_stream(tmpconn))
509 return tmpconn;
512 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
513 tmpconn=tmpconn->next_stream) {
514 if (rh.stream_id == tmpconn->stream_id &&
515 !tmpconn->base_.marked_for_close) {
516 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
517 return tmpconn;
521 return NULL; /* probably a begin relay cell */
524 /** Pack the relay_header_t host-order structure <b>src</b> into
525 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
526 * about the wire format.
528 void
529 relay_header_pack(uint8_t *dest, const relay_header_t *src)
531 set_uint8(dest, src->command);
532 set_uint16(dest+1, htons(src->recognized));
533 set_uint16(dest+3, htons(src->stream_id));
534 memcpy(dest+5, src->integrity, 4);
535 set_uint16(dest+9, htons(src->length));
538 /** Unpack the network-order buffer <b>src</b> into a host-order
539 * relay_header_t structure <b>dest</b>.
541 void
542 relay_header_unpack(relay_header_t *dest, const uint8_t *src)
544 dest->command = get_uint8(src);
545 dest->recognized = ntohs(get_uint16(src+1));
546 dest->stream_id = ntohs(get_uint16(src+3));
547 memcpy(dest->integrity, src+5, 4);
548 dest->length = ntohs(get_uint16(src+9));
551 /** Convert the relay <b>command</b> into a human-readable string. */
552 static const char *
553 relay_command_to_string(uint8_t command)
555 static char buf[64];
556 switch (command) {
557 case RELAY_COMMAND_BEGIN: return "BEGIN";
558 case RELAY_COMMAND_DATA: return "DATA";
559 case RELAY_COMMAND_END: return "END";
560 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
561 case RELAY_COMMAND_SENDME: return "SENDME";
562 case RELAY_COMMAND_EXTEND: return "EXTEND";
563 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
564 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
565 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
566 case RELAY_COMMAND_DROP: return "DROP";
567 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
568 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
569 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
570 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
571 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
572 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
573 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
574 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
575 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
576 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
577 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
578 return "RENDEZVOUS_ESTABLISHED";
579 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
580 case RELAY_COMMAND_EXTEND2: return "EXTEND2";
581 case RELAY_COMMAND_EXTENDED2: return "EXTENDED2";
582 default:
583 tor_snprintf(buf, sizeof(buf), "Unrecognized relay command %u",
584 (unsigned)command);
585 return buf;
589 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
590 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
591 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
592 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
593 * destination hop for OP->OR cells.
595 * If you can't send the cell, mark the circuit for close and return -1. Else
596 * return 0.
598 MOCK_IMPL(int,
599 relay_send_command_from_edge_,(streamid_t stream_id, circuit_t *circ,
600 uint8_t relay_command, const char *payload,
601 size_t payload_len, crypt_path_t *cpath_layer,
602 const char *filename, int lineno))
604 cell_t cell;
605 relay_header_t rh;
606 cell_direction_t cell_direction;
607 /* XXXX NM Split this function into a separate versions per circuit type? */
609 tor_assert(circ);
610 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
612 memset(&cell, 0, sizeof(cell_t));
613 cell.command = CELL_RELAY;
614 if (CIRCUIT_IS_ORIGIN(circ)) {
615 tor_assert(cpath_layer);
616 cell.circ_id = circ->n_circ_id;
617 cell_direction = CELL_DIRECTION_OUT;
618 } else {
619 tor_assert(! cpath_layer);
620 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
621 cell_direction = CELL_DIRECTION_IN;
624 memset(&rh, 0, sizeof(rh));
625 rh.command = relay_command;
626 rh.stream_id = stream_id;
627 rh.length = payload_len;
628 relay_header_pack(cell.payload, &rh);
629 if (payload_len)
630 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
632 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
633 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
635 /* If we are sending an END cell and this circuit is used for a tunneled
636 * directory request, advance its state. */
637 if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
638 geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
639 DIRREQ_END_CELL_SENT);
641 if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
642 /* if we're using relaybandwidthrate, this conn wants priority */
643 channel_timestamp_client(circ->n_chan);
646 if (cell_direction == CELL_DIRECTION_OUT) {
647 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
648 if (origin_circ->remaining_relay_early_cells > 0 &&
649 (relay_command == RELAY_COMMAND_EXTEND ||
650 relay_command == RELAY_COMMAND_EXTEND2 ||
651 cpath_layer != origin_circ->cpath)) {
652 /* If we've got any relay_early cells left and (we're sending
653 * an extend cell or we're not talking to the first hop), use
654 * one of them. Don't worry about the conn protocol version:
655 * append_cell_to_circuit_queue will fix it up. */
656 cell.command = CELL_RELAY_EARLY;
657 --origin_circ->remaining_relay_early_cells;
658 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
659 (int)origin_circ->remaining_relay_early_cells);
660 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
661 * task 878. */
662 origin_circ->relay_early_commands[
663 origin_circ->relay_early_cells_sent++] = relay_command;
664 } else if (relay_command == RELAY_COMMAND_EXTEND ||
665 relay_command == RELAY_COMMAND_EXTEND2) {
666 /* If no RELAY_EARLY cells can be sent over this circuit, log which
667 * commands have been sent as RELAY_EARLY cells before; helps debug
668 * task 878. */
669 smartlist_t *commands_list = smartlist_new();
670 int i = 0;
671 char *commands = NULL;
672 for (; i < origin_circ->relay_early_cells_sent; i++)
673 smartlist_add(commands_list, (char *)
674 relay_command_to_string(origin_circ->relay_early_commands[i]));
675 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
676 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
677 "but we have run out of RELAY_EARLY cells on that circuit. "
678 "Commands sent before: %s", commands);
679 tor_free(commands);
680 smartlist_free(commands_list);
684 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
685 stream_id, filename, lineno) < 0) {
686 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
687 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
688 return -1;
690 return 0;
693 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
694 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
695 * that's sending the relay cell, or NULL if it's a control cell.
696 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
697 * for OP->OR cells.
699 * If you can't send the cell, mark the circuit for close and
700 * return -1. Else return 0.
703 connection_edge_send_command(edge_connection_t *fromconn,
704 uint8_t relay_command, const char *payload,
705 size_t payload_len)
707 /* XXXX NM Split this function into a separate versions per circuit type? */
708 circuit_t *circ;
709 crypt_path_t *cpath_layer = fromconn->cpath_layer;
710 tor_assert(fromconn);
711 circ = fromconn->on_circuit;
713 if (fromconn->base_.marked_for_close) {
714 log_warn(LD_BUG,
715 "called on conn that's already marked for close at %s:%d.",
716 fromconn->base_.marked_for_close_file,
717 fromconn->base_.marked_for_close);
718 return 0;
721 if (!circ) {
722 if (fromconn->base_.type == CONN_TYPE_AP) {
723 log_info(LD_APP,"no circ. Closing conn.");
724 connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
725 END_STREAM_REASON_INTERNAL);
726 } else {
727 log_info(LD_EXIT,"no circ. Closing conn.");
728 fromconn->edge_has_sent_end = 1; /* no circ to send to */
729 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
730 connection_mark_for_close(TO_CONN(fromconn));
732 return -1;
735 return relay_send_command_from_edge(fromconn->stream_id, circ,
736 relay_command, payload,
737 payload_len, cpath_layer);
740 /** How many times will I retry a stream that fails due to DNS
741 * resolve failure or misc error?
743 #define MAX_RESOLVE_FAILURES 3
745 /** Return 1 if reason is something that you should retry if you
746 * get the end cell before you've connected; else return 0. */
747 static int
748 edge_reason_is_retriable(int reason)
750 return reason == END_STREAM_REASON_HIBERNATING ||
751 reason == END_STREAM_REASON_RESOURCELIMIT ||
752 reason == END_STREAM_REASON_EXITPOLICY ||
753 reason == END_STREAM_REASON_RESOLVEFAILED ||
754 reason == END_STREAM_REASON_MISC ||
755 reason == END_STREAM_REASON_NOROUTE;
758 /** Called when we receive an END cell on a stream that isn't open yet,
759 * from the client side.
760 * Arguments are as for connection_edge_process_relay_cell().
762 static int
763 connection_ap_process_end_not_open(
764 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
765 entry_connection_t *conn, crypt_path_t *layer_hint)
767 node_t *exitrouter;
768 int reason = *(cell->payload+RELAY_HEADER_SIZE);
769 int control_reason;
770 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
771 (void) layer_hint; /* unused */
773 if (rh->length > 0) {
774 if (reason == END_STREAM_REASON_TORPROTOCOL ||
775 reason == END_STREAM_REASON_DESTROY) {
776 /* Both of these reasons could mean a failed tag
777 * hit the exit and it complained. Do not probe.
778 * Fail the circuit. */
779 circ->path_state = PATH_STATE_USE_FAILED;
780 return -END_CIRC_REASON_TORPROTOCOL;
781 } else if (reason == END_STREAM_REASON_INTERNAL) {
782 /* We can't infer success or failure, since older Tors report
783 * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
784 } else {
785 /* Path bias: If we get a valid reason code from the exit,
786 * it wasn't due to tagging.
788 * We rely on recognized+digest being strong enough to make
789 * tags unlikely to allow us to get tagged, yet 'recognized'
790 * reason codes here. */
791 pathbias_mark_use_success(circ);
795 if (rh->length == 0) {
796 reason = END_STREAM_REASON_MISC;
799 control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
801 if (edge_reason_is_retriable(reason) &&
802 /* avoid retry if rend */
803 !connection_edge_is_rendezvous_stream(edge_conn)) {
804 const char *chosen_exit_digest =
805 circ->build_state->chosen_exit->identity_digest;
806 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
807 safe_str(conn->socks_request->address),
808 stream_end_reason_to_string(reason));
809 exitrouter = node_get_mutable_by_id(chosen_exit_digest);
810 switch (reason) {
811 case END_STREAM_REASON_EXITPOLICY: {
812 tor_addr_t addr;
813 tor_addr_make_unspec(&addr);
814 if (rh->length >= 5) {
815 int ttl = -1;
816 tor_addr_make_unspec(&addr);
817 if (rh->length == 5 || rh->length == 9) {
818 tor_addr_from_ipv4n(&addr,
819 get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
820 if (rh->length == 9)
821 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
822 } else if (rh->length == 17 || rh->length == 21) {
823 tor_addr_from_ipv6_bytes(&addr,
824 (char*)(cell->payload+RELAY_HEADER_SIZE+1));
825 if (rh->length == 21)
826 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
828 if (tor_addr_is_null(&addr)) {
829 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
830 safe_str(conn->socks_request->address));
831 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
832 return 0;
835 if ((tor_addr_family(&addr) == AF_INET &&
836 !conn->entry_cfg.ipv4_traffic) ||
837 (tor_addr_family(&addr) == AF_INET6 &&
838 !conn->entry_cfg.ipv6_traffic)) {
839 log_fn(LOG_PROTOCOL_WARN, LD_APP,
840 "Got an EXITPOLICY failure on a connection with a "
841 "mismatched family. Closing.");
842 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
843 return 0;
845 if (get_options()->ClientDNSRejectInternalAddresses &&
846 tor_addr_is_internal(&addr, 0)) {
847 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
848 safe_str(conn->socks_request->address));
849 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
850 return 0;
853 client_dns_set_addressmap(conn,
854 conn->socks_request->address, &addr,
855 conn->chosen_exit_name, ttl);
858 char new_addr[TOR_ADDR_BUF_LEN];
859 tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
860 if (strcmp(conn->socks_request->address, new_addr)) {
861 strlcpy(conn->socks_request->address, new_addr,
862 sizeof(conn->socks_request->address));
863 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
867 /* check if the exit *ought* to have allowed it */
869 adjust_exit_policy_from_exitpolicy_failure(circ,
870 conn,
871 exitrouter,
872 &addr);
874 if (conn->chosen_exit_optional ||
875 conn->chosen_exit_retries) {
876 /* stop wanting a specific exit */
877 conn->chosen_exit_optional = 0;
878 /* A non-zero chosen_exit_retries can happen if we set a
879 * TrackHostExits for this address under a port that the exit
880 * relay allows, but then try the same address with a different
881 * port that it doesn't allow to exit. We shouldn't unregister
882 * the mapping, since it is probably still wanted on the
883 * original port. But now we give away to the exit relay that
884 * we probably have a TrackHostExits on it. So be it. */
885 conn->chosen_exit_retries = 0;
886 tor_free(conn->chosen_exit_name); /* clears it */
888 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
889 return 0;
890 /* else, conn will get closed below */
891 break;
893 case END_STREAM_REASON_CONNECTREFUSED:
894 if (!conn->chosen_exit_optional)
895 break; /* break means it'll close, below */
896 /* Else fall through: expire this circuit, clear the
897 * chosen_exit_name field, and try again. */
898 /* Falls through. */
899 case END_STREAM_REASON_RESOLVEFAILED:
900 case END_STREAM_REASON_TIMEOUT:
901 case END_STREAM_REASON_MISC:
902 case END_STREAM_REASON_NOROUTE:
903 if (client_dns_incr_failures(conn->socks_request->address)
904 < MAX_RESOLVE_FAILURES) {
905 /* We haven't retried too many times; reattach the connection. */
906 circuit_log_path(LOG_INFO,LD_APP,circ);
907 /* Mark this circuit "unusable for new streams". */
908 mark_circuit_unusable_for_new_conns(circ);
910 if (conn->chosen_exit_optional) {
911 /* stop wanting a specific exit */
912 conn->chosen_exit_optional = 0;
913 tor_free(conn->chosen_exit_name); /* clears it */
915 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
916 return 0;
917 /* else, conn will get closed below */
918 } else {
919 log_notice(LD_APP,
920 "Have tried resolving or connecting to address '%s' "
921 "at %d different places. Giving up.",
922 safe_str(conn->socks_request->address),
923 MAX_RESOLVE_FAILURES);
924 /* clear the failures, so it will have a full try next time */
925 client_dns_clear_failures(conn->socks_request->address);
927 break;
928 case END_STREAM_REASON_HIBERNATING:
929 case END_STREAM_REASON_RESOURCELIMIT:
930 if (exitrouter) {
931 policies_set_node_exitpolicy_to_reject_all(exitrouter);
933 if (conn->chosen_exit_optional) {
934 /* stop wanting a specific exit */
935 conn->chosen_exit_optional = 0;
936 tor_free(conn->chosen_exit_name); /* clears it */
938 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
939 return 0;
940 /* else, will close below */
941 break;
942 } /* end switch */
943 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
946 log_info(LD_APP,
947 "Edge got end (%s) before we're connected. Marking for close.",
948 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
949 circuit_log_path(LOG_INFO,LD_APP,circ);
950 /* need to test because of detach_retriable */
951 if (!ENTRY_TO_CONN(conn)->marked_for_close)
952 connection_mark_unattached_ap(conn, control_reason);
953 return 0;
956 /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
957 * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
958 * told us which address it rejected, then <b>addr</b> is that address;
959 * otherwise it is AF_UNSPEC.
961 * If we are sure the node should have allowed this address, mark the node as
962 * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
963 * for this particular address.
965 static void
966 adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
967 entry_connection_t *conn,
968 node_t *node,
969 const tor_addr_t *addr)
971 int make_reject_all = 0;
972 const sa_family_t family = tor_addr_family(addr);
974 if (node) {
975 tor_addr_t tmp;
976 int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
977 if (family == AF_UNSPEC) {
978 make_reject_all = 1;
979 } else if (node_exit_policy_is_exact(node, family) &&
980 asked_for_family != -1 && !conn->chosen_exit_name) {
981 make_reject_all = 1;
984 if (make_reject_all) {
985 log_info(LD_APP,
986 "Exitrouter %s seems to be more restrictive than its exit "
987 "policy. Not using this router as exit for now.",
988 node_describe(node));
989 policies_set_node_exitpolicy_to_reject_all(node);
993 if (family != AF_UNSPEC)
994 addr_policy_append_reject_addr(&circ->prepend_policy, addr);
997 /** Helper: change the socks_request-&gt;address field on conn to the
998 * dotted-quad representation of <b>new_addr</b>,
999 * and send an appropriate REMAP event. */
1000 static void
1001 remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
1003 tor_addr_to_str(conn->socks_request->address, new_addr,
1004 sizeof(conn->socks_request->address),
1006 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1007 REMAP_STREAM_SOURCE_EXIT);
1010 /** Extract the contents of a connected cell in <b>cell</b>, whose relay
1011 * header has already been parsed into <b>rh</b>. On success, set
1012 * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
1013 * the ttl of that address, in seconds, and return 0. On failure, return
1014 * -1. */
1015 STATIC int
1016 connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
1017 tor_addr_t *addr_out, int *ttl_out)
1019 uint32_t bytes;
1020 const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
1022 tor_addr_make_unspec(addr_out);
1023 *ttl_out = -1;
1024 if (rh->length == 0)
1025 return 0;
1026 if (rh->length < 4)
1027 return -1;
1028 bytes = ntohl(get_uint32(payload));
1030 /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
1031 if (bytes != 0) {
1032 /* v4 address */
1033 tor_addr_from_ipv4h(addr_out, bytes);
1034 if (rh->length >= 8) {
1035 bytes = ntohl(get_uint32(payload + 4));
1036 if (bytes <= INT32_MAX)
1037 *ttl_out = bytes;
1039 } else {
1040 if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
1041 return -1;
1042 if (get_uint8(payload + 4) != 6)
1043 return -1;
1044 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
1045 bytes = ntohl(get_uint32(payload + 21));
1046 if (bytes <= INT32_MAX)
1047 *ttl_out = (int) bytes;
1049 return 0;
1052 /** Drop all storage held by <b>addr</b>. */
1053 STATIC void
1054 address_ttl_free(address_ttl_t *addr)
1056 if (!addr)
1057 return;
1058 tor_free(addr->hostname);
1059 tor_free(addr);
1062 /** Parse a resolved cell in <b>cell</b>, with parsed header in <b>rh</b>.
1063 * Return -1 on parse error. On success, add one or more newly allocated
1064 * address_ttl_t to <b>addresses_out</b>; set *<b>errcode_out</b> to
1065 * one of 0, RESOLVED_TYPE_ERROR, or RESOLVED_TYPE_ERROR_TRANSIENT, and
1066 * return 0. */
1067 STATIC int
1068 resolved_cell_parse(const cell_t *cell, const relay_header_t *rh,
1069 smartlist_t *addresses_out, int *errcode_out)
1071 const uint8_t *cp;
1072 uint8_t answer_type;
1073 size_t answer_len;
1074 address_ttl_t *addr;
1075 size_t remaining;
1076 int errcode = 0;
1077 smartlist_t *addrs;
1079 tor_assert(cell);
1080 tor_assert(rh);
1081 tor_assert(addresses_out);
1082 tor_assert(errcode_out);
1084 *errcode_out = 0;
1086 if (rh->length > RELAY_PAYLOAD_SIZE)
1087 return -1;
1089 addrs = smartlist_new();
1091 cp = cell->payload + RELAY_HEADER_SIZE;
1093 remaining = rh->length;
1094 while (remaining) {
1095 const uint8_t *cp_orig = cp;
1096 if (remaining < 2)
1097 goto err;
1098 answer_type = *cp++;
1099 answer_len = *cp++;
1100 if (remaining < 2 + answer_len + 4) {
1101 goto err;
1103 if (answer_type == RESOLVED_TYPE_IPV4) {
1104 if (answer_len != 4) {
1105 goto err;
1107 addr = tor_malloc_zero(sizeof(*addr));
1108 tor_addr_from_ipv4n(&addr->addr, get_uint32(cp));
1109 cp += 4;
1110 addr->ttl = ntohl(get_uint32(cp));
1111 cp += 4;
1112 smartlist_add(addrs, addr);
1113 } else if (answer_type == RESOLVED_TYPE_IPV6) {
1114 if (answer_len != 16)
1115 goto err;
1116 addr = tor_malloc_zero(sizeof(*addr));
1117 tor_addr_from_ipv6_bytes(&addr->addr, (const char*) cp);
1118 cp += 16;
1119 addr->ttl = ntohl(get_uint32(cp));
1120 cp += 4;
1121 smartlist_add(addrs, addr);
1122 } else if (answer_type == RESOLVED_TYPE_HOSTNAME) {
1123 if (answer_len == 0) {
1124 goto err;
1126 addr = tor_malloc_zero(sizeof(*addr));
1127 addr->hostname = tor_memdup_nulterm(cp, answer_len);
1128 cp += answer_len;
1129 addr->ttl = ntohl(get_uint32(cp));
1130 cp += 4;
1131 smartlist_add(addrs, addr);
1132 } else if (answer_type == RESOLVED_TYPE_ERROR_TRANSIENT ||
1133 answer_type == RESOLVED_TYPE_ERROR) {
1134 errcode = answer_type;
1135 /* Ignore the error contents */
1136 cp += answer_len + 4;
1137 } else {
1138 cp += answer_len + 4;
1140 tor_assert(((ssize_t)remaining) >= (cp - cp_orig));
1141 remaining -= (cp - cp_orig);
1144 if (errcode && smartlist_len(addrs) == 0) {
1145 /* Report an error only if there were no results. */
1146 *errcode_out = errcode;
1149 smartlist_add_all(addresses_out, addrs);
1150 smartlist_free(addrs);
1152 return 0;
1154 err:
1155 /* On parse error, don't report any results */
1156 SMARTLIST_FOREACH(addrs, address_ttl_t *, a, address_ttl_free(a));
1157 smartlist_free(addrs);
1158 return -1;
1161 /** Helper for connection_edge_process_resolved_cell: given an error code,
1162 * an entry_connection, and a list of address_ttl_t *, report the best answer
1163 * to the entry_connection. */
1164 static void
1165 connection_ap_handshake_socks_got_resolved_cell(entry_connection_t *conn,
1166 int error_code,
1167 smartlist_t *results)
1169 address_ttl_t *addr_ipv4 = NULL;
1170 address_ttl_t *addr_ipv6 = NULL;
1171 address_ttl_t *addr_hostname = NULL;
1172 address_ttl_t *addr_best = NULL;
1174 /* If it's an error code, that's easy. */
1175 if (error_code) {
1176 tor_assert(error_code == RESOLVED_TYPE_ERROR ||
1177 error_code == RESOLVED_TYPE_ERROR_TRANSIENT);
1178 connection_ap_handshake_socks_resolved(conn,
1179 error_code,0,NULL,-1,-1);
1180 return;
1183 /* Get the first answer of each type. */
1184 SMARTLIST_FOREACH_BEGIN(results, address_ttl_t *, addr) {
1185 if (addr->hostname) {
1186 if (!addr_hostname) {
1187 addr_hostname = addr;
1189 } else if (tor_addr_family(&addr->addr) == AF_INET) {
1190 if (!addr_ipv4 && conn->entry_cfg.ipv4_traffic) {
1191 addr_ipv4 = addr;
1193 } else if (tor_addr_family(&addr->addr) == AF_INET6) {
1194 if (!addr_ipv6 && conn->entry_cfg.ipv6_traffic) {
1195 addr_ipv6 = addr;
1198 } SMARTLIST_FOREACH_END(addr);
1200 /* Now figure out which type we wanted to deliver. */
1201 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR) {
1202 if (addr_hostname) {
1203 connection_ap_handshake_socks_resolved(conn,
1204 RESOLVED_TYPE_HOSTNAME,
1205 strlen(addr_hostname->hostname),
1206 (uint8_t*)addr_hostname->hostname,
1207 addr_hostname->ttl,-1);
1208 } else {
1209 connection_ap_handshake_socks_resolved(conn,
1210 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1212 return;
1215 if (conn->entry_cfg.prefer_ipv6) {
1216 addr_best = addr_ipv6 ? addr_ipv6 : addr_ipv4;
1217 } else {
1218 addr_best = addr_ipv4 ? addr_ipv4 : addr_ipv6;
1221 /* Now convert it to the ugly old interface */
1222 if (! addr_best) {
1223 connection_ap_handshake_socks_resolved(conn,
1224 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1225 return;
1228 connection_ap_handshake_socks_resolved_addr(conn,
1229 &addr_best->addr,
1230 addr_best->ttl,
1231 -1);
1233 remap_event_helper(conn, &addr_best->addr);
1236 /** Handle a RELAY_COMMAND_RESOLVED cell that we received on a non-open AP
1237 * stream. */
1238 STATIC int
1239 connection_edge_process_resolved_cell(edge_connection_t *conn,
1240 const cell_t *cell,
1241 const relay_header_t *rh)
1243 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1244 smartlist_t *resolved_addresses = NULL;
1245 int errcode = 0;
1247 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
1248 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
1249 "not in state resolve_wait. Dropping.");
1250 return 0;
1252 tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
1254 resolved_addresses = smartlist_new();
1255 if (resolved_cell_parse(cell, rh, resolved_addresses, &errcode)) {
1256 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1257 "Dropping malformed 'resolved' cell");
1258 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1259 goto done;
1262 if (get_options()->ClientDNSRejectInternalAddresses) {
1263 int orig_len = smartlist_len(resolved_addresses);
1264 SMARTLIST_FOREACH_BEGIN(resolved_addresses, address_ttl_t *, addr) {
1265 if (addr->hostname == NULL && tor_addr_is_internal(&addr->addr, 0)) {
1266 log_info(LD_APP, "Got a resolved cell with answer %s; dropping that "
1267 "answer.",
1268 safe_str_client(fmt_addr(&addr->addr)));
1269 address_ttl_free(addr);
1270 SMARTLIST_DEL_CURRENT(resolved_addresses, addr);
1272 } SMARTLIST_FOREACH_END(addr);
1273 if (orig_len && smartlist_len(resolved_addresses) == 0) {
1274 log_info(LD_APP, "Got a resolved cell with only private addresses; "
1275 "dropping it.");
1276 connection_ap_handshake_socks_resolved(entry_conn,
1277 RESOLVED_TYPE_ERROR_TRANSIENT,
1278 0, NULL, 0, TIME_MAX);
1279 connection_mark_unattached_ap(entry_conn,
1280 END_STREAM_REASON_TORPROTOCOL);
1281 goto done;
1285 connection_ap_handshake_socks_got_resolved_cell(entry_conn,
1286 errcode,
1287 resolved_addresses);
1289 connection_mark_unattached_ap(entry_conn,
1290 END_STREAM_REASON_DONE |
1291 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1293 done:
1294 SMARTLIST_FOREACH(resolved_addresses, address_ttl_t *, addr,
1295 address_ttl_free(addr));
1296 smartlist_free(resolved_addresses);
1297 return 0;
1300 /** An incoming relay cell has arrived from circuit <b>circ</b> to
1301 * stream <b>conn</b>.
1303 * The arguments here are the same as in
1304 * connection_edge_process_relay_cell() below; this function is called
1305 * from there when <b>conn</b> is defined and not in an open state.
1307 static int
1308 connection_edge_process_relay_cell_not_open(
1309 relay_header_t *rh, cell_t *cell, circuit_t *circ,
1310 edge_connection_t *conn, crypt_path_t *layer_hint)
1312 if (rh->command == RELAY_COMMAND_END) {
1313 if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
1314 return connection_ap_process_end_not_open(rh, cell,
1315 TO_ORIGIN_CIRCUIT(circ),
1316 EDGE_TO_ENTRY_CONN(conn),
1317 layer_hint);
1318 } else {
1319 /* we just got an 'end', don't need to send one */
1320 conn->edge_has_sent_end = 1;
1321 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
1322 END_STREAM_REASON_FLAG_REMOTE;
1323 connection_mark_for_close(TO_CONN(conn));
1324 return 0;
1328 if (conn->base_.type == CONN_TYPE_AP &&
1329 rh->command == RELAY_COMMAND_CONNECTED) {
1330 tor_addr_t addr;
1331 int ttl;
1332 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1333 tor_assert(CIRCUIT_IS_ORIGIN(circ));
1334 if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
1335 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1336 "Got 'connected' while not in state connect_wait. Dropping.");
1337 return 0;
1339 CONNECTION_AP_EXPECT_NONPENDING(entry_conn);
1340 conn->base_.state = AP_CONN_STATE_OPEN;
1341 log_info(LD_APP,"'connected' received for circid %u streamid %d "
1342 "after %d seconds.",
1343 (unsigned)circ->n_circ_id,
1344 rh->stream_id,
1345 (int)(time(NULL) - conn->base_.timestamp_lastread));
1346 if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
1347 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1348 "Got a badly formatted connected cell. Closing.");
1349 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1350 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1352 if (tor_addr_family(&addr) != AF_UNSPEC) {
1353 const sa_family_t family = tor_addr_family(&addr);
1354 if (tor_addr_is_null(&addr) ||
1355 (get_options()->ClientDNSRejectInternalAddresses &&
1356 tor_addr_is_internal(&addr, 0))) {
1357 log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
1358 fmt_addr(&addr));
1359 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1360 connection_mark_unattached_ap(entry_conn,
1361 END_STREAM_REASON_TORPROTOCOL);
1362 return 0;
1365 if ((family == AF_INET && ! entry_conn->entry_cfg.ipv4_traffic) ||
1366 (family == AF_INET6 && ! entry_conn->entry_cfg.ipv6_traffic)) {
1367 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1368 "Got a connected cell to %s with unsupported address family."
1369 " Closing.", fmt_addr(&addr));
1370 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1371 connection_mark_unattached_ap(entry_conn,
1372 END_STREAM_REASON_TORPROTOCOL);
1373 return 0;
1376 client_dns_set_addressmap(entry_conn,
1377 entry_conn->socks_request->address, &addr,
1378 entry_conn->chosen_exit_name, ttl);
1380 remap_event_helper(entry_conn, &addr);
1382 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
1383 /* don't send a socks reply to transparent conns */
1384 tor_assert(entry_conn->socks_request != NULL);
1385 if (!entry_conn->socks_request->has_finished)
1386 connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
1388 /* Was it a linked dir conn? If so, a dir request just started to
1389 * fetch something; this could be a bootstrap status milestone. */
1390 log_debug(LD_APP, "considering");
1391 if (TO_CONN(conn)->linked_conn &&
1392 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
1393 connection_t *dirconn = TO_CONN(conn)->linked_conn;
1394 log_debug(LD_APP, "it is! %d", dirconn->purpose);
1395 switch (dirconn->purpose) {
1396 case DIR_PURPOSE_FETCH_CERTIFICATE:
1397 if (consensus_is_waiting_for_certs())
1398 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
1399 break;
1400 case DIR_PURPOSE_FETCH_CONSENSUS:
1401 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
1402 break;
1403 case DIR_PURPOSE_FETCH_SERVERDESC:
1404 case DIR_PURPOSE_FETCH_MICRODESC:
1405 if (TO_DIR_CONN(dirconn)->router_purpose == ROUTER_PURPOSE_GENERAL)
1406 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
1407 count_loading_descriptors_progress());
1408 break;
1411 /* This is definitely a success, so forget about any pending data we
1412 * had sent. */
1413 if (entry_conn->pending_optimistic_data) {
1414 buf_free(entry_conn->pending_optimistic_data);
1415 entry_conn->pending_optimistic_data = NULL;
1418 /* handle anything that might have queued */
1419 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1420 /* (We already sent an end cell if possible) */
1421 connection_mark_for_close(TO_CONN(conn));
1422 return 0;
1424 return 0;
1426 if (conn->base_.type == CONN_TYPE_AP &&
1427 rh->command == RELAY_COMMAND_RESOLVED) {
1428 return connection_edge_process_resolved_cell(conn, cell, rh);
1431 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1432 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
1433 rh->command, conn->base_.state,
1434 conn_state_to_string(conn->base_.type, conn->base_.state));
1435 return 0; /* for forward compatibility, don't kill the circuit */
1436 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1437 // connection_mark_for_close(conn);
1438 // return -1;
1441 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
1442 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
1443 * destined for <b>conn</b>.
1445 * If <b>layer_hint</b> is defined, then we're the origin of the
1446 * circuit, and it specifies the hop that packaged <b>cell</b>.
1448 * Return -reason if you want to warn and tear down the circuit, else 0.
1450 static int
1451 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
1452 edge_connection_t *conn,
1453 crypt_path_t *layer_hint)
1455 static int num_seen=0;
1456 relay_header_t rh;
1457 unsigned domain = layer_hint?LD_APP:LD_EXIT;
1458 int reason;
1459 int optimistic_data = 0; /* Set to 1 if we receive data on a stream
1460 * that's in the EXIT_CONN_STATE_RESOLVING
1461 * or EXIT_CONN_STATE_CONNECTING states. */
1463 tor_assert(cell);
1464 tor_assert(circ);
1466 relay_header_unpack(&rh, cell->payload);
1467 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1468 num_seen++;
1469 log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
1470 num_seen, rh.command, rh.stream_id);
1472 if (rh.length > RELAY_PAYLOAD_SIZE) {
1473 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1474 "Relay cell length field too long. Closing circuit.");
1475 return - END_CIRC_REASON_TORPROTOCOL;
1478 if (rh.stream_id == 0) {
1479 switch (rh.command) {
1480 case RELAY_COMMAND_BEGIN:
1481 case RELAY_COMMAND_CONNECTED:
1482 case RELAY_COMMAND_END:
1483 case RELAY_COMMAND_RESOLVE:
1484 case RELAY_COMMAND_RESOLVED:
1485 case RELAY_COMMAND_BEGIN_DIR:
1486 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
1487 "stream_id. Dropping.", (int)rh.command);
1488 return 0;
1489 default:
1494 /* either conn is NULL, in which case we've got a control cell, or else
1495 * conn points to the recognized stream. */
1497 if (conn && !connection_state_is_open(TO_CONN(conn))) {
1498 if (conn->base_.type == CONN_TYPE_EXIT &&
1499 (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
1500 conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
1501 rh.command == RELAY_COMMAND_DATA) {
1502 /* Allow DATA cells to be delivered to an exit node in state
1503 * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
1504 * This speeds up HTTP, for example. */
1505 optimistic_data = 1;
1506 } else if (rh.stream_id == 0 && rh.command == RELAY_COMMAND_DATA) {
1507 log_warn(LD_BUG, "Somehow I had a connection that matched a "
1508 "data cell with stream ID 0.");
1509 } else {
1510 return connection_edge_process_relay_cell_not_open(
1511 &rh, cell, circ, conn, layer_hint);
1515 switch (rh.command) {
1516 case RELAY_COMMAND_DROP:
1517 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1518 return 0;
1519 case RELAY_COMMAND_BEGIN:
1520 case RELAY_COMMAND_BEGIN_DIR:
1521 if (layer_hint &&
1522 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1523 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1524 "Relay begin request unsupported at AP. Dropping.");
1525 return 0;
1527 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1528 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1529 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1530 "Relay begin request to Hidden Service "
1531 "from intermediary node. Dropping.");
1532 return 0;
1534 if (conn) {
1535 log_fn(LOG_PROTOCOL_WARN, domain,
1536 "Begin cell for known stream. Dropping.");
1537 return 0;
1539 if (rh.command == RELAY_COMMAND_BEGIN_DIR &&
1540 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1541 /* Assign this circuit and its app-ward OR connection a unique ID,
1542 * so that we can measure download times. The local edge and dir
1543 * connection will be assigned the same ID when they are created
1544 * and linked. */
1545 static uint64_t next_id = 0;
1546 circ->dirreq_id = ++next_id;
1547 TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
1550 return connection_exit_begin_conn(cell, circ);
1551 case RELAY_COMMAND_DATA:
1552 ++stats_n_data_cells_received;
1553 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1554 (!layer_hint && --circ->deliver_window < 0)) {
1555 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1556 "(relay data) circ deliver_window below 0. Killing.");
1557 if (conn) {
1558 /* XXXX Do we actually need to do this? Will killing the circuit
1559 * not send an END and mark the stream for close as appropriate? */
1560 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1561 connection_mark_for_close(TO_CONN(conn));
1563 return -END_CIRC_REASON_TORPROTOCOL;
1565 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1566 layer_hint->deliver_window : circ->deliver_window);
1568 circuit_consider_sending_sendme(circ, layer_hint);
1570 if (rh.stream_id == 0) {
1571 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay data cell with zero "
1572 "stream_id. Dropping.");
1573 return 0;
1574 } else if (!conn) {
1575 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1576 rh.stream_id);
1577 return 0;
1580 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1581 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1582 "(relay data) conn deliver_window below 0. Killing.");
1583 return -END_CIRC_REASON_TORPROTOCOL;
1586 stats_n_data_bytes_received += rh.length;
1587 connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
1588 rh.length, TO_CONN(conn));
1590 if (!optimistic_data) {
1591 /* Only send a SENDME if we're not getting optimistic data; otherwise
1592 * a SENDME could arrive before the CONNECTED.
1594 connection_edge_consider_sending_sendme(conn);
1597 return 0;
1598 case RELAY_COMMAND_END:
1599 reason = rh.length > 0 ?
1600 get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1601 if (!conn) {
1602 log_info(domain,"end cell (%s) dropped, unknown stream.",
1603 stream_end_reason_to_string(reason));
1604 return 0;
1606 /* XXX add to this log_fn the exit node's nickname? */
1607 log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
1608 "Removing stream.",
1609 conn->base_.s,
1610 stream_end_reason_to_string(reason),
1611 conn->stream_id);
1612 if (conn->base_.type == CONN_TYPE_AP) {
1613 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1614 if (entry_conn->socks_request &&
1615 !entry_conn->socks_request->has_finished)
1616 log_warn(LD_BUG,
1617 "open stream hasn't sent socks answer yet? Closing.");
1619 /* We just *got* an end; no reason to send one. */
1620 conn->edge_has_sent_end = 1;
1621 if (!conn->end_reason)
1622 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1623 if (!conn->base_.marked_for_close) {
1624 /* only mark it if not already marked. it's possible to
1625 * get the 'end' right around when the client hangs up on us. */
1626 connection_mark_and_flush(TO_CONN(conn));
1628 return 0;
1629 case RELAY_COMMAND_EXTEND:
1630 case RELAY_COMMAND_EXTEND2: {
1631 static uint64_t total_n_extend=0, total_nonearly=0;
1632 total_n_extend++;
1633 if (rh.stream_id) {
1634 log_fn(LOG_PROTOCOL_WARN, domain,
1635 "'extend' cell received for non-zero stream. Dropping.");
1636 return 0;
1638 if (cell->command != CELL_RELAY_EARLY &&
1639 !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
1640 #define EARLY_WARNING_INTERVAL 3600
1641 static ratelim_t early_warning_limit =
1642 RATELIM_INIT(EARLY_WARNING_INTERVAL);
1643 char *m;
1644 if (cell->command == CELL_RELAY) {
1645 ++total_nonearly;
1646 if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
1647 double percentage = ((double)total_nonearly)/total_n_extend;
1648 percentage *= 100;
1649 log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
1650 "but not via RELAY_EARLY. Dropping.%s", m);
1651 log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
1652 "all EXTEND cells for this reason)", percentage);
1653 tor_free(m);
1655 } else {
1656 log_fn(LOG_WARN, domain,
1657 "EXTEND cell received, in a cell with type %d! Dropping.",
1658 cell->command);
1660 return 0;
1662 return circuit_extend(cell, circ);
1664 case RELAY_COMMAND_EXTENDED:
1665 case RELAY_COMMAND_EXTENDED2:
1666 if (!layer_hint) {
1667 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1668 "'extended' unsupported at non-origin. Dropping.");
1669 return 0;
1671 log_debug(domain,"Got an extended cell! Yay.");
1673 extended_cell_t extended_cell;
1674 if (extended_cell_parse(&extended_cell, rh.command,
1675 (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
1676 rh.length)<0) {
1677 log_warn(LD_PROTOCOL,
1678 "Can't parse EXTENDED cell; killing circuit.");
1679 return -END_CIRC_REASON_TORPROTOCOL;
1681 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1682 &extended_cell.created_cell)) < 0) {
1683 circuit_mark_for_close(circ, -reason);
1684 return 0; /* We don't want to cause a warning, so we mark the circuit
1685 * here. */
1688 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1689 log_info(domain,"circuit_send_next_onion_skin() failed.");
1690 return reason;
1692 return 0;
1693 case RELAY_COMMAND_TRUNCATE:
1694 if (layer_hint) {
1695 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1696 "'truncate' unsupported at origin. Dropping.");
1697 return 0;
1699 if (circ->n_hop) {
1700 if (circ->n_chan)
1701 log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
1702 extend_info_free(circ->n_hop);
1703 circ->n_hop = NULL;
1704 tor_free(circ->n_chan_create_cell);
1705 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
1707 if (circ->n_chan) {
1708 uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
1709 circuit_clear_cell_queue(circ, circ->n_chan);
1710 channel_send_destroy(circ->n_circ_id, circ->n_chan,
1711 trunc_reason);
1712 circuit_set_n_circid_chan(circ, 0, NULL);
1714 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1716 char payload[1];
1717 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1718 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1719 payload, sizeof(payload), NULL);
1721 return 0;
1722 case RELAY_COMMAND_TRUNCATED:
1723 if (!layer_hint) {
1724 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1725 "'truncated' unsupported at non-origin. Dropping.");
1726 return 0;
1728 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
1729 get_uint8(cell->payload + RELAY_HEADER_SIZE));
1730 return 0;
1731 case RELAY_COMMAND_CONNECTED:
1732 if (conn) {
1733 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1734 "'connected' unsupported while open. Closing circ.");
1735 return -END_CIRC_REASON_TORPROTOCOL;
1737 log_info(domain,
1738 "'connected' received on circid %u for streamid %d, "
1739 "no conn attached anymore. Ignoring.",
1740 (unsigned)circ->n_circ_id, rh.stream_id);
1741 return 0;
1742 case RELAY_COMMAND_SENDME:
1743 if (!rh.stream_id) {
1744 if (layer_hint) {
1745 if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
1746 CIRCWINDOW_START_MAX) {
1747 static struct ratelim_t exit_warn_ratelim = RATELIM_INIT(600);
1748 log_fn_ratelim(&exit_warn_ratelim, LOG_WARN, LD_PROTOCOL,
1749 "Unexpected sendme cell from exit relay. "
1750 "Closing circ.");
1751 return -END_CIRC_REASON_TORPROTOCOL;
1753 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1754 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1755 layer_hint->package_window);
1756 circuit_resume_edge_reading(circ, layer_hint);
1757 } else {
1758 if (circ->package_window + CIRCWINDOW_INCREMENT >
1759 CIRCWINDOW_START_MAX) {
1760 static struct ratelim_t client_warn_ratelim = RATELIM_INIT(600);
1761 log_fn_ratelim(&client_warn_ratelim,LOG_PROTOCOL_WARN, LD_PROTOCOL,
1762 "Unexpected sendme cell from client. "
1763 "Closing circ (window %d).",
1764 circ->package_window);
1765 return -END_CIRC_REASON_TORPROTOCOL;
1767 circ->package_window += CIRCWINDOW_INCREMENT;
1768 log_debug(LD_APP,
1769 "circ-level sendme at non-origin, packagewindow %d.",
1770 circ->package_window);
1771 circuit_resume_edge_reading(circ, layer_hint);
1773 return 0;
1775 if (!conn) {
1776 log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
1777 rh.stream_id);
1778 return 0;
1780 conn->package_window += STREAMWINDOW_INCREMENT;
1781 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1782 conn->package_window);
1783 if (circuit_queue_streams_are_blocked(circ)) {
1784 /* Still waiting for queue to flush; don't touch conn */
1785 return 0;
1787 connection_start_reading(TO_CONN(conn));
1788 /* handle whatever might still be on the inbuf */
1789 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1790 /* (We already sent an end cell if possible) */
1791 connection_mark_for_close(TO_CONN(conn));
1792 return 0;
1794 return 0;
1795 case RELAY_COMMAND_RESOLVE:
1796 if (layer_hint) {
1797 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1798 "resolve request unsupported at AP; dropping.");
1799 return 0;
1800 } else if (conn) {
1801 log_fn(LOG_PROTOCOL_WARN, domain,
1802 "resolve request for known stream; dropping.");
1803 return 0;
1804 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1805 log_fn(LOG_PROTOCOL_WARN, domain,
1806 "resolve request on circ with purpose %d; dropping",
1807 circ->purpose);
1808 return 0;
1810 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1811 return 0;
1812 case RELAY_COMMAND_RESOLVED:
1813 if (conn) {
1814 log_fn(LOG_PROTOCOL_WARN, domain,
1815 "'resolved' unsupported while open. Closing circ.");
1816 return -END_CIRC_REASON_TORPROTOCOL;
1818 log_info(domain,
1819 "'resolved' received, no conn attached anymore. Ignoring.");
1820 return 0;
1821 case RELAY_COMMAND_ESTABLISH_INTRO:
1822 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1823 case RELAY_COMMAND_INTRODUCE1:
1824 case RELAY_COMMAND_INTRODUCE2:
1825 case RELAY_COMMAND_INTRODUCE_ACK:
1826 case RELAY_COMMAND_RENDEZVOUS1:
1827 case RELAY_COMMAND_RENDEZVOUS2:
1828 case RELAY_COMMAND_INTRO_ESTABLISHED:
1829 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1830 rend_process_relay_cell(circ, layer_hint,
1831 rh.command, rh.length,
1832 cell->payload+RELAY_HEADER_SIZE);
1833 return 0;
1835 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1836 "Received unknown relay command %d. Perhaps the other side is using "
1837 "a newer version of Tor? Dropping.",
1838 rh.command);
1839 return 0; /* for forward compatibility, don't kill the circuit */
1842 /** How many relay_data cells have we built, ever? */
1843 uint64_t stats_n_data_cells_packaged = 0;
1844 /** How many bytes of data have we put in relay_data cells have we built,
1845 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1846 * every relay cell we ever sent were completely full of data. */
1847 uint64_t stats_n_data_bytes_packaged = 0;
1848 /** How many relay_data cells have we received, ever? */
1849 uint64_t stats_n_data_cells_received = 0;
1850 /** How many bytes of data have we received relay_data cells, ever? This would
1851 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1852 * ever received were completely full of data. */
1853 uint64_t stats_n_data_bytes_received = 0;
1855 /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
1856 * <b>package_partial</b> is true), and the appropriate package windows aren't
1857 * empty, grab a cell and send it down the circuit.
1859 * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
1860 * *<b>max_cells</b> by the number of cells packaged.
1862 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1863 * be marked for close, else return 0.
1866 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
1867 int *max_cells)
1869 size_t bytes_to_process, length;
1870 char payload[CELL_PAYLOAD_SIZE];
1871 circuit_t *circ;
1872 const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
1873 int sending_from_optimistic = 0;
1874 entry_connection_t *entry_conn =
1875 conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
1876 const int sending_optimistically =
1877 entry_conn &&
1878 conn->base_.type == CONN_TYPE_AP &&
1879 conn->base_.state != AP_CONN_STATE_OPEN;
1880 crypt_path_t *cpath_layer = conn->cpath_layer;
1882 tor_assert(conn);
1884 if (conn->base_.marked_for_close) {
1885 log_warn(LD_BUG,
1886 "called on conn that's already marked for close at %s:%d.",
1887 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
1888 return 0;
1891 if (max_cells && *max_cells <= 0)
1892 return 0;
1894 repeat_connection_edge_package_raw_inbuf:
1896 circ = circuit_get_by_edge_conn(conn);
1897 if (!circ) {
1898 log_info(domain,"conn has no circuit! Closing.");
1899 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1900 return -1;
1903 if (circuit_consider_stop_edge_reading(circ, cpath_layer))
1904 return 0;
1906 if (conn->package_window <= 0) {
1907 log_info(domain,"called with package_window %d. Skipping.",
1908 conn->package_window);
1909 connection_stop_reading(TO_CONN(conn));
1910 return 0;
1913 sending_from_optimistic = entry_conn &&
1914 entry_conn->sending_optimistic_data != NULL;
1916 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
1917 bytes_to_process = buf_datalen(entry_conn->sending_optimistic_data);
1918 if (PREDICT_UNLIKELY(!bytes_to_process)) {
1919 log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
1920 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
1921 sending_from_optimistic = 0;
1923 } else {
1924 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
1927 if (!bytes_to_process)
1928 return 0;
1930 if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
1931 return 0;
1933 if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
1934 length = RELAY_PAYLOAD_SIZE;
1935 } else {
1936 length = bytes_to_process;
1938 stats_n_data_bytes_packaged += length;
1939 stats_n_data_cells_packaged += 1;
1941 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
1942 /* XXXX We could be more efficient here by sometimes packing
1943 * previously-sent optimistic data in the same cell with data
1944 * from the inbuf. */
1945 fetch_from_buf(payload, length, entry_conn->sending_optimistic_data);
1946 if (!buf_datalen(entry_conn->sending_optimistic_data)) {
1947 buf_free(entry_conn->sending_optimistic_data);
1948 entry_conn->sending_optimistic_data = NULL;
1950 } else {
1951 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1954 log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
1955 conn->base_.s,
1956 (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
1958 if (sending_optimistically && !sending_from_optimistic) {
1959 /* This is new optimistic data; remember it in case we need to detach and
1960 retry */
1961 if (!entry_conn->pending_optimistic_data)
1962 entry_conn->pending_optimistic_data = buf_new();
1963 write_to_buf(payload, length, entry_conn->pending_optimistic_data);
1966 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1967 payload, length) < 0 )
1968 /* circuit got marked for close, don't continue, don't need to mark conn */
1969 return 0;
1971 if (!cpath_layer) { /* non-rendezvous exit */
1972 tor_assert(circ->package_window > 0);
1973 circ->package_window--;
1974 } else { /* we're an AP, or an exit on a rendezvous circ */
1975 tor_assert(cpath_layer->package_window > 0);
1976 cpath_layer->package_window--;
1979 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1980 connection_stop_reading(TO_CONN(conn));
1981 log_debug(domain,"conn->package_window reached 0.");
1982 circuit_consider_stop_edge_reading(circ, cpath_layer);
1983 return 0; /* don't process the inbuf any more */
1985 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1987 if (max_cells) {
1988 *max_cells -= 1;
1989 if (*max_cells <= 0)
1990 return 0;
1993 /* handle more if there's more, or return 0 if there isn't */
1994 goto repeat_connection_edge_package_raw_inbuf;
1997 /** Called when we've just received a relay data cell, when
1998 * we've just finished flushing all bytes to stream <b>conn</b>,
1999 * or when we've flushed *some* bytes to the stream <b>conn</b>.
2001 * If conn->outbuf is not too full, and our deliver window is
2002 * low, send back a suitable number of stream-level sendme cells.
2004 void
2005 connection_edge_consider_sending_sendme(edge_connection_t *conn)
2007 circuit_t *circ;
2009 if (connection_outbuf_too_full(TO_CONN(conn)))
2010 return;
2012 circ = circuit_get_by_edge_conn(conn);
2013 if (!circ) {
2014 /* this can legitimately happen if the destroy has already
2015 * arrived and torn down the circuit */
2016 log_info(LD_APP,"No circuit associated with conn. Skipping.");
2017 return;
2020 while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
2021 log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
2022 "Outbuf %d, Queuing stream sendme.",
2023 (int)conn->base_.outbuf_flushlen);
2024 conn->deliver_window += STREAMWINDOW_INCREMENT;
2025 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
2026 NULL, 0) < 0) {
2027 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
2028 return; /* the circuit's closed, don't continue */
2033 /** The circuit <b>circ</b> has received a circuit-level sendme
2034 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
2035 * attached streams and let them resume reading and packaging, if
2036 * their stream windows allow it.
2038 static void
2039 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
2041 if (circuit_queue_streams_are_blocked(circ)) {
2042 log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
2043 return;
2045 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
2047 if (CIRCUIT_IS_ORIGIN(circ))
2048 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
2049 circ, layer_hint);
2050 else
2051 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
2052 circ, layer_hint);
2055 void
2056 stream_choice_seed_weak_rng(void)
2058 crypto_seed_weak_rng(&stream_choice_rng);
2061 /** A helper function for circuit_resume_edge_reading() above.
2062 * The arguments are the same, except that <b>conn</b> is the head
2063 * of a linked list of edge streams that should each be considered.
2065 static int
2066 circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
2067 circuit_t *circ,
2068 crypt_path_t *layer_hint)
2070 edge_connection_t *conn;
2071 int n_packaging_streams, n_streams_left;
2072 int packaged_this_round;
2073 int cells_on_queue;
2074 int cells_per_conn;
2075 edge_connection_t *chosen_stream = NULL;
2076 int max_to_package;
2078 if (first_conn == NULL) {
2079 /* Don't bother to try to do the rest of this if there are no connections
2080 * to resume. */
2081 return 0;
2084 /* How many cells do we have space for? It will be the minimum of
2085 * the number needed to exhaust the package window, and the minimum
2086 * needed to fill the cell queue. */
2087 max_to_package = circ->package_window;
2088 if (CIRCUIT_IS_ORIGIN(circ)) {
2089 cells_on_queue = circ->n_chan_cells.n;
2090 } else {
2091 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2092 cells_on_queue = or_circ->p_chan_cells.n;
2094 if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
2095 max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
2097 /* Once we used to start listening on the streams in the order they
2098 * appeared in the linked list. That leads to starvation on the
2099 * streams that appeared later on the list, since the first streams
2100 * would always get to read first. Instead, we just pick a random
2101 * stream on the list, and enable reading for streams starting at that
2102 * point (and wrapping around as if the list were circular). It would
2103 * probably be better to actually remember which streams we've
2104 * serviced in the past, but this is simple and effective. */
2106 /* Select a stream uniformly at random from the linked list. We
2107 * don't need cryptographic randomness here. */
2109 int num_streams = 0;
2110 for (conn = first_conn; conn; conn = conn->next_stream) {
2111 num_streams++;
2112 if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
2113 chosen_stream = conn;
2115 /* Invariant: chosen_stream has been chosen uniformly at random from
2116 * among the first num_streams streams on first_conn.
2118 * (Note that we iterate over every stream on the circuit, so that after
2119 * we've considered the first stream, we've chosen it with P=1; and
2120 * after we consider the second stream, we've switched to it with P=1/2
2121 * and stayed with the first stream with P=1/2; and after we've
2122 * considered the third stream, we've switched to it with P=1/3 and
2123 * remained with one of the first two streams with P=(2/3), giving each
2124 * one P=(1/2)(2/3) )=(1/3).) */
2128 /* Count how many non-marked streams there are that have anything on
2129 * their inbuf, and enable reading on all of the connections. */
2130 n_packaging_streams = 0;
2131 /* Activate reading starting from the chosen stream */
2132 for (conn=chosen_stream; conn; conn = conn->next_stream) {
2133 /* Start reading for the streams starting from here */
2134 if (conn->base_.marked_for_close || conn->package_window <= 0)
2135 continue;
2136 if (!layer_hint || conn->cpath_layer == layer_hint) {
2137 connection_start_reading(TO_CONN(conn));
2139 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2140 ++n_packaging_streams;
2143 /* Go back and do the ones we skipped, circular-style */
2144 for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
2145 if (conn->base_.marked_for_close || conn->package_window <= 0)
2146 continue;
2147 if (!layer_hint || conn->cpath_layer == layer_hint) {
2148 connection_start_reading(TO_CONN(conn));
2150 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2151 ++n_packaging_streams;
2155 if (n_packaging_streams == 0) /* avoid divide-by-zero */
2156 return 0;
2158 again:
2160 cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
2162 packaged_this_round = 0;
2163 n_streams_left = 0;
2165 /* Iterate over all connections. Package up to cells_per_conn cells on
2166 * each. Update packaged_this_round with the total number of cells
2167 * packaged, and n_streams_left with the number that still have data to
2168 * package.
2170 for (conn=first_conn; conn; conn=conn->next_stream) {
2171 if (conn->base_.marked_for_close || conn->package_window <= 0)
2172 continue;
2173 if (!layer_hint || conn->cpath_layer == layer_hint) {
2174 int n = cells_per_conn, r;
2175 /* handle whatever might still be on the inbuf */
2176 r = connection_edge_package_raw_inbuf(conn, 1, &n);
2178 /* Note how many we packaged */
2179 packaged_this_round += (cells_per_conn-n);
2181 if (r<0) {
2182 /* Problem while packaging. (We already sent an end cell if
2183 * possible) */
2184 connection_mark_for_close(TO_CONN(conn));
2185 continue;
2188 /* If there's still data to read, we'll be coming back to this stream. */
2189 if (connection_get_inbuf_len(TO_CONN(conn)))
2190 ++n_streams_left;
2192 /* If the circuit won't accept any more data, return without looking
2193 * at any more of the streams. Any connections that should be stopped
2194 * have already been stopped by connection_edge_package_raw_inbuf. */
2195 if (circuit_consider_stop_edge_reading(circ, layer_hint))
2196 return -1;
2197 /* XXXX should we also stop immediately if we fill up the cell queue?
2198 * Probably. */
2202 /* If we made progress, and we are willing to package more, and there are
2203 * any streams left that want to package stuff... try again!
2205 if (packaged_this_round && packaged_this_round < max_to_package &&
2206 n_streams_left) {
2207 max_to_package -= packaged_this_round;
2208 n_packaging_streams = n_streams_left;
2209 goto again;
2212 return 0;
2215 /** Check if the package window for <b>circ</b> is empty (at
2216 * hop <b>layer_hint</b> if it's defined).
2218 * If yes, tell edge streams to stop reading and return 1.
2219 * Else return 0.
2221 static int
2222 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
2224 edge_connection_t *conn = NULL;
2225 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
2227 if (!layer_hint) {
2228 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2229 log_debug(domain,"considering circ->package_window %d",
2230 circ->package_window);
2231 if (circ->package_window <= 0) {
2232 log_debug(domain,"yes, not-at-origin. stopped.");
2233 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
2234 connection_stop_reading(TO_CONN(conn));
2235 return 1;
2237 return 0;
2239 /* else, layer hint is defined, use it */
2240 log_debug(domain,"considering layer_hint->package_window %d",
2241 layer_hint->package_window);
2242 if (layer_hint->package_window <= 0) {
2243 log_debug(domain,"yes, at-origin. stopped.");
2244 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
2245 conn=conn->next_stream) {
2246 if (conn->cpath_layer == layer_hint)
2247 connection_stop_reading(TO_CONN(conn));
2249 return 1;
2251 return 0;
2254 /** Check if the deliver_window for circuit <b>circ</b> (at hop
2255 * <b>layer_hint</b> if it's defined) is low enough that we should
2256 * send a circuit-level sendme back down the circuit. If so, send
2257 * enough sendmes that the window would be overfull if we sent any
2258 * more.
2260 static void
2261 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
2263 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
2264 // layer_hint ? "defined" : "null");
2265 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
2266 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
2267 log_debug(LD_CIRC,"Queuing circuit sendme.");
2268 if (layer_hint)
2269 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
2270 else
2271 circ->deliver_window += CIRCWINDOW_INCREMENT;
2272 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
2273 NULL, 0, layer_hint) < 0) {
2274 log_warn(LD_CIRC,
2275 "relay_send_command_from_edge failed. Circuit's closed.");
2276 return; /* the circuit's closed, don't continue */
2281 #ifdef ACTIVE_CIRCUITS_PARANOIA
2282 #define assert_cmux_ok_paranoid(chan) \
2283 assert_circuit_mux_okay(chan)
2284 #else
2285 #define assert_cmux_ok_paranoid(chan)
2286 #endif
2288 /** The total number of cells we have allocated. */
2289 static size_t total_cells_allocated = 0;
2291 /** Release storage held by <b>cell</b>. */
2292 static inline void
2293 packed_cell_free_unchecked(packed_cell_t *cell)
2295 --total_cells_allocated;
2296 tor_free(cell);
2299 /** Allocate and return a new packed_cell_t. */
2300 STATIC packed_cell_t *
2301 packed_cell_new(void)
2303 ++total_cells_allocated;
2304 return tor_malloc_zero(sizeof(packed_cell_t));
2307 /** Return a packed cell used outside by channel_t lower layer */
2308 void
2309 packed_cell_free(packed_cell_t *cell)
2311 if (!cell)
2312 return;
2313 packed_cell_free_unchecked(cell);
2316 /** Log current statistics for cell pool allocation at log level
2317 * <b>severity</b>. */
2318 void
2319 dump_cell_pool_usage(int severity)
2321 int n_circs = 0;
2322 int n_cells = 0;
2323 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
2324 n_cells += c->n_chan_cells.n;
2325 if (!CIRCUIT_IS_ORIGIN(c))
2326 n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
2327 ++n_circs;
2329 SMARTLIST_FOREACH_END(c);
2330 tor_log(severity, LD_MM,
2331 "%d cells allocated on %d circuits. %d cells leaked.",
2332 n_cells, n_circs, (int)total_cells_allocated - n_cells);
2335 /** Allocate a new copy of packed <b>cell</b>. */
2336 static inline packed_cell_t *
2337 packed_cell_copy(const cell_t *cell, int wide_circ_ids)
2339 packed_cell_t *c = packed_cell_new();
2340 cell_pack(c, cell, wide_circ_ids);
2341 return c;
2344 /** Append <b>cell</b> to the end of <b>queue</b>. */
2345 void
2346 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
2348 TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
2349 ++queue->n;
2352 /** Append a newly allocated copy of <b>cell</b> to the end of the
2353 * <b>exitward</b> (or app-ward) <b>queue</b> of <b>circ</b>. If
2354 * <b>use_stats</b> is true, record statistics about the cell.
2356 void
2357 cell_queue_append_packed_copy(circuit_t *circ, cell_queue_t *queue,
2358 int exitward, const cell_t *cell,
2359 int wide_circ_ids, int use_stats)
2361 packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
2362 (void)circ;
2363 (void)exitward;
2364 (void)use_stats;
2366 copy->inserted_time = (uint32_t) monotime_coarse_absolute_msec();
2368 cell_queue_append(queue, copy);
2371 /** Initialize <b>queue</b> as an empty cell queue. */
2372 void
2373 cell_queue_init(cell_queue_t *queue)
2375 memset(queue, 0, sizeof(cell_queue_t));
2376 TOR_SIMPLEQ_INIT(&queue->head);
2379 /** Remove and free every cell in <b>queue</b>. */
2380 void
2381 cell_queue_clear(cell_queue_t *queue)
2383 packed_cell_t *cell;
2384 while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
2385 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2386 packed_cell_free_unchecked(cell);
2388 TOR_SIMPLEQ_INIT(&queue->head);
2389 queue->n = 0;
2392 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
2393 * <b>queue</b> is empty. */
2394 STATIC packed_cell_t *
2395 cell_queue_pop(cell_queue_t *queue)
2397 packed_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
2398 if (!cell)
2399 return NULL;
2400 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2401 --queue->n;
2402 return cell;
2405 /** Return the total number of bytes used for each packed_cell in a queue.
2406 * Approximate. */
2407 size_t
2408 packed_cell_mem_cost(void)
2410 return sizeof(packed_cell_t);
2413 /* DOCDOC */
2414 STATIC size_t
2415 cell_queues_get_total_allocation(void)
2417 return total_cells_allocated * packed_cell_mem_cost();
2420 /** How long after we've been low on memory should we try to conserve it? */
2421 #define MEMORY_PRESSURE_INTERVAL (30*60)
2423 /** The time at which we were last low on memory. */
2424 static time_t last_time_under_memory_pressure = 0;
2426 /** Check whether we've got too much space used for cells. If so,
2427 * call the OOM handler and return 1. Otherwise, return 0. */
2428 STATIC int
2429 cell_queues_check_size(void)
2431 size_t alloc = cell_queues_get_total_allocation();
2432 alloc += buf_get_total_allocation();
2433 alloc += tor_zlib_get_total_allocation();
2434 const size_t rend_cache_total = rend_cache_get_total_allocation();
2435 alloc += rend_cache_total;
2436 if (alloc >= get_options()->MaxMemInQueues_low_threshold) {
2437 last_time_under_memory_pressure = approx_time();
2438 if (alloc >= get_options()->MaxMemInQueues) {
2439 /* If we're spending over 20% of the memory limit on hidden service
2440 * descriptors, free them until we're down to 10%.
2442 if (rend_cache_total > get_options()->MaxMemInQueues / 5) {
2443 const size_t bytes_to_remove =
2444 rend_cache_total - (size_t)(get_options()->MaxMemInQueues / 10);
2445 alloc -= hs_cache_handle_oom(time(NULL), bytes_to_remove);
2447 circuits_handle_oom(alloc);
2448 return 1;
2451 return 0;
2454 /** Return true if we've been under memory pressure in the last
2455 * MEMORY_PRESSURE_INTERVAL seconds. */
2457 have_been_under_memory_pressure(void)
2459 return last_time_under_memory_pressure + MEMORY_PRESSURE_INTERVAL
2460 < approx_time();
2464 * Update the number of cells available on the circuit's n_chan or p_chan's
2465 * circuit mux.
2467 void
2468 update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
2469 const char *file, int lineno)
2471 channel_t *chan = NULL;
2472 or_circuit_t *or_circ = NULL;
2473 circuitmux_t *cmux = NULL;
2475 tor_assert(circ);
2477 /* Okay, get the channel */
2478 if (direction == CELL_DIRECTION_OUT) {
2479 chan = circ->n_chan;
2480 } else {
2481 or_circ = TO_OR_CIRCUIT(circ);
2482 chan = or_circ->p_chan;
2485 tor_assert(chan);
2486 tor_assert(chan->cmux);
2488 /* Now get the cmux */
2489 cmux = chan->cmux;
2491 /* Cmux sanity check */
2492 if (! circuitmux_is_circuit_attached(cmux, circ)) {
2493 log_warn(LD_BUG, "called on non-attached circuit from %s:%d",
2494 file, lineno);
2495 return;
2497 tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
2499 assert_cmux_ok_paranoid(chan);
2501 /* Update the number of cells we have for the circuit mux */
2502 if (direction == CELL_DIRECTION_OUT) {
2503 circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
2504 } else {
2505 circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
2508 assert_cmux_ok_paranoid(chan);
2511 /** Remove all circuits from the cmux on <b>chan</b>.
2513 * If <b>circuits_out</b> is non-NULL, add all detached circuits to
2514 * <b>circuits_out</b>.
2516 void
2517 channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
2519 tor_assert(chan);
2520 tor_assert(chan->cmux);
2522 circuitmux_detach_all_circuits(chan->cmux, circuits_out);
2523 chan->num_n_circuits = 0;
2524 chan->num_p_circuits = 0;
2527 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
2528 * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
2529 * and start or stop reading as appropriate.
2531 * If <b>stream_id</b> is nonzero, block only the edge connection whose
2532 * stream_id matches it.
2534 * Returns the number of streams whose status we changed.
2536 static int
2537 set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
2538 int block, streamid_t stream_id)
2540 edge_connection_t *edge = NULL;
2541 int n = 0;
2542 if (circ->n_chan == chan) {
2543 circ->streams_blocked_on_n_chan = block;
2544 if (CIRCUIT_IS_ORIGIN(circ))
2545 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
2546 } else {
2547 circ->streams_blocked_on_p_chan = block;
2548 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
2549 edge = TO_OR_CIRCUIT(circ)->n_streams;
2552 for (; edge; edge = edge->next_stream) {
2553 connection_t *conn = TO_CONN(edge);
2554 if (stream_id && edge->stream_id != stream_id)
2555 continue;
2557 if (edge->edge_blocked_on_circ != block) {
2558 ++n;
2559 edge->edge_blocked_on_circ = block;
2562 if (!conn->read_event) {
2563 /* This connection is a placeholder for something; probably a DNS
2564 * request. It can't actually stop or start reading.*/
2565 continue;
2568 if (block) {
2569 if (connection_is_reading(conn))
2570 connection_stop_reading(conn);
2571 } else {
2572 /* Is this right? */
2573 if (!connection_is_reading(conn))
2574 connection_start_reading(conn);
2578 return n;
2581 /** Extract the command from a packed cell. */
2582 static uint8_t
2583 packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
2585 if (wide_circ_ids) {
2586 return get_uint8(cell->body+4);
2587 } else {
2588 return get_uint8(cell->body+2);
2592 /** Extract the circuit ID from a packed cell. */
2593 circid_t
2594 packed_cell_get_circid(const packed_cell_t *cell, int wide_circ_ids)
2596 if (wide_circ_ids) {
2597 return ntohl(get_uint32(cell->body));
2598 } else {
2599 return ntohs(get_uint16(cell->body));
2603 /** Pull as many cells as possible (but no more than <b>max</b>) from the
2604 * queue of the first active circuit on <b>chan</b>, and write them to
2605 * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
2606 * the active circuit pointer to the next active circuit in the ring. */
2607 MOCK_IMPL(int,
2608 channel_flush_from_first_active_circuit, (channel_t *chan, int max))
2610 circuitmux_t *cmux = NULL;
2611 int n_flushed = 0;
2612 cell_queue_t *queue, *destroy_queue=NULL;
2613 circuit_t *circ;
2614 or_circuit_t *or_circ;
2615 int streams_blocked;
2616 packed_cell_t *cell;
2618 /* Get the cmux */
2619 tor_assert(chan);
2620 tor_assert(chan->cmux);
2621 cmux = chan->cmux;
2623 /* Main loop: pick a circuit, send a cell, update the cmux */
2624 while (n_flushed < max) {
2625 circ = circuitmux_get_first_active_circuit(cmux, &destroy_queue);
2626 if (destroy_queue) {
2627 /* this code is duplicated from some of the logic below. Ugly! XXXX */
2628 tor_assert(destroy_queue->n > 0);
2629 cell = cell_queue_pop(destroy_queue);
2630 channel_write_packed_cell(chan, cell);
2631 /* Update the cmux destroy counter */
2632 circuitmux_notify_xmit_destroy(cmux);
2633 cell = NULL;
2634 ++n_flushed;
2635 continue;
2637 /* If it returns NULL, no cells left to send */
2638 if (!circ) break;
2639 assert_cmux_ok_paranoid(chan);
2641 if (circ->n_chan == chan) {
2642 queue = &circ->n_chan_cells;
2643 streams_blocked = circ->streams_blocked_on_n_chan;
2644 } else {
2645 or_circ = TO_OR_CIRCUIT(circ);
2646 tor_assert(or_circ->p_chan == chan);
2647 queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
2648 streams_blocked = circ->streams_blocked_on_p_chan;
2651 /* Circuitmux told us this was active, so it should have cells */
2652 if (/*BUG(*/ queue->n == 0 /*)*/) {
2653 log_warn(LD_BUG, "Found a supposedly active circuit with no cells "
2654 "to send. Trying to recover.");
2655 circuitmux_set_num_cells(cmux, circ, 0);
2656 if (! circ->marked_for_close)
2657 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
2658 continue;
2661 tor_assert(queue->n > 0);
2664 * Get just one cell here; once we've sent it, that can change the circuit
2665 * selection, so we have to loop around for another even if this circuit
2666 * has more than one.
2668 cell = cell_queue_pop(queue);
2670 /* Calculate the exact time that this cell has spent in the queue. */
2671 if (get_options()->CellStatistics ||
2672 get_options()->TestingEnableCellStatsEvent) {
2673 uint32_t msec_waiting;
2674 uint32_t msec_now = (uint32_t)monotime_coarse_absolute_msec();
2675 msec_waiting = msec_now - cell->inserted_time;
2677 if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
2678 or_circ = TO_OR_CIRCUIT(circ);
2679 or_circ->total_cell_waiting_time += msec_waiting;
2680 or_circ->processed_cells++;
2683 if (get_options()->TestingEnableCellStatsEvent) {
2684 uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
2686 testing_cell_stats_entry_t *ent =
2687 tor_malloc_zero(sizeof(testing_cell_stats_entry_t));
2688 ent->command = command;
2689 ent->waiting_time = msec_waiting / 10;
2690 ent->removed = 1;
2691 if (circ->n_chan == chan)
2692 ent->exitward = 1;
2693 if (!circ->testing_cell_stats)
2694 circ->testing_cell_stats = smartlist_new();
2695 smartlist_add(circ->testing_cell_stats, ent);
2699 /* If we just flushed our queue and this circuit is used for a
2700 * tunneled directory request, possibly advance its state. */
2701 if (queue->n == 0 && chan->dirreq_id)
2702 geoip_change_dirreq_state(chan->dirreq_id,
2703 DIRREQ_TUNNELED,
2704 DIRREQ_CIRC_QUEUE_FLUSHED);
2706 /* Now send the cell */
2707 channel_write_packed_cell(chan, cell);
2708 cell = NULL;
2711 * Don't packed_cell_free_unchecked(cell) here because the channel will
2712 * do so when it gets out of the channel queue (probably already did, in
2713 * which case that was an immediate double-free bug).
2716 /* Update the counter */
2717 ++n_flushed;
2720 * Now update the cmux; tell it we've just sent a cell, and how many
2721 * we have left.
2723 circuitmux_notify_xmit_cells(cmux, circ, 1);
2724 circuitmux_set_num_cells(cmux, circ, queue->n);
2725 if (queue->n == 0)
2726 log_debug(LD_GENERAL, "Made a circuit inactive.");
2728 /* Is the cell queue low enough to unblock all the streams that are waiting
2729 * to write to this circuit? */
2730 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
2731 set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
2733 /* If n_flushed < max still, loop around and pick another circuit */
2736 /* Okay, we're done sending now */
2737 assert_cmux_ok_paranoid(chan);
2739 return n_flushed;
2742 #if 0
2743 /** Indicate the current preferred cap for middle circuits; zero disables
2744 * the cap. Right now it's just a constant, ORCIRC_MAX_MIDDLE_CELLS, but
2745 * the logic in append_cell_to_circuit_queue() is written to be correct
2746 * if we want to base it on a consensus param or something that might change
2747 * in the future.
2749 static int
2750 get_max_middle_cells(void)
2752 return ORCIRC_MAX_MIDDLE_CELLS;
2754 #endif
2756 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
2757 * transmitting in <b>direction</b>. */
2758 void
2759 append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
2760 cell_t *cell, cell_direction_t direction,
2761 streamid_t fromstream)
2763 or_circuit_t *orcirc = NULL;
2764 cell_queue_t *queue;
2765 int streams_blocked;
2766 #if 0
2767 uint32_t tgt_max_middle_cells, p_len, n_len, tmp, hard_max_middle_cells;
2768 #endif
2770 int exitward;
2771 if (circ->marked_for_close)
2772 return;
2774 exitward = (direction == CELL_DIRECTION_OUT);
2775 if (exitward) {
2776 queue = &circ->n_chan_cells;
2777 streams_blocked = circ->streams_blocked_on_n_chan;
2778 } else {
2779 orcirc = TO_OR_CIRCUIT(circ);
2780 queue = &orcirc->p_chan_cells;
2781 streams_blocked = circ->streams_blocked_on_p_chan;
2785 * Disabling this for now because of a possible guard discovery attack
2787 #if 0
2788 /* Are we a middle circuit about to exceed ORCIRC_MAX_MIDDLE_CELLS? */
2789 if ((circ->n_chan != NULL) && CIRCUIT_IS_ORCIRC(circ)) {
2790 orcirc = TO_OR_CIRCUIT(circ);
2791 if (orcirc->p_chan) {
2792 /* We are a middle circuit if we have both n_chan and p_chan */
2793 /* We'll need to know the current preferred maximum */
2794 tgt_max_middle_cells = get_max_middle_cells();
2795 if (tgt_max_middle_cells > 0) {
2796 /* Do we need to initialize middle_max_cells? */
2797 if (orcirc->max_middle_cells == 0) {
2798 orcirc->max_middle_cells = tgt_max_middle_cells;
2799 } else {
2800 if (tgt_max_middle_cells > orcirc->max_middle_cells) {
2801 /* If we want to increase the cap, we can do so right away */
2802 orcirc->max_middle_cells = tgt_max_middle_cells;
2803 } else if (tgt_max_middle_cells < orcirc->max_middle_cells) {
2805 * If we're shrinking the cap, we can't shrink past either queue;
2806 * compare tgt_max_middle_cells rather than tgt_max_middle_cells *
2807 * ORCIRC_MAX_MIDDLE_KILL_THRESH so the queues don't shrink enough
2808 * to generate spurious warnings, either.
2810 n_len = circ->n_chan_cells.n;
2811 p_len = orcirc->p_chan_cells.n;
2812 tmp = tgt_max_middle_cells;
2813 if (tmp < n_len) tmp = n_len;
2814 if (tmp < p_len) tmp = p_len;
2815 orcirc->max_middle_cells = tmp;
2817 /* else no change */
2819 } else {
2820 /* tgt_max_middle_cells == 0 indicates we should disable the cap */
2821 orcirc->max_middle_cells = 0;
2824 /* Now we know orcirc->max_middle_cells is set correctly */
2825 if (orcirc->max_middle_cells > 0) {
2826 hard_max_middle_cells =
2827 (uint32_t)(((double)orcirc->max_middle_cells) *
2828 ORCIRC_MAX_MIDDLE_KILL_THRESH);
2830 if ((unsigned)queue->n + 1 >= hard_max_middle_cells) {
2831 /* Queueing this cell would put queue over the kill theshold */
2832 log_warn(LD_CIRC,
2833 "Got a cell exceeding the hard cap of %u in the "
2834 "%s direction on middle circ ID %u on chan ID "
2835 U64_FORMAT "; killing the circuit.",
2836 hard_max_middle_cells,
2837 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2838 (direction == CELL_DIRECTION_OUT) ?
2839 circ->n_circ_id : orcirc->p_circ_id,
2840 U64_PRINTF_ARG(
2841 (direction == CELL_DIRECTION_OUT) ?
2842 circ->n_chan->global_identifier :
2843 orcirc->p_chan->global_identifier));
2844 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2845 return;
2846 } else if ((unsigned)queue->n + 1 == orcirc->max_middle_cells) {
2847 /* Only use ==, not >= for this test so we don't spam the log */
2848 log_warn(LD_CIRC,
2849 "While trying to queue a cell, reached the soft cap of %u "
2850 "in the %s direction on middle circ ID %u "
2851 "on chan ID " U64_FORMAT ".",
2852 orcirc->max_middle_cells,
2853 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2854 (direction == CELL_DIRECTION_OUT) ?
2855 circ->n_circ_id : orcirc->p_circ_id,
2856 U64_PRINTF_ARG(
2857 (direction == CELL_DIRECTION_OUT) ?
2858 circ->n_chan->global_identifier :
2859 orcirc->p_chan->global_identifier));
2864 #endif
2866 cell_queue_append_packed_copy(circ, queue, exitward, cell,
2867 chan->wide_circ_ids, 1);
2869 if (PREDICT_UNLIKELY(cell_queues_check_size())) {
2870 /* We ran the OOM handler */
2871 if (circ->marked_for_close)
2872 return;
2875 /* If we have too many cells on the circuit, we should stop reading from
2876 * the edge streams for a while. */
2877 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
2878 set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
2880 if (streams_blocked && fromstream) {
2881 /* This edge connection is apparently not blocked; block it. */
2882 set_streams_blocked_on_circ(circ, chan, 1, fromstream);
2885 update_circuit_on_cmux(circ, direction);
2886 if (queue->n == 1) {
2887 /* This was the first cell added to the queue. We just made this
2888 * circuit active. */
2889 log_debug(LD_GENERAL, "Made a circuit active.");
2892 /* New way: mark this as having waiting cells for the scheduler */
2893 scheduler_channel_has_waiting_cells(chan);
2896 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
2897 * have at least 18 bytes of free space. The encoding is, as specified in
2898 * tor-spec.txt:
2899 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
2900 * LENGTH [1 byte]
2901 * ADDRESS [length bytes]
2902 * Return the number of bytes added, or -1 on error */
2904 append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
2906 uint32_t a;
2907 switch (tor_addr_family(addr)) {
2908 case AF_INET:
2909 payload_out[0] = RESOLVED_TYPE_IPV4;
2910 payload_out[1] = 4;
2911 a = tor_addr_to_ipv4n(addr);
2912 memcpy(payload_out+2, &a, 4);
2913 return 6;
2914 case AF_INET6:
2915 payload_out[0] = RESOLVED_TYPE_IPV6;
2916 payload_out[1] = 16;
2917 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
2918 return 18;
2919 case AF_UNSPEC:
2920 default:
2921 return -1;
2925 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
2926 * encoded as by append_address_to_payload(), try to decode the address into
2927 * *<b>addr_out</b>. Return the next byte in the payload after the address on
2928 * success, or NULL on failure. */
2929 const uint8_t *
2930 decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
2931 int payload_len)
2933 if (payload_len < 2)
2934 return NULL;
2935 if (payload_len < 2+payload[1])
2936 return NULL;
2938 switch (payload[0]) {
2939 case RESOLVED_TYPE_IPV4:
2940 if (payload[1] != 4)
2941 return NULL;
2942 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
2943 break;
2944 case RESOLVED_TYPE_IPV6:
2945 if (payload[1] != 16)
2946 return NULL;
2947 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
2948 break;
2949 default:
2950 tor_addr_make_unspec(addr_out);
2951 break;
2953 return payload + 2 + payload[1];
2956 /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
2957 void
2958 circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
2960 cell_queue_t *queue;
2961 cell_direction_t direction;
2963 if (circ->n_chan == chan) {
2964 queue = &circ->n_chan_cells;
2965 direction = CELL_DIRECTION_OUT;
2966 } else {
2967 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
2968 tor_assert(orcirc->p_chan == chan);
2969 queue = &orcirc->p_chan_cells;
2970 direction = CELL_DIRECTION_IN;
2973 /* Clear the queue */
2974 cell_queue_clear(queue);
2976 /* Update the cell counter in the cmux */
2977 if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
2978 update_circuit_on_cmux(circ, direction);
2981 /** Fail with an assert if the circuit mux on chan is corrupt
2983 void
2984 assert_circuit_mux_okay(channel_t *chan)
2986 tor_assert(chan);
2987 tor_assert(chan->cmux);
2989 circuitmux_assert_okay(chan->cmux);
2992 /** Return 1 if we shouldn't restart reading on this circuit, even if
2993 * we get a SENDME. Else return 0.
2995 static int
2996 circuit_queue_streams_are_blocked(circuit_t *circ)
2998 if (CIRCUIT_IS_ORIGIN(circ)) {
2999 return circ->streams_blocked_on_n_chan;
3000 } else {
3001 return circ->streams_blocked_on_p_chan;