Merge branch 'bug8185_025' into maint-0.2.9
[tor/appveyor.git] / src / or / relay.c
blobe7f99fda08224e713776c755c35d9ea9ecc36aab
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.
11 **/
13 #define RELAY_PRIVATE
14 #include "or.h"
15 #include "addressmap.h"
16 #include "buffers.h"
17 #include "channel.h"
18 #include "circpathbias.h"
19 #include "circuitbuild.h"
20 #include "circuitlist.h"
21 #include "circuituse.h"
22 #include "config.h"
23 #include "connection.h"
24 #include "connection_edge.h"
25 #include "connection_or.h"
26 #include "control.h"
27 #include "geoip.h"
28 #include "main.h"
29 #include "networkstatus.h"
30 #include "nodelist.h"
31 #include "onion.h"
32 #include "policies.h"
33 #include "reasons.h"
34 #include "relay.h"
35 #include "rendcache.h"
36 #include "rendcommon.h"
37 #include "router.h"
38 #include "routerlist.h"
39 #include "routerparse.h"
40 #include "scheduler.h"
42 static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
43 cell_direction_t cell_direction,
44 crypt_path_t *layer_hint);
46 static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
47 edge_connection_t *conn,
48 crypt_path_t *layer_hint);
49 static void circuit_consider_sending_sendme(circuit_t *circ,
50 crypt_path_t *layer_hint);
51 static void circuit_resume_edge_reading(circuit_t *circ,
52 crypt_path_t *layer_hint);
53 static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
54 circuit_t *circ,
55 crypt_path_t *layer_hint);
56 static int circuit_consider_stop_edge_reading(circuit_t *circ,
57 crypt_path_t *layer_hint);
58 static int circuit_queue_streams_are_blocked(circuit_t *circ);
59 static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
60 entry_connection_t *conn,
61 node_t *node,
62 const tor_addr_t *addr);
63 #if 0
64 static int get_max_middle_cells(void);
65 #endif
67 /** Stop reading on edge connections when we have this many cells
68 * waiting on the appropriate queue. */
69 #define CELL_QUEUE_HIGHWATER_SIZE 256
70 /** Start reading from edge connections again when we get down to this many
71 * cells. */
72 #define CELL_QUEUE_LOWWATER_SIZE 64
74 /** Stats: how many relay cells have originated at this hop, or have
75 * been relayed onward (not recognized at this hop)?
77 uint64_t stats_n_relay_cells_relayed = 0;
78 /** Stats: how many relay cells have been delivered to streams at this
79 * hop?
81 uint64_t stats_n_relay_cells_delivered = 0;
83 /** Used to tell which stream to read from first on a circuit. */
84 static tor_weak_rng_t stream_choice_rng = TOR_WEAK_RNG_INIT;
86 /** Update digest from the payload of cell. Assign integrity part to
87 * cell.
89 static void
90 relay_set_digest(crypto_digest_t *digest, cell_t *cell)
92 char integrity[4];
93 relay_header_t rh;
95 crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
96 crypto_digest_get_digest(digest, integrity, 4);
97 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
98 // integrity[0], integrity[1], integrity[2], integrity[3]);
99 relay_header_unpack(&rh, cell->payload);
100 memcpy(rh.integrity, integrity, 4);
101 relay_header_pack(cell->payload, &rh);
104 /** Does the digest for this circuit indicate that this cell is for us?
106 * Update digest from the payload of cell (with the integrity part set
107 * to 0). If the integrity part is valid, return 1, else restore digest
108 * and cell to their original state and return 0.
110 static int
111 relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
113 uint32_t received_integrity, calculated_integrity;
114 relay_header_t rh;
115 crypto_digest_t *backup_digest=NULL;
117 backup_digest = crypto_digest_dup(digest);
119 relay_header_unpack(&rh, cell->payload);
120 memcpy(&received_integrity, rh.integrity, 4);
121 memset(rh.integrity, 0, 4);
122 relay_header_pack(cell->payload, &rh);
124 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
125 // received_integrity[0], received_integrity[1],
126 // received_integrity[2], received_integrity[3]);
128 crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
129 crypto_digest_get_digest(digest, (char*) &calculated_integrity, 4);
131 if (calculated_integrity != received_integrity) {
132 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
133 // (%d vs %d).", received_integrity, calculated_integrity);
134 /* restore digest to its old form */
135 crypto_digest_assign(digest, backup_digest);
136 /* restore the relay header */
137 memcpy(rh.integrity, &received_integrity, 4);
138 relay_header_pack(cell->payload, &rh);
139 crypto_digest_free(backup_digest);
140 return 0;
142 crypto_digest_free(backup_digest);
143 return 1;
146 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
147 * (in place).
149 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
151 * Returns 0.
153 static int
154 relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
155 int encrypt_mode)
157 (void)encrypt_mode;
158 crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
160 return 0;
163 /** Receive a relay cell:
164 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
165 * origin; decrypt if we're headed toward the exit).
166 * - Check if recognized (if exitward).
167 * - If recognized and the digest checks out, then find if there's a stream
168 * that the cell is intended for, and deliver it to the right
169 * connection_edge.
170 * - If not recognized, then we need to relay it: append it to the appropriate
171 * cell_queue on <b>circ</b>.
173 * Return -<b>reason</b> on failure.
176 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
177 cell_direction_t cell_direction)
179 channel_t *chan = NULL;
180 crypt_path_t *layer_hint=NULL;
181 char recognized=0;
182 int reason;
184 tor_assert(cell);
185 tor_assert(circ);
186 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
187 cell_direction == CELL_DIRECTION_IN);
188 if (circ->marked_for_close)
189 return 0;
191 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
192 log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
193 return -END_CIRC_REASON_INTERNAL;
196 if (recognized) {
197 edge_connection_t *conn = NULL;
199 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
200 pathbias_check_probe_response(circ, cell);
202 /* We need to drop this cell no matter what to avoid code that expects
203 * a certain purpose (such as the hidserv code). */
204 return 0;
207 conn = relay_lookup_conn(circ, cell, cell_direction, layer_hint);
208 if (cell_direction == CELL_DIRECTION_OUT) {
209 ++stats_n_relay_cells_delivered;
210 log_debug(LD_OR,"Sending away from origin.");
211 if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
212 < 0) {
213 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
214 "connection_edge_process_relay_cell (away from origin) "
215 "failed.");
216 return reason;
219 if (cell_direction == CELL_DIRECTION_IN) {
220 ++stats_n_relay_cells_delivered;
221 log_debug(LD_OR,"Sending to origin.");
222 if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
223 layer_hint)) < 0) {
224 log_warn(LD_OR,
225 "connection_edge_process_relay_cell (at origin) failed.");
226 return reason;
229 return 0;
232 /* not recognized. pass it on. */
233 if (cell_direction == CELL_DIRECTION_OUT) {
234 cell->circ_id = circ->n_circ_id; /* switch it */
235 chan = circ->n_chan;
236 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
237 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
238 chan = TO_OR_CIRCUIT(circ)->p_chan;
239 } else {
240 log_fn(LOG_PROTOCOL_WARN, LD_OR,
241 "Dropping unrecognized inbound cell on origin circuit.");
242 /* If we see unrecognized cells on path bias testing circs,
243 * it's bad mojo. Those circuits need to die.
244 * XXX: Shouldn't they always die? */
245 if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
246 TO_ORIGIN_CIRCUIT(circ)->path_state = PATH_STATE_USE_FAILED;
247 return -END_CIRC_REASON_TORPROTOCOL;
248 } else {
249 return 0;
253 if (!chan) {
254 // XXXX Can this splice stuff be done more cleanly?
255 if (! CIRCUIT_IS_ORIGIN(circ) &&
256 TO_OR_CIRCUIT(circ)->rend_splice &&
257 cell_direction == CELL_DIRECTION_OUT) {
258 or_circuit_t *splice_ = TO_OR_CIRCUIT(circ)->rend_splice;
259 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
260 tor_assert(splice_->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
261 cell->circ_id = splice_->p_circ_id;
262 cell->command = CELL_RELAY; /* can't be relay_early anyway */
263 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice_),
264 CELL_DIRECTION_IN)) < 0) {
265 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
266 "circuits");
267 /* XXXX Do this here, or just return -1? */
268 circuit_mark_for_close(circ, -reason);
269 return reason;
271 return 0;
273 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
274 "Didn't recognize cell, but circ stops here! Closing circ.");
275 return -END_CIRC_REASON_TORPROTOCOL;
278 log_debug(LD_OR,"Passing on unrecognized cell.");
280 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
281 * we might kill the circ before we relay
282 * the cells. */
284 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
285 return 0;
288 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
289 * <b>circ</b> in direction <b>cell_direction</b>.
291 * If cell_direction == CELL_DIRECTION_IN:
292 * - If we're at the origin (we're the OP), for hops 1..N,
293 * decrypt cell. If recognized, stop.
294 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
296 * If cell_direction == CELL_DIRECTION_OUT:
297 * - decrypt one hop. Check if recognized.
299 * If cell is recognized, set *recognized to 1, and set
300 * *layer_hint to the hop that recognized it.
302 * Return -1 to indicate that we should mark the circuit for close,
303 * else return 0.
306 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
307 crypt_path_t **layer_hint, char *recognized)
309 relay_header_t rh;
311 tor_assert(circ);
312 tor_assert(cell);
313 tor_assert(recognized);
314 tor_assert(cell_direction == CELL_DIRECTION_IN ||
315 cell_direction == CELL_DIRECTION_OUT);
317 if (cell_direction == CELL_DIRECTION_IN) {
318 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
319 * We'll want to do layered decrypts. */
320 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
321 thishop = cpath;
322 if (thishop->state != CPATH_STATE_OPEN) {
323 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
324 "Relay cell before first created cell? Closing.");
325 return -1;
327 do { /* Remember: cpath is in forward order, that is, first hop first. */
328 tor_assert(thishop);
330 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
331 return -1;
333 relay_header_unpack(&rh, cell->payload);
334 if (rh.recognized == 0) {
335 /* it's possibly recognized. have to check digest to be sure. */
336 if (relay_digest_matches(thishop->b_digest, cell)) {
337 *recognized = 1;
338 *layer_hint = thishop;
339 return 0;
343 thishop = thishop->next;
344 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
345 log_fn(LOG_PROTOCOL_WARN, LD_OR,
346 "Incoming cell at client not recognized. Closing.");
347 return -1;
348 } else { /* we're in the middle. Just one crypt. */
349 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
350 cell->payload, 1) < 0)
351 return -1;
352 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
353 // "the client.");
355 } else /* cell_direction == CELL_DIRECTION_OUT */ {
356 /* we're in the middle. Just one crypt. */
358 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
359 cell->payload, 0) < 0)
360 return -1;
362 relay_header_unpack(&rh, cell->payload);
363 if (rh.recognized == 0) {
364 /* it's possibly recognized. have to check digest to be sure. */
365 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
366 *recognized = 1;
367 return 0;
371 return 0;
374 /** Package a relay cell from an edge:
375 * - Encrypt it to the right layer
376 * - Append it to the appropriate cell_queue on <b>circ</b>.
378 static int
379 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
380 cell_direction_t cell_direction,
381 crypt_path_t *layer_hint, streamid_t on_stream,
382 const char *filename, int lineno)
384 channel_t *chan; /* where to send the cell */
386 if (circ->marked_for_close) {
387 /* Circuit is marked; send nothing. */
388 return 0;
391 if (cell_direction == CELL_DIRECTION_OUT) {
392 crypt_path_t *thishop; /* counter for repeated crypts */
393 chan = circ->n_chan;
394 if (!chan) {
395 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d has n_chan==NULL."
396 " Dropping.", filename, lineno);
397 return 0; /* just drop it */
399 if (!CIRCUIT_IS_ORIGIN(circ)) {
400 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d on non-origin "
401 "circ. Dropping.", filename, lineno);
402 return 0; /* just drop it */
405 relay_set_digest(layer_hint->f_digest, cell);
407 thishop = layer_hint;
408 /* moving from farthest to nearest hop */
409 do {
410 tor_assert(thishop);
411 /* XXXX RD This is a bug, right? */
412 log_debug(LD_OR,"crypting a layer of the relay cell.");
413 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
414 return -1;
417 thishop = thishop->prev;
418 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
420 } else { /* incoming cell */
421 or_circuit_t *or_circ;
422 if (CIRCUIT_IS_ORIGIN(circ)) {
423 /* We should never package an _incoming_ cell from the circuit
424 * origin; that means we messed up somewhere. */
425 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
426 assert_circuit_ok(circ);
427 return 0; /* just drop it */
429 or_circ = TO_OR_CIRCUIT(circ);
430 chan = or_circ->p_chan;
431 relay_set_digest(or_circ->p_digest, cell);
432 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
433 return -1;
435 ++stats_n_relay_cells_relayed;
437 append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
438 return 0;
441 /** If cell's stream_id matches the stream_id of any conn that's
442 * attached to circ, return that conn, else return NULL.
444 static edge_connection_t *
445 relay_lookup_conn(circuit_t *circ, cell_t *cell,
446 cell_direction_t cell_direction, crypt_path_t *layer_hint)
448 edge_connection_t *tmpconn;
449 relay_header_t rh;
451 relay_header_unpack(&rh, cell->payload);
453 if (!rh.stream_id)
454 return NULL;
456 /* IN or OUT cells could have come from either direction, now
457 * that we allow rendezvous *to* an OP.
460 if (CIRCUIT_IS_ORIGIN(circ)) {
461 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
462 tmpconn=tmpconn->next_stream) {
463 if (rh.stream_id == tmpconn->stream_id &&
464 !tmpconn->base_.marked_for_close &&
465 tmpconn->cpath_layer == layer_hint) {
466 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
467 return tmpconn;
470 } else {
471 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
472 tmpconn=tmpconn->next_stream) {
473 if (rh.stream_id == tmpconn->stream_id &&
474 !tmpconn->base_.marked_for_close) {
475 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
476 if (cell_direction == CELL_DIRECTION_OUT ||
477 connection_edge_is_rendezvous_stream(tmpconn))
478 return tmpconn;
481 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
482 tmpconn=tmpconn->next_stream) {
483 if (rh.stream_id == tmpconn->stream_id &&
484 !tmpconn->base_.marked_for_close) {
485 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
486 return tmpconn;
490 return NULL; /* probably a begin relay cell */
493 /** Pack the relay_header_t host-order structure <b>src</b> into
494 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
495 * about the wire format.
497 void
498 relay_header_pack(uint8_t *dest, const relay_header_t *src)
500 set_uint8(dest, src->command);
501 set_uint16(dest+1, htons(src->recognized));
502 set_uint16(dest+3, htons(src->stream_id));
503 memcpy(dest+5, src->integrity, 4);
504 set_uint16(dest+9, htons(src->length));
507 /** Unpack the network-order buffer <b>src</b> into a host-order
508 * relay_header_t structure <b>dest</b>.
510 void
511 relay_header_unpack(relay_header_t *dest, const uint8_t *src)
513 dest->command = get_uint8(src);
514 dest->recognized = ntohs(get_uint16(src+1));
515 dest->stream_id = ntohs(get_uint16(src+3));
516 memcpy(dest->integrity, src+5, 4);
517 dest->length = ntohs(get_uint16(src+9));
520 /** Convert the relay <b>command</b> into a human-readable string. */
521 static const char *
522 relay_command_to_string(uint8_t command)
524 static char buf[64];
525 switch (command) {
526 case RELAY_COMMAND_BEGIN: return "BEGIN";
527 case RELAY_COMMAND_DATA: return "DATA";
528 case RELAY_COMMAND_END: return "END";
529 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
530 case RELAY_COMMAND_SENDME: return "SENDME";
531 case RELAY_COMMAND_EXTEND: return "EXTEND";
532 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
533 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
534 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
535 case RELAY_COMMAND_DROP: return "DROP";
536 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
537 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
538 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
539 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
540 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
541 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
542 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
543 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
544 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
545 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
546 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
547 return "RENDEZVOUS_ESTABLISHED";
548 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
549 case RELAY_COMMAND_EXTEND2: return "EXTEND2";
550 case RELAY_COMMAND_EXTENDED2: return "EXTENDED2";
551 default:
552 tor_snprintf(buf, sizeof(buf), "Unrecognized relay command %u",
553 (unsigned)command);
554 return buf;
558 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
559 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
560 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
561 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
562 * destination hop for OP->OR cells.
564 * If you can't send the cell, mark the circuit for close and return -1. Else
565 * return 0.
568 relay_send_command_from_edge_(streamid_t stream_id, circuit_t *circ,
569 uint8_t relay_command, const char *payload,
570 size_t payload_len, crypt_path_t *cpath_layer,
571 const char *filename, int lineno)
573 cell_t cell;
574 relay_header_t rh;
575 cell_direction_t cell_direction;
576 /* XXXX NM Split this function into a separate versions per circuit type? */
578 tor_assert(circ);
579 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
581 memset(&cell, 0, sizeof(cell_t));
582 cell.command = CELL_RELAY;
583 if (cpath_layer) {
584 cell.circ_id = circ->n_circ_id;
585 cell_direction = CELL_DIRECTION_OUT;
586 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
587 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
588 cell_direction = CELL_DIRECTION_IN;
589 } else {
590 return -1;
593 memset(&rh, 0, sizeof(rh));
594 rh.command = relay_command;
595 rh.stream_id = stream_id;
596 rh.length = payload_len;
597 relay_header_pack(cell.payload, &rh);
598 if (payload_len)
599 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
601 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
602 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
604 /* If we are sending an END cell and this circuit is used for a tunneled
605 * directory request, advance its state. */
606 if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
607 geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
608 DIRREQ_END_CELL_SENT);
610 if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
611 /* if we're using relaybandwidthrate, this conn wants priority */
612 channel_timestamp_client(circ->n_chan);
615 if (cell_direction == CELL_DIRECTION_OUT) {
616 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
617 if (origin_circ->remaining_relay_early_cells > 0 &&
618 (relay_command == RELAY_COMMAND_EXTEND ||
619 relay_command == RELAY_COMMAND_EXTEND2 ||
620 cpath_layer != origin_circ->cpath)) {
621 /* If we've got any relay_early cells left and (we're sending
622 * an extend cell or we're not talking to the first hop), use
623 * one of them. Don't worry about the conn protocol version:
624 * append_cell_to_circuit_queue will fix it up. */
625 cell.command = CELL_RELAY_EARLY;
626 --origin_circ->remaining_relay_early_cells;
627 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
628 (int)origin_circ->remaining_relay_early_cells);
629 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
630 * task 878. */
631 origin_circ->relay_early_commands[
632 origin_circ->relay_early_cells_sent++] = relay_command;
633 } else if (relay_command == RELAY_COMMAND_EXTEND ||
634 relay_command == RELAY_COMMAND_EXTEND2) {
635 /* If no RELAY_EARLY cells can be sent over this circuit, log which
636 * commands have been sent as RELAY_EARLY cells before; helps debug
637 * task 878. */
638 smartlist_t *commands_list = smartlist_new();
639 int i = 0;
640 char *commands = NULL;
641 for (; i < origin_circ->relay_early_cells_sent; i++)
642 smartlist_add(commands_list, (char *)
643 relay_command_to_string(origin_circ->relay_early_commands[i]));
644 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
645 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
646 "but we have run out of RELAY_EARLY cells on that circuit. "
647 "Commands sent before: %s", commands);
648 tor_free(commands);
649 smartlist_free(commands_list);
653 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
654 stream_id, filename, lineno) < 0) {
655 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
656 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
657 return -1;
659 return 0;
662 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
663 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
664 * that's sending the relay cell, or NULL if it's a control cell.
665 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
666 * for OP->OR cells.
668 * If you can't send the cell, mark the circuit for close and
669 * return -1. Else return 0.
672 connection_edge_send_command(edge_connection_t *fromconn,
673 uint8_t relay_command, const char *payload,
674 size_t payload_len)
676 /* XXXX NM Split this function into a separate versions per circuit type? */
677 circuit_t *circ;
678 crypt_path_t *cpath_layer = fromconn->cpath_layer;
679 tor_assert(fromconn);
680 circ = fromconn->on_circuit;
682 if (fromconn->base_.marked_for_close) {
683 log_warn(LD_BUG,
684 "called on conn that's already marked for close at %s:%d.",
685 fromconn->base_.marked_for_close_file,
686 fromconn->base_.marked_for_close);
687 return 0;
690 if (!circ) {
691 if (fromconn->base_.type == CONN_TYPE_AP) {
692 log_info(LD_APP,"no circ. Closing conn.");
693 connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
694 END_STREAM_REASON_INTERNAL);
695 } else {
696 log_info(LD_EXIT,"no circ. Closing conn.");
697 fromconn->edge_has_sent_end = 1; /* no circ to send to */
698 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
699 connection_mark_for_close(TO_CONN(fromconn));
701 return -1;
704 if (circ->marked_for_close) {
705 /* The circuit has been marked, but not freed yet. When it's freed, it
706 * will mark this connection for close. */
707 return -1;
710 return relay_send_command_from_edge(fromconn->stream_id, circ,
711 relay_command, payload,
712 payload_len, cpath_layer);
715 /** How many times will I retry a stream that fails due to DNS
716 * resolve failure or misc error?
718 #define MAX_RESOLVE_FAILURES 3
720 /** Return 1 if reason is something that you should retry if you
721 * get the end cell before you've connected; else return 0. */
722 static int
723 edge_reason_is_retriable(int reason)
725 return reason == END_STREAM_REASON_HIBERNATING ||
726 reason == END_STREAM_REASON_RESOURCELIMIT ||
727 reason == END_STREAM_REASON_EXITPOLICY ||
728 reason == END_STREAM_REASON_RESOLVEFAILED ||
729 reason == END_STREAM_REASON_MISC ||
730 reason == END_STREAM_REASON_NOROUTE;
733 /** Called when we receive an END cell on a stream that isn't open yet,
734 * from the client side.
735 * Arguments are as for connection_edge_process_relay_cell().
737 static int
738 connection_ap_process_end_not_open(
739 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
740 entry_connection_t *conn, crypt_path_t *layer_hint)
742 node_t *exitrouter;
743 int reason = *(cell->payload+RELAY_HEADER_SIZE);
744 int control_reason;
745 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
746 (void) layer_hint; /* unused */
748 if (rh->length > 0) {
749 if (reason == END_STREAM_REASON_TORPROTOCOL ||
750 reason == END_STREAM_REASON_DESTROY) {
751 /* Both of these reasons could mean a failed tag
752 * hit the exit and it complained. Do not probe.
753 * Fail the circuit. */
754 circ->path_state = PATH_STATE_USE_FAILED;
755 return -END_CIRC_REASON_TORPROTOCOL;
756 } else if (reason == END_STREAM_REASON_INTERNAL) {
757 /* We can't infer success or failure, since older Tors report
758 * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
759 } else {
760 /* Path bias: If we get a valid reason code from the exit,
761 * it wasn't due to tagging.
763 * We rely on recognized+digest being strong enough to make
764 * tags unlikely to allow us to get tagged, yet 'recognized'
765 * reason codes here. */
766 pathbias_mark_use_success(circ);
770 if (rh->length == 0) {
771 reason = END_STREAM_REASON_MISC;
774 control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
776 if (edge_reason_is_retriable(reason) &&
777 /* avoid retry if rend */
778 !connection_edge_is_rendezvous_stream(edge_conn)) {
779 const char *chosen_exit_digest =
780 circ->build_state->chosen_exit->identity_digest;
781 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
782 safe_str(conn->socks_request->address),
783 stream_end_reason_to_string(reason));
784 exitrouter = node_get_mutable_by_id(chosen_exit_digest);
785 switch (reason) {
786 case END_STREAM_REASON_EXITPOLICY: {
787 tor_addr_t addr;
788 tor_addr_make_unspec(&addr);
789 if (rh->length >= 5) {
790 int ttl = -1;
791 tor_addr_make_unspec(&addr);
792 if (rh->length == 5 || rh->length == 9) {
793 tor_addr_from_ipv4n(&addr,
794 get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
795 if (rh->length == 9)
796 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
797 } else if (rh->length == 17 || rh->length == 21) {
798 tor_addr_from_ipv6_bytes(&addr,
799 (char*)(cell->payload+RELAY_HEADER_SIZE+1));
800 if (rh->length == 21)
801 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
803 if (tor_addr_is_null(&addr)) {
804 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
805 safe_str(conn->socks_request->address));
806 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
807 return 0;
810 if ((tor_addr_family(&addr) == AF_INET &&
811 !conn->entry_cfg.ipv4_traffic) ||
812 (tor_addr_family(&addr) == AF_INET6 &&
813 !conn->entry_cfg.ipv6_traffic)) {
814 log_fn(LOG_PROTOCOL_WARN, LD_APP,
815 "Got an EXITPOLICY failure on a connection with a "
816 "mismatched family. Closing.");
817 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
818 return 0;
820 if (get_options()->ClientDNSRejectInternalAddresses &&
821 tor_addr_is_internal(&addr, 0)) {
822 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
823 safe_str(conn->socks_request->address));
824 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
825 return 0;
828 client_dns_set_addressmap(conn,
829 conn->socks_request->address, &addr,
830 conn->chosen_exit_name, ttl);
833 char new_addr[TOR_ADDR_BUF_LEN];
834 tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
835 if (strcmp(conn->socks_request->address, new_addr)) {
836 strlcpy(conn->socks_request->address, new_addr,
837 sizeof(conn->socks_request->address));
838 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
842 /* check if the exit *ought* to have allowed it */
844 adjust_exit_policy_from_exitpolicy_failure(circ,
845 conn,
846 exitrouter,
847 &addr);
849 if (conn->chosen_exit_optional ||
850 conn->chosen_exit_retries) {
851 /* stop wanting a specific exit */
852 conn->chosen_exit_optional = 0;
853 /* A non-zero chosen_exit_retries can happen if we set a
854 * TrackHostExits for this address under a port that the exit
855 * relay allows, but then try the same address with a different
856 * port that it doesn't allow to exit. We shouldn't unregister
857 * the mapping, since it is probably still wanted on the
858 * original port. But now we give away to the exit relay that
859 * we probably have a TrackHostExits on it. So be it. */
860 conn->chosen_exit_retries = 0;
861 tor_free(conn->chosen_exit_name); /* clears it */
863 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
864 return 0;
865 /* else, conn will get closed below */
866 break;
868 case END_STREAM_REASON_CONNECTREFUSED:
869 if (!conn->chosen_exit_optional)
870 break; /* break means it'll close, below */
871 /* Else fall through: expire this circuit, clear the
872 * chosen_exit_name field, and try again. */
873 /* Falls through. */
874 case END_STREAM_REASON_RESOLVEFAILED:
875 case END_STREAM_REASON_TIMEOUT:
876 case END_STREAM_REASON_MISC:
877 case END_STREAM_REASON_NOROUTE:
878 if (client_dns_incr_failures(conn->socks_request->address)
879 < MAX_RESOLVE_FAILURES) {
880 /* We haven't retried too many times; reattach the connection. */
881 circuit_log_path(LOG_INFO,LD_APP,circ);
882 /* Mark this circuit "unusable for new streams". */
883 mark_circuit_unusable_for_new_conns(circ);
885 if (conn->chosen_exit_optional) {
886 /* stop wanting a specific exit */
887 conn->chosen_exit_optional = 0;
888 tor_free(conn->chosen_exit_name); /* clears it */
890 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
891 return 0;
892 /* else, conn will get closed below */
893 } else {
894 log_notice(LD_APP,
895 "Have tried resolving or connecting to address '%s' "
896 "at %d different places. Giving up.",
897 safe_str(conn->socks_request->address),
898 MAX_RESOLVE_FAILURES);
899 /* clear the failures, so it will have a full try next time */
900 client_dns_clear_failures(conn->socks_request->address);
902 break;
903 case END_STREAM_REASON_HIBERNATING:
904 case END_STREAM_REASON_RESOURCELIMIT:
905 if (exitrouter) {
906 policies_set_node_exitpolicy_to_reject_all(exitrouter);
908 if (conn->chosen_exit_optional) {
909 /* stop wanting a specific exit */
910 conn->chosen_exit_optional = 0;
911 tor_free(conn->chosen_exit_name); /* clears it */
913 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
914 return 0;
915 /* else, will close below */
916 break;
917 } /* end switch */
918 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
921 log_info(LD_APP,
922 "Edge got end (%s) before we're connected. Marking for close.",
923 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
924 circuit_log_path(LOG_INFO,LD_APP,circ);
925 /* need to test because of detach_retriable */
926 if (!ENTRY_TO_CONN(conn)->marked_for_close)
927 connection_mark_unattached_ap(conn, control_reason);
928 return 0;
931 /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
932 * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
933 * told us which address it rejected, then <b>addr</b> is that address;
934 * otherwise it is AF_UNSPEC.
936 * If we are sure the node should have allowed this address, mark the node as
937 * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
938 * for this particular address.
940 static void
941 adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
942 entry_connection_t *conn,
943 node_t *node,
944 const tor_addr_t *addr)
946 int make_reject_all = 0;
947 const sa_family_t family = tor_addr_family(addr);
949 if (node) {
950 tor_addr_t tmp;
951 int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
952 if (family == AF_UNSPEC) {
953 make_reject_all = 1;
954 } else if (node_exit_policy_is_exact(node, family) &&
955 asked_for_family != -1 && !conn->chosen_exit_name) {
956 make_reject_all = 1;
959 if (make_reject_all) {
960 log_info(LD_APP,
961 "Exitrouter %s seems to be more restrictive than its exit "
962 "policy. Not using this router as exit for now.",
963 node_describe(node));
964 policies_set_node_exitpolicy_to_reject_all(node);
968 if (family != AF_UNSPEC)
969 addr_policy_append_reject_addr(&circ->prepend_policy, addr);
972 /** Helper: change the socks_request-&gt;address field on conn to the
973 * dotted-quad representation of <b>new_addr</b>,
974 * and send an appropriate REMAP event. */
975 static void
976 remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
978 tor_addr_to_str(conn->socks_request->address, new_addr,
979 sizeof(conn->socks_request->address),
981 control_event_stream_status(conn, STREAM_EVENT_REMAP,
982 REMAP_STREAM_SOURCE_EXIT);
985 /** Extract the contents of a connected cell in <b>cell</b>, whose relay
986 * header has already been parsed into <b>rh</b>. On success, set
987 * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
988 * the ttl of that address, in seconds, and return 0. On failure, return
989 * -1. */
990 STATIC int
991 connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
992 tor_addr_t *addr_out, int *ttl_out)
994 uint32_t bytes;
995 const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
997 tor_addr_make_unspec(addr_out);
998 *ttl_out = -1;
999 if (rh->length == 0)
1000 return 0;
1001 if (rh->length < 4)
1002 return -1;
1003 bytes = ntohl(get_uint32(payload));
1005 /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
1006 if (bytes != 0) {
1007 /* v4 address */
1008 tor_addr_from_ipv4h(addr_out, bytes);
1009 if (rh->length >= 8) {
1010 bytes = ntohl(get_uint32(payload + 4));
1011 if (bytes <= INT32_MAX)
1012 *ttl_out = bytes;
1014 } else {
1015 if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
1016 return -1;
1017 if (get_uint8(payload + 4) != 6)
1018 return -1;
1019 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
1020 bytes = ntohl(get_uint32(payload + 21));
1021 if (bytes <= INT32_MAX)
1022 *ttl_out = (int) bytes;
1024 return 0;
1027 /** Drop all storage held by <b>addr</b>. */
1028 STATIC void
1029 address_ttl_free(address_ttl_t *addr)
1031 if (!addr)
1032 return;
1033 tor_free(addr->hostname);
1034 tor_free(addr);
1037 /** Parse a resolved cell in <b>cell</b>, with parsed header in <b>rh</b>.
1038 * Return -1 on parse error. On success, add one or more newly allocated
1039 * address_ttl_t to <b>addresses_out</b>; set *<b>errcode_out</b> to
1040 * one of 0, RESOLVED_TYPE_ERROR, or RESOLVED_TYPE_ERROR_TRANSIENT, and
1041 * return 0. */
1042 STATIC int
1043 resolved_cell_parse(const cell_t *cell, const relay_header_t *rh,
1044 smartlist_t *addresses_out, int *errcode_out)
1046 const uint8_t *cp;
1047 uint8_t answer_type;
1048 size_t answer_len;
1049 address_ttl_t *addr;
1050 size_t remaining;
1051 int errcode = 0;
1052 smartlist_t *addrs;
1054 tor_assert(cell);
1055 tor_assert(rh);
1056 tor_assert(addresses_out);
1057 tor_assert(errcode_out);
1059 *errcode_out = 0;
1061 if (rh->length > RELAY_PAYLOAD_SIZE)
1062 return -1;
1064 addrs = smartlist_new();
1066 cp = cell->payload + RELAY_HEADER_SIZE;
1068 remaining = rh->length;
1069 while (remaining) {
1070 const uint8_t *cp_orig = cp;
1071 if (remaining < 2)
1072 goto err;
1073 answer_type = *cp++;
1074 answer_len = *cp++;
1075 if (remaining < 2 + answer_len + 4) {
1076 goto err;
1078 if (answer_type == RESOLVED_TYPE_IPV4) {
1079 if (answer_len != 4) {
1080 goto err;
1082 addr = tor_malloc_zero(sizeof(*addr));
1083 tor_addr_from_ipv4n(&addr->addr, get_uint32(cp));
1084 cp += 4;
1085 addr->ttl = ntohl(get_uint32(cp));
1086 cp += 4;
1087 smartlist_add(addrs, addr);
1088 } else if (answer_type == RESOLVED_TYPE_IPV6) {
1089 if (answer_len != 16)
1090 goto err;
1091 addr = tor_malloc_zero(sizeof(*addr));
1092 tor_addr_from_ipv6_bytes(&addr->addr, (const char*) cp);
1093 cp += 16;
1094 addr->ttl = ntohl(get_uint32(cp));
1095 cp += 4;
1096 smartlist_add(addrs, addr);
1097 } else if (answer_type == RESOLVED_TYPE_HOSTNAME) {
1098 if (answer_len == 0) {
1099 goto err;
1101 addr = tor_malloc_zero(sizeof(*addr));
1102 addr->hostname = tor_memdup_nulterm(cp, answer_len);
1103 cp += answer_len;
1104 addr->ttl = ntohl(get_uint32(cp));
1105 cp += 4;
1106 smartlist_add(addrs, addr);
1107 } else if (answer_type == RESOLVED_TYPE_ERROR_TRANSIENT ||
1108 answer_type == RESOLVED_TYPE_ERROR) {
1109 errcode = answer_type;
1110 /* Ignore the error contents */
1111 cp += answer_len + 4;
1112 } else {
1113 cp += answer_len + 4;
1115 tor_assert(((ssize_t)remaining) >= (cp - cp_orig));
1116 remaining -= (cp - cp_orig);
1119 if (errcode && smartlist_len(addrs) == 0) {
1120 /* Report an error only if there were no results. */
1121 *errcode_out = errcode;
1124 smartlist_add_all(addresses_out, addrs);
1125 smartlist_free(addrs);
1127 return 0;
1129 err:
1130 /* On parse error, don't report any results */
1131 SMARTLIST_FOREACH(addrs, address_ttl_t *, a, address_ttl_free(a));
1132 smartlist_free(addrs);
1133 return -1;
1136 /** Helper for connection_edge_process_resolved_cell: given an error code,
1137 * an entry_connection, and a list of address_ttl_t *, report the best answer
1138 * to the entry_connection. */
1139 static void
1140 connection_ap_handshake_socks_got_resolved_cell(entry_connection_t *conn,
1141 int error_code,
1142 smartlist_t *results)
1144 address_ttl_t *addr_ipv4 = NULL;
1145 address_ttl_t *addr_ipv6 = NULL;
1146 address_ttl_t *addr_hostname = NULL;
1147 address_ttl_t *addr_best = NULL;
1149 /* If it's an error code, that's easy. */
1150 if (error_code) {
1151 tor_assert(error_code == RESOLVED_TYPE_ERROR ||
1152 error_code == RESOLVED_TYPE_ERROR_TRANSIENT);
1153 connection_ap_handshake_socks_resolved(conn,
1154 error_code,0,NULL,-1,-1);
1155 return;
1158 /* Get the first answer of each type. */
1159 SMARTLIST_FOREACH_BEGIN(results, address_ttl_t *, addr) {
1160 if (addr->hostname) {
1161 if (!addr_hostname) {
1162 addr_hostname = addr;
1164 } else if (tor_addr_family(&addr->addr) == AF_INET) {
1165 if (!addr_ipv4 && conn->entry_cfg.ipv4_traffic) {
1166 addr_ipv4 = addr;
1168 } else if (tor_addr_family(&addr->addr) == AF_INET6) {
1169 if (!addr_ipv6 && conn->entry_cfg.ipv6_traffic) {
1170 addr_ipv6 = addr;
1173 } SMARTLIST_FOREACH_END(addr);
1175 /* Now figure out which type we wanted to deliver. */
1176 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR) {
1177 if (addr_hostname) {
1178 connection_ap_handshake_socks_resolved(conn,
1179 RESOLVED_TYPE_HOSTNAME,
1180 strlen(addr_hostname->hostname),
1181 (uint8_t*)addr_hostname->hostname,
1182 addr_hostname->ttl,-1);
1183 } else {
1184 connection_ap_handshake_socks_resolved(conn,
1185 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1187 return;
1190 if (conn->entry_cfg.prefer_ipv6) {
1191 addr_best = addr_ipv6 ? addr_ipv6 : addr_ipv4;
1192 } else {
1193 addr_best = addr_ipv4 ? addr_ipv4 : addr_ipv6;
1196 /* Now convert it to the ugly old interface */
1197 if (! addr_best) {
1198 connection_ap_handshake_socks_resolved(conn,
1199 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1200 return;
1203 connection_ap_handshake_socks_resolved_addr(conn,
1204 &addr_best->addr,
1205 addr_best->ttl,
1206 -1);
1208 remap_event_helper(conn, &addr_best->addr);
1211 /** Handle a RELAY_COMMAND_RESOLVED cell that we received on a non-open AP
1212 * stream. */
1213 STATIC int
1214 connection_edge_process_resolved_cell(edge_connection_t *conn,
1215 const cell_t *cell,
1216 const relay_header_t *rh)
1218 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1219 smartlist_t *resolved_addresses = NULL;
1220 int errcode = 0;
1222 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
1223 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
1224 "not in state resolve_wait. Dropping.");
1225 return 0;
1227 tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
1229 resolved_addresses = smartlist_new();
1230 if (resolved_cell_parse(cell, rh, resolved_addresses, &errcode)) {
1231 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1232 "Dropping malformed 'resolved' cell");
1233 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1234 goto done;
1237 if (get_options()->ClientDNSRejectInternalAddresses) {
1238 int orig_len = smartlist_len(resolved_addresses);
1239 SMARTLIST_FOREACH_BEGIN(resolved_addresses, address_ttl_t *, addr) {
1240 if (addr->hostname == NULL && tor_addr_is_internal(&addr->addr, 0)) {
1241 log_info(LD_APP, "Got a resolved cell with answer %s; dropping that "
1242 "answer.",
1243 safe_str_client(fmt_addr(&addr->addr)));
1244 address_ttl_free(addr);
1245 SMARTLIST_DEL_CURRENT(resolved_addresses, addr);
1247 } SMARTLIST_FOREACH_END(addr);
1248 if (orig_len && smartlist_len(resolved_addresses) == 0) {
1249 log_info(LD_APP, "Got a resolved cell with only private addresses; "
1250 "dropping it.");
1251 connection_ap_handshake_socks_resolved(entry_conn,
1252 RESOLVED_TYPE_ERROR_TRANSIENT,
1253 0, NULL, 0, TIME_MAX);
1254 connection_mark_unattached_ap(entry_conn,
1255 END_STREAM_REASON_TORPROTOCOL);
1256 goto done;
1260 connection_ap_handshake_socks_got_resolved_cell(entry_conn,
1261 errcode,
1262 resolved_addresses);
1264 connection_mark_unattached_ap(entry_conn,
1265 END_STREAM_REASON_DONE |
1266 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1268 done:
1269 SMARTLIST_FOREACH(resolved_addresses, address_ttl_t *, addr,
1270 address_ttl_free(addr));
1271 smartlist_free(resolved_addresses);
1272 return 0;
1275 /** An incoming relay cell has arrived from circuit <b>circ</b> to
1276 * stream <b>conn</b>.
1278 * The arguments here are the same as in
1279 * connection_edge_process_relay_cell() below; this function is called
1280 * from there when <b>conn</b> is defined and not in an open state.
1282 static int
1283 connection_edge_process_relay_cell_not_open(
1284 relay_header_t *rh, cell_t *cell, circuit_t *circ,
1285 edge_connection_t *conn, crypt_path_t *layer_hint)
1287 if (rh->command == RELAY_COMMAND_END) {
1288 if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
1289 return connection_ap_process_end_not_open(rh, cell,
1290 TO_ORIGIN_CIRCUIT(circ),
1291 EDGE_TO_ENTRY_CONN(conn),
1292 layer_hint);
1293 } else {
1294 /* we just got an 'end', don't need to send one */
1295 conn->edge_has_sent_end = 1;
1296 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
1297 END_STREAM_REASON_FLAG_REMOTE;
1298 connection_mark_for_close(TO_CONN(conn));
1299 return 0;
1303 if (conn->base_.type == CONN_TYPE_AP &&
1304 rh->command == RELAY_COMMAND_CONNECTED) {
1305 tor_addr_t addr;
1306 int ttl;
1307 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1308 tor_assert(CIRCUIT_IS_ORIGIN(circ));
1309 if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
1310 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1311 "Got 'connected' while not in state connect_wait. Dropping.");
1312 return 0;
1314 CONNECTION_AP_EXPECT_NONPENDING(entry_conn);
1315 conn->base_.state = AP_CONN_STATE_OPEN;
1316 log_info(LD_APP,"'connected' received for circid %u streamid %d "
1317 "after %d seconds.",
1318 (unsigned)circ->n_circ_id,
1319 rh->stream_id,
1320 (int)(time(NULL) - conn->base_.timestamp_lastread));
1321 if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
1322 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1323 "Got a badly formatted connected cell. Closing.");
1324 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1325 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1327 if (tor_addr_family(&addr) != AF_UNSPEC) {
1328 const sa_family_t family = tor_addr_family(&addr);
1329 if (tor_addr_is_null(&addr) ||
1330 (get_options()->ClientDNSRejectInternalAddresses &&
1331 tor_addr_is_internal(&addr, 0))) {
1332 log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
1333 fmt_addr(&addr));
1334 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1335 connection_mark_unattached_ap(entry_conn,
1336 END_STREAM_REASON_TORPROTOCOL);
1337 return 0;
1340 if ((family == AF_INET && ! entry_conn->entry_cfg.ipv4_traffic) ||
1341 (family == AF_INET6 && ! entry_conn->entry_cfg.ipv6_traffic)) {
1342 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1343 "Got a connected cell to %s with unsupported address family."
1344 " Closing.", fmt_addr(&addr));
1345 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1346 connection_mark_unattached_ap(entry_conn,
1347 END_STREAM_REASON_TORPROTOCOL);
1348 return 0;
1351 client_dns_set_addressmap(entry_conn,
1352 entry_conn->socks_request->address, &addr,
1353 entry_conn->chosen_exit_name, ttl);
1355 remap_event_helper(entry_conn, &addr);
1357 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
1358 /* don't send a socks reply to transparent conns */
1359 tor_assert(entry_conn->socks_request != NULL);
1360 if (!entry_conn->socks_request->has_finished)
1361 connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
1363 /* Was it a linked dir conn? If so, a dir request just started to
1364 * fetch something; this could be a bootstrap status milestone. */
1365 log_debug(LD_APP, "considering");
1366 if (TO_CONN(conn)->linked_conn &&
1367 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
1368 connection_t *dirconn = TO_CONN(conn)->linked_conn;
1369 log_debug(LD_APP, "it is! %d", dirconn->purpose);
1370 switch (dirconn->purpose) {
1371 case DIR_PURPOSE_FETCH_CERTIFICATE:
1372 if (consensus_is_waiting_for_certs())
1373 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
1374 break;
1375 case DIR_PURPOSE_FETCH_CONSENSUS:
1376 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
1377 break;
1378 case DIR_PURPOSE_FETCH_SERVERDESC:
1379 case DIR_PURPOSE_FETCH_MICRODESC:
1380 if (TO_DIR_CONN(dirconn)->router_purpose == ROUTER_PURPOSE_GENERAL)
1381 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
1382 count_loading_descriptors_progress());
1383 break;
1386 /* This is definitely a success, so forget about any pending data we
1387 * had sent. */
1388 if (entry_conn->pending_optimistic_data) {
1389 buf_free(entry_conn->pending_optimistic_data);
1390 entry_conn->pending_optimistic_data = NULL;
1393 /* handle anything that might have queued */
1394 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1395 /* (We already sent an end cell if possible) */
1396 connection_mark_for_close(TO_CONN(conn));
1397 return 0;
1399 return 0;
1401 if (conn->base_.type == CONN_TYPE_AP &&
1402 rh->command == RELAY_COMMAND_RESOLVED) {
1403 return connection_edge_process_resolved_cell(conn, cell, rh);
1406 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1407 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
1408 rh->command, conn->base_.state,
1409 conn_state_to_string(conn->base_.type, conn->base_.state));
1410 return 0; /* for forward compatibility, don't kill the circuit */
1411 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1412 // connection_mark_for_close(conn);
1413 // return -1;
1416 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
1417 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
1418 * destined for <b>conn</b>.
1420 * If <b>layer_hint</b> is defined, then we're the origin of the
1421 * circuit, and it specifies the hop that packaged <b>cell</b>.
1423 * Return -reason if you want to warn and tear down the circuit, else 0.
1425 static int
1426 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
1427 edge_connection_t *conn,
1428 crypt_path_t *layer_hint)
1430 static int num_seen=0;
1431 relay_header_t rh;
1432 unsigned domain = layer_hint?LD_APP:LD_EXIT;
1433 int reason;
1434 int optimistic_data = 0; /* Set to 1 if we receive data on a stream
1435 * that's in the EXIT_CONN_STATE_RESOLVING
1436 * or EXIT_CONN_STATE_CONNECTING states. */
1438 tor_assert(cell);
1439 tor_assert(circ);
1441 relay_header_unpack(&rh, cell->payload);
1442 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1443 num_seen++;
1444 log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
1445 num_seen, rh.command, rh.stream_id);
1447 if (rh.length > RELAY_PAYLOAD_SIZE) {
1448 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1449 "Relay cell length field too long. Closing circuit.");
1450 return - END_CIRC_REASON_TORPROTOCOL;
1453 if (rh.stream_id == 0) {
1454 switch (rh.command) {
1455 case RELAY_COMMAND_BEGIN:
1456 case RELAY_COMMAND_CONNECTED:
1457 case RELAY_COMMAND_END:
1458 case RELAY_COMMAND_RESOLVE:
1459 case RELAY_COMMAND_RESOLVED:
1460 case RELAY_COMMAND_BEGIN_DIR:
1461 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
1462 "stream_id. Dropping.", (int)rh.command);
1463 return 0;
1464 default:
1469 /* either conn is NULL, in which case we've got a control cell, or else
1470 * conn points to the recognized stream. */
1472 if (conn && !connection_state_is_open(TO_CONN(conn))) {
1473 if (conn->base_.type == CONN_TYPE_EXIT &&
1474 (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
1475 conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
1476 rh.command == RELAY_COMMAND_DATA) {
1477 /* Allow DATA cells to be delivered to an exit node in state
1478 * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
1479 * This speeds up HTTP, for example. */
1480 optimistic_data = 1;
1481 } else if (rh.stream_id == 0 && rh.command == RELAY_COMMAND_DATA) {
1482 log_warn(LD_BUG, "Somehow I had a connection that matched a "
1483 "data cell with stream ID 0.");
1484 } else {
1485 return connection_edge_process_relay_cell_not_open(
1486 &rh, cell, circ, conn, layer_hint);
1490 switch (rh.command) {
1491 case RELAY_COMMAND_DROP:
1492 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1493 return 0;
1494 case RELAY_COMMAND_BEGIN:
1495 case RELAY_COMMAND_BEGIN_DIR:
1496 if (layer_hint &&
1497 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1498 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1499 "Relay begin request unsupported at AP. Dropping.");
1500 return 0;
1502 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1503 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1504 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1505 "Relay begin request to Hidden Service "
1506 "from intermediary node. Dropping.");
1507 return 0;
1509 if (conn) {
1510 log_fn(LOG_PROTOCOL_WARN, domain,
1511 "Begin cell for known stream. Dropping.");
1512 return 0;
1514 if (rh.command == RELAY_COMMAND_BEGIN_DIR &&
1515 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1516 /* Assign this circuit and its app-ward OR connection a unique ID,
1517 * so that we can measure download times. The local edge and dir
1518 * connection will be assigned the same ID when they are created
1519 * and linked. */
1520 static uint64_t next_id = 0;
1521 circ->dirreq_id = ++next_id;
1522 TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
1525 return connection_exit_begin_conn(cell, circ);
1526 case RELAY_COMMAND_DATA:
1527 ++stats_n_data_cells_received;
1528 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1529 (!layer_hint && --circ->deliver_window < 0)) {
1530 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1531 "(relay data) circ deliver_window below 0. Killing.");
1532 if (conn) {
1533 /* XXXX Do we actually need to do this? Will killing the circuit
1534 * not send an END and mark the stream for close as appropriate? */
1535 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1536 connection_mark_for_close(TO_CONN(conn));
1538 return -END_CIRC_REASON_TORPROTOCOL;
1540 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1541 layer_hint->deliver_window : circ->deliver_window);
1543 circuit_consider_sending_sendme(circ, layer_hint);
1545 if (rh.stream_id == 0) {
1546 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay data cell with zero "
1547 "stream_id. Dropping.");
1548 return 0;
1549 } else if (!conn) {
1550 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1551 rh.stream_id);
1552 return 0;
1555 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1556 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1557 "(relay data) conn deliver_window below 0. Killing.");
1558 return -END_CIRC_REASON_TORPROTOCOL;
1561 stats_n_data_bytes_received += rh.length;
1562 connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
1563 rh.length, TO_CONN(conn));
1565 if (!optimistic_data) {
1566 /* Only send a SENDME if we're not getting optimistic data; otherwise
1567 * a SENDME could arrive before the CONNECTED.
1569 connection_edge_consider_sending_sendme(conn);
1572 return 0;
1573 case RELAY_COMMAND_END:
1574 reason = rh.length > 0 ?
1575 get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1576 if (!conn) {
1577 log_info(domain,"end cell (%s) dropped, unknown stream.",
1578 stream_end_reason_to_string(reason));
1579 return 0;
1581 /* XXX add to this log_fn the exit node's nickname? */
1582 log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
1583 "Removing stream.",
1584 conn->base_.s,
1585 stream_end_reason_to_string(reason),
1586 conn->stream_id);
1587 if (conn->base_.type == CONN_TYPE_AP) {
1588 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1589 if (entry_conn->socks_request &&
1590 !entry_conn->socks_request->has_finished)
1591 log_warn(LD_BUG,
1592 "open stream hasn't sent socks answer yet? Closing.");
1594 /* We just *got* an end; no reason to send one. */
1595 conn->edge_has_sent_end = 1;
1596 if (!conn->end_reason)
1597 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1598 if (!conn->base_.marked_for_close) {
1599 /* only mark it if not already marked. it's possible to
1600 * get the 'end' right around when the client hangs up on us. */
1601 connection_mark_and_flush(TO_CONN(conn));
1603 return 0;
1604 case RELAY_COMMAND_EXTEND:
1605 case RELAY_COMMAND_EXTEND2: {
1606 static uint64_t total_n_extend=0, total_nonearly=0;
1607 total_n_extend++;
1608 if (rh.stream_id) {
1609 log_fn(LOG_PROTOCOL_WARN, domain,
1610 "'extend' cell received for non-zero stream. Dropping.");
1611 return 0;
1613 if (cell->command != CELL_RELAY_EARLY &&
1614 !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
1615 #define EARLY_WARNING_INTERVAL 3600
1616 static ratelim_t early_warning_limit =
1617 RATELIM_INIT(EARLY_WARNING_INTERVAL);
1618 char *m;
1619 if (cell->command == CELL_RELAY) {
1620 ++total_nonearly;
1621 if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
1622 double percentage = ((double)total_nonearly)/total_n_extend;
1623 percentage *= 100;
1624 log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
1625 "but not via RELAY_EARLY. Dropping.%s", m);
1626 log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
1627 "all EXTEND cells for this reason)", percentage);
1628 tor_free(m);
1630 } else {
1631 log_fn(LOG_WARN, domain,
1632 "EXTEND cell received, in a cell with type %d! Dropping.",
1633 cell->command);
1635 return 0;
1637 return circuit_extend(cell, circ);
1639 case RELAY_COMMAND_EXTENDED:
1640 case RELAY_COMMAND_EXTENDED2:
1641 if (!layer_hint) {
1642 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1643 "'extended' unsupported at non-origin. Dropping.");
1644 return 0;
1646 log_debug(domain,"Got an extended cell! Yay.");
1648 extended_cell_t extended_cell;
1649 if (extended_cell_parse(&extended_cell, rh.command,
1650 (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
1651 rh.length)<0) {
1652 log_warn(LD_PROTOCOL,
1653 "Can't parse EXTENDED cell; killing circuit.");
1654 return -END_CIRC_REASON_TORPROTOCOL;
1656 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1657 &extended_cell.created_cell)) < 0) {
1658 circuit_mark_for_close(circ, -reason);
1659 return 0; /* We don't want to cause a warning, so we mark the circuit
1660 * here. */
1663 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1664 log_info(domain,"circuit_send_next_onion_skin() failed.");
1665 return reason;
1667 return 0;
1668 case RELAY_COMMAND_TRUNCATE:
1669 if (layer_hint) {
1670 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1671 "'truncate' unsupported at origin. Dropping.");
1672 return 0;
1674 if (circ->n_hop) {
1675 if (circ->n_chan)
1676 log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
1677 extend_info_free(circ->n_hop);
1678 circ->n_hop = NULL;
1679 tor_free(circ->n_chan_create_cell);
1680 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
1682 if (circ->n_chan) {
1683 uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
1684 circuit_clear_cell_queue(circ, circ->n_chan);
1685 channel_send_destroy(circ->n_circ_id, circ->n_chan,
1686 trunc_reason);
1687 circuit_set_n_circid_chan(circ, 0, NULL);
1689 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1691 char payload[1];
1692 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1693 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1694 payload, sizeof(payload), NULL);
1696 return 0;
1697 case RELAY_COMMAND_TRUNCATED:
1698 if (!layer_hint) {
1699 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1700 "'truncated' unsupported at non-origin. Dropping.");
1701 return 0;
1703 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
1704 get_uint8(cell->payload + RELAY_HEADER_SIZE));
1705 return 0;
1706 case RELAY_COMMAND_CONNECTED:
1707 if (conn) {
1708 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1709 "'connected' unsupported while open. Closing circ.");
1710 return -END_CIRC_REASON_TORPROTOCOL;
1712 log_info(domain,
1713 "'connected' received on circid %u for streamid %d, "
1714 "no conn attached anymore. Ignoring.",
1715 (unsigned)circ->n_circ_id, rh.stream_id);
1716 return 0;
1717 case RELAY_COMMAND_SENDME:
1718 if (!rh.stream_id) {
1719 if (layer_hint) {
1720 if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
1721 CIRCWINDOW_START_MAX) {
1722 static struct ratelim_t exit_warn_ratelim = RATELIM_INIT(600);
1723 log_fn_ratelim(&exit_warn_ratelim, LOG_WARN, LD_PROTOCOL,
1724 "Unexpected sendme cell from exit relay. "
1725 "Closing circ.");
1726 return -END_CIRC_REASON_TORPROTOCOL;
1728 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1729 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1730 layer_hint->package_window);
1731 circuit_resume_edge_reading(circ, layer_hint);
1732 } else {
1733 if (circ->package_window + CIRCWINDOW_INCREMENT >
1734 CIRCWINDOW_START_MAX) {
1735 static struct ratelim_t client_warn_ratelim = RATELIM_INIT(600);
1736 log_fn_ratelim(&client_warn_ratelim,LOG_PROTOCOL_WARN, LD_PROTOCOL,
1737 "Unexpected sendme cell from client. "
1738 "Closing circ (window %d).",
1739 circ->package_window);
1740 return -END_CIRC_REASON_TORPROTOCOL;
1742 circ->package_window += CIRCWINDOW_INCREMENT;
1743 log_debug(LD_APP,
1744 "circ-level sendme at non-origin, packagewindow %d.",
1745 circ->package_window);
1746 circuit_resume_edge_reading(circ, layer_hint);
1748 return 0;
1750 if (!conn) {
1751 log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
1752 rh.stream_id);
1753 return 0;
1755 conn->package_window += STREAMWINDOW_INCREMENT;
1756 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1757 conn->package_window);
1758 if (circuit_queue_streams_are_blocked(circ)) {
1759 /* Still waiting for queue to flush; don't touch conn */
1760 return 0;
1762 connection_start_reading(TO_CONN(conn));
1763 /* handle whatever might still be on the inbuf */
1764 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1765 /* (We already sent an end cell if possible) */
1766 connection_mark_for_close(TO_CONN(conn));
1767 return 0;
1769 return 0;
1770 case RELAY_COMMAND_RESOLVE:
1771 if (layer_hint) {
1772 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1773 "resolve request unsupported at AP; dropping.");
1774 return 0;
1775 } else if (conn) {
1776 log_fn(LOG_PROTOCOL_WARN, domain,
1777 "resolve request for known stream; dropping.");
1778 return 0;
1779 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1780 log_fn(LOG_PROTOCOL_WARN, domain,
1781 "resolve request on circ with purpose %d; dropping",
1782 circ->purpose);
1783 return 0;
1785 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1786 return 0;
1787 case RELAY_COMMAND_RESOLVED:
1788 if (conn) {
1789 log_fn(LOG_PROTOCOL_WARN, domain,
1790 "'resolved' unsupported while open. Closing circ.");
1791 return -END_CIRC_REASON_TORPROTOCOL;
1793 log_info(domain,
1794 "'resolved' received, no conn attached anymore. Ignoring.");
1795 return 0;
1796 case RELAY_COMMAND_ESTABLISH_INTRO:
1797 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1798 case RELAY_COMMAND_INTRODUCE1:
1799 case RELAY_COMMAND_INTRODUCE2:
1800 case RELAY_COMMAND_INTRODUCE_ACK:
1801 case RELAY_COMMAND_RENDEZVOUS1:
1802 case RELAY_COMMAND_RENDEZVOUS2:
1803 case RELAY_COMMAND_INTRO_ESTABLISHED:
1804 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1805 rend_process_relay_cell(circ, layer_hint,
1806 rh.command, rh.length,
1807 cell->payload+RELAY_HEADER_SIZE);
1808 return 0;
1810 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1811 "Received unknown relay command %d. Perhaps the other side is using "
1812 "a newer version of Tor? Dropping.",
1813 rh.command);
1814 return 0; /* for forward compatibility, don't kill the circuit */
1817 /** How many relay_data cells have we built, ever? */
1818 uint64_t stats_n_data_cells_packaged = 0;
1819 /** How many bytes of data have we put in relay_data cells have we built,
1820 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1821 * every relay cell we ever sent were completely full of data. */
1822 uint64_t stats_n_data_bytes_packaged = 0;
1823 /** How many relay_data cells have we received, ever? */
1824 uint64_t stats_n_data_cells_received = 0;
1825 /** How many bytes of data have we received relay_data cells, ever? This would
1826 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1827 * ever received were completely full of data. */
1828 uint64_t stats_n_data_bytes_received = 0;
1830 /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
1831 * <b>package_partial</b> is true), and the appropriate package windows aren't
1832 * empty, grab a cell and send it down the circuit.
1834 * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
1835 * *<b>max_cells</b> by the number of cells packaged.
1837 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1838 * be marked for close, else return 0.
1841 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
1842 int *max_cells)
1844 size_t bytes_to_process, length;
1845 char payload[CELL_PAYLOAD_SIZE];
1846 circuit_t *circ;
1847 const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
1848 int sending_from_optimistic = 0;
1849 entry_connection_t *entry_conn =
1850 conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
1851 const int sending_optimistically =
1852 entry_conn &&
1853 conn->base_.type == CONN_TYPE_AP &&
1854 conn->base_.state != AP_CONN_STATE_OPEN;
1855 crypt_path_t *cpath_layer = conn->cpath_layer;
1857 tor_assert(conn);
1859 if (conn->base_.marked_for_close) {
1860 log_warn(LD_BUG,
1861 "called on conn that's already marked for close at %s:%d.",
1862 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
1863 return 0;
1866 if (max_cells && *max_cells <= 0)
1867 return 0;
1869 repeat_connection_edge_package_raw_inbuf:
1871 circ = circuit_get_by_edge_conn(conn);
1872 if (!circ) {
1873 log_info(domain,"conn has no circuit! Closing.");
1874 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1875 return -1;
1878 if (circuit_consider_stop_edge_reading(circ, cpath_layer))
1879 return 0;
1881 if (conn->package_window <= 0) {
1882 log_info(domain,"called with package_window %d. Skipping.",
1883 conn->package_window);
1884 connection_stop_reading(TO_CONN(conn));
1885 return 0;
1888 sending_from_optimistic = entry_conn &&
1889 entry_conn->sending_optimistic_data != NULL;
1891 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
1892 bytes_to_process = buf_datalen(entry_conn->sending_optimistic_data);
1893 if (PREDICT_UNLIKELY(!bytes_to_process)) {
1894 log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
1895 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
1896 sending_from_optimistic = 0;
1898 } else {
1899 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
1902 if (!bytes_to_process)
1903 return 0;
1905 if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
1906 return 0;
1908 if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
1909 length = RELAY_PAYLOAD_SIZE;
1910 } else {
1911 length = bytes_to_process;
1913 stats_n_data_bytes_packaged += length;
1914 stats_n_data_cells_packaged += 1;
1916 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
1917 /* XXXX We could be more efficient here by sometimes packing
1918 * previously-sent optimistic data in the same cell with data
1919 * from the inbuf. */
1920 fetch_from_buf(payload, length, entry_conn->sending_optimistic_data);
1921 if (!buf_datalen(entry_conn->sending_optimistic_data)) {
1922 buf_free(entry_conn->sending_optimistic_data);
1923 entry_conn->sending_optimistic_data = NULL;
1925 } else {
1926 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1929 log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
1930 conn->base_.s,
1931 (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
1933 if (sending_optimistically && !sending_from_optimistic) {
1934 /* This is new optimistic data; remember it in case we need to detach and
1935 retry */
1936 if (!entry_conn->pending_optimistic_data)
1937 entry_conn->pending_optimistic_data = buf_new();
1938 write_to_buf(payload, length, entry_conn->pending_optimistic_data);
1941 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1942 payload, length) < 0 )
1943 /* circuit got marked for close, don't continue, don't need to mark conn */
1944 return 0;
1946 if (!cpath_layer) { /* non-rendezvous exit */
1947 tor_assert(circ->package_window > 0);
1948 circ->package_window--;
1949 } else { /* we're an AP, or an exit on a rendezvous circ */
1950 tor_assert(cpath_layer->package_window > 0);
1951 cpath_layer->package_window--;
1954 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1955 connection_stop_reading(TO_CONN(conn));
1956 log_debug(domain,"conn->package_window reached 0.");
1957 circuit_consider_stop_edge_reading(circ, cpath_layer);
1958 return 0; /* don't process the inbuf any more */
1960 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1962 if (max_cells) {
1963 *max_cells -= 1;
1964 if (*max_cells <= 0)
1965 return 0;
1968 /* handle more if there's more, or return 0 if there isn't */
1969 goto repeat_connection_edge_package_raw_inbuf;
1972 /** Called when we've just received a relay data cell, when
1973 * we've just finished flushing all bytes to stream <b>conn</b>,
1974 * or when we've flushed *some* bytes to the stream <b>conn</b>.
1976 * If conn->outbuf is not too full, and our deliver window is
1977 * low, send back a suitable number of stream-level sendme cells.
1979 void
1980 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1982 circuit_t *circ;
1984 if (connection_outbuf_too_full(TO_CONN(conn)))
1985 return;
1987 circ = circuit_get_by_edge_conn(conn);
1988 if (!circ) {
1989 /* this can legitimately happen if the destroy has already
1990 * arrived and torn down the circuit */
1991 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1992 return;
1995 while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1996 log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
1997 "Outbuf %d, Queuing stream sendme.",
1998 (int)conn->base_.outbuf_flushlen);
1999 conn->deliver_window += STREAMWINDOW_INCREMENT;
2000 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
2001 NULL, 0) < 0) {
2002 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
2003 return; /* the circuit's closed, don't continue */
2008 /** The circuit <b>circ</b> has received a circuit-level sendme
2009 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
2010 * attached streams and let them resume reading and packaging, if
2011 * their stream windows allow it.
2013 static void
2014 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
2016 if (circuit_queue_streams_are_blocked(circ)) {
2017 log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
2018 return;
2020 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
2022 if (CIRCUIT_IS_ORIGIN(circ))
2023 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
2024 circ, layer_hint);
2025 else
2026 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
2027 circ, layer_hint);
2030 void
2031 stream_choice_seed_weak_rng(void)
2033 crypto_seed_weak_rng(&stream_choice_rng);
2036 /** A helper function for circuit_resume_edge_reading() above.
2037 * The arguments are the same, except that <b>conn</b> is the head
2038 * of a linked list of edge streams that should each be considered.
2040 static int
2041 circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
2042 circuit_t *circ,
2043 crypt_path_t *layer_hint)
2045 edge_connection_t *conn;
2046 int n_packaging_streams, n_streams_left;
2047 int packaged_this_round;
2048 int cells_on_queue;
2049 int cells_per_conn;
2050 edge_connection_t *chosen_stream = NULL;
2051 int max_to_package;
2053 if (first_conn == NULL) {
2054 /* Don't bother to try to do the rest of this if there are no connections
2055 * to resume. */
2056 return 0;
2059 /* How many cells do we have space for? It will be the minimum of
2060 * the number needed to exhaust the package window, and the minimum
2061 * needed to fill the cell queue. */
2062 max_to_package = circ->package_window;
2063 if (CIRCUIT_IS_ORIGIN(circ)) {
2064 cells_on_queue = circ->n_chan_cells.n;
2065 } else {
2066 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2067 cells_on_queue = or_circ->p_chan_cells.n;
2069 if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
2070 max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
2072 /* Once we used to start listening on the streams in the order they
2073 * appeared in the linked list. That leads to starvation on the
2074 * streams that appeared later on the list, since the first streams
2075 * would always get to read first. Instead, we just pick a random
2076 * stream on the list, and enable reading for streams starting at that
2077 * point (and wrapping around as if the list were circular). It would
2078 * probably be better to actually remember which streams we've
2079 * serviced in the past, but this is simple and effective. */
2081 /* Select a stream uniformly at random from the linked list. We
2082 * don't need cryptographic randomness here. */
2084 int num_streams = 0;
2085 for (conn = first_conn; conn; conn = conn->next_stream) {
2086 num_streams++;
2087 if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
2088 chosen_stream = conn;
2090 /* Invariant: chosen_stream has been chosen uniformly at random from
2091 * among the first num_streams streams on first_conn.
2093 * (Note that we iterate over every stream on the circuit, so that after
2094 * we've considered the first stream, we've chosen it with P=1; and
2095 * after we consider the second stream, we've switched to it with P=1/2
2096 * and stayed with the first stream with P=1/2; and after we've
2097 * considered the third stream, we've switched to it with P=1/3 and
2098 * remained with one of the first two streams with P=(2/3), giving each
2099 * one P=(1/2)(2/3) )=(1/3).) */
2103 /* Count how many non-marked streams there are that have anything on
2104 * their inbuf, and enable reading on all of the connections. */
2105 n_packaging_streams = 0;
2106 /* Activate reading starting from the chosen stream */
2107 for (conn=chosen_stream; conn; conn = conn->next_stream) {
2108 /* Start reading for the streams starting from here */
2109 if (conn->base_.marked_for_close || conn->package_window <= 0)
2110 continue;
2111 if (!layer_hint || conn->cpath_layer == layer_hint) {
2112 connection_start_reading(TO_CONN(conn));
2114 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2115 ++n_packaging_streams;
2118 /* Go back and do the ones we skipped, circular-style */
2119 for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
2120 if (conn->base_.marked_for_close || conn->package_window <= 0)
2121 continue;
2122 if (!layer_hint || conn->cpath_layer == layer_hint) {
2123 connection_start_reading(TO_CONN(conn));
2125 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2126 ++n_packaging_streams;
2130 if (n_packaging_streams == 0) /* avoid divide-by-zero */
2131 return 0;
2133 again:
2135 cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
2137 packaged_this_round = 0;
2138 n_streams_left = 0;
2140 /* Iterate over all connections. Package up to cells_per_conn cells on
2141 * each. Update packaged_this_round with the total number of cells
2142 * packaged, and n_streams_left with the number that still have data to
2143 * package.
2145 for (conn=first_conn; conn; conn=conn->next_stream) {
2146 if (conn->base_.marked_for_close || conn->package_window <= 0)
2147 continue;
2148 if (!layer_hint || conn->cpath_layer == layer_hint) {
2149 int n = cells_per_conn, r;
2150 /* handle whatever might still be on the inbuf */
2151 r = connection_edge_package_raw_inbuf(conn, 1, &n);
2153 /* Note how many we packaged */
2154 packaged_this_round += (cells_per_conn-n);
2156 if (r<0) {
2157 /* Problem while packaging. (We already sent an end cell if
2158 * possible) */
2159 connection_mark_for_close(TO_CONN(conn));
2160 continue;
2163 /* If there's still data to read, we'll be coming back to this stream. */
2164 if (connection_get_inbuf_len(TO_CONN(conn)))
2165 ++n_streams_left;
2167 /* If the circuit won't accept any more data, return without looking
2168 * at any more of the streams. Any connections that should be stopped
2169 * have already been stopped by connection_edge_package_raw_inbuf. */
2170 if (circuit_consider_stop_edge_reading(circ, layer_hint))
2171 return -1;
2172 /* XXXX should we also stop immediately if we fill up the cell queue?
2173 * Probably. */
2177 /* If we made progress, and we are willing to package more, and there are
2178 * any streams left that want to package stuff... try again!
2180 if (packaged_this_round && packaged_this_round < max_to_package &&
2181 n_streams_left) {
2182 max_to_package -= packaged_this_round;
2183 n_packaging_streams = n_streams_left;
2184 goto again;
2187 return 0;
2190 /** Check if the package window for <b>circ</b> is empty (at
2191 * hop <b>layer_hint</b> if it's defined).
2193 * If yes, tell edge streams to stop reading and return 1.
2194 * Else return 0.
2196 static int
2197 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
2199 edge_connection_t *conn = NULL;
2200 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
2202 if (!layer_hint) {
2203 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2204 log_debug(domain,"considering circ->package_window %d",
2205 circ->package_window);
2206 if (circ->package_window <= 0) {
2207 log_debug(domain,"yes, not-at-origin. stopped.");
2208 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
2209 connection_stop_reading(TO_CONN(conn));
2210 return 1;
2212 return 0;
2214 /* else, layer hint is defined, use it */
2215 log_debug(domain,"considering layer_hint->package_window %d",
2216 layer_hint->package_window);
2217 if (layer_hint->package_window <= 0) {
2218 log_debug(domain,"yes, at-origin. stopped.");
2219 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
2220 conn=conn->next_stream) {
2221 if (conn->cpath_layer == layer_hint)
2222 connection_stop_reading(TO_CONN(conn));
2224 return 1;
2226 return 0;
2229 /** Check if the deliver_window for circuit <b>circ</b> (at hop
2230 * <b>layer_hint</b> if it's defined) is low enough that we should
2231 * send a circuit-level sendme back down the circuit. If so, send
2232 * enough sendmes that the window would be overfull if we sent any
2233 * more.
2235 static void
2236 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
2238 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
2239 // layer_hint ? "defined" : "null");
2240 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
2241 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
2242 log_debug(LD_CIRC,"Queuing circuit sendme.");
2243 if (layer_hint)
2244 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
2245 else
2246 circ->deliver_window += CIRCWINDOW_INCREMENT;
2247 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
2248 NULL, 0, layer_hint) < 0) {
2249 log_warn(LD_CIRC,
2250 "relay_send_command_from_edge failed. Circuit's closed.");
2251 return; /* the circuit's closed, don't continue */
2256 #ifdef ACTIVE_CIRCUITS_PARANOIA
2257 #define assert_cmux_ok_paranoid(chan) \
2258 assert_circuit_mux_okay(chan)
2259 #else
2260 #define assert_cmux_ok_paranoid(chan)
2261 #endif
2263 /** The total number of cells we have allocated. */
2264 static size_t total_cells_allocated = 0;
2266 /** Release storage held by <b>cell</b>. */
2267 static inline void
2268 packed_cell_free_unchecked(packed_cell_t *cell)
2270 --total_cells_allocated;
2271 tor_free(cell);
2274 /** Allocate and return a new packed_cell_t. */
2275 STATIC packed_cell_t *
2276 packed_cell_new(void)
2278 ++total_cells_allocated;
2279 return tor_malloc_zero(sizeof(packed_cell_t));
2282 /** Return a packed cell used outside by channel_t lower layer */
2283 void
2284 packed_cell_free(packed_cell_t *cell)
2286 if (!cell)
2287 return;
2288 packed_cell_free_unchecked(cell);
2291 /** Log current statistics for cell pool allocation at log level
2292 * <b>severity</b>. */
2293 void
2294 dump_cell_pool_usage(int severity)
2296 int n_circs = 0;
2297 int n_cells = 0;
2298 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
2299 n_cells += c->n_chan_cells.n;
2300 if (!CIRCUIT_IS_ORIGIN(c))
2301 n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
2302 ++n_circs;
2304 SMARTLIST_FOREACH_END(c);
2305 tor_log(severity, LD_MM,
2306 "%d cells allocated on %d circuits. %d cells leaked.",
2307 n_cells, n_circs, (int)total_cells_allocated - n_cells);
2310 /** Allocate a new copy of packed <b>cell</b>. */
2311 static inline packed_cell_t *
2312 packed_cell_copy(const cell_t *cell, int wide_circ_ids)
2314 packed_cell_t *c = packed_cell_new();
2315 cell_pack(c, cell, wide_circ_ids);
2316 return c;
2319 /** Append <b>cell</b> to the end of <b>queue</b>. */
2320 void
2321 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
2323 TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
2324 ++queue->n;
2327 /** Append a newly allocated copy of <b>cell</b> to the end of the
2328 * <b>exitward</b> (or app-ward) <b>queue</b> of <b>circ</b>. If
2329 * <b>use_stats</b> is true, record statistics about the cell.
2331 void
2332 cell_queue_append_packed_copy(circuit_t *circ, cell_queue_t *queue,
2333 int exitward, const cell_t *cell,
2334 int wide_circ_ids, int use_stats)
2336 packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
2337 (void)circ;
2338 (void)exitward;
2339 (void)use_stats;
2341 copy->inserted_time = (uint32_t) monotime_coarse_absolute_msec();
2343 cell_queue_append(queue, copy);
2346 /** Initialize <b>queue</b> as an empty cell queue. */
2347 void
2348 cell_queue_init(cell_queue_t *queue)
2350 memset(queue, 0, sizeof(cell_queue_t));
2351 TOR_SIMPLEQ_INIT(&queue->head);
2354 /** Remove and free every cell in <b>queue</b>. */
2355 void
2356 cell_queue_clear(cell_queue_t *queue)
2358 packed_cell_t *cell;
2359 while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
2360 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2361 packed_cell_free_unchecked(cell);
2363 TOR_SIMPLEQ_INIT(&queue->head);
2364 queue->n = 0;
2367 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
2368 * <b>queue</b> is empty. */
2369 STATIC packed_cell_t *
2370 cell_queue_pop(cell_queue_t *queue)
2372 packed_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
2373 if (!cell)
2374 return NULL;
2375 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2376 --queue->n;
2377 return cell;
2380 /** Return the total number of bytes used for each packed_cell in a queue.
2381 * Approximate. */
2382 size_t
2383 packed_cell_mem_cost(void)
2385 return sizeof(packed_cell_t);
2388 /* DOCDOC */
2389 STATIC size_t
2390 cell_queues_get_total_allocation(void)
2392 return total_cells_allocated * packed_cell_mem_cost();
2395 /** How long after we've been low on memory should we try to conserve it? */
2396 #define MEMORY_PRESSURE_INTERVAL (30*60)
2398 /** The time at which we were last low on memory. */
2399 static time_t last_time_under_memory_pressure = 0;
2401 /** Check whether we've got too much space used for cells. If so,
2402 * call the OOM handler and return 1. Otherwise, return 0. */
2403 STATIC int
2404 cell_queues_check_size(void)
2406 size_t alloc = cell_queues_get_total_allocation();
2407 alloc += buf_get_total_allocation();
2408 alloc += tor_zlib_get_total_allocation();
2409 const size_t rend_cache_total = rend_cache_get_total_allocation();
2410 alloc += rend_cache_total;
2411 if (alloc >= get_options()->MaxMemInQueues_low_threshold) {
2412 last_time_under_memory_pressure = approx_time();
2413 if (alloc >= get_options()->MaxMemInQueues) {
2414 /* If we're spending over 20% of the memory limit on hidden service
2415 * descriptors, free them until we're down to 10%.
2417 if (rend_cache_total > get_options()->MaxMemInQueues / 5) {
2418 const size_t bytes_to_remove =
2419 rend_cache_total - (size_t)(get_options()->MaxMemInQueues / 10);
2420 rend_cache_clean_v2_descs_as_dir(time(NULL), bytes_to_remove);
2421 alloc -= rend_cache_total;
2422 alloc += rend_cache_get_total_allocation();
2424 circuits_handle_oom(alloc);
2425 return 1;
2428 return 0;
2431 /** Return true if we've been under memory pressure in the last
2432 * MEMORY_PRESSURE_INTERVAL seconds. */
2434 have_been_under_memory_pressure(void)
2436 return last_time_under_memory_pressure + MEMORY_PRESSURE_INTERVAL
2437 < approx_time();
2441 * Update the number of cells available on the circuit's n_chan or p_chan's
2442 * circuit mux.
2444 void
2445 update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
2446 const char *file, int lineno)
2448 channel_t *chan = NULL;
2449 or_circuit_t *or_circ = NULL;
2450 circuitmux_t *cmux = NULL;
2452 tor_assert(circ);
2454 /* Okay, get the channel */
2455 if (direction == CELL_DIRECTION_OUT) {
2456 chan = circ->n_chan;
2457 } else {
2458 or_circ = TO_OR_CIRCUIT(circ);
2459 chan = or_circ->p_chan;
2462 tor_assert(chan);
2463 tor_assert(chan->cmux);
2465 /* Now get the cmux */
2466 cmux = chan->cmux;
2468 /* Cmux sanity check */
2469 if (! circuitmux_is_circuit_attached(cmux, circ)) {
2470 log_warn(LD_BUG, "called on non-attached circuit from %s:%d",
2471 file, lineno);
2472 return;
2474 tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
2476 assert_cmux_ok_paranoid(chan);
2478 /* Update the number of cells we have for the circuit mux */
2479 if (direction == CELL_DIRECTION_OUT) {
2480 circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
2481 } else {
2482 circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
2485 assert_cmux_ok_paranoid(chan);
2488 /** Remove all circuits from the cmux on <b>chan</b>.
2490 * If <b>circuits_out</b> is non-NULL, add all detached circuits to
2491 * <b>circuits_out</b>.
2493 void
2494 channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
2496 tor_assert(chan);
2497 tor_assert(chan->cmux);
2499 circuitmux_detach_all_circuits(chan->cmux, circuits_out);
2500 chan->num_n_circuits = 0;
2501 chan->num_p_circuits = 0;
2504 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
2505 * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
2506 * and start or stop reading as appropriate.
2508 * If <b>stream_id</b> is nonzero, block only the edge connection whose
2509 * stream_id matches it.
2511 * Returns the number of streams whose status we changed.
2513 static int
2514 set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
2515 int block, streamid_t stream_id)
2517 edge_connection_t *edge = NULL;
2518 int n = 0;
2519 if (circ->n_chan == chan) {
2520 circ->streams_blocked_on_n_chan = block;
2521 if (CIRCUIT_IS_ORIGIN(circ))
2522 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
2523 } else {
2524 circ->streams_blocked_on_p_chan = block;
2525 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
2526 edge = TO_OR_CIRCUIT(circ)->n_streams;
2529 for (; edge; edge = edge->next_stream) {
2530 connection_t *conn = TO_CONN(edge);
2531 if (stream_id && edge->stream_id != stream_id)
2532 continue;
2534 if (edge->edge_blocked_on_circ != block) {
2535 ++n;
2536 edge->edge_blocked_on_circ = block;
2539 if (!conn->read_event) {
2540 /* This connection is a placeholder for something; probably a DNS
2541 * request. It can't actually stop or start reading.*/
2542 continue;
2545 if (block) {
2546 if (connection_is_reading(conn))
2547 connection_stop_reading(conn);
2548 } else {
2549 /* Is this right? */
2550 if (!connection_is_reading(conn))
2551 connection_start_reading(conn);
2555 return n;
2558 /** Extract the command from a packed cell. */
2559 static uint8_t
2560 packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
2562 if (wide_circ_ids) {
2563 return get_uint8(cell->body+4);
2564 } else {
2565 return get_uint8(cell->body+2);
2569 /** Extract the circuit ID from a packed cell. */
2570 circid_t
2571 packed_cell_get_circid(const packed_cell_t *cell, int wide_circ_ids)
2573 if (wide_circ_ids) {
2574 return ntohl(get_uint32(cell->body));
2575 } else {
2576 return ntohs(get_uint16(cell->body));
2580 /** Pull as many cells as possible (but no more than <b>max</b>) from the
2581 * queue of the first active circuit on <b>chan</b>, and write them to
2582 * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
2583 * the active circuit pointer to the next active circuit in the ring. */
2584 MOCK_IMPL(int,
2585 channel_flush_from_first_active_circuit, (channel_t *chan, int max))
2587 circuitmux_t *cmux = NULL;
2588 int n_flushed = 0;
2589 cell_queue_t *queue, *destroy_queue=NULL;
2590 circuit_t *circ;
2591 or_circuit_t *or_circ;
2592 int streams_blocked;
2593 packed_cell_t *cell;
2595 /* Get the cmux */
2596 tor_assert(chan);
2597 tor_assert(chan->cmux);
2598 cmux = chan->cmux;
2600 /* Main loop: pick a circuit, send a cell, update the cmux */
2601 while (n_flushed < max) {
2602 circ = circuitmux_get_first_active_circuit(cmux, &destroy_queue);
2603 if (destroy_queue) {
2604 /* this code is duplicated from some of the logic below. Ugly! XXXX */
2605 tor_assert(destroy_queue->n > 0);
2606 cell = cell_queue_pop(destroy_queue);
2607 channel_write_packed_cell(chan, cell);
2608 /* Update the cmux destroy counter */
2609 circuitmux_notify_xmit_destroy(cmux);
2610 cell = NULL;
2611 ++n_flushed;
2612 continue;
2614 /* If it returns NULL, no cells left to send */
2615 if (!circ) break;
2616 assert_cmux_ok_paranoid(chan);
2618 if (circ->n_chan == chan) {
2619 queue = &circ->n_chan_cells;
2620 streams_blocked = circ->streams_blocked_on_n_chan;
2621 } else {
2622 or_circ = TO_OR_CIRCUIT(circ);
2623 tor_assert(or_circ->p_chan == chan);
2624 queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
2625 streams_blocked = circ->streams_blocked_on_p_chan;
2628 /* Circuitmux told us this was active, so it should have cells */
2629 if (/*BUG(*/ queue->n == 0 /*)*/) {
2630 log_warn(LD_BUG, "Found a supposedly active circuit with no cells "
2631 "to send. Trying to recover.");
2632 circuitmux_set_num_cells(cmux, circ, 0);
2633 if (! circ->marked_for_close)
2634 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
2635 continue;
2638 tor_assert(queue->n > 0);
2641 * Get just one cell here; once we've sent it, that can change the circuit
2642 * selection, so we have to loop around for another even if this circuit
2643 * has more than one.
2645 cell = cell_queue_pop(queue);
2647 /* Calculate the exact time that this cell has spent in the queue. */
2648 if (get_options()->CellStatistics ||
2649 get_options()->TestingEnableCellStatsEvent) {
2650 uint32_t msec_waiting;
2651 uint32_t msec_now = (uint32_t)monotime_coarse_absolute_msec();
2652 msec_waiting = msec_now - cell->inserted_time;
2654 if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
2655 or_circ = TO_OR_CIRCUIT(circ);
2656 or_circ->total_cell_waiting_time += msec_waiting;
2657 or_circ->processed_cells++;
2660 if (get_options()->TestingEnableCellStatsEvent) {
2661 uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
2663 testing_cell_stats_entry_t *ent =
2664 tor_malloc_zero(sizeof(testing_cell_stats_entry_t));
2665 ent->command = command;
2666 ent->waiting_time = msec_waiting / 10;
2667 ent->removed = 1;
2668 if (circ->n_chan == chan)
2669 ent->exitward = 1;
2670 if (!circ->testing_cell_stats)
2671 circ->testing_cell_stats = smartlist_new();
2672 smartlist_add(circ->testing_cell_stats, ent);
2676 /* If we just flushed our queue and this circuit is used for a
2677 * tunneled directory request, possibly advance its state. */
2678 if (queue->n == 0 && chan->dirreq_id)
2679 geoip_change_dirreq_state(chan->dirreq_id,
2680 DIRREQ_TUNNELED,
2681 DIRREQ_CIRC_QUEUE_FLUSHED);
2683 /* Now send the cell */
2684 channel_write_packed_cell(chan, cell);
2685 cell = NULL;
2688 * Don't packed_cell_free_unchecked(cell) here because the channel will
2689 * do so when it gets out of the channel queue (probably already did, in
2690 * which case that was an immediate double-free bug).
2693 /* Update the counter */
2694 ++n_flushed;
2697 * Now update the cmux; tell it we've just sent a cell, and how many
2698 * we have left.
2700 circuitmux_notify_xmit_cells(cmux, circ, 1);
2701 circuitmux_set_num_cells(cmux, circ, queue->n);
2702 if (queue->n == 0)
2703 log_debug(LD_GENERAL, "Made a circuit inactive.");
2705 /* Is the cell queue low enough to unblock all the streams that are waiting
2706 * to write to this circuit? */
2707 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
2708 set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
2710 /* If n_flushed < max still, loop around and pick another circuit */
2713 /* Okay, we're done sending now */
2714 assert_cmux_ok_paranoid(chan);
2716 return n_flushed;
2719 #if 0
2720 /** Indicate the current preferred cap for middle circuits; zero disables
2721 * the cap. Right now it's just a constant, ORCIRC_MAX_MIDDLE_CELLS, but
2722 * the logic in append_cell_to_circuit_queue() is written to be correct
2723 * if we want to base it on a consensus param or something that might change
2724 * in the future.
2726 static int
2727 get_max_middle_cells(void)
2729 return ORCIRC_MAX_MIDDLE_CELLS;
2731 #endif
2733 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
2734 * transmitting in <b>direction</b>. */
2735 void
2736 append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
2737 cell_t *cell, cell_direction_t direction,
2738 streamid_t fromstream)
2740 or_circuit_t *orcirc = NULL;
2741 cell_queue_t *queue;
2742 int streams_blocked;
2743 #if 0
2744 uint32_t tgt_max_middle_cells, p_len, n_len, tmp, hard_max_middle_cells;
2745 #endif
2747 int exitward;
2748 if (circ->marked_for_close)
2749 return;
2751 exitward = (direction == CELL_DIRECTION_OUT);
2752 if (exitward) {
2753 queue = &circ->n_chan_cells;
2754 streams_blocked = circ->streams_blocked_on_n_chan;
2755 } else {
2756 orcirc = TO_OR_CIRCUIT(circ);
2757 queue = &orcirc->p_chan_cells;
2758 streams_blocked = circ->streams_blocked_on_p_chan;
2762 * Disabling this for now because of a possible guard discovery attack
2764 #if 0
2765 /* Are we a middle circuit about to exceed ORCIRC_MAX_MIDDLE_CELLS? */
2766 if ((circ->n_chan != NULL) && CIRCUIT_IS_ORCIRC(circ)) {
2767 orcirc = TO_OR_CIRCUIT(circ);
2768 if (orcirc->p_chan) {
2769 /* We are a middle circuit if we have both n_chan and p_chan */
2770 /* We'll need to know the current preferred maximum */
2771 tgt_max_middle_cells = get_max_middle_cells();
2772 if (tgt_max_middle_cells > 0) {
2773 /* Do we need to initialize middle_max_cells? */
2774 if (orcirc->max_middle_cells == 0) {
2775 orcirc->max_middle_cells = tgt_max_middle_cells;
2776 } else {
2777 if (tgt_max_middle_cells > orcirc->max_middle_cells) {
2778 /* If we want to increase the cap, we can do so right away */
2779 orcirc->max_middle_cells = tgt_max_middle_cells;
2780 } else if (tgt_max_middle_cells < orcirc->max_middle_cells) {
2782 * If we're shrinking the cap, we can't shrink past either queue;
2783 * compare tgt_max_middle_cells rather than tgt_max_middle_cells *
2784 * ORCIRC_MAX_MIDDLE_KILL_THRESH so the queues don't shrink enough
2785 * to generate spurious warnings, either.
2787 n_len = circ->n_chan_cells.n;
2788 p_len = orcirc->p_chan_cells.n;
2789 tmp = tgt_max_middle_cells;
2790 if (tmp < n_len) tmp = n_len;
2791 if (tmp < p_len) tmp = p_len;
2792 orcirc->max_middle_cells = tmp;
2794 /* else no change */
2796 } else {
2797 /* tgt_max_middle_cells == 0 indicates we should disable the cap */
2798 orcirc->max_middle_cells = 0;
2801 /* Now we know orcirc->max_middle_cells is set correctly */
2802 if (orcirc->max_middle_cells > 0) {
2803 hard_max_middle_cells =
2804 (uint32_t)(((double)orcirc->max_middle_cells) *
2805 ORCIRC_MAX_MIDDLE_KILL_THRESH);
2807 if ((unsigned)queue->n + 1 >= hard_max_middle_cells) {
2808 /* Queueing this cell would put queue over the kill theshold */
2809 log_warn(LD_CIRC,
2810 "Got a cell exceeding the hard cap of %u in the "
2811 "%s direction on middle circ ID %u on chan ID "
2812 U64_FORMAT "; killing the circuit.",
2813 hard_max_middle_cells,
2814 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2815 (direction == CELL_DIRECTION_OUT) ?
2816 circ->n_circ_id : orcirc->p_circ_id,
2817 U64_PRINTF_ARG(
2818 (direction == CELL_DIRECTION_OUT) ?
2819 circ->n_chan->global_identifier :
2820 orcirc->p_chan->global_identifier));
2821 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2822 return;
2823 } else if ((unsigned)queue->n + 1 == orcirc->max_middle_cells) {
2824 /* Only use ==, not >= for this test so we don't spam the log */
2825 log_warn(LD_CIRC,
2826 "While trying to queue a cell, reached the soft cap of %u "
2827 "in the %s direction on middle circ ID %u "
2828 "on chan ID " U64_FORMAT ".",
2829 orcirc->max_middle_cells,
2830 (direction == CELL_DIRECTION_OUT) ? "n" : "p",
2831 (direction == CELL_DIRECTION_OUT) ?
2832 circ->n_circ_id : orcirc->p_circ_id,
2833 U64_PRINTF_ARG(
2834 (direction == CELL_DIRECTION_OUT) ?
2835 circ->n_chan->global_identifier :
2836 orcirc->p_chan->global_identifier));
2841 #endif
2843 cell_queue_append_packed_copy(circ, queue, exitward, cell,
2844 chan->wide_circ_ids, 1);
2846 if (PREDICT_UNLIKELY(cell_queues_check_size())) {
2847 /* We ran the OOM handler */
2848 if (circ->marked_for_close)
2849 return;
2852 /* If we have too many cells on the circuit, we should stop reading from
2853 * the edge streams for a while. */
2854 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
2855 set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
2857 if (streams_blocked && fromstream) {
2858 /* This edge connection is apparently not blocked; block it. */
2859 set_streams_blocked_on_circ(circ, chan, 1, fromstream);
2862 update_circuit_on_cmux(circ, direction);
2863 if (queue->n == 1) {
2864 /* This was the first cell added to the queue. We just made this
2865 * circuit active. */
2866 log_debug(LD_GENERAL, "Made a circuit active.");
2869 /* New way: mark this as having waiting cells for the scheduler */
2870 scheduler_channel_has_waiting_cells(chan);
2873 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
2874 * have at least 18 bytes of free space. The encoding is, as specified in
2875 * tor-spec.txt:
2876 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
2877 * LENGTH [1 byte]
2878 * ADDRESS [length bytes]
2879 * Return the number of bytes added, or -1 on error */
2881 append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
2883 uint32_t a;
2884 switch (tor_addr_family(addr)) {
2885 case AF_INET:
2886 payload_out[0] = RESOLVED_TYPE_IPV4;
2887 payload_out[1] = 4;
2888 a = tor_addr_to_ipv4n(addr);
2889 memcpy(payload_out+2, &a, 4);
2890 return 6;
2891 case AF_INET6:
2892 payload_out[0] = RESOLVED_TYPE_IPV6;
2893 payload_out[1] = 16;
2894 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
2895 return 18;
2896 case AF_UNSPEC:
2897 default:
2898 return -1;
2902 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
2903 * encoded as by append_address_to_payload(), try to decode the address into
2904 * *<b>addr_out</b>. Return the next byte in the payload after the address on
2905 * success, or NULL on failure. */
2906 const uint8_t *
2907 decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
2908 int payload_len)
2910 if (payload_len < 2)
2911 return NULL;
2912 if (payload_len < 2+payload[1])
2913 return NULL;
2915 switch (payload[0]) {
2916 case RESOLVED_TYPE_IPV4:
2917 if (payload[1] != 4)
2918 return NULL;
2919 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
2920 break;
2921 case RESOLVED_TYPE_IPV6:
2922 if (payload[1] != 16)
2923 return NULL;
2924 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
2925 break;
2926 default:
2927 tor_addr_make_unspec(addr_out);
2928 break;
2930 return payload + 2 + payload[1];
2933 /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
2934 void
2935 circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
2937 cell_queue_t *queue;
2938 cell_direction_t direction;
2940 if (circ->n_chan == chan) {
2941 queue = &circ->n_chan_cells;
2942 direction = CELL_DIRECTION_OUT;
2943 } else {
2944 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
2945 tor_assert(orcirc->p_chan == chan);
2946 queue = &orcirc->p_chan_cells;
2947 direction = CELL_DIRECTION_IN;
2950 /* Clear the queue */
2951 cell_queue_clear(queue);
2953 /* Update the cell counter in the cmux */
2954 if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
2955 update_circuit_on_cmux(circ, direction);
2958 /** Fail with an assert if the circuit mux on chan is corrupt
2960 void
2961 assert_circuit_mux_okay(channel_t *chan)
2963 tor_assert(chan);
2964 tor_assert(chan->cmux);
2966 circuitmux_assert_okay(chan->cmux);
2969 /** Return 1 if we shouldn't restart reading on this circuit, even if
2970 * we get a SENDME. Else return 0.
2972 static int
2973 circuit_queue_streams_are_blocked(circuit_t *circ)
2975 if (CIRCUIT_IS_ORIGIN(circ)) {
2976 return circ->streams_blocked_on_n_chan;
2977 } else {
2978 return circ->streams_blocked_on_p_chan;