Tor 0.4.9.13
Loading...
Searching...
No Matches
relay.c
Go to the documentation of this file.
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-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file relay.c
9 * \brief Handle relay cell encryption/decryption, plus packaging and
10 * receiving from circuits, plus queuing on circuits.
11 *
12 * This is a core modules that makes Tor work. It's responsible for
13 * dealing with RELAY cells (the ones that travel more than one hop along a
14 * circuit), by:
15 * <ul>
16 * <li>constructing relays cells,
17 * <li>encrypting relay cells,
18 * <li>decrypting relay cells,
19 * <li>demultiplexing relay cells as they arrive on a connection,
20 * <li>queueing relay cells for retransmission,
21 * <li>or handling relay cells that are for us to receive (as an exit or a
22 * client).
23 * </ul>
24 *
25 * RELAY cells are generated throughout the code at the client or relay side,
26 * using relay_send_command_from_edge() or one of the functions like
27 * connection_edge_send_command() that calls it. Of particular interest is
28 * connection_edge_package_raw_inbuf(), which takes information that has
29 * arrived on an edge connection socket, and packages it as a RELAY_DATA cell
30 * -- this is how information is actually sent across the Tor network. The
31 * cryptography for these functions is handled deep in
32 * circuit_package_relay_cell(), which either adds a single layer of
33 * encryption (if we're an exit), or multiple layers (if we're the origin of
34 * the circuit). After construction and encryption, the RELAY cells are
35 * passed to append_cell_to_circuit_queue(), which queues them for
36 * transmission and tells the circuitmux (see circuitmux.c) that the circuit
37 * is waiting to send something.
38 *
39 * Incoming RELAY cells arrive at circuit_receive_relay_cell(), called from
40 * command.c. There they are decrypted and, if they are for us, are passed to
41 * connection_edge_process_relay_cell(). If they're not for us, they're
42 * re-queued for retransmission again with append_cell_to_circuit_queue().
43 *
44 * The connection_edge_process_relay_cell() function handles all the different
45 * types of relay cells, launching requests or transmitting data as needed.
46 **/
47
48#include "lib/log/log.h"
49#define RELAY_PRIVATE
50#include "core/or/or.h"
52#include "lib/err/backtrace.h"
53#include "lib/buf/buffers.h"
54#include "core/or/channel.h"
55#include "feature/client/circpathbias.h"
57#include "core/or/circuitlist.h"
58#include "core/or/circuituse.h"
60#include "core/or/extendinfo.h"
62#include "app/config/config.h"
70#include "feature/relay/dns.h"
73#include "feature/hs/hs_cache.h"
77#include "core/or/onion.h"
78#include "core/or/policies.h"
79#include "core/or/reasons.h"
80#include "core/or/relay.h"
85#include "core/or/scheduler.h"
88#include "core/or/relay_msg.h"
89
90#include "core/or/cell_st.h"
97#include "core/or/or_circuit_st.h"
101#include "core/or/sendme.h"
104#include "core/or/conflux.h"
105#include "core/or/conflux_util.h"
106#include "core/or/conflux_pool.h"
107#include "core/or/relay_msg_st.h"
108
110 const relay_msg_t *msg,
111 cell_direction_t cell_direction,
112 crypt_path_t *layer_hint);
113
114static void circuit_resume_edge_reading(circuit_t *circ,
115 crypt_path_t *layer_hint);
117 circuit_t *circ,
118 crypt_path_t *layer_hint);
120 crypt_path_t *layer_hint);
123 entry_connection_t *conn,
124 node_t *node,
125 const tor_addr_t *addr);
127 circuit_t *circ,
128 edge_connection_t *conn,
129 crypt_path_t *layer_hint);
130static void set_block_state_for_streams(circuit_t *circ,
131 edge_connection_t *stream_list,
132 int block, streamid_t stream_id);
133
134/** Stats: how many relay cells have originated at this hop, or have
135 * been relayed onward (not recognized at this hop)?
136 */
138/** Stats: how many relay cells have been delivered to streams at this
139 * hop?
140 */
142/** Stats: how many circuits have we closed due to the cell queue limit being
143 * reached (see append_cell_to_circuit_queue()) */
145uint64_t stats_n_circ_max_cell_outq_reached = 0;
146
147/**
148 * Update channel usage state based on the type of relay cell and
149 * circuit properties.
150 *
151 * This is needed to determine if a client channel is being
152 * used for application traffic, and if a relay channel is being
153 * used for multihop circuits and application traffic. The decision
154 * to pad in channelpadding.c depends upon this info (as well as
155 * consensus parameters) to decide what channels to pad.
156 */
157static void
159{
160 if (CIRCUIT_IS_ORIGIN(circ)) {
161 /*
162 * The client state was first set much earlier in
163 * circuit_send_next_onion_skin(), so we can start padding as early as
164 * possible.
165 *
166 * However, if padding turns out to be expensive, we may want to not do
167 * it until actual application traffic starts flowing (which is controlled
168 * via consensus param nf_pad_before_usage).
169 *
170 * So: If we're an origin circuit and we've created a full length circuit,
171 * then any CELL_RELAY cell means application data. Increase the usage
172 * state of the channel to indicate this.
173 *
174 * We want to wait for CELL_RELAY specifically here, so we know that
175 * the channel was definitely being used for data and not for extends.
176 * By default, we pad as soon as a channel has been used for *any*
177 * circuits, so this state is irrelevant to the padding decision in
178 * the default case. However, if padding turns out to be expensive,
179 * we would like the ability to avoid padding until we're absolutely
180 * sure that a channel is used for enough application data to be worth
181 * padding.
182 *
183 * (So it does not matter that CELL_RELAY_EARLY can actually contain
184 * application data. This is only a load reducing option and that edge
185 * case does not matter if we're desperately trying to reduce overhead
186 * anyway. See also consensus parameter nf_pad_before_usage).
187 */
188 if (BUG(!circ->n_chan))
189 return;
190
191 if (circ->n_chan->channel_usage == CHANNEL_USED_FOR_FULL_CIRCS &&
192 cell->command == CELL_RELAY) {
193 circ->n_chan->channel_usage = CHANNEL_USED_FOR_USER_TRAFFIC;
194 }
195 } else {
196 /* If we're a relay circuit, the question is more complicated. Basically:
197 * we only want to pad connections that carry multihop (anonymous)
198 * circuits.
199 *
200 * We assume we're more than one hop if either the previous hop
201 * is not a client, or if the previous hop is a client and there's
202 * a next hop. Then, circuit traffic starts at RELAY_EARLY, and
203 * user application traffic starts when we see RELAY cells.
204 */
205 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
206
207 if (BUG(!or_circ->p_chan))
208 return;
209
210 if (!channel_is_client(or_circ->p_chan) ||
211 (channel_is_client(or_circ->p_chan) && circ->n_chan)) {
212 if (cell->command == CELL_RELAY_EARLY) {
213 if (or_circ->p_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS) {
214 or_circ->p_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
215 }
216 } else if (cell->command == CELL_RELAY) {
217 or_circ->p_chan->channel_usage = CHANNEL_USED_FOR_USER_TRAFFIC;
218 }
219 }
220 }
221}
222
223/** Receive a relay cell:
224 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
225 * origin; decrypt if we're headed toward the exit).
226 * - Check if recognized (if exitward).
227 * - If recognized and the digest checks out, then find if there's a stream
228 * that the cell is intended for, and deliver it to the right
229 * connection_edge.
230 * - If not recognized, then we need to relay it: append it to the appropriate
231 * cell_queue on <b>circ</b>.
232 *
233 * Return -<b>reason</b> on failure, else 0.
234 */
235int
237 cell_direction_t cell_direction)
238{
239 channel_t *chan = NULL;
240 crypt_path_t *layer_hint=NULL;
241 char recognized=0;
242 int reason;
243
244 tor_assert(cell);
245 tor_assert(circ);
246 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
247 cell_direction == CELL_DIRECTION_IN);
248 if (circ->marked_for_close)
249 return 0;
250
251 if (relay_decrypt_cell(circ, cell, cell_direction, &layer_hint, &recognized)
252 < 0) {
253 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
254 "relay crypt failed. Dropping connection.");
255 return -END_CIRC_REASON_INTERNAL;
256 }
257
259
260 if (recognized) {
261 edge_connection_t *conn = NULL;
262 relay_cell_fmt_t format = circuit_get_relay_format(circ, layer_hint);
263
264 relay_msg_t msg_buf;
265 if (relay_msg_decode_cell_in_place(format, cell, &msg_buf) < 0) {
266 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
267 "Received undecodable relay cell");
268 return -END_CIRC_REASON_TORPROTOCOL;
269 }
270 const relay_msg_t *msg = &msg_buf;
271
273 if (pathbias_check_probe_response(circ, msg) == -1) {
275 }
276
277 /* We need to drop this cell no matter what to avoid code that expects
278 * a certain purpose (such as the hidserv code). */
279 return 0;
280 }
281
282 conn = relay_lookup_conn(circ, msg, cell_direction, layer_hint);
283 if (cell_direction == CELL_DIRECTION_OUT) {
285 log_debug(LD_OR,"Sending away from origin.");
286 reason = connection_edge_process_relay_cell(msg, circ, conn, NULL);
287 if (reason < 0) {
288 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
289 "connection_edge_process_relay_cell (away from origin) "
290 "failed.");
291 return reason;
292 }
293 } else if (cell_direction == CELL_DIRECTION_IN) {
295 log_debug(LD_OR,"Sending to origin.");
296 reason = connection_edge_process_relay_cell(msg, circ, conn,
297 layer_hint);
298 if (reason < 0) {
299 /* If a client is trying to connect to unknown hidden service port,
300 * END_CIRC_AT_ORIGIN is sent back so we can then close the circuit.
301 * Do not log warn as this is an expected behavior for a service. */
302 if (reason != END_CIRC_AT_ORIGIN) {
303 log_warn(LD_OR,
304 "connection_edge_process_relay_cell (at origin) failed.");
305 }
306 return reason;
307 }
308 }
309 return 0;
310 }
311
312 /* not recognized. inform circpad and pass it on. */
313 circpad_deliver_unrecognized_cell_events(circ, cell_direction);
314
315 if (cell_direction == CELL_DIRECTION_OUT) {
316 cell->circ_id = circ->n_circ_id; /* switch it */
317 chan = circ->n_chan;
318 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
319 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
320 chan = TO_OR_CIRCUIT(circ)->p_chan;
321 } else {
322 log_fn(LOG_PROTOCOL_WARN, LD_OR,
323 "Dropping unrecognized inbound cell on origin circuit.");
324 /* If we see unrecognized cells on path bias testing circs,
325 * it's bad mojo. Those circuits need to die.
326 * XXX: Shouldn't they always die? */
329 return -END_CIRC_REASON_TORPROTOCOL;
330 } else {
331 return 0;
332 }
333 }
334
335 if (!chan) {
336 // XXXX Can this splice stuff be done more cleanly?
337 if (! CIRCUIT_IS_ORIGIN(circ) &&
338 TO_OR_CIRCUIT(circ)->rend_splice &&
339 cell_direction == CELL_DIRECTION_OUT) {
340 or_circuit_t *splice_ = TO_OR_CIRCUIT(circ)->rend_splice;
343 cell->circ_id = splice_->p_circ_id;
344 cell->command = CELL_RELAY; /* can't be relay_early anyway */
345 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice_),
346 CELL_DIRECTION_IN)) < 0) {
347 log_info(LD_REND, "Error relaying cell across rendezvous; closing "
348 "circuits");
349 return reason;
350 }
351 return 0;
352 }
353 if (BUG(CIRCUIT_IS_ORIGIN(circ))) {
354 /* Should be impossible at this point. */
355 return -END_CIRC_REASON_TORPROTOCOL;
356 }
357 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
358 if (++or_circ->n_cells_discarded_at_end == 1) {
359 time_t seconds_open = approx_time() - circ->timestamp_created.tv_sec;
360 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
361 "Didn't recognize a cell, but circ stops here! Closing circuit. "
362 "It was created %ld seconds ago.", (long)seconds_open);
363 }
364 return -END_CIRC_REASON_TORPROTOCOL;
365 }
366
367 log_debug(LD_OR,"Passing on unrecognized cell.");
368
369 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
370 * we might kill the circ before we relay
371 * the cells. */
372
373 if (append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0) < 0) {
374 return -END_CIRC_REASON_RESOURCELIMIT;
375 }
376 return 0;
377}
378
379/** Package a relay cell from an edge:
380 * - Encrypt it to the right layer
381 * - Append it to the appropriate cell_queue on <b>circ</b>.
382 *
383 * Return 1 if the cell was successfully sent as in queued on the circuit.
384 * Return 0 if the cell needs to be dropped as in ignored.
385 * Return -1 on error for which the circuit should be marked for close. */
386MOCK_IMPL(int,
388 cell_direction_t cell_direction,
389 crypt_path_t *layer_hint, streamid_t on_stream,
390 const char *filename, int lineno))
391{
392 channel_t *chan; /* where to send the cell */
393
394 if (circ->marked_for_close) {
395 /* Circuit is marked; send nothing. */
396 return 0;
397 }
398
399 if (cell_direction == CELL_DIRECTION_OUT) {
400 chan = circ->n_chan;
401 if (!chan) {
402 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d has n_chan==NULL."
403 " Dropping. Circuit is in state %s (%d), and is "
404 "%smarked for close. (%s:%d, %d)", filename, lineno,
405 circuit_state_to_string(circ->state), circ->state,
406 circ->marked_for_close ? "" : "not ",
409 if (CIRCUIT_IS_ORIGIN(circ)) {
411 }
412 log_backtrace(LOG_WARN,LD_BUG,"");
413 return 0; /* just drop it */
414 }
415 if (!CIRCUIT_IS_ORIGIN(circ)) {
416 log_warn(LD_BUG,"outgoing relay cell sent from %s:%d on non-origin "
417 "circ. Dropping.", filename, lineno);
418 log_backtrace(LOG_WARN,LD_BUG,"");
419 return 0; /* just drop it */
420 }
421
422 relay_encrypt_cell_outbound(cell, TO_ORIGIN_CIRCUIT(circ), layer_hint);
423
424 /* Update circ written totals for control port */
425 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
426 ocirc->n_written_circ_bw = tor_add_u32_nowrap(ocirc->n_written_circ_bw,
428
429 } else { /* incoming cell */
430 if (CIRCUIT_IS_ORIGIN(circ)) {
431 /* We should never package an _incoming_ cell from the circuit
432 * origin; that means we messed up somewhere. */
433 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
434 assert_circuit_ok(circ);
435 return 0; /* just drop it */
436 }
437 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
438 if (relay_encrypt_cell_inbound(cell, or_circ) < 0) {
439 return -1;
440 }
441 chan = or_circ->p_chan;
442 }
444
445 return append_cell_to_circuit_queue(circ, chan, cell,
446 cell_direction, on_stream);
447}
448
449/** If cell's stream_id matches the stream_id of any conn that's
450 * attached to circ, return that conn, else return NULL.
451 */
452static edge_connection_t *
454 cell_direction_t cell_direction, crypt_path_t *layer_hint)
455{
456 edge_connection_t *tmpconn;
457
458 if (!msg->stream_id)
459 return NULL;
460
461 /* IN or OUT cells could have come from either direction, now
462 * that we allow rendezvous *to* an OP.
463 */
464 if (CIRCUIT_IS_ORIGIN(circ)) {
465 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
466 tmpconn=tmpconn->next_stream) {
467 if (msg->stream_id == tmpconn->stream_id &&
468 !tmpconn->base_.marked_for_close &&
469 edge_uses_cpath(tmpconn, layer_hint)) {
470 log_debug(LD_APP,"found conn for stream %d.", msg->stream_id);
471 return tmpconn;
472 }
473 }
474 } else {
475 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
476 tmpconn=tmpconn->next_stream) {
477 if (msg->stream_id == tmpconn->stream_id &&
478 !tmpconn->base_.marked_for_close) {
479 log_debug(LD_EXIT,"found conn for stream %d.", msg->stream_id);
480 if (cell_direction == CELL_DIRECTION_OUT ||
482 return tmpconn;
483 }
484 }
485 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
486 tmpconn=tmpconn->next_stream) {
487 if (msg->stream_id == tmpconn->stream_id &&
488 !tmpconn->base_.marked_for_close) {
489 log_debug(LD_EXIT,"found conn for stream %d.", msg->stream_id);
490 return tmpconn;
491 }
492 }
493 }
494 return NULL; /* probably a begin relay cell */
495}
496
497#ifdef TOR_UNIT_TESTS
498/** Pack the relay_header_t host-order structure <b>src</b> into
499 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
500 * about the wire format.
501 */
502void
503relay_header_pack(uint8_t *dest, const relay_header_t *src)
504{
505 set_uint8(dest, src->command);
506 set_uint16(dest+1, htons(src->recognized));
507 set_uint16(dest+3, htons(src->stream_id));
508 memcpy(dest+5, src->integrity, 4);
509 set_uint16(dest+9, htons(src->length));
510}
511
512/** Unpack the network-order buffer <b>src</b> into a host-order
513 * relay_header_t structure <b>dest</b>.
514 */
515void
516relay_header_unpack(relay_header_t *dest, const uint8_t *src)
517{
518 dest->command = get_uint8(src);
519 dest->recognized = ntohs(get_uint16(src+1));
520 dest->stream_id = ntohs(get_uint16(src+3));
521 memcpy(dest->integrity, src+5, 4);
522 dest->length = ntohs(get_uint16(src+9));
523}
524#endif
525
526/** Convert the relay <b>command</b> into a human-readable string. */
527const char *
529{
530 static char buf[64];
531 switch (command) {
532 case RELAY_COMMAND_BEGIN: return "BEGIN";
533 case RELAY_COMMAND_DATA: return "DATA";
534 case RELAY_COMMAND_END: return "END";
535 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
536 case RELAY_COMMAND_SENDME: return "SENDME";
537 case RELAY_COMMAND_EXTEND: return "EXTEND";
538 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
539 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
540 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
541 case RELAY_COMMAND_DROP: return "DROP";
542 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
543 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
544 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
545 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
546 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
547 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
548 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
549 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
550 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
551 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
552 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
553 return "RENDEZVOUS_ESTABLISHED";
554 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
555 case RELAY_COMMAND_EXTEND2: return "EXTEND2";
556 case RELAY_COMMAND_EXTENDED2: return "EXTENDED2";
557 case RELAY_COMMAND_PADDING_NEGOTIATE: return "PADDING_NEGOTIATE";
558 case RELAY_COMMAND_PADDING_NEGOTIATED: return "PADDING_NEGOTIATED";
559 case RELAY_COMMAND_CONFLUX_LINK: return "CONFLUX_LINK";
560 case RELAY_COMMAND_CONFLUX_LINKED: return "CONFLUX_LINKED";
561 case RELAY_COMMAND_CONFLUX_LINKED_ACK: return "CONFLUX_LINKED_ACK";
562 case RELAY_COMMAND_CONFLUX_SWITCH: return "CONFLUX_SWITCH";
563 default:
564 tor_snprintf(buf, sizeof(buf), "Unrecognized relay command %u",
565 (unsigned)command);
566 return buf;
567 }
568}
569
570/** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
571 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
572 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
573 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
574 * destination hop for OP->OR cells.
575 *
576 * If you can't send the cell, mark the circuit for close and return -1. Else
577 * return 0.
578 */
579MOCK_IMPL(int,
581 uint8_t relay_command, const char *payload,
582 size_t payload_len, crypt_path_t *cpath_layer,
583 const char *filename, int lineno))
584{
585 cell_t cell;
586 cell_direction_t cell_direction;
587 circuit_t *circ = orig_circ;
588
589 /* If conflux is enabled, decide which leg to send on, and use that */
590 if (orig_circ->conflux && conflux_should_multiplex(relay_command)) {
591 circ = conflux_decide_circ_for_send(orig_circ->conflux, orig_circ,
592 relay_command);
593 if (!circ) {
594 /* Something is wrong with the conflux set. We are done. */
595 return -1;
596 }
597 /* Conflux circuits always send multiplexed relay commands to
598 * to the last hop. (Non-multiplexed commands go on their
599 * original circuit and hop). */
600 cpath_layer = conflux_get_destination_hop(circ);
601 }
602
603 /* This is possible because we have protocol error paths when deciding the
604 * next circuit to send which can close the whole set. Bail out early. */
605 if (circ->marked_for_close) {
606 return -1;
607 }
608
609 /* XXXX NM Split this function into a separate versions per circuit type? */
610
611 tor_assert(circ);
612
613 size_t msg_body_len;
614 {
615 relay_cell_fmt_t cell_format = circuit_get_relay_format(circ, cpath_layer);
616 relay_msg_t msg = {0};
617 if (payload_len >
618 relay_cell_max_payload_size(cell_format, relay_command)) {
619 // TODO CGO: Rate-limit this?
620 log_warn(LD_BUG, "Tried to send a command %d of length %d in "
621 "a v%d cell, from %s:%d",
622 (int)relay_command, (int)payload_len, (int)cell_format,
623 filename, lineno);
624 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
625 return -1;
626 }
627
628 msg.command = relay_command;
629 msg.stream_id = stream_id;
630 msg.length = payload_len;
631 msg.body = (const uint8_t *) payload;
632 msg_body_len = msg.length;
633 // If this cell should be RELAY_EARLY, we'll change the type
634 // later in this function.
635 msg.is_relay_early = false;
636
637 if (relay_msg_encode_cell(cell_format, &msg, &cell) < 0) {
638 // We already called IF_BUG_ONCE in relay_msg_encode_cell.
639 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
640 return -1;
641 }
642 }
643
644 cell.command = CELL_RELAY;
645 if (CIRCUIT_IS_ORIGIN(circ)) {
646 tor_assert(cpath_layer);
647 cell.circ_id = circ->n_circ_id;
648 cell_direction = CELL_DIRECTION_OUT;
649 } else {
650 tor_assert(! cpath_layer);
651 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
652 cell_direction = CELL_DIRECTION_IN;
653 }
654
655 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
656 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
657
658 /* Tell circpad we're sending a relay cell */
659 circpad_deliver_sent_relay_cell_events(circ, relay_command);
660
661 /* If we are sending an END cell and this circuit is used for a tunneled
662 * directory request, advance its state. */
663 if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
664 geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
666
667 if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
668 /* if we're using relaybandwidthrate, this conn wants priority */
670 }
671
672 if (cell_direction == CELL_DIRECTION_OUT) {
673 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
674 if (origin_circ->remaining_relay_early_cells > 0 &&
675 (relay_command == RELAY_COMMAND_EXTEND ||
676 relay_command == RELAY_COMMAND_EXTEND2 ||
677 cpath_layer != origin_circ->cpath)) {
678 /* If we've got any relay_early cells left and (we're sending
679 * an extend cell or we're not talking to the first hop), use
680 * one of them. Don't worry about the conn protocol version:
681 * append_cell_to_circuit_queue will fix it up. */
682 cell.command = CELL_RELAY_EARLY;
683 /* If we're out of relay early cells, tell circpad */
684 if (--origin_circ->remaining_relay_early_cells == 0)
686 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
687 (int)origin_circ->remaining_relay_early_cells);
688 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
689 * task 878. */
690 origin_circ->relay_early_commands[
691 origin_circ->relay_early_cells_sent++] = relay_command;
692 } else if (relay_command == RELAY_COMMAND_EXTEND ||
693 relay_command == RELAY_COMMAND_EXTEND2) {
694 /* If no RELAY_EARLY cells can be sent over this circuit, log which
695 * commands have been sent as RELAY_EARLY cells before; helps debug
696 * task 878. */
697 smartlist_t *commands_list = smartlist_new();
698 int i = 0;
699 char *commands = NULL;
700 for (; i < origin_circ->relay_early_cells_sent; i++)
701 smartlist_add(commands_list, (char *)
703 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
704 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
705 "but we have run out of RELAY_EARLY cells on that circuit. "
706 "Commands sent before: %s", commands);
707 tor_free(commands);
708 smartlist_free(commands_list);
709 }
710
711 /* Let's assume we're well-behaved: Anything that we decide to send is
712 * valid, delivered data. */
713 circuit_sent_valid_data(origin_circ, msg_body_len);
714 }
715
716 int ret = circuit_package_relay_cell(&cell, circ, cell_direction,
717 cpath_layer, stream_id, filename,
718 lineno);
719 if (ret < 0) {
720 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
721 return -1;
722 } else if (ret == 0) {
723 /* This means we should drop the cell or that the circuit was already
724 * marked for close. At this point in time, we do NOT close the circuit if
725 * the cell is dropped. It is not the case with arti where each circuit
726 * protocol violation will lead to closing the circuit. */
727 return 0;
728 }
729
730 /* At this point, we are certain that the cell was queued on the circuit and
731 * thus will be sent on the wire. */
732
733 if (circ->conflux) {
734 conflux_note_cell_sent(circ->conflux, circ, relay_command);
735 }
736
737 /* If applicable, note the cell digest for the SENDME version 1 purpose if
738 * we need to. This call needs to be after the circuit_package_relay_cell()
739 * because the cell digest is set within that function. */
740 if (relay_command == RELAY_COMMAND_DATA) {
741 sendme_record_cell_digest_on_circ(circ, cpath_layer);
742
743 /* Handle the circuit-level SENDME package window. */
744 if (sendme_note_circuit_data_packaged(circ, cpath_layer) < 0) {
745 /* Package window has gone under 0. Protocol issue. */
746 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
747 "Circuit package window is below 0. Closing circuit.");
748 circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
749 return -1;
750 }
751 }
752
753 return 0;
754}
755
756/** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
757 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
758 * that's sending the relay cell, or NULL if it's a control cell.
759 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
760 * for OP->OR cells.
761 *
762 * If you can't send the cell, mark the circuit for close and
763 * return -1. Else return 0.
764 */
765int
767 uint8_t relay_command, const char *payload,
768 size_t payload_len)
769{
770 /* XXXX NM Split this function into a separate versions per circuit type? */
771 circuit_t *circ;
772 crypt_path_t *cpath_layer = fromconn->cpath_layer;
773 tor_assert(fromconn);
774
775 circ = fromconn->on_circuit;
776
777 if (fromconn->base_.marked_for_close) {
778 log_warn(LD_BUG,
779 "called on conn that's already marked for close at %s:%d.",
780 fromconn->base_.marked_for_close_file,
781 fromconn->base_.marked_for_close);
782 return 0;
783 }
784
785 if (!circ) {
786 if (fromconn->base_.type == CONN_TYPE_AP) {
787 log_info(LD_APP,"no circ. Closing conn.");
788 connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
789 END_STREAM_REASON_INTERNAL);
790 } else {
791 log_info(LD_EXIT,"no circ. Closing conn.");
792 fromconn->edge_has_sent_end = 1; /* no circ to send to */
793 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
794 connection_mark_for_close(TO_CONN(fromconn));
795 }
796 return -1;
797 }
798
799 if (circ->marked_for_close) {
800 /* The circuit has been marked, but not freed yet. When it's freed, it
801 * will mark this connection for close. */
802 return -1;
803 }
804
805#ifdef MEASUREMENTS_21206
806 /* Keep track of the number of RELAY_DATA cells sent for directory
807 * connections. */
808 connection_t *linked_conn = TO_CONN(fromconn)->linked_conn;
809
810 if (linked_conn && linked_conn->type == CONN_TYPE_DIR) {
811 ++(TO_DIR_CONN(linked_conn)->data_cells_sent);
812 }
813#endif /* defined(MEASUREMENTS_21206) */
814
815 return relay_send_command_from_edge(fromconn->stream_id, circ,
816 relay_command, payload,
817 payload_len, cpath_layer);
818}
819
820/** How many times will I retry a stream that fails due to DNS
821 * resolve failure or misc error?
822 */
823#define MAX_RESOLVE_FAILURES 3
824
825/** Return 1 if reason is something that you should retry if you
826 * get the end cell before you've connected; else return 0. */
827static int
829{
830 return reason == END_STREAM_REASON_HIBERNATING ||
831 reason == END_STREAM_REASON_RESOURCELIMIT ||
832 reason == END_STREAM_REASON_EXITPOLICY ||
833 reason == END_STREAM_REASON_RESOLVEFAILED ||
834 reason == END_STREAM_REASON_MISC ||
835 reason == END_STREAM_REASON_NOROUTE;
836}
837
838/** Called when we receive an END cell on a stream that isn't open yet,
839 * from the client side.
840 * Arguments are as for connection_edge_process_relay_cell().
841 */
842static int
844 const relay_msg_t *msg, origin_circuit_t *circ,
845 entry_connection_t *conn, crypt_path_t *layer_hint)
846{
847 node_t *exitrouter;
848 /* Defense in depth, the caller checks this but this protect us for the
849 * future, this is C afterall. No reason in the END cell. */
850 if (msg->length == 0) {
851 return -END_CIRC_REASON_TORPROTOCOL;
852 }
853 int reason = get_uint8(msg->body);
854 int control_reason;
855 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
856 (void) layer_hint; /* unused */
857
858 if (msg->length > 0) {
859 if (reason == END_STREAM_REASON_TORPROTOCOL ||
860 reason == END_STREAM_REASON_DESTROY) {
861 /* Both of these reasons could mean a failed tag
862 * hit the exit and it complained. Do not probe.
863 * Fail the circuit. */
865 return -END_CIRC_REASON_TORPROTOCOL;
866 } else if (reason == END_STREAM_REASON_INTERNAL) {
867 /* We can't infer success or failure, since older Tors report
868 * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
869 } else {
870 /* Path bias: If we get a valid reason code from the exit,
871 * it wasn't due to tagging.
872 *
873 * We rely on recognized+digest being strong enough to make
874 * tags unlikely to allow us to get tagged, yet 'recognized'
875 * reason codes here. */
877 }
878 }
879
880 /* This end cell is now valid. */
881 circuit_read_valid_data(circ, msg->length);
882
883 /* Generate a reason code that we will use for controller events. This
884 * is the reason the END cell contained, with
885 * END_STREAM_REASON_FLAG_REMOTE to make it clear that it came from
886 * the other side of the circuit. As an exception, if the other side
887 * sent us a reason of 0, replace that with MISC so we don't get
888 * confused on our side (because we use 0 to mean successful connect).
889 */
890 control_reason = (reason ? reason : END_STREAM_REASON_MISC) |
892
893 if (edge_reason_is_retriable(reason) &&
894 /* avoid retry if rend */
896 /* also don't retry if it was a begindir request: those are tunneled
897 * requests to a specific relay, and if that relay didn't want
898 * it, asking again isn't going to work better. */
899 !conn->use_begindir) {
900 const char *chosen_exit_digest =
902 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
903 safe_str(conn->socks_request->address),
905 exitrouter = node_get_mutable_by_id(chosen_exit_digest);
906 switch (reason) {
907 case END_STREAM_REASON_EXITPOLICY: {
908 tor_addr_t addr;
910 if (msg->length >= 5) {
911 int ttl = -1;
913 if (msg->length == 5 || msg->length == 9) {
914 tor_addr_from_ipv4n(&addr, get_uint32(msg->body + 1));
915 if (msg->length == 9)
916 ttl = (int)ntohl(get_uint32(msg->body + 5));
917 } else if (msg->length == 17 || msg->length == 21) {
918 tor_addr_from_ipv6_bytes(&addr, msg->body + 1);
919 if (msg->length == 21)
920 ttl = (int)ntohl(get_uint32(msg->body + 17));
921 }
922 if (tor_addr_is_null(&addr)) {
923 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
924 safe_str(conn->socks_request->address));
925 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
926 return 0;
927 }
928
929 if ((tor_addr_family(&addr) == AF_INET &&
930 !conn->entry_cfg.ipv4_traffic) ||
931 (tor_addr_family(&addr) == AF_INET6 &&
932 !conn->entry_cfg.ipv6_traffic)) {
933 log_fn(LOG_PROTOCOL_WARN, LD_APP,
934 "Got an EXITPOLICY failure on a connection with a "
935 "mismatched family. Closing.");
936 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
937 return 0;
938 }
939 if (get_options()->ClientDNSRejectInternalAddresses &&
940 tor_addr_is_internal(&addr, 0)) {
941 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
942 safe_str(conn->socks_request->address));
943 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
944 return 0;
945 }
946
948 conn->socks_request->address, &addr,
949 conn->chosen_exit_name, ttl);
950
951 {
952 char new_addr[TOR_ADDR_BUF_LEN];
953 tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
954 if (strcmp(conn->socks_request->address, new_addr)) {
955 strlcpy(conn->socks_request->address, new_addr,
956 sizeof(conn->socks_request->address));
957 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
958 }
959 }
960 }
961 /* check if the exit *ought* to have allowed it */
962
964 conn,
965 exitrouter,
966 &addr);
967
968 if (conn->chosen_exit_optional ||
969 conn->chosen_exit_retries) {
970 /* stop wanting a specific exit */
971 conn->chosen_exit_optional = 0;
972 /* A non-zero chosen_exit_retries can happen if we set a
973 * TrackHostExits for this address under a port that the exit
974 * relay allows, but then try the same address with a different
975 * port that it doesn't allow to exit. We shouldn't unregister
976 * the mapping, since it is probably still wanted on the
977 * original port. But now we give away to the exit relay that
978 * we probably have a TrackHostExits on it. So be it. */
979 conn->chosen_exit_retries = 0;
980 tor_free(conn->chosen_exit_name); /* clears it */
981 }
982 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
983 return 0;
984 /* else, conn will get closed below */
985 break;
986 }
987 case END_STREAM_REASON_CONNECTREFUSED:
988 if (!conn->chosen_exit_optional)
989 break; /* break means it'll close, below */
990 /* Else fall through: expire this circuit, clear the
991 * chosen_exit_name field, and try again. */
992 FALLTHROUGH;
993 case END_STREAM_REASON_RESOLVEFAILED:
994 case END_STREAM_REASON_TIMEOUT:
995 case END_STREAM_REASON_MISC:
996 case END_STREAM_REASON_NOROUTE:
999 /* We haven't retried too many times; reattach the connection. */
1001 /* Mark this circuit "unusable for new streams". */
1003
1004 if (conn->chosen_exit_optional) {
1005 /* stop wanting a specific exit */
1006 conn->chosen_exit_optional = 0;
1007 tor_free(conn->chosen_exit_name); /* clears it */
1008 }
1009 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
1010 return 0;
1011 /* else, conn will get closed below */
1012 } else {
1013 log_notice(LD_APP,
1014 "Have tried resolving or connecting to address '%s' "
1015 "at %d different places. Giving up.",
1016 safe_str(conn->socks_request->address),
1018 /* clear the failures, so it will have a full try next time */
1020 }
1021 break;
1022 case END_STREAM_REASON_HIBERNATING:
1023 case END_STREAM_REASON_RESOURCELIMIT:
1024 if (exitrouter) {
1026 }
1027 if (conn->chosen_exit_optional) {
1028 /* stop wanting a specific exit */
1029 conn->chosen_exit_optional = 0;
1030 tor_free(conn->chosen_exit_name); /* clears it */
1031 }
1032 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
1033 return 0;
1034 /* else, will close below */
1035 break;
1036 } /* end switch */
1037 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
1038 }
1039
1040 log_info(LD_APP,
1041 "Edge got end (%s) before we're connected. Marking for close.",
1042 stream_end_reason_to_string(msg->length > 0 ? reason : -1));
1044 /* need to test because of detach_retriable */
1045 if (!ENTRY_TO_CONN(conn)->marked_for_close)
1046 connection_mark_unattached_ap(conn, control_reason);
1047 return 0;
1048}
1049
1050/** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
1051 * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
1052 * told us which address it rejected, then <b>addr</b> is that address;
1053 * otherwise it is AF_UNSPEC.
1054 *
1055 * If we are sure the node should have allowed this address, mark the node as
1056 * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
1057 * for this particular address.
1058 **/
1059static void
1061 entry_connection_t *conn,
1062 node_t *node,
1063 const tor_addr_t *addr)
1064{
1065 int make_reject_all = 0;
1066 const sa_family_t family = tor_addr_family(addr);
1067
1068 if (node) {
1069 tor_addr_t tmp;
1070 int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
1071 if (family == AF_UNSPEC) {
1072 make_reject_all = 1;
1073 } else if (node_exit_policy_is_exact(node, family) &&
1074 asked_for_family != -1 && !conn->chosen_exit_name) {
1075 make_reject_all = 1;
1076 }
1077
1078 if (make_reject_all) {
1079 log_info(LD_APP,
1080 "Exitrouter %s seems to be more restrictive than its exit "
1081 "policy. Not using this router as exit for now.",
1082 node_describe(node));
1084 }
1085 }
1086
1087 if (family != AF_UNSPEC)
1089}
1090
1091/** Helper: change the socks_request-&gt;address field on conn to the
1092 * dotted-quad representation of <b>new_addr</b>,
1093 * and send an appropriate REMAP event. */
1094static void
1096{
1097 tor_addr_to_str(conn->socks_request->address, new_addr,
1098 sizeof(conn->socks_request->address),
1099 1);
1100 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1102}
1103
1104/** Extract the contents of a connected cell in <b>cell</b>, whose relay
1105 * header has already been parsed into <b>rh</b>. On success, set
1106 * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
1107 * the ttl of that address, in seconds, and return 0. On failure, return
1108 * -1.
1109 *
1110 * Note that the resulting address can be UNSPEC if the connected cell had no
1111 * address (as for a stream to an union service or a tunneled directory
1112 * connection), and that the ttl can be absent (in which case <b>ttl_out</b>
1113 * is set to -1). */
1114STATIC int
1116 int *ttl_out)
1117{
1118 uint32_t bytes;
1119 const uint8_t *payload = msg->body;
1120
1121 tor_addr_make_unspec(addr_out);
1122 *ttl_out = -1;
1123 if (msg->length == 0)
1124 return 0;
1125 if (msg->length < 4)
1126 return -1;
1127 bytes = ntohl(get_uint32(payload));
1128
1129 /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
1130 if (bytes != 0) {
1131 /* v4 address */
1132 tor_addr_from_ipv4h(addr_out, bytes);
1133 if (msg->length >= 8) {
1134 bytes = ntohl(get_uint32(payload + 4));
1135 if (bytes <= INT32_MAX)
1136 *ttl_out = bytes;
1137 }
1138 } else {
1139 if (msg->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
1140 return -1;
1141 if (get_uint8(payload + 4) != 6)
1142 return -1;
1143 tor_addr_from_ipv6_bytes(addr_out, (payload + 5));
1144 bytes = ntohl(get_uint32(payload + 21));
1145 if (bytes <= INT32_MAX)
1146 *ttl_out = (int) bytes;
1147 }
1148 return 0;
1149}
1150
1151/** Drop all storage held by <b>addr</b>. */
1152STATIC void
1153address_ttl_free_(address_ttl_t *addr)
1154{
1155 if (!addr)
1156 return;
1157 tor_free(addr->hostname);
1158 tor_free(addr);
1159}
1160
1161/** Parse a resolved cell in <b>cell</b>, with parsed header in <b>rh</b>.
1162 * Return -1 on parse error. On success, add one or more newly allocated
1163 * address_ttl_t to <b>addresses_out</b>; set *<b>errcode_out</b> to
1164 * one of 0, RESOLVED_TYPE_ERROR, or RESOLVED_TYPE_ERROR_TRANSIENT, and
1165 * return 0. */
1166STATIC int
1168 int *errcode_out)
1169{
1170 const uint8_t *cp;
1171 uint8_t answer_type;
1172 size_t answer_len;
1173 address_ttl_t *addr;
1174 size_t remaining;
1175 int errcode = 0;
1176 smartlist_t *addrs;
1177
1178 tor_assert(msg);
1179 tor_assert(addresses_out);
1180 tor_assert(errcode_out);
1181
1182 *errcode_out = 0;
1183
1184 if (msg->length > RELAY_PAYLOAD_SIZE_MAX)
1185 return -1;
1186
1187 addrs = smartlist_new();
1188
1189 cp = msg->body;
1190
1191 remaining = msg->length;
1192 while (remaining) {
1193 const uint8_t *cp_orig = cp;
1194 if (remaining < 2)
1195 goto err;
1196 answer_type = *cp++;
1197 answer_len = *cp++;
1198 if (remaining < 2 + answer_len + 4) {
1199 goto err;
1200 }
1201 if (answer_type == RESOLVED_TYPE_IPV4) {
1202 if (answer_len != 4) {
1203 goto err;
1204 }
1205 addr = tor_malloc_zero(sizeof(*addr));
1206 tor_addr_from_ipv4n(&addr->addr, get_uint32(cp));
1207 cp += 4;
1208 addr->ttl = ntohl(get_uint32(cp));
1209 cp += 4;
1210 smartlist_add(addrs, addr);
1211 } else if (answer_type == RESOLVED_TYPE_IPV6) {
1212 if (answer_len != 16)
1213 goto err;
1214 addr = tor_malloc_zero(sizeof(*addr));
1215 tor_addr_from_ipv6_bytes(&addr->addr, cp);
1216 cp += 16;
1217 addr->ttl = ntohl(get_uint32(cp));
1218 cp += 4;
1219 smartlist_add(addrs, addr);
1220 } else if (answer_type == RESOLVED_TYPE_HOSTNAME) {
1221 if (answer_len == 0) {
1222 goto err;
1223 }
1224 addr = tor_malloc_zero(sizeof(*addr));
1225 addr->hostname = tor_memdup_nulterm(cp, answer_len);
1226 cp += answer_len;
1227 addr->ttl = ntohl(get_uint32(cp));
1228 cp += 4;
1229 smartlist_add(addrs, addr);
1230 } else if (answer_type == RESOLVED_TYPE_ERROR_TRANSIENT ||
1231 answer_type == RESOLVED_TYPE_ERROR) {
1232 errcode = answer_type;
1233 /* Ignore the error contents */
1234 cp += answer_len + 4;
1235 } else {
1236 cp += answer_len + 4;
1237 }
1238 tor_assert(((ssize_t)remaining) >= (cp - cp_orig));
1239 remaining -= (cp - cp_orig);
1240 }
1241
1242 if (errcode && smartlist_len(addrs) == 0) {
1243 /* Report an error only if there were no results. */
1244 *errcode_out = errcode;
1245 }
1246
1247 smartlist_add_all(addresses_out, addrs);
1248 smartlist_free(addrs);
1249
1250 return 0;
1251
1252 err:
1253 /* On parse error, don't report any results */
1254 SMARTLIST_FOREACH(addrs, address_ttl_t *, a, address_ttl_free(a));
1255 smartlist_free(addrs);
1256 return -1;
1257}
1258
1259/** Helper for connection_edge_process_resolved_cell: given an error code,
1260 * an entry_connection, and a list of address_ttl_t *, report the best answer
1261 * to the entry_connection. */
1262static void
1264 int error_code,
1265 smartlist_t *results)
1266{
1267 address_ttl_t *addr_ipv4 = NULL;
1268 address_ttl_t *addr_ipv6 = NULL;
1269 address_ttl_t *addr_hostname = NULL;
1270 address_ttl_t *addr_best = NULL;
1271
1272 /* If it's an error code, that's easy. */
1273 if (error_code) {
1274 tor_assert(error_code == RESOLVED_TYPE_ERROR ||
1275 error_code == RESOLVED_TYPE_ERROR_TRANSIENT);
1277 error_code,0,NULL,-1,-1);
1278 return;
1279 }
1280
1281 /* Get the first answer of each type. */
1282 SMARTLIST_FOREACH_BEGIN(results, address_ttl_t *, addr) {
1283 if (addr->hostname) {
1284 if (!addr_hostname) {
1285 addr_hostname = addr;
1286 }
1287 } else if (tor_addr_family(&addr->addr) == AF_INET) {
1288 if (!addr_ipv4 && conn->entry_cfg.ipv4_traffic) {
1289 addr_ipv4 = addr;
1290 }
1291 } else if (tor_addr_family(&addr->addr) == AF_INET6) {
1292 if (!addr_ipv6 && conn->entry_cfg.ipv6_traffic) {
1293 addr_ipv6 = addr;
1294 }
1295 }
1296 } SMARTLIST_FOREACH_END(addr);
1297
1298 /* Now figure out which type we wanted to deliver. */
1300 if (addr_hostname) {
1302 RESOLVED_TYPE_HOSTNAME,
1303 strlen(addr_hostname->hostname),
1304 (uint8_t*)addr_hostname->hostname,
1305 addr_hostname->ttl,-1);
1306 } else {
1308 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
1309 }
1310 return;
1311 }
1312
1313 if (conn->entry_cfg.prefer_ipv6) {
1314 addr_best = addr_ipv6 ? addr_ipv6 : addr_ipv4;
1315 } else {
1316 addr_best = addr_ipv4 ? addr_ipv4 : addr_ipv6;
1317 }
1318
1319 /* Now convert it to the ugly old interface */
1320 if (! addr_best) {
1322 RESOLVED_TYPE_NOERROR,0,NULL,-1,-1);
1323 return;
1324 }
1325
1327 &addr_best->addr,
1328 addr_best->ttl,
1329 -1);
1330
1331 remap_event_helper(conn, &addr_best->addr);
1332}
1333
1334/** Handle a RELAY_COMMAND_RESOLVED cell that we received on a non-open AP
1335 * stream. */
1336STATIC int
1338 const relay_msg_t *msg)
1339{
1340 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1341 smartlist_t *resolved_addresses = NULL;
1342 int errcode = 0;
1343
1344 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
1345 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
1346 "not in state resolve_wait. Dropping.");
1347 return 0;
1348 }
1349 tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
1350
1351 resolved_addresses = smartlist_new();
1352 if (resolved_cell_parse(msg, resolved_addresses, &errcode)) {
1353 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1354 "Dropping malformed 'resolved' cell");
1355 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1356 goto done;
1357 }
1358
1359 if (get_options()->ClientDNSRejectInternalAddresses) {
1360 int orig_len = smartlist_len(resolved_addresses);
1361 SMARTLIST_FOREACH_BEGIN(resolved_addresses, address_ttl_t *, addr) {
1362 if (addr->hostname == NULL && tor_addr_is_internal(&addr->addr, 0)) {
1363 log_info(LD_APP, "Got a resolved cell with answer %s; dropping that "
1364 "answer.",
1365 safe_str_client(fmt_addr(&addr->addr)));
1366 address_ttl_free(addr);
1367 SMARTLIST_DEL_CURRENT(resolved_addresses, addr);
1368 }
1369 } SMARTLIST_FOREACH_END(addr);
1370 if (orig_len && smartlist_len(resolved_addresses) == 0) {
1371 log_info(LD_APP, "Got a resolved cell with only private addresses; "
1372 "dropping it.");
1374 RESOLVED_TYPE_ERROR_TRANSIENT,
1375 0, NULL, 0, TIME_MAX);
1376 connection_mark_unattached_ap(entry_conn,
1377 END_STREAM_REASON_TORPROTOCOL);
1378 goto done;
1379 }
1380 }
1381
1382 /* This is valid data at this point. Count it */
1383 if (conn->on_circuit && CIRCUIT_IS_ORIGIN(conn->on_circuit)) {
1385 msg->length);
1386 }
1387
1389 errcode,
1390 resolved_addresses);
1391
1392 connection_mark_unattached_ap(entry_conn,
1393 END_STREAM_REASON_DONE |
1395
1396 done:
1397 SMARTLIST_FOREACH(resolved_addresses, address_ttl_t *, addr,
1398 address_ttl_free(addr));
1399 smartlist_free(resolved_addresses);
1400 return 0;
1401}
1402
1403/** An incoming relay cell has arrived from circuit <b>circ</b> to
1404 * stream <b>conn</b>.
1405 *
1406 * The arguments here are the same as in
1407 * connection_edge_process_relay_cell() below; this function is called
1408 * from there when <b>conn</b> is defined and not in an open state.
1409 */
1410static int
1412 const relay_msg_t *msg, circuit_t *circ,
1413 edge_connection_t *conn, crypt_path_t *layer_hint)
1414{
1415 if (msg->command == RELAY_COMMAND_END) {
1416 /* No reason in the END cell. */
1417 if (msg->length == 0) {
1418 return -END_CIRC_REASON_TORPROTOCOL;
1419 }
1420 if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
1422 TO_ORIGIN_CIRCUIT(circ),
1423 EDGE_TO_ENTRY_CONN(conn),
1424 layer_hint);
1425 } else {
1426 /* we just got an 'end', don't need to send one */
1427 conn->edge_has_sent_end = 1;
1429 connection_mark_for_close(TO_CONN(conn));
1430 return 0;
1431 }
1432 }
1433
1434 if (conn->base_.type == CONN_TYPE_AP &&
1435 msg->command == RELAY_COMMAND_CONNECTED) {
1436 tor_addr_t addr;
1437 int ttl;
1438 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1440 if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
1441 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1442 "Got 'connected' while not in state connect_wait. Dropping.");
1443 return 0;
1444 }
1445 CONNECTION_AP_EXPECT_NONPENDING(entry_conn);
1446 conn->base_.state = AP_CONN_STATE_OPEN;
1447 log_info(LD_APP,"'connected' received for circid %u streamid %d "
1448 "after %d seconds.",
1449 (unsigned)circ->n_circ_id,
1450 msg->stream_id,
1451 (int)(time(NULL) - conn->base_.timestamp_last_read_allowed));
1452 if (connected_cell_parse(msg, &addr, &ttl) < 0) {
1453 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1454 "Got a badly formatted connected cell. Closing.");
1455 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1456 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
1457 return 0;
1458 }
1459 if (tor_addr_family(&addr) != AF_UNSPEC) {
1460 /* The family is not UNSPEC: so we were given an address in the
1461 * connected cell. (This is normal, except for BEGINDIR and onion
1462 * service streams.) */
1463 const sa_family_t family = tor_addr_family(&addr);
1464 if (tor_addr_is_null(&addr) ||
1465 (get_options()->ClientDNSRejectInternalAddresses &&
1466 tor_addr_is_internal(&addr, 0))) {
1467 log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
1468 safe_str(fmt_addr(&addr)));
1469 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1470 connection_mark_unattached_ap(entry_conn,
1471 END_STREAM_REASON_TORPROTOCOL);
1472 return 0;
1473 }
1474
1475 if ((family == AF_INET && ! entry_conn->entry_cfg.ipv4_traffic) ||
1476 (family == AF_INET6 && ! entry_conn->entry_cfg.ipv6_traffic)) {
1477 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1478 "Got a connected cell to %s with unsupported address family."
1479 " Closing.", safe_str(fmt_addr(&addr)));
1480 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1481 connection_mark_unattached_ap(entry_conn,
1482 END_STREAM_REASON_TORPROTOCOL);
1483 return 0;
1484 }
1485
1486 client_dns_set_addressmap(entry_conn,
1487 entry_conn->socks_request->address, &addr,
1488 entry_conn->chosen_exit_name, ttl);
1489
1490 remap_event_helper(entry_conn, &addr);
1491 }
1493 /* don't send a socks reply to transparent conns */
1494 tor_assert(entry_conn->socks_request != NULL);
1495 if (!entry_conn->socks_request->has_finished) {
1496 connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
1497 }
1498
1499 /* Was it a linked dir conn? If so, a dir request just started to
1500 * fetch something; this could be a bootstrap status milestone. */
1501 log_debug(LD_APP, "considering");
1502 if (TO_CONN(conn)->linked_conn &&
1503 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
1504 connection_t *dirconn = TO_CONN(conn)->linked_conn;
1505 log_debug(LD_APP, "it is! %d", dirconn->purpose);
1506 switch (dirconn->purpose) {
1509 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
1510 break;
1512 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
1513 break;
1516 if (TO_DIR_CONN(dirconn)->router_purpose == ROUTER_PURPOSE_GENERAL)
1517 control_event_boot_dir(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
1519 break;
1520 }
1521 }
1522 /* This is definitely a success, so forget about any pending data we
1523 * had sent. */
1524 if (entry_conn->pending_optimistic_data) {
1525 buf_free(entry_conn->pending_optimistic_data);
1526 entry_conn->pending_optimistic_data = NULL;
1527 }
1528
1529 /* This is valid data at this point. Count it */
1530 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1531
1532 /* handle anything that might have queued */
1533 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1534 /* (We already sent an end cell if possible) */
1535 connection_mark_for_close(TO_CONN(conn));
1536 return 0;
1537 }
1538 return 0;
1539 }
1540 if (conn->base_.type == CONN_TYPE_AP &&
1541 msg->command == RELAY_COMMAND_RESOLVED) {
1542 return connection_edge_process_resolved_cell(conn, msg);
1543 }
1544
1545 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1546 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
1547 msg->command, conn->base_.state,
1548 conn_state_to_string(conn->base_.type, conn->base_.state));
1549 return 0; /* for forward compatibility, don't kill the circuit */
1550// connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1551// connection_mark_for_close(conn);
1552// return -1;
1553}
1554
1555/** Process a SENDME cell that arrived on <b>circ</b>. If it is a stream level
1556 * cell, it is destined for the given <b>conn</b>. If it is a circuit level
1557 * cell, it is destined for the <b>layer_hint</b>. The <b>domain</b> is the
1558 * logging domain that should be used.
1559 *
1560 * Return 0 if everything went well or a negative value representing a circuit
1561 * end reason on error for which the caller is responsible for closing it. */
1562static int
1564 edge_connection_t *conn, crypt_path_t *layer_hint,
1565 int domain)
1566{
1567 int ret;
1568
1569 tor_assert(msg);
1570
1571 if (!msg->stream_id) {
1572 /* Circuit level SENDME cell. */
1573 ret = sendme_process_circuit_level(layer_hint, circ, msg->body,
1574 msg->length);
1575 if (ret < 0) {
1576 return ret;
1577 }
1578 /* Resume reading on any streams now that we've processed a valid
1579 * SENDME cell that updated our package window. */
1580 circuit_resume_edge_reading(circ, layer_hint);
1581 /* We are done, the rest of the code is for the stream level. */
1582 return 0;
1583 }
1584
1585 /* No connection, might be half edge state. We are done if so. */
1586 if (!conn) {
1587 if (CIRCUIT_IS_ORIGIN(circ)) {
1588 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1590 msg->stream_id)) {
1591 circuit_read_valid_data(ocirc, msg->length);
1592 log_info(domain, "Sendme cell on circ %u valid on half-closed "
1593 "stream id %d",
1594 ocirc->global_identifier, msg->stream_id);
1595 }
1596 }
1597
1598 log_info(domain, "SENDME cell dropped, unknown stream (streamid %d).",
1599 msg->stream_id);
1600 return 0;
1601 }
1602
1603 /* Stream level SENDME cell. */
1604 // TODO: Turn this off for cc_alg=1,2,3; use XON/XOFF instead
1605 ret = sendme_process_stream_level(conn, circ, msg->length);
1606 if (ret < 0) {
1607 /* Means we need to close the circuit with reason ret. */
1608 return ret;
1609 }
1610
1611 /* We've now processed properly a SENDME cell, all windows have been
1612 * properly updated, we'll read on the edge connection to see if we can
1613 * get data out towards the end point (Exit or client) since we are now
1614 * allowed to deliver more cells. */
1615
1617 /* Still waiting for queue to flush; don't touch conn */
1618 return 0;
1619 }
1621 /* handle whatever might still be on the inbuf */
1622 if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
1623 /* (We already sent an end cell if possible) */
1624 connection_mark_for_close(TO_CONN(conn));
1625 return 0;
1626 }
1627 return 0;
1628}
1629
1630/** A helper for connection_edge_process_relay_cell(): Actually handles the
1631 * cell that we received on the connection.
1632 *
1633 * The arguments are the same as in the parent function
1634 * connection_edge_process_relay_cell(), plus the relay header <b>rh</b> as
1635 * unpacked by the parent function, and <b>optimistic_data</b> as set by the
1636 * parent function.
1637 */
1638STATIC int
1640 edge_connection_t *conn, crypt_path_t *layer_hint,
1641 int optimistic_data)
1642{
1643 unsigned domain = layer_hint?LD_APP:LD_EXIT;
1644 int reason;
1645
1646 tor_assert(msg);
1647
1648 /* First pass the cell to the circuit padding subsystem, in case it's a
1649 * padding cell or circuit that should be handled there. */
1650 if (circpad_check_received_cell(msg, circ, layer_hint) == 0) {
1651 log_debug(domain, "Cell handled as circuit padding");
1652 return 0;
1653 }
1654
1655 /* Now handle all the other commands */
1656 switch (msg->command) {
1657 case RELAY_COMMAND_CONFLUX_LINK:
1658 conflux_process_link(circ, msg);
1659 return 0;
1660 case RELAY_COMMAND_CONFLUX_LINKED:
1661 conflux_process_linked(circ, layer_hint, msg);
1662 return 0;
1663 case RELAY_COMMAND_CONFLUX_LINKED_ACK:
1665 return 0;
1666 case RELAY_COMMAND_CONFLUX_SWITCH:
1667 return conflux_process_switch_command(circ, layer_hint, msg);
1668 case RELAY_COMMAND_BEGIN:
1669 case RELAY_COMMAND_BEGIN_DIR:
1670 if (layer_hint &&
1672 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1673 "Relay begin request unsupported at AP. Dropping.");
1674 return 0;
1675 }
1677 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1678 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1679 "Relay begin request to Hidden Service "
1680 "from intermediary node. Dropping.");
1681 return 0;
1682 }
1683 if (conn) {
1684 log_fn(LOG_PROTOCOL_WARN, domain,
1685 "Begin cell for known stream. Dropping.");
1686 return 0;
1687 }
1688 if (msg->command == RELAY_COMMAND_BEGIN_DIR &&
1690 /* Assign this circuit and its app-ward OR connection a unique ID,
1691 * so that we can measure download times. The local edge and dir
1692 * connection will be assigned the same ID when they are created
1693 * and linked. */
1694 static uint64_t next_id = 0;
1695 circ->dirreq_id = ++next_id;
1696 TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
1697 }
1698 return connection_exit_begin_conn(msg, circ);
1699 case RELAY_COMMAND_DATA:
1701
1702 if (msg->stream_id == 0) {
1703 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay data cell with zero "
1704 "stream_id. Dropping.");
1705 return 0;
1706 } else if (!conn) {
1707 if (CIRCUIT_IS_ORIGIN(circ)) {
1708 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1710 msg->stream_id)) {
1711 circuit_read_valid_data(ocirc, msg->length);
1712 log_info(domain,
1713 "data cell on circ %u valid on half-closed "
1714 "stream id %d", ocirc->global_identifier, msg->stream_id);
1715 }
1716 }
1717
1718 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1719 msg->stream_id);
1720 return 0;
1721 }
1722
1723 /* Update our stream-level deliver window that we just received a DATA
1724 * cell. Going below 0 means we have a protocol level error so the
1725 * stream and circuit are closed. */
1726 if (sendme_stream_data_received(conn) < 0) {
1727 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1728 "(relay data) conn deliver_window below 0. Killing.");
1729 connection_edge_end_close(conn, END_STREAM_REASON_TORPROTOCOL);
1730 return -END_CIRC_REASON_TORPROTOCOL;
1731 }
1732 /* Total all valid application bytes delivered */
1733 if (CIRCUIT_IS_ORIGIN(circ) && msg->length > 0) {
1734 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1735 }
1736
1737 /* For onion service connection, update the metrics. */
1738 if (conn->hs_ident) {
1739 hs_metrics_app_write_bytes(&conn->hs_ident->identity_pk,
1740 conn->hs_ident->orig_virtual_port,
1741 msg->length);
1742 }
1743
1744 stats_n_data_bytes_received += msg->length;
1745 connection_buf_add((char*) msg->body, msg->length, TO_CONN(conn));
1746
1747#ifdef MEASUREMENTS_21206
1748 /* Count number of RELAY_DATA cells received on a linked directory
1749 * connection. */
1750 connection_t *linked_conn = TO_CONN(conn)->linked_conn;
1751
1752 if (linked_conn && linked_conn->type == CONN_TYPE_DIR) {
1753 ++(TO_DIR_CONN(linked_conn)->data_cells_received);
1754 }
1755#endif /* defined(MEASUREMENTS_21206) */
1756
1757 if (!optimistic_data) {
1758 /* Only send a SENDME if we're not getting optimistic data; otherwise
1759 * a SENDME could arrive before the CONNECTED.
1760 */
1762 }
1763
1764 return 0;
1765 case RELAY_COMMAND_XOFF:
1766 if (!conn) {
1767 if (CIRCUIT_IS_ORIGIN(circ)) {
1768 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1769 if (relay_crypt_from_last_hop(ocirc, layer_hint) &&
1771 msg->stream_id)) {
1772 circuit_read_valid_data(ocirc, msg->length);
1773 }
1774 }
1775 return 0;
1776 }
1777
1778 if (circuit_process_stream_xoff(conn, layer_hint)) {
1779 if (CIRCUIT_IS_ORIGIN(circ)) {
1780 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1781 }
1782 }
1783 return 0;
1784 case RELAY_COMMAND_XON:
1785 if (!conn) {
1786 if (CIRCUIT_IS_ORIGIN(circ)) {
1787 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1788 if (relay_crypt_from_last_hop(ocirc, layer_hint) &&
1790 msg->stream_id)) {
1791 circuit_read_valid_data(ocirc, msg->length);
1792 }
1793 }
1794 return 0;
1795 }
1796
1797 if (circuit_process_stream_xon(conn, layer_hint, msg)) {
1798 if (CIRCUIT_IS_ORIGIN(circ)) {
1799 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1800 }
1801 }
1802 return 0;
1803 case RELAY_COMMAND_END:
1804 /* Kill the circuit, the END cell has no reason. */
1805 if (msg->length == 0) {
1806 return -END_CIRC_REASON_TORPROTOCOL;
1807 }
1808 reason = get_uint8(msg->body);
1809 if (reason == 0) {
1810 /* Not a valid END reason; don't let it alias our local "no error"
1811 * value in end_reason (see same exception in end_not_open). */
1812 reason = END_STREAM_REASON_MISC;
1813 }
1814 if (!conn) {
1815 if (CIRCUIT_IS_ORIGIN(circ)) {
1816 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1817 if (relay_crypt_from_last_hop(ocirc, layer_hint) &&
1819 msg->stream_id)) {
1820
1821 circuit_read_valid_data(ocirc, msg->length);
1822 log_info(domain,
1823 "end cell (%s) on circ %u valid on half-closed "
1824 "stream id %d",
1826 ocirc->global_identifier, msg->stream_id);
1827 return 0;
1828 }
1829 }
1830 log_info(domain,"end cell (%s) dropped, unknown stream.",
1832 return 0;
1833 }
1834/* XXX add to this log_fn the exit node's nickname? */
1835 log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
1836 "Removing stream.",
1837 conn->base_.s,
1839 conn->stream_id);
1840 if (conn->base_.type == CONN_TYPE_AP) {
1841 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1842 if (entry_conn->socks_request &&
1843 !entry_conn->socks_request->has_finished)
1844 log_warn(LD_BUG,
1845 "open stream hasn't sent socks answer yet? Closing.");
1846 }
1847 /* We just *got* an end; no reason to send one. */
1848 conn->edge_has_sent_end = 1;
1849 if (!conn->end_reason)
1851 if (!conn->base_.marked_for_close) {
1852 /* only mark it if not already marked. it's possible to
1853 * get the 'end' right around when the client hangs up on us. */
1854 connection_mark_and_flush(TO_CONN(conn));
1855
1856 /* Total all valid application bytes delivered */
1857 if (CIRCUIT_IS_ORIGIN(circ)) {
1858 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1859 }
1860 }
1861 return 0;
1862 case RELAY_COMMAND_EXTEND:
1863 case RELAY_COMMAND_EXTEND2: {
1864 static uint64_t total_n_extend=0, total_nonearly=0;
1865 total_n_extend++;
1866 if (msg->stream_id) {
1867 log_fn(LOG_PROTOCOL_WARN, domain,
1868 "'extend' cell received for non-zero stream. Dropping.");
1869 return 0;
1870 }
1871 if (!msg->is_relay_early &&
1872 !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
1873#define EARLY_WARNING_INTERVAL 3600
1874 static ratelim_t early_warning_limit =
1875 RATELIM_INIT(EARLY_WARNING_INTERVAL);
1876 char *m;
1877 if (!msg->is_relay_early) {
1878 ++total_nonearly;
1879 if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
1880 double percentage = ((double)total_nonearly)/total_n_extend;
1881 percentage *= 100;
1882 log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
1883 "but not via RELAY_EARLY. Dropping.%s", m);
1884 log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
1885 "all EXTEND cells for this reason)", percentage);
1886 tor_free(m);
1887 }
1888 } else {
1889 log_fn(LOG_WARN, domain,
1890 "EXTEND cell received, in a cell with type %d! Dropping.",
1891 msg->command);
1892 }
1893 return 0;
1894 }
1895 return circuit_extend(msg, circ);
1896 }
1897 case RELAY_COMMAND_EXTENDED:
1898 case RELAY_COMMAND_EXTENDED2:
1899 if (!layer_hint) {
1900 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1901 "'extended' unsupported at non-origin. Dropping.");
1902 return 0;
1903 }
1904 log_debug(domain,"Got an extended cell! Yay.");
1905 {
1906 extended_cell_t extended_cell;
1907 if (extended_cell_parse(&extended_cell, msg->command,
1908 msg->body, msg->length) < 0) {
1909 log_warn(LD_PROTOCOL,
1910 "Can't parse EXTENDED cell; killing circuit.");
1911 return -END_CIRC_REASON_TORPROTOCOL;
1912 }
1913 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1914 &extended_cell.created_cell)) < 0) {
1915 circuit_mark_for_close(circ, -reason);
1916 return 0; /* We don't want to cause a warning, so we mark the circuit
1917 * here. */
1918 }
1919 }
1920 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1921 log_info(domain,"circuit_send_next_onion_skin() failed.");
1922 return reason;
1923 }
1924 /* Total all valid bytes delivered. */
1925 if (CIRCUIT_IS_ORIGIN(circ)) {
1926 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1927 }
1928 return 0;
1929 case RELAY_COMMAND_TRUNCATE:
1930 if (layer_hint) {
1931 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1932 "'truncate' unsupported at origin. Dropping.");
1933 return 0;
1934 }
1935 if (circ->n_hop) {
1936 if (circ->n_chan)
1937 log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
1938 extend_info_free(circ->n_hop);
1939 circ->n_hop = NULL;
1942 }
1943 if (circ->n_chan) {
1944 /* The TRUNCATE cell doesn't contain a reason, protocol violation. */
1945 if (msg->length == 0) {
1946 return -END_CIRC_REASON_TORPROTOCOL;
1947 }
1948 uint8_t trunc_reason = get_uint8(msg->body);
1949 circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_N_CHAN);
1950 circuit_clear_cell_queue(circ, circ->n_chan);
1952 trunc_reason);
1953 circuit_set_n_circid_chan(circ, 0, NULL);
1954 }
1955 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1956 {
1957 char payload[1];
1958 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1959 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1960 payload, sizeof(payload), NULL);
1961 }
1962 return 0;
1963 case RELAY_COMMAND_TRUNCATED:
1964 if (!layer_hint) {
1965 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1966 "'truncated' unsupported at non-origin. Dropping.");
1967 return 0;
1968 }
1969
1970 /* Count the truncated as valid, for completeness. The
1971 * circuit is being torn down anyway, though. */
1972 if (CIRCUIT_IS_ORIGIN(circ)) {
1973 circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), msg->length);
1974 }
1975 /* The TRUNCATED cell doesn't contain a reason, protocol violation. */
1976 if (msg->length == 0) {
1977 return -END_CIRC_REASON_TORPROTOCOL;
1978 }
1980 return 0;
1981 case RELAY_COMMAND_CONNECTED:
1982 if (conn) {
1983 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1984 "'connected' unsupported while open. Closing circ.");
1985 return -END_CIRC_REASON_TORPROTOCOL;
1986 }
1987
1988 if (CIRCUIT_IS_ORIGIN(circ)) {
1989 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1991 msg->stream_id)) {
1992 circuit_read_valid_data(ocirc, msg->length);
1993 log_info(domain,
1994 "connected cell on circ %u valid on half-closed "
1995 "stream id %d", ocirc->global_identifier, msg->stream_id);
1996 return 0;
1997 }
1998 }
1999
2000 log_info(domain,
2001 "'connected' received on circid %u for streamid %d, "
2002 "no conn attached anymore. Ignoring.",
2003 (unsigned)circ->n_circ_id, msg->stream_id);
2004 return 0;
2005 case RELAY_COMMAND_SENDME:
2006 return process_sendme_cell(msg, circ, conn, layer_hint, domain);
2007 case RELAY_COMMAND_RESOLVE:
2008 if (layer_hint) {
2009 log_fn(LOG_PROTOCOL_WARN, LD_APP,
2010 "resolve request unsupported at AP; dropping.");
2011 return 0;
2012 } else if (conn) {
2013 log_fn(LOG_PROTOCOL_WARN, domain,
2014 "resolve request for known stream; dropping.");
2015 return 0;
2016 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
2017 log_fn(LOG_PROTOCOL_WARN, domain,
2018 "resolve request on circ with purpose %d; dropping",
2019 circ->purpose);
2020 return 0;
2021 }
2023 case RELAY_COMMAND_RESOLVED:
2024 if (conn) {
2025 log_fn(LOG_PROTOCOL_WARN, domain,
2026 "'resolved' unsupported while open. Closing circ.");
2027 return -END_CIRC_REASON_TORPROTOCOL;
2028 }
2029
2030 if (CIRCUIT_IS_ORIGIN(circ)) {
2031 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
2032 if (relay_crypt_from_last_hop(ocirc, layer_hint) &&
2034 msg->stream_id)) {
2035 circuit_read_valid_data(ocirc, msg->length);
2036 log_info(domain,
2037 "resolved cell on circ %u valid on half-closed "
2038 "stream id %d", ocirc->global_identifier, msg->stream_id);
2039 return 0;
2040 }
2041 }
2042
2043 log_info(domain,
2044 "'resolved' received, no conn attached anymore. Ignoring.");
2045 return 0;
2046 case RELAY_COMMAND_ESTABLISH_INTRO:
2047 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
2048 case RELAY_COMMAND_INTRODUCE1:
2049 case RELAY_COMMAND_INTRODUCE2:
2050 case RELAY_COMMAND_INTRODUCE_ACK:
2051 case RELAY_COMMAND_RENDEZVOUS1:
2052 case RELAY_COMMAND_RENDEZVOUS2:
2053 case RELAY_COMMAND_INTRO_ESTABLISHED:
2054 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
2055 rend_process_relay_cell(circ, layer_hint,
2056 msg->command, msg->length, msg->body);
2057 return 0;
2058 }
2059 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2060 "Received unknown relay command %d. Perhaps the other side is using "
2061 "a newer version of Tor? Dropping.",
2062 msg->command);
2063 return 0; /* for forward compatibility, don't kill the circuit */
2064}
2065
2066/** An incoming relay cell has arrived on circuit <b>circ</b>. If
2067 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
2068 * destined for <b>conn</b>.
2069 *
2070 * If <b>layer_hint</b> is defined, then we're the origin of the
2071 * circuit, and it specifies the hop that packaged <b>cell</b>.
2072 *
2073 * Return -reason if you want to warn and tear down the circuit, else 0.
2074 */
2075STATIC int
2077 edge_connection_t *conn,
2078 crypt_path_t *layer_hint)
2079{
2080 static int num_seen=0;
2081 unsigned domain = layer_hint?LD_APP:LD_EXIT;
2082
2083 tor_assert(msg);
2084 tor_assert(circ);
2085
2086// log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
2087 num_seen++;
2088 log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
2089 num_seen, msg->command, msg->stream_id);
2090
2091 if (msg->stream_id == 0) {
2092 switch (msg->command) {
2093 case RELAY_COMMAND_BEGIN:
2094 case RELAY_COMMAND_CONNECTED:
2095 case RELAY_COMMAND_END:
2096 case RELAY_COMMAND_RESOLVE:
2097 case RELAY_COMMAND_RESOLVED:
2098 case RELAY_COMMAND_BEGIN_DIR:
2099 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %u with zero "
2100 "stream_id. Dropping.", msg->command);
2101 return 0;
2102 default:
2103 ;
2104 }
2105 }
2106
2107 /* Regardless of conflux or not, we always decide to send a SENDME
2108 * for RELAY_DATA immediately
2109 */
2110 if (msg->command == RELAY_COMMAND_DATA) {
2111 /* Update our circuit-level deliver window that we received a DATA cell.
2112 * If the deliver window goes below 0, we end the circuit and stream due
2113 * to a protocol failure. */
2114 if (sendme_circuit_data_received(circ, layer_hint) < 0) {
2115 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2116 "(relay data) circ deliver_window below 0. Killing.");
2117 connection_edge_end_close(conn, END_STREAM_REASON_TORPROTOCOL);
2118 return -END_CIRC_REASON_TORPROTOCOL;
2119 }
2120
2121 /* Consider sending a circuit-level SENDME cell. */
2122 sendme_circuit_consider_sending(circ, layer_hint);
2123
2124 /* Continue on to process the data cell via conflux or not */
2125 }
2126
2127 /* Conflux handling: If conflux is disabled, or the relay command is not
2128 * multiplexed across circuits, then process it immediately.
2129 *
2130 * Otherwise, we need to process the relay cell against our conflux
2131 * queues, and if doing so results in ordered cells to deliver, we
2132 * dequeue and process those in-order until there are no more.
2133 */
2134 if (!circ->conflux || !conflux_should_multiplex(msg->command)) {
2135 return connection_edge_process_ordered_relay_cell(msg, circ, conn,
2136 layer_hint);
2137 } else {
2138 // If conflux says this cell is in-order, then begin processing
2139 // cells from queue until there are none. Otherwise, we do nothing
2140 // until further cells arrive.
2141 if (conflux_process_relay_msg(circ->conflux, circ, layer_hint,
2142 (relay_msg_t *) msg)) {
2143 conflux_msg_t *c_msg = NULL;
2144
2145 /* First, process this cell */
2147 msg, circ, conn, layer_hint);
2148 if (ret < 0) {
2149 return ret;
2150 }
2151
2152 /* Now, check queue for more */
2153 while ((c_msg = conflux_dequeue_relay_msg(circ))) {
2154 conn = relay_lookup_conn(circ, c_msg->msg, CELL_DIRECTION_OUT,
2155 layer_hint);
2157 conn,
2158 layer_hint);
2159 if (ret < 0) {
2160 /* Negative return value is a fatal error. Return early and tear down
2161 * circuit */
2162 conflux_relay_msg_free(c_msg);
2163 return ret;
2164 }
2165 conflux_relay_msg_free(c_msg);
2166 }
2167 }
2168 }
2169
2170 return 0;
2171}
2172
2173/**
2174 * Helper function to process a relay cell that is in the proper order
2175 * for processing right now. */
2176static int
2178 circuit_t *circ,
2179 edge_connection_t *conn,
2180 crypt_path_t *layer_hint)
2181{
2182 int optimistic_data = 0; /* Set to 1 if we receive data on a stream
2183 * that's in the EXIT_CONN_STATE_RESOLVING
2184 * or EXIT_CONN_STATE_CONNECTING states. */
2185
2186 /* Tell circpad that we've received a recognized cell */
2187 circpad_deliver_recognized_relay_cell_events(circ, msg->command, layer_hint);
2188
2189 /* either conn is NULL, in which case we've got a control cell, or else
2190 * conn points to the recognized stream. */
2191 if (conn && !connection_state_is_open(TO_CONN(conn))) {
2192 if (conn->base_.type == CONN_TYPE_EXIT &&
2193 (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
2194 conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
2195 msg->command == RELAY_COMMAND_DATA) {
2196 /* Allow DATA cells to be delivered to an exit node in state
2197 * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
2198 * This speeds up HTTP, for example. */
2199 optimistic_data = 1;
2200 } else if (msg->stream_id == 0 && msg->command == RELAY_COMMAND_DATA) {
2201 log_warn(LD_BUG, "Somehow I had a connection that matched a "
2202 "data cell with stream ID 0.");
2203 } else {
2205 msg, circ, conn, layer_hint);
2206 }
2207 }
2208
2209 return handle_relay_msg(msg, circ, conn, layer_hint, optimistic_data);
2210}
2211
2212/** How many relay_data cells have we built, ever? */
2214/** How many bytes of data have we put in relay_data cells have we built,
2215 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
2216 * every relay cell we ever sent were completely full of data. */
2218/** How many relay_data cells have we received, ever? */
2220/** How many bytes of data have we received relay_data cells, ever? This would
2221 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
2222 * ever received were completely full of data. */
2224
2225/**
2226 * Called when initializing a circuit, or when we have reached the end of the
2227 * window in which we need to send some randomness so that incoming sendme
2228 * cells will be unpredictable. Resets the flags and picks a new window.
2229 */
2230void
2232{
2234 // XXX: do we need to change this check for congestion control?
2237}
2238
2239/**
2240 * Helper. Return the number of bytes that should be put into a cell from a
2241 * given edge connection on which <b>n_available</b> bytes are available.
2242 */
2243STATIC size_t
2245 int package_partial,
2246 circuit_t *on_circuit,
2247 crypt_path_t *cpath)
2248{
2249 if (!n_available)
2250 return 0;
2251
2252 /* Do we need to force this payload to have space for randomness? */
2253 const bool force_random_bytes =
2254 (on_circuit->send_randomness_after_n_cells == 0) &&
2255 (! on_circuit->have_sent_sufficiently_random_cell);
2256
2257 relay_cell_fmt_t cell_format = circuit_get_relay_format(on_circuit, cpath);
2258 size_t target_length =
2259 relay_cell_max_payload_size(cell_format, RELAY_COMMAND_DATA);
2260
2261#define RELAY_CELL_PADDING_GAP 4
2262
2263 /* Any relay data payload containing fewer than this many real bytes is
2264 * considered to have enough randomness to. */
2265 size_t target_length_with_random = target_length -
2266 RELAY_CELL_PADDING_GAP - 16;
2267 if (force_random_bytes) {
2268 target_length = target_length_with_random;
2269 }
2270
2271 /* Decide how many bytes we will actually put into this cell. */
2272 size_t package_length;
2273 if (n_available >= target_length) { /* A full payload is available. */
2274 package_length = target_length;
2275 } else { /* not a full payload available */
2276 if (package_partial)
2277 package_length = n_available; /* just take whatever's available now */
2278 else
2279 return 0; /* nothing to do until we have a full payload */
2280 }
2281
2282 /* If we reach this point, we will be definitely sending the cell. */
2283 tor_assert_nonfatal(package_length > 0);
2284
2285 if (package_length <= target_length_with_random) {
2286 /* This cell will have enough randomness in the padding to make a future
2287 * sendme cell unpredictable. */
2288 on_circuit->have_sent_sufficiently_random_cell = 1;
2289 }
2290
2291 if (on_circuit->send_randomness_after_n_cells == 0) {
2292 /* Either this cell, or some previous cell, had enough padding to
2293 * ensure sendme unpredictability. */
2294 tor_assert_nonfatal(on_circuit->have_sent_sufficiently_random_cell);
2295 /* Pick a new interval in which we need to send randomness. */
2297 }
2298
2299 --on_circuit->send_randomness_after_n_cells;
2300
2301 return package_length;
2302}
2303
2304/** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
2305 * <b>package_partial</b> is true), and the appropriate package windows aren't
2306 * empty, grab a cell and send it down the circuit.
2307 *
2308 * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
2309 * *<b>max_cells</b> by the number of cells packaged.
2310 *
2311 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
2312 * be marked for close, else return 0.
2313 */
2314int
2316 int *max_cells)
2317{
2318 size_t bytes_to_process, length;
2319 char payload[CELL_PAYLOAD_SIZE];
2320 circuit_t *circ;
2321 const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
2322 int sending_from_optimistic = 0;
2323 entry_connection_t *entry_conn =
2324 conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
2325 const int sending_optimistically =
2326 entry_conn &&
2327 conn->base_.type == CONN_TYPE_AP &&
2328 conn->base_.state != AP_CONN_STATE_OPEN;
2329 crypt_path_t *cpath_layer = conn->cpath_layer;
2330
2331 tor_assert(conn);
2332
2333 if (BUG(conn->base_.marked_for_close)) {
2334 log_warn(LD_BUG,
2335 "called on conn that's already marked for close at %s:%d.",
2336 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
2337 return 0;
2338 }
2339
2340 if (max_cells && *max_cells <= 0)
2341 return 0;
2342
2343 repeat_connection_edge_package_raw_inbuf:
2344
2345 circ = circuit_get_by_edge_conn(conn);
2346 if (!circ) {
2347 log_info(domain,"conn has no circuit! Closing.");
2349 return -1;
2350 }
2351
2352 if (circuit_consider_stop_edge_reading(circ, cpath_layer))
2353 return 0;
2354
2355 if (conn->package_window <= 0) {
2356 log_info(domain,"called with package_window %d. Skipping.",
2357 conn->package_window);
2359 return 0;
2360 }
2361
2362 sending_from_optimistic = entry_conn &&
2363 entry_conn->sending_optimistic_data != NULL;
2364
2365 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
2366 bytes_to_process = buf_datalen(entry_conn->sending_optimistic_data);
2367 if (PREDICT_UNLIKELY(!bytes_to_process)) {
2368 log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
2369 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
2370 sending_from_optimistic = 0;
2371 }
2372 } else {
2373 bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
2374 }
2375
2376 length = connection_edge_get_inbuf_bytes_to_package(bytes_to_process,
2377 package_partial, circ,
2378 cpath_layer);
2379 if (!length)
2380 return 0;
2381
2382 /* If we reach this point, we will definitely be packaging bytes into
2383 * a cell. */
2384
2387
2388 if (PREDICT_UNLIKELY(sending_from_optimistic)) {
2389 /* XXXX We could be more efficient here by sometimes packing
2390 * previously-sent optimistic data in the same cell with data
2391 * from the inbuf. */
2392 buf_get_bytes(entry_conn->sending_optimistic_data, payload, length);
2393 if (!buf_datalen(entry_conn->sending_optimistic_data)) {
2394 buf_free(entry_conn->sending_optimistic_data);
2395 entry_conn->sending_optimistic_data = NULL;
2396 }
2397 } else {
2398 connection_buf_get_bytes(payload, length, TO_CONN(conn));
2399 }
2400
2401 log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
2402 conn->base_.s,
2403 (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
2404
2405 if (sending_optimistically && !sending_from_optimistic) {
2406 /* This is new optimistic data; remember it in case we need to detach and
2407 retry */
2408 if (!entry_conn->pending_optimistic_data)
2409 entry_conn->pending_optimistic_data = buf_new();
2410 buf_add(entry_conn->pending_optimistic_data, payload, length);
2411 }
2412
2413 /* Send a data cell. This handles the circuit package window. */
2414 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
2415 payload, length) < 0 ) {
2416 /* circuit got marked for close, don't continue, don't need to mark conn */
2417 return 0;
2418 }
2419
2420 /* Handle the stream-level SENDME package window. */
2421 if (sendme_note_stream_data_packaged(conn, length) < 0) {
2423 log_debug(domain,"conn->package_window reached 0.");
2424 circuit_consider_stop_edge_reading(circ, cpath_layer);
2425 return 0; /* don't process the inbuf any more */
2426 }
2427 log_debug(domain,"conn->package_window is now %d",conn->package_window);
2428
2429 if (max_cells) {
2430 *max_cells -= 1;
2431 if (*max_cells <= 0)
2432 return 0;
2433 }
2434
2435 /* handle more if there's more, or return 0 if there isn't */
2436 goto repeat_connection_edge_package_raw_inbuf;
2437}
2438
2439/** The circuit <b>circ</b> has received a circuit-level sendme
2440 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
2441 * attached streams and let them resume reading and packaging, if
2442 * their stream windows allow it.
2443 */
2444static void
2446{
2448 log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
2449 return;
2450 }
2451
2452 /* If we have a conflux negotiated, and it still can't send on
2453 * any circuit, then do not resume sending. */
2454 if (circ->conflux && !conflux_can_send(circ->conflux)) {
2455 log_debug(layer_hint?LD_APP:LD_EXIT,
2456 "Conflux can't send, not resuming edges");
2457 return;
2458 }
2459
2460 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
2461
2462 if (CIRCUIT_IS_ORIGIN(circ))
2464 circ, layer_hint);
2465 else
2467 circ, layer_hint);
2468}
2469
2470/** A helper function for circuit_resume_edge_reading() above.
2471 * The arguments are the same, except that <b>conn</b> is the head
2472 * of a linked list of edge streams that should each be considered.
2473 */
2474static int
2476 circuit_t *circ,
2477 crypt_path_t *layer_hint)
2478{
2479 edge_connection_t *conn;
2480 int n_packaging_streams, n_streams_left;
2481 int packaged_this_round;
2482 int cells_on_queue;
2483 int cells_per_conn;
2484 edge_connection_t *chosen_stream = NULL;
2485 int max_to_package;
2486
2487 if (first_conn == NULL) {
2488 /* Don't bother to try to do the rest of this if there are no connections
2489 * to resume. */
2490 return 0;
2491 }
2492
2493 /* Once we used to start listening on the streams in the order they
2494 * appeared in the linked list. That leads to starvation on the
2495 * streams that appeared later on the list, since the first streams
2496 * would always get to read first. Instead, we just pick a random
2497 * stream on the list, and enable reading for streams starting at that
2498 * point (and wrapping around as if the list were circular). It would
2499 * probably be better to actually remember which streams we've
2500 * serviced in the past, but this is simple and effective. */
2501
2502 /* Select a stream uniformly at random from the linked list. We
2503 * don't need cryptographic randomness here. */
2504 {
2505 int num_streams = 0;
2506 for (conn = first_conn; conn; conn = conn->next_stream) {
2507 num_streams++;
2508
2509 if (crypto_fast_rng_one_in_n(get_thread_fast_rng(), num_streams)) {
2510 chosen_stream = conn;
2511 }
2512 /* Invariant: chosen_stream has been chosen uniformly at random from
2513 * among the first num_streams streams on first_conn.
2514 *
2515 * (Note that we iterate over every stream on the circuit, so that after
2516 * we've considered the first stream, we've chosen it with P=1; and
2517 * after we consider the second stream, we've switched to it with P=1/2
2518 * and stayed with the first stream with P=1/2; and after we've
2519 * considered the third stream, we've switched to it with P=1/3 and
2520 * remained with one of the first two streams with P=(2/3), giving each
2521 * one P=(1/2)(2/3) )=(1/3).) */
2522 }
2523 }
2524
2525 /* Count how many non-marked streams there are that have anything on
2526 * their inbuf, and enable reading on all of the connections. */
2527 n_packaging_streams = 0;
2528 /* Activate reading starting from the chosen stream */
2529 for (conn=chosen_stream; conn; conn = conn->next_stream) {
2530 /* Start reading for the streams starting from here */
2531 if (conn->base_.marked_for_close || conn->package_window <= 0)
2532 continue;
2533
2534 if (edge_uses_cpath(conn, layer_hint)) {
2535 if (!conn->xoff_received) {
2537 }
2538
2539 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2540 ++n_packaging_streams;
2541 }
2542 }
2543 /* Go back and do the ones we skipped, circular-style */
2544 for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
2545 if (conn->base_.marked_for_close || conn->package_window <= 0)
2546 continue;
2547
2548 if (edge_uses_cpath(conn, layer_hint)) {
2549 if (!conn->xoff_received) {
2551 }
2552
2553 if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
2554 ++n_packaging_streams;
2555 }
2556 }
2557
2558 if (n_packaging_streams == 0) /* avoid divide-by-zero */
2559 return 0;
2560
2561 again:
2562
2563 /* If we're using conflux, the circuit we decide to send on may change
2564 * after we're sending. Get it again, and re-check package windows
2565 * for it */
2566 if (circ->conflux) {
2567 if (circuit_consider_stop_edge_reading(circ, layer_hint))
2568 return -1;
2569
2570 circ = conflux_decide_next_circ(circ->conflux);
2571
2572 /* Get the destination layer hint for this circuit */
2573 layer_hint = conflux_get_destination_hop(circ);
2574 }
2575
2576 /* How many cells do we have space for? It will be the minimum of
2577 * the number needed to exhaust the package window, and the minimum
2578 * needed to fill the cell queue. */
2579 max_to_package = congestion_control_get_package_window(circ, layer_hint);
2580 if (CIRCUIT_IS_ORIGIN(circ)) {
2581 cells_on_queue = circ->n_chan_cells.n;
2582 } else {
2583 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2584 cells_on_queue = or_circ->p_chan_cells.n;
2585 }
2586 if (cell_queue_highwatermark() - cells_on_queue < max_to_package)
2587 max_to_package = cell_queue_highwatermark() - cells_on_queue;
2588
2589 cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
2590
2591 packaged_this_round = 0;
2592 n_streams_left = 0;
2593
2594 /* Iterate over all connections. Package up to cells_per_conn cells on
2595 * each. Update packaged_this_round with the total number of cells
2596 * packaged, and n_streams_left with the number that still have data to
2597 * package.
2598 */
2599 for (conn=first_conn; conn; conn=conn->next_stream) {
2600 if (conn->base_.marked_for_close || conn->package_window <= 0)
2601 continue;
2602 if (edge_uses_cpath(conn, layer_hint)) {
2603 int n = cells_per_conn, r;
2604 /* handle whatever might still be on the inbuf */
2605 r = connection_edge_package_raw_inbuf(conn, 1, &n);
2606
2607 /* Note how many we packaged */
2608 packaged_this_round += (cells_per_conn-n);
2609
2610 if (r<0) {
2611 /* Problem while packaging. (We already sent an end cell if
2612 * possible) */
2613 connection_mark_for_close(TO_CONN(conn));
2614 continue;
2615 }
2616
2617 /* If there's still data to read, we'll be coming back to this stream. */
2618 if (connection_get_inbuf_len(TO_CONN(conn)))
2619 ++n_streams_left;
2620
2621 /* If the circuit won't accept any more data, return without looking
2622 * at any more of the streams. Any connections that should be stopped
2623 * have already been stopped by connection_edge_package_raw_inbuf. */
2624 if (circuit_consider_stop_edge_reading(circ, layer_hint))
2625 return -1;
2626 /* XXXX should we also stop immediately if we fill up the cell queue?
2627 * Probably. */
2628 }
2629 }
2630
2631 /* If we made progress, and we are willing to package more, and there are
2632 * any streams left that want to package stuff... try again!
2633 */
2634 if (packaged_this_round && packaged_this_round < max_to_package &&
2635 n_streams_left) {
2636 n_packaging_streams = n_streams_left;
2637 goto again;
2638 }
2639
2640 return 0;
2641}
2642
2643/** Check if the package window for <b>circ</b> is empty (at
2644 * hop <b>layer_hint</b> if it's defined).
2645 *
2646 * If yes, tell edge streams to stop reading and return 1.
2647 * Else return 0.
2648 */
2649static int
2651{
2652 edge_connection_t *conn = NULL;
2653 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
2654
2655 if (!layer_hint) {
2656 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2657 log_debug(domain,"considering circ->package_window %d",
2658 circ->package_window);
2659 if (circuit_get_package_window(circ, layer_hint) <= 0) {
2660 log_debug(domain,"yes, not-at-origin. stopped.");
2661 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
2663 return 1;
2664 }
2665 return 0;
2666 }
2667 /* else, layer hint is defined, use it */
2668 log_debug(domain,"considering layer_hint->package_window %d",
2669 layer_hint->package_window);
2670 if (circuit_get_package_window(circ, layer_hint) <= 0) {
2671 log_debug(domain,"yes, at-origin. stopped.");
2672 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
2673 conn=conn->next_stream) {
2674 if (edge_uses_cpath(conn, layer_hint))
2676 }
2677 return 1;
2678 }
2679 return 0;
2680}
2681
2682/** The total number of cells we have allocated. */
2683static size_t total_cells_allocated = 0;
2684
2685/** Release storage held by <b>cell</b>. */
2686static inline void
2692
2693/** Allocate and return a new packed_cell_t. */
2696{
2698 return tor_malloc_zero(sizeof(packed_cell_t));
2699}
2700
2701/** Return a packed cell used outside by channel_t lower layer */
2702void
2704{
2705 if (!cell)
2706 return;
2708}
2709
2710/** Log current statistics for cell pool allocation at log level
2711 * <b>severity</b>. */
2712void
2714{
2715 int n_circs = 0;
2716 int n_cells = 0;
2718 n_cells += c->n_chan_cells.n;
2719 if (!CIRCUIT_IS_ORIGIN(c))
2720 n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
2721 ++n_circs;
2722 }
2723 SMARTLIST_FOREACH_END(c);
2724 tor_log(severity, LD_MM,
2725 "%d cells allocated on %d circuits. %d cells leaked.",
2726 n_cells, n_circs, (int)total_cells_allocated - n_cells);
2727}
2728
2729/** Allocate a new copy of packed <b>cell</b>. */
2730static inline packed_cell_t *
2731packed_cell_copy(const cell_t *cell, int wide_circ_ids)
2732{
2734 cell_pack(c, cell, wide_circ_ids);
2735 return c;
2736}
2737
2738/** Append <b>cell</b> to the end of <b>queue</b>. */
2739void
2741{
2742 TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
2743 ++queue->n;
2744}
2745
2746/** Append a newly allocated copy of <b>cell</b> to the end of the
2747 * <b>exitward</b> (or app-ward) <b>queue</b> of <b>circ</b>. If
2748 * <b>use_stats</b> is true, record statistics about the cell.
2749 */
2750void
2752 int exitward, const cell_t *cell,
2753 int wide_circ_ids, int use_stats)
2754{
2755 packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
2756 (void)circ;
2757 (void)exitward;
2758 (void)use_stats;
2759
2761
2762 cell_queue_append(queue, copy);
2763}
2764
2765/** Initialize <b>queue</b> as an empty cell queue. */
2766void
2768{
2769 memset(queue, 0, sizeof(cell_queue_t));
2770 TOR_SIMPLEQ_INIT(&queue->head);
2771}
2772
2773/** Remove and free every cell in <b>queue</b>. */
2774void
2776{
2777 packed_cell_t *cell;
2778 while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
2779 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2781 }
2782 TOR_SIMPLEQ_INIT(&queue->head);
2783 queue->n = 0;
2784}
2785
2786/** Extract and return the cell at the head of <b>queue</b>; return NULL if
2787 * <b>queue</b> is empty. */
2790{
2791 packed_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
2792 if (!cell)
2793 return NULL;
2794 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2795 --queue->n;
2796 return cell;
2797}
2798
2799/** Initialize <b>queue</b> as an empty cell queue. */
2800void
2802{
2803 memset(queue, 0, sizeof(destroy_cell_queue_t));
2804 TOR_SIMPLEQ_INIT(&queue->head);
2805}
2806
2807/** Remove and free every cell in <b>queue</b>. */
2808void
2810{
2811 destroy_cell_t *cell;
2812 while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
2813 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2814 tor_free(cell);
2815 }
2816 TOR_SIMPLEQ_INIT(&queue->head);
2817 queue->n = 0;
2818}
2819
2820/** Extract and return the cell at the head of <b>queue</b>; return NULL if
2821 * <b>queue</b> is empty. */
2824{
2825 destroy_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
2826 if (!cell)
2827 return NULL;
2828 TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
2829 --queue->n;
2830 return cell;
2831}
2832
2833/** Append a destroy cell for <b>circid</b> to <b>queue</b>. */
2834void
2836 circid_t circid,
2837 uint8_t reason)
2838{
2839 destroy_cell_t *cell = tor_malloc_zero(sizeof(destroy_cell_t));
2840 cell->circid = circid;
2841 cell->reason = reason;
2842 /* Not yet used, but will be required for OOM handling. */
2844
2845 TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
2846 ++queue->n;
2847}
2848
2849/** Convert a destroy_cell_t to a newly allocated cell_t. Frees its input. */
2850static packed_cell_t *
2852{
2853 packed_cell_t *packed = packed_cell_new();
2854 cell_t cell;
2855 memset(&cell, 0, sizeof(cell));
2856 cell.circ_id = inp->circid;
2857 cell.command = CELL_DESTROY;
2858 cell.payload[0] = inp->reason;
2859 cell_pack(packed, &cell, wide_circ_ids);
2860
2861 tor_free(inp);
2862 return packed;
2863}
2864
2865/** Return the total number of bytes used for each packed_cell in a queue.
2866 * Approximate. */
2867size_t
2869{
2870 return sizeof(packed_cell_t);
2871}
2872
2873/* DOCDOC */
2874size_t
2875cell_queues_get_total_allocation(void)
2876{
2878}
2879
2880/** How long after we've been low on memory should we try to conserve it? */
2881#define MEMORY_PRESSURE_INTERVAL (30*60)
2882
2883/** The time at which we were last low on memory. */
2885
2886/** Statistics on how many bytes were removed by the OOM per type. */
2888uint64_t oom_stats_n_bytes_removed_cell = 0;
2889uint64_t oom_stats_n_bytes_removed_geoip = 0;
2890uint64_t oom_stats_n_bytes_removed_hsdir = 0;
2891
2892/** If true, the mainloop needs to run cell_queues_reclaim_memory(). */
2894
2895/** Check whether we've got too much space used for cells. If so,
2896 * then schedle the OOM handler (if reclaim_immediately is true) or
2897 * free the memory (if reclaim_immediately is false) and return 1.
2898 * Otherwise, return 0. */
2899static int
2900cell_queues_check_reclaim_impl(bool reclaim_immediately)
2901{
2902 size_t removed = 0;
2903 time_t now = time(NULL);
2904 size_t alloc = cell_queues_get_total_allocation();
2906 alloc += buf_get_total_allocation();
2908 const size_t hs_cache_total = hs_cache_get_total_allocation();
2909 alloc += hs_cache_total;
2910 const size_t geoip_client_cache_total =
2911 geoip_client_cache_total_allocation();
2912 alloc += geoip_client_cache_total;
2913 const size_t dns_cache_total = dns_cache_total_allocation();
2914 alloc += dns_cache_total;
2915 const size_t conflux_total = conflux_get_total_bytes_allocation();
2916 alloc += conflux_total;
2917
2918 if (alloc >= get_options()->MaxMemInQueues_low_threshold) {
2920
2921 if (alloc >= get_options()->MaxMemInQueues && ! reclaim_immediately) {
2922 /* Note that we're breaking the mainloop because we are OOM. */
2924
2925 /* We stop invoking any more pending callbacks after this one,
2926 * since we want to reclaim free memory immediately.
2927 *
2928 * We do not use a post-loop callback since that would wait
2929 * for many other callbacks, which could themselves allocate more
2930 * memory.
2931 */
2933 return 1;
2934 } else if (alloc >= get_options()->MaxMemInQueues && reclaim_immediately) {
2935 /* We are reclaiming the memory _now_ */
2936
2937 /* Note this overload down */
2938 rep_hist_note_overload(OVERLOAD_GENERAL);
2939
2940 /* If we're spending over the configured limit on hidden service
2941 * descriptors, free them until we're down to 50% of the limit. */
2942 if (hs_cache_total > hs_cache_get_max_bytes()) {
2943 const size_t bytes_to_remove =
2944 hs_cache_total - (size_t)(hs_cache_get_max_bytes() / 2);
2945 removed = hs_cache_handle_oom(bytes_to_remove);
2946 oom_stats_n_bytes_removed_hsdir += removed;
2947 alloc -= removed;
2948 static ratelim_t hs_cache_oom_ratelim = RATELIM_INIT(600);
2949 log_fn_ratelim(&hs_cache_oom_ratelim, LOG_NOTICE, LD_REND,
2950 "HSDir cache exceeded limit "
2951 "(%"TOR_PRIuSZ " > %"PRIu64 " bytes). "
2952 "Pruned %"TOR_PRIuSZ " bytes during cell_queues_check_size.",
2953 hs_cache_total, hs_cache_get_max_bytes(), removed);
2954 }
2955 if (geoip_client_cache_total > get_options()->MaxMemInQueues / 5) {
2956 const size_t bytes_to_remove =
2957 geoip_client_cache_total -
2958 (size_t)(get_options()->MaxMemInQueues / 10);
2959 removed = geoip_client_cache_handle_oom(now, bytes_to_remove);
2960 oom_stats_n_bytes_removed_geoip += removed;
2961 alloc -= removed;
2962 }
2963 if (dns_cache_total > get_options()->MaxMemInQueues / 5) {
2964 const size_t bytes_to_remove =
2965 dns_cache_total - (size_t)(get_options()->MaxMemInQueues / 10);
2966 removed = dns_cache_handle_oom(now, bytes_to_remove);
2968 alloc -= removed;
2969 }
2970 /* Like onion service above, try to go down to 10% if we are above 20% */
2971 if (conflux_total > get_options()->MaxMemInQueues / 5) {
2972 const size_t bytes_to_remove =
2973 conflux_total - (size_t)(get_options()->MaxMemInQueues / 10);
2974 removed = conflux_handle_oom(bytes_to_remove);
2975 oom_stats_n_bytes_removed_cell += removed;
2976 alloc -= removed;
2977 }
2978 removed = circuits_handle_oom(alloc);
2979 oom_stats_n_bytes_removed_cell += removed;
2980 return 1;
2981 }
2982 }
2983 return 0;
2984}
2985
2986/**
2987 * Check whether we are out of ram; if so, schedule an OOM scan, and
2988 * return 1. Otherwise return 0.
2989 */
2990STATIC int
2992{
2993 return cell_queues_check_reclaim_impl(false);
2994}
2995
2996/**
2997 * Assuming we are out of ram,
2998 * try to reclaim memory until we are below our threshold.
2999 *
3000 * Note that this function tends to free circuits, conflux join points,
3001 * and other structures. Do not call it while holding live references
3002 * to such objects. */
3003void
3009
3010/** Return true if we've been under memory pressure in the last
3011 * MEMORY_PRESSURE_INTERVAL seconds. */
3012bool
3018
3019/**
3020 * Update the number of cells available on the circuit's n_chan or p_chan's
3021 * circuit mux.
3022 */
3023void
3025 const char *file, int lineno)
3026{
3027 channel_t *chan = NULL;
3028 or_circuit_t *or_circ = NULL;
3029 circuitmux_t *cmux = NULL;
3030
3031 tor_assert(circ);
3032
3033 /* Okay, get the channel */
3034 if (direction == CELL_DIRECTION_OUT) {
3035 chan = circ->n_chan;
3036 } else {
3037 or_circ = TO_OR_CIRCUIT(circ);
3038 chan = or_circ->p_chan;
3039 }
3040
3041 tor_assert(chan);
3042 tor_assert(chan->cmux);
3043
3044 /* Now get the cmux */
3045 cmux = chan->cmux;
3046
3047 /* Cmux sanity check */
3048 if (! circuitmux_is_circuit_attached(cmux, circ)) {
3049 log_warn(LD_BUG, "called on non-attached circuit from %s:%d",
3050 file, lineno);
3051 return;
3052 }
3053 tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
3054
3055 /* Update the number of cells we have for the circuit mux */
3056 if (direction == CELL_DIRECTION_OUT) {
3057 circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
3058 } else {
3059 circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
3060 }
3061}
3062
3063/** Remove all circuits from the cmux on <b>chan</b>.
3064 *
3065 * If <b>circuits_out</b> is non-NULL, add all detached circuits to
3066 * <b>circuits_out</b>.
3067 **/
3068void
3070{
3071 tor_assert(chan);
3072 tor_assert(chan->cmux);
3073
3074 circuitmux_detach_all_circuits(chan->cmux, circuits_out);
3075 chan->num_n_circuits = 0;
3076 chan->num_p_circuits = 0;
3077}
3078
3079/**
3080 * Called when a circuit becomes blocked or unblocked due to the channel
3081 * cell queue.
3082 *
3083 * Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
3084 * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
3085 * and start or stop reading as appropriate.
3086 */
3087static void
3089{
3090 edge_connection_t *edge = NULL;
3091 if (circ->n_chan == chan) {
3092 circ->circuit_blocked_on_n_chan = block;
3093 if (CIRCUIT_IS_ORIGIN(circ))
3094 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
3095 } else {
3096 circ->circuit_blocked_on_p_chan = block;
3098 edge = TO_OR_CIRCUIT(circ)->n_streams;
3099 }
3100
3101 set_block_state_for_streams(circ, edge, block, 0);
3102}
3103
3104/**
3105 * Helper function to block or unblock streams in a stream list.
3106 *
3107 * If <b>stream_id</b> is 0, apply the <b>block</b> state to all streams
3108 * in the stream list. If it is non-zero, only apply to that specific stream.
3109 */
3110static void
3112 int block, streamid_t stream_id)
3113{
3114 /* If we have a conflux object, we need to examine its status before
3115 * blocking and unblocking streams. */
3116 if (circ->conflux) {
3117 bool can_send = conflux_can_send(circ->conflux);
3118
3119 if (block && can_send) {
3120 /* Don't actually block streams, since conflux can send*/
3121 return;
3122 } else if (!block && !can_send) {
3123 /* Don't actually unblock streams, since conflux still can't send */
3124 return;
3125 }
3126 }
3127
3128 for (edge_connection_t *edge = stream_list; edge; edge = edge->next_stream) {
3129 connection_t *conn = TO_CONN(edge);
3130 if (stream_id && edge->stream_id != stream_id)
3131 continue;
3132
3133 if (!conn->read_event || edge->xoff_received ||
3134 conn->marked_for_close) {
3135 /* This connection should not start or stop reading. */
3136 continue;
3137 }
3138
3139 if (block) {
3140 if (connection_is_reading(conn))
3142 } else {
3143 /* Is this right? */
3144 if (!connection_is_reading(conn))
3146 }
3147 }
3148}
3149
3150/** Extract the command from a packed cell. */
3151uint8_t
3152packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
3153{
3154 if (wide_circ_ids) {
3155 return get_uint8(cell->body+4);
3156 } else {
3157 return get_uint8(cell->body+2);
3158 }
3159}
3160
3161/** Extract the circuit ID from a packed cell. */
3163packed_cell_get_circid(const packed_cell_t *cell, int wide_circ_ids)
3164{
3165 if (wide_circ_ids) {
3166 return ntohl(get_uint32(cell->body));
3167 } else {
3168 return ntohs(get_uint16(cell->body));
3169 }
3170}
3171
3172/** Pull as many cells as possible (but no more than <b>max</b>) from the
3173 * queue of the first active circuit on <b>chan</b>, and write them to
3174 * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
3175 * the active circuit pointer to the next active circuit in the ring. */
3176MOCK_IMPL(int,
3178{
3179 circuitmux_t *cmux = NULL;
3180 int n_flushed = 0;
3181 cell_queue_t *queue;
3182 destroy_cell_queue_t *destroy_queue=NULL;
3183 circuit_t *circ;
3184 or_circuit_t *or_circ;
3185 int circ_blocked;
3186 packed_cell_t *cell;
3187
3188 /* Get the cmux */
3189 tor_assert(chan);
3190 tor_assert(chan->cmux);
3191 cmux = chan->cmux;
3192
3193 /* Main loop: pick a circuit, send a cell, update the cmux */
3194 while (n_flushed < max) {
3195 circ = circuitmux_get_first_active_circuit(cmux, &destroy_queue);
3196 if (destroy_queue) {
3197 destroy_cell_t *dcell;
3198 /* this code is duplicated from some of the logic below. Ugly! XXXX */
3199 /* If we are given a destroy_queue here, then it is required to be
3200 * nonempty... */
3201 tor_assert(destroy_queue->n > 0);
3202 dcell = destroy_cell_queue_pop(destroy_queue);
3203 /* ...and pop() will always yield a cell from a nonempty queue. */
3204 tor_assert(dcell);
3205 /* frees dcell */
3206 cell = destroy_cell_to_packed_cell(dcell, chan->wide_circ_ids);
3207 /* Send the DESTROY cell. It is very unlikely that this fails but just
3208 * in case, get rid of the channel. */
3209 if (channel_write_packed_cell(chan, cell) < 0) {
3210 /* The cell has been freed. */
3212 continue;
3213 }
3214 /* Update the cmux destroy counter */
3216 cell = NULL;
3217 ++n_flushed;
3218 continue;
3219 }
3220 /* If it returns NULL, no cells left to send */
3221 if (!circ) break;
3222
3223 if (circ->n_chan == chan) {
3224 queue = &circ->n_chan_cells;
3225 circ_blocked = circ->circuit_blocked_on_n_chan;
3226 } else {
3227 or_circ = TO_OR_CIRCUIT(circ);
3228 tor_assert(or_circ->p_chan == chan);
3229 queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
3230 circ_blocked = circ->circuit_blocked_on_p_chan;
3231 }
3232
3233 /* Circuitmux told us this was active, so it should have cells.
3234 *
3235 * Note: In terms of logic and coherence, this should never happen but the
3236 * cmux dragon is powerful. Reason is that when the OOM is triggered, when
3237 * cleaning up circuits, we mark them for close and then clear their cell
3238 * queues. And so, we can have a circuit considered active by the cmux
3239 * dragon but without cells. The cmux subsystem is only notified of this
3240 * when the circuit is freed which leaves a tiny window between close and
3241 * free to end up here.
3242 *
3243 * We are accepting this as an "ok" race else the changes are likely non
3244 * trivial to make the mark for close to set the num cells to 0 and change
3245 * the free functions to detach the circuit conditionally without creating
3246 * a chain effect of madness.
3247 *
3248 * The lesson here is arti will prevail and leave the cmux dragon alone. */
3249 if (queue->n == 0) {
3250 circuitmux_set_num_cells(cmux, circ, 0);
3251 if (! circ->marked_for_close)
3252 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
3253 continue;
3254 }
3255
3256 tor_assert(queue->n > 0);
3257
3258 /*
3259 * Get just one cell here; once we've sent it, that can change the circuit
3260 * selection, so we have to loop around for another even if this circuit
3261 * has more than one.
3262 */
3263 cell = cell_queue_pop(queue);
3264
3265 /* Calculate the exact time that this cell has spent in the queue. */
3266 if (get_options()->CellStatistics ||
3267 get_options()->TestingEnableCellStatsEvent) {
3268 uint32_t timestamp_now = monotime_coarse_get_stamp();
3269 uint32_t msec_waiting =
3271 timestamp_now - cell->inserted_timestamp);
3272
3273 if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
3274 or_circ = TO_OR_CIRCUIT(circ);
3275 or_circ->total_cell_waiting_time += msec_waiting;
3276 or_circ->processed_cells++;
3277 }
3278
3279 if (get_options()->TestingEnableCellStatsEvent) {
3280 uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
3281
3283 tor_malloc_zero(sizeof(testing_cell_stats_entry_t));
3284 ent->command = command;
3285 ent->waiting_time = msec_waiting / 10;
3286 ent->removed = 1;
3287 if (circ->n_chan == chan)
3288 ent->exitward = 1;
3289 if (!circ->testing_cell_stats)
3292 }
3293 }
3294
3295 /* If we just flushed our queue and this circuit is used for a
3296 * tunneled directory request, possibly advance its state. */
3297 if (queue->n == 0 && chan->dirreq_id)
3298 geoip_change_dirreq_state(chan->dirreq_id,
3299 DIRREQ_TUNNELED,
3301
3302 /* Now send the cell. It is very unlikely that this fails but just in
3303 * case, get rid of the channel. */
3304 if (channel_write_packed_cell(chan, cell) < 0) {
3305 /* The cell has been freed at this point. */
3307 continue;
3308 }
3309 cell = NULL;
3310
3311 /*
3312 * Don't packed_cell_free_unchecked(cell) here because the channel will
3313 * do so when it gets out of the channel queue (probably already did, in
3314 * which case that was an immediate double-free bug).
3315 */
3316
3317 /* Update the counter */
3318 ++n_flushed;
3319
3320 /*
3321 * Now update the cmux; tell it we've just sent a cell, and how many
3322 * we have left.
3323 */
3324 circuitmux_notify_xmit_cells(cmux, circ, 1);
3325 circuitmux_set_num_cells(cmux, circ, queue->n);
3326 if (queue->n == 0)
3327 log_debug(LD_GENERAL, "Made a circuit inactive.");
3328
3329 /* Is the cell queue low enough to unblock all the streams that are waiting
3330 * to write to this circuit? */
3331 if (circ_blocked && queue->n <= cell_queue_lowwatermark())
3332 set_circuit_blocked_on_chan(circ, chan, 0); /* unblock streams */
3333
3334 /* If n_flushed < max still, loop around and pick another circuit */
3335 }
3336
3337 /* Okay, we're done sending now */
3338 return n_flushed;
3339}
3340
3341/* Minimum value is the maximum circuit window size.
3342 *
3343 * This value is set to a lower bound we believe is reasonable with congestion
3344 * control and basic network running parameters.
3345 *
3346 * SENDME cells makes it that we can control how many cells can be inflight on
3347 * a circuit from end to end. This logic makes it that on any circuit cell
3348 * queue, we have a maximum of cells possible.
3349 *
3350 * Because the Tor protocol allows for a client to exit at any hop in a
3351 * circuit and a circuit can be of a maximum of 8 hops, so in theory the
3352 * normal worst case will be the circuit window start value times the maximum
3353 * number of hops (8). Having more cells then that means something is wrong.
3354 *
3355 * However, because padding cells aren't counted in the package window, we set
3356 * the maximum size to a reasonably large size for which we expect that we'll
3357 * never reach in theory. And if we ever do because of future changes, we'll
3358 * be able to control it with a consensus parameter.
3359 *
3360 * XXX: Unfortunately, END cells aren't accounted for in the circuit window
3361 * which means that for instance if a client opens 8001 streams, the 8001
3362 * following END cells will queue up in the circuit which will get closed if
3363 * the max limit is 8000. Which is sad because it is allowed by the Tor
3364 * protocol. But, we need an upper bound on circuit queue in order to avoid
3365 * DoS memory pressure so the default size is a middle ground between not
3366 * having any limit and having a very restricted one. This is why we can also
3367 * control it through a consensus parameter. */
3368#define RELAY_CIRC_CELL_QUEUE_SIZE_MIN 50
3369/* We can't have a consensus parameter above this value. */
3370#define RELAY_CIRC_CELL_QUEUE_SIZE_MAX INT32_MAX
3371/* Default value is set to a large value so we can handle padding cells
3372 * properly which aren't accounted for in the SENDME window. Default is 2500
3373 * allowed cells in the queue resulting in ~1MB. */
3374#define RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT \
3375 (50 * RELAY_CIRC_CELL_QUEUE_SIZE_MIN)
3376
3377/* The maximum number of cells a circuit queue can contain. This is updated at
3378 * every new consensus and controlled by a parameter. */
3379static int32_t max_circuit_cell_queue_size =
3380 RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT;
3381/** Maximum number of cell on an outbound circuit queue. This is updated at
3382 * every new consensus and controlled by a parameter. This default is incorrect
3383 * and won't be used at all except in unit tests. */
3385 RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT;
3386
3387/** Return consensus parameter "circ_max_cell_queue_size". The given ns can be
3388 * NULL. */
3389static uint32_t
3391{
3392 return networkstatus_get_param(ns, "circ_max_cell_queue_size",
3393 RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT,
3394 RELAY_CIRC_CELL_QUEUE_SIZE_MIN,
3395 RELAY_CIRC_CELL_QUEUE_SIZE_MAX);
3396}
3397
3398/** Return consensus parameter "circ_max_cell_queue_size_out". The given ns can
3399 * be NULL. */
3400static uint32_t
3402{
3403 return networkstatus_get_param(ns, "circ_max_cell_queue_size_out",
3405 RELAY_CIRC_CELL_QUEUE_SIZE_MIN,
3406 RELAY_CIRC_CELL_QUEUE_SIZE_MAX);
3407}
3408
3409/* Called when the consensus has changed. At this stage, the global consensus
3410 * object has NOT been updated. It is called from
3411 * notify_before_networkstatus_changes(). */
3412void
3413relay_consensus_has_changed(const networkstatus_t *ns)
3414{
3415 tor_assert(ns);
3416
3417 /* Update the circuit max cell queue size from the consensus. */
3418 max_circuit_cell_queue_size =
3422}
3423
3424/** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
3425 * transmitting in <b>direction</b>.
3426 *
3427 * The given <b>cell</b> is copied onto the circuit queue so the caller must
3428 * cleanup the memory.
3429 *
3430 * This function is part of the fast path.
3431 *
3432 * Return 1 if the cell was successfully sent.
3433 * Return 0 if the cell can not be sent. The caller MUST NOT close the circuit.
3434 * Return -1 indicating an error and that the caller should mark the circuit
3435 * for close. */
3436int
3438 cell_t *cell, cell_direction_t direction,
3439 streamid_t fromstream)
3440{
3441 or_circuit_t *orcirc = NULL;
3442 edge_connection_t *stream_list = NULL;
3443 cell_queue_t *queue;
3444 int32_t max_queue_size;
3445 int circ_blocked;
3446 int exitward;
3447 if (circ->marked_for_close) {
3448 return 0;
3449 }
3450
3451 exitward = (direction == CELL_DIRECTION_OUT);
3452 if (exitward) {
3453 queue = &circ->n_chan_cells;
3454 circ_blocked = circ->circuit_blocked_on_n_chan;
3455 max_queue_size = max_circuit_cell_queue_size_out;
3456 if (CIRCUIT_IS_ORIGIN(circ))
3457 stream_list = TO_ORIGIN_CIRCUIT(circ)->p_streams;
3458 } else {
3459 orcirc = TO_OR_CIRCUIT(circ);
3460 queue = &orcirc->p_chan_cells;
3461 circ_blocked = circ->circuit_blocked_on_p_chan;
3462 max_queue_size = max_circuit_cell_queue_size;
3463 stream_list = TO_OR_CIRCUIT(circ)->n_streams;
3464 }
3465
3466 if (PREDICT_UNLIKELY(queue->n >= max_queue_size)) {
3467 /* This DoS defense only applies at the Guard as in the p_chan is likely
3468 * a client IP attacking the network. */
3469 if (exitward && CIRCUIT_IS_ORCIRC(circ)) {
3470 stats_n_circ_max_cell_outq_reached++;
3471 dos_note_circ_max_outq(CONST_TO_OR_CIRCUIT(circ)->p_chan);
3472 }
3473
3474 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3475 "%s circuit has %d cells in its queue, maximum allowed is %d. "
3476 "Closing circuit for safety reasons.",
3477 (exitward) ? "Outbound" : "Inbound", queue->n,
3478 max_queue_size);
3480 return -1;
3481 }
3482
3483 /* Very important that we copy to the circuit queue because all calls to
3484 * this function use the stack for the cell memory. */
3485 cell_queue_append_packed_copy(circ, queue, exitward, cell,
3486 chan->wide_circ_ids, 1);
3487
3488 /* Check and run the OOM if needed. */
3489 if (PREDICT_UNLIKELY(cell_queues_check_size())) {
3490 /* We ran the OOM handler which might have closed this circuit. */
3491 if (circ->marked_for_close) {
3492 return 0;
3493 }
3494 }
3495
3496 /* If we have too many cells on the circuit, note that it should
3497 * be blocked from new cells. */
3498 if (!circ_blocked && queue->n >= cell_queue_highwatermark())
3499 set_circuit_blocked_on_chan(circ, chan, 1);
3500
3501 if (circ_blocked && fromstream) {
3502 /* This edge connection is apparently not blocked; this can happen for
3503 * new streams on a blocked circuit, for their CONNECTED response.
3504 * block it now, unless we have conflux. */
3505 set_block_state_for_streams(circ, stream_list, 1, fromstream);
3506 }
3507
3508 update_circuit_on_cmux(circ, direction);
3509 if (queue->n == 1) {
3510 /* This was the first cell added to the queue. We just made this
3511 * circuit active. */
3512 log_debug(LD_GENERAL, "Made a circuit active.");
3513 }
3514
3515 /* New way: mark this as having waiting cells for the scheduler */
3517 return 1;
3518}
3519
3520/** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
3521 * have at least 18 bytes of free space. The encoding is, as specified in
3522 * tor-spec.txt:
3523 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
3524 * LENGTH [1 byte]
3525 * ADDRESS [length bytes]
3526 * Return the number of bytes added, or -1 on error */
3527int
3528append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
3529{
3530 uint32_t a;
3531 switch (tor_addr_family(addr)) {
3532 case AF_INET:
3533 payload_out[0] = RESOLVED_TYPE_IPV4;
3534 payload_out[1] = 4;
3535 a = tor_addr_to_ipv4n(addr);
3536 memcpy(payload_out+2, &a, 4);
3537 return 6;
3538 case AF_INET6:
3539 payload_out[0] = RESOLVED_TYPE_IPV6;
3540 payload_out[1] = 16;
3541 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
3542 return 18;
3543 case AF_UNSPEC:
3544 default:
3545 return -1;
3546 }
3547}
3548
3549/** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
3550 * encoded as by append_address_to_payload(), try to decode the address into
3551 * *<b>addr_out</b>. Return the next byte in the payload after the address on
3552 * success, or NULL on failure. */
3553const uint8_t *
3554decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
3555 int payload_len)
3556{
3557 if (payload_len < 2)
3558 return NULL;
3559 if (payload_len < 2+payload[1])
3560 return NULL;
3561
3562 switch (payload[0]) {
3563 case RESOLVED_TYPE_IPV4:
3564 if (payload[1] != 4)
3565 return NULL;
3566 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
3567 break;
3568 case RESOLVED_TYPE_IPV6:
3569 if (payload[1] != 16)
3570 return NULL;
3571 tor_addr_from_ipv6_bytes(addr_out, (payload+2));
3572 break;
3573 default:
3574 tor_addr_make_unspec(addr_out);
3575 break;
3576 }
3577 return payload + 2 + payload[1];
3578}
3579
3580/** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
3581void
3583{
3584 cell_queue_t *queue;
3585 cell_direction_t direction;
3586
3587 if (circ->n_chan == chan) {
3588 queue = &circ->n_chan_cells;
3589 direction = CELL_DIRECTION_OUT;
3590 } else {
3591 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
3592 tor_assert(orcirc->p_chan == chan);
3593 queue = &orcirc->p_chan_cells;
3594 direction = CELL_DIRECTION_IN;
3595 }
3596
3597 /* Clear the queue */
3598 cell_queue_clear(queue);
3599
3600 /* Update the cell counter in the cmux */
3601 if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
3602 update_circuit_on_cmux(circ, direction);
3603}
3604
3605/** Return 1 if we shouldn't restart reading on this circuit, even if
3606 * we get a SENDME. Else return 0.
3607*/
3608static int
3610{
3611 if (CIRCUIT_IS_ORIGIN(circ)) {
3612 return circ->circuit_blocked_on_n_chan;
3613 } else {
3614 return circ->circuit_blocked_on_p_chan;
3615 }
3616}
3617
3618/** Return the format to use.
3619 *
3620 * NULL can be passed but not for both. */
3623{
3624 if (circ && CIRCUIT_IS_ORCIRC(circ)) {
3625 return CONST_TO_OR_CIRCUIT(circ)->relay_cell_format;
3626 } else if (cpath) {
3627 return cpath->relay_cell_format;
3628 } else {
3629 /* We end up here when both params are NULL, which is not allowed, or when
3630 * only an origin circuit is given (which again is not allowed). */
3631 tor_assert_unreached();
3632 }
3633}
3634
3635/**
3636 * Return the maximum relay payload that can be sent to the chosen
3637 * point, with the specified command.
3638 */
3639size_t
3641 uint8_t relay_command)
3642{
3643 relay_cell_fmt_t fmt = circuit_get_relay_format(circ, cpath);
3644 return relay_cell_max_payload_size(fmt, relay_command);
3645}
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition address.c:889
void tor_addr_make_unspec(tor_addr_t *a)
Definition address.c:225
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition address.c:1349
int tor_addr_is_null(const tor_addr_t *addr)
Definition address.c:780
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition address.c:328
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const uint8_t *ipv6_bytes)
Definition address.c:900
static uint32_t tor_addr_to_ipv4n(const tor_addr_t *a)
Definition address.h:154
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:189
#define tor_addr_to_in6_addr8(x)
Definition address.h:137
#define tor_addr_from_ipv4h(dest, v4addr)
Definition address.h:329
#define fmt_addr(a)
Definition address.h:241
#define TOR_ADDR_BUF_LEN
Definition address.h:226
int client_dns_incr_failures(const char *address)
Definition addressmap.c:638
void client_dns_set_addressmap(entry_connection_t *for_conn, const char *address, const tor_addr_t *val, const char *exitname, int ttl)
Definition addressmap.c:728
void client_dns_clear_failures(const char *address)
Definition addressmap.c:660
Header for addressmap.c.
time_t approx_time(void)
Definition approx_time.c:32
Header for backtrace.c.
buf_t * buf_new(void)
Definition buffers.c:365
int buf_add(buf_t *buf, const char *string, size_t string_len)
Definition buffers.c:527
size_t buf_datalen(const buf_t *buf)
Definition buffers.c:394
int buf_get_bytes(buf_t *buf, char *string, size_t string_len)
Definition buffers.c:637
Header file for buffers.c.
static void set_uint16(void *cp, uint16_t v)
Definition bytes.h:78
static uint16_t get_uint16(const void *cp)
Definition bytes.h:42
static uint8_t get_uint8(const void *cp)
Definition bytes.h:23
static void set_uint8(void *cp, uint8_t v)
Definition bytes.h:31
static uint32_t get_uint32(const void *cp)
Definition bytes.h:54
Cell queue structures.
Fixed-size cell structure.
void channel_timestamp_client(channel_t *chan)
Definition channel.c:3267
int channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
Definition channel.c:2100
int channel_is_client(const channel_t *chan)
Definition channel.c:2987
void channel_mark_for_close(channel_t *chan)
Definition channel.c:1150
int channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
Definition channel.c:1544
Header file for channel.c.
void pathbias_count_valid_cells(circuit_t *circ, const relay_msg_t *msg)
int pathbias_check_probe_response(circuit_t *circ, const relay_msg_t *msg)
void pathbias_mark_use_success(origin_circuit_t *circ)
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
int circuit_send_next_onion_skin(origin_circuit_t *circ)
int circuit_finish_handshake(origin_circuit_t *circ, const created_cell_t *reply)
int circuit_truncated(origin_circuit_t *circ, int reason)
Header file for circuitbuild.c.
int circuit_extend(const relay_msg_t *rmsg, struct circuit_t *circ)
Header for feature/relay/circuitbuild_relay.c.
void circuit_synchronize_written_or_bandwidth(const circuit_t *c, circuit_channel_direction_t dir)
void circuit_set_n_circid_chan(circuit_t *circ, circid_t id, channel_t *chan)
void circuit_set_state(circuit_t *circ, uint8_t state)
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
void assert_circuit_ok(const circuit_t *c)
const char * circuit_state_to_string(int state)
size_t circuits_handle_oom(size_t current_allocation)
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
smartlist_t * circuit_get_global_list(void)
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_PATH_BIAS_TESTING
#define CIRCUIT_STATE_OPEN
Definition circuitlist.h:32
#define CIRCUIT_IS_ORCIRC(c)
#define CIRCUIT_IS_ORIGIN(c)
#define CIRCUIT_PURPOSE_OR
Definition circuitlist.h:39
#define CIRCUIT_PURPOSE_S_REND_JOINED
#define CIRCUIT_PURPOSE_REND_ESTABLISHED
Definition circuitlist.h:47
cell_direction_t circuitmux_attached_circuit_direction(circuitmux_t *cmux, circuit_t *circ)
Definition circuitmux.c:549
void circuitmux_notify_xmit_destroy(circuitmux_t *cmux)
void circuitmux_detach_all_circuits(circuitmux_t *cmux, smartlist_t *detached_out)
Definition circuitmux.c:214
void circuitmux_notify_xmit_cells(circuitmux_t *cmux, circuit_t *circ, unsigned int n_cells)
int circuitmux_is_circuit_attached(circuitmux_t *cmux, circuit_t *circ)
Definition circuitmux.c:627
void circuitmux_set_num_cells(circuitmux_t *cmux, circuit_t *circ, unsigned int n_cells)
Definition circuitmux.c:999
circuit_t * circuitmux_get_first_active_circuit(circuitmux_t *cmux, destroy_cell_queue_t **destroy_queue_out)
int circpad_check_received_cell(const relay_msg_t *msg, circuit_t *circ, crypt_path_t *layer_hint)
void circpad_deliver_sent_relay_cell_events(circuit_t *circ, uint8_t relay_command)
void circpad_deliver_unrecognized_cell_events(circuit_t *circ, cell_direction_t dir)
void circpad_machine_event_circ_has_no_relay_early(origin_circuit_t *circ)
void circpad_deliver_recognized_relay_cell_events(circuit_t *circ, uint8_t relay_command, crypt_path_t *layer_hint)
Header file for circuitpadding.c.
void circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
void circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Header file for circuituse.c.
void tor_libevent_exit_loop_after_callback(struct event_base *base)
struct event_base * tor_libevent_get_base(void)
uint64_t monotime_coarse_stamp_units_to_approx_msec(uint64_t units)
uint32_t monotime_coarse_get_stamp(void)
size_t tor_compress_get_total_allocation(void)
Definition compress.c:488
Headers for compress.c.
const or_options_t * get_options(void)
Definition config.c:949
tor_cmdline_mode_t command
Definition config.c:2481
Header file for config.c.
void conflux_note_cell_sent(conflux_t *cfx, circuit_t *circ, uint8_t relay_command)
Definition conflux.c:578
bool conflux_should_multiplex(int relay_command)
Definition conflux.c:59
circuit_t * conflux_decide_next_circ(conflux_t *cfx)
Definition conflux.c:659
conflux_msg_t * conflux_dequeue_relay_msg(circuit_t *circ)
Definition conflux.c:967
circuit_t * conflux_decide_circ_for_send(conflux_t *cfx, circuit_t *orig_circ, uint8_t relay_command)
Definition conflux.c:489
bool conflux_process_relay_msg(conflux_t *cfx, circuit_t *in_circ, crypt_path_t *layer_hint, const relay_msg_t *msg)
Definition conflux.c:885
int conflux_process_switch_command(circuit_t *in_circ, crypt_path_t *layer_hint, const relay_msg_t *msg)
Definition conflux.c:787
size_t conflux_handle_oom(size_t bytes_to_remove)
Definition conflux.c:201
uint64_t conflux_get_total_bytes_allocation(void)
Definition conflux.c:194
Public APIs for conflux multipath support.
void conflux_process_linked_ack(circuit_t *circ)
void conflux_process_link(circuit_t *circ, const relay_msg_t *msg)
void conflux_process_linked(circuit_t *circ, crypt_path_t *layer_hint, const relay_msg_t *msg)
Header file for conflux_pool.c.
crypt_path_t * conflux_get_destination_hop(circuit_t *circ)
int circuit_get_package_window(circuit_t *circ, const crypt_path_t *cpath)
bool conflux_can_send(conflux_t *cfx)
bool relay_crypt_from_last_hop(const origin_circuit_t *circ, const crypt_path_t *layer_hint)
bool edge_uses_cpath(const edge_connection_t *conn, const crypt_path_t *cpath)
Header file for conflux_util.c.
int congestion_control_get_package_window(const circuit_t *circ, const crypt_path_t *cpath)
Public APIs for congestion control.
static int32_t cell_queue_highwatermark(void)
static int32_t cell_queue_lowwatermark(void)
bool circuit_process_stream_xoff(edge_connection_t *conn, const crypt_path_t *layer_hint)
bool circuit_process_stream_xon(edge_connection_t *conn, const crypt_path_t *layer_hint, const relay_msg_t *msg)
APIs for stream flow control on congestion controlled circuits.
int connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
int connection_state_is_open(connection_t *conn)
const char * conn_state_to_string(int type, int state)
Definition connection.c:301
Header file for connection.c.
#define CONN_TYPE_AP
Definition connection.h:51
#define CONN_TYPE_DIR
Definition connection.h:55
#define CONN_TYPE_EXIT
Definition connection.h:46
int connection_half_edge_is_valid_data(const smartlist_t *half_conns, streamid_t stream_id)
int connection_exit_begin_resolve(const relay_msg_t *msg, or_circuit_t *circ)
int connection_ap_detach_retriable(entry_connection_t *conn, origin_circuit_t *circ, int reason)
void connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply, size_t replylen, int endreason)
int connection_half_edge_is_valid_end(smartlist_t *half_conns, streamid_t stream_id)
void connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
int connection_half_edge_is_valid_connected(const smartlist_t *half_conns, streamid_t stream_id)
int connection_exit_begin_conn(const relay_msg_t *msg, circuit_t *circ)
entry_connection_t * EDGE_TO_ENTRY_CONN(edge_connection_t *c)
void connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn, const tor_addr_t *answer, int ttl, time_t expires)
int connection_half_edge_is_valid_resolved(smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
size_t half_streams_get_total_allocation(void)
int connection_half_edge_is_valid_sendme(const smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
void connection_ap_handshake_socks_resolved(entry_connection_t *conn, int answer_type, size_t answer_len, const uint8_t *answer, int ttl, time_t expires)
Header file for connection_edge.c.
#define EXIT_CONN_STATE_CONNECTING
#define AP_CONN_STATE_CONNECT_WAIT
#define AP_CONN_STATE_OPEN
#define AP_CONN_STATE_RESOLVE_WAIT
#define EXIT_CONN_STATE_RESOLVING
void cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
Header file for connection_or.c.
void control_event_boot_dir(bootstrap_status_t status, int progress)
void control_event_bootstrap(bootstrap_status_t status, int progress)
int control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp, int reason_code)
Header file for control_events.c.
#define REMAP_STREAM_SOURCE_EXIT
Circuit-build-stse structure.
Common functions for using (pseudo-)random number generators.
#define crypto_fast_rng_one_in_n(rng, n)
Definition crypto_rand.h:80
crypto_fast_rng_t * get_thread_fast_rng(void)
unsigned crypto_fast_rng_get_uint(crypto_fast_rng_t *rng, unsigned limit)
Common functions for cryptographic routines.
const char * node_describe(const node_t *node)
Definition describe.c:160
Header file for describe.c.
Destroy-cell queue structures.
Client/server directory connection structure.
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition directory.c:89
Header file for directory.c.
#define DIR_PURPOSE_FETCH_CERTIFICATE
Definition directory.h:57
#define DIR_PURPOSE_FETCH_MICRODESC
Definition directory.h:65
#define DIR_PURPOSE_FETCH_CONSENSUS
Definition directory.h:54
#define DIR_PURPOSE_FETCH_SERVERDESC
Definition directory.h:36
Header file for dns.c.
Entry connection structure.
#define ENTRY_TO_EDGE_CONN(c)
Extend-info structure.
Header for core/or/extendinfo.c.
Header file for geoip_stats.c.
@ DIRREQ_END_CELL_SENT
Definition geoip_stats.h:69
@ DIRREQ_CIRC_QUEUE_FLUSHED
Definition geoip_stats.h:72
uint64_t hs_cache_get_max_bytes(void)
Definition hs_cache.c:1260
size_t hs_cache_handle_oom(size_t min_remove_bytes)
Definition hs_cache.c:1191
Header file for hs_cache.c.
Header for feature/hs/hs_metrics.c.
#define hs_metrics_app_write_bytes(i, port, n)
Definition hs_metrics.h:47
uint16_t sa_family_t
Definition inaddr_st.h:77
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition log.c:591
Headers for log.c.
#define log_fn(severity, domain, args,...)
Definition log.h:283
#define LD_REND
Definition log.h:84
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition log.h:288
#define LD_APP
Definition log.h:78
#define LD_PROTOCOL
Definition log.h:72
#define LD_OR
Definition log.h:92
#define LD_MM
Definition log.h:74
#define LD_BUG
Definition log.h:86
#define LD_GENERAL
Definition log.h:62
#define LOG_NOTICE
Definition log.h:50
#define LOG_WARN
Definition log.h:53
#define LOG_INFO
Definition log.h:45
void connection_stop_reading(connection_t *conn)
Definition mainloop.c:614
void connection_start_reading(connection_t *conn)
Definition mainloop.c:636
int connection_is_reading(const connection_t *conn)
Definition mainloop.c:501
Header file for mainloop.c.
#define tor_free(p)
Definition malloc.h:56
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
int consensus_is_waiting_for_certs(void)
Header file for networkstatus.c.
int node_exit_policy_is_exact(const node_t *node, sa_family_t family)
Definition nodelist.c:1630
node_t * node_get_mutable_by_id(const char *identity_digest)
Definition nodelist.c:197
int count_loading_descriptors_progress(void)
Definition nodelist.c:2826
Header file for nodelist.c.
int extended_cell_parse(extended_cell_t *cell_out, const uint8_t command, const uint8_t *payload, size_t payload_len)
Definition onion.c:409
Header file for onion.c.
Master header file for Tor-specific functionality.
#define CELL_PAYLOAD_SIZE
Definition or.h:529
#define END_STREAM_REASON_CANT_ATTACH
Definition or.h:308
#define END_STREAM_REASON_FLAG_REMOTE
Definition or.h:339
uint32_t circid_t
Definition or.h:588
uint16_t streamid_t
Definition or.h:590
#define TO_CIRCUIT(x)
Definition or.h:951
#define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
Definition or.h:346
#define TO_CONN(c)
Definition or.h:709
cell_direction_t
Definition or.h:427
@ CELL_DIRECTION_OUT
Definition or.h:429
@ CELL_DIRECTION_IN
Definition or.h:428
#define RELAY_PAYLOAD_SIZE_MAX
Definition or.h:576
relay_cell_fmt_t
Definition or.h:538
#define END_CIRC_AT_ORIGIN
Definition or.h:370
#define ENTRY_TO_CONN(c)
Definition or.h:712
#define CIRCWINDOW_INCREMENT
Definition or.h:450
Origin circuit structure.
@ PATH_STATE_USE_FAILED
void addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
Definition policies.c:1617
void policies_set_node_exitpolicy_to_reject_all(node_t *node)
Definition policies.c:2196
Header file for policies.c.
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition ratelim.c:42
const char * stream_end_reason_to_string(int reason)
Definition reasons.c:68
Header file for reasons.c.
int channel_flush_from_first_active_circuit(channel_t *chan, int max)
Definition relay.c:3177
static int connection_edge_process_relay_cell_not_open(const relay_msg_t *msg, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint)
Definition relay.c:1411
void destroy_cell_queue_init(destroy_cell_queue_t *queue)
Definition relay.c:2801
void cell_queues_reclaim_memory(void)
Definition relay.c:3004
static int connection_ap_process_end_not_open(const relay_msg_t *msg, origin_circuit_t *circ, entry_connection_t *conn, crypt_path_t *layer_hint)
Definition relay.c:843
static int circuit_resume_edge_reading_helper(edge_connection_t *conn, circuit_t *circ, crypt_path_t *layer_hint)
Definition relay.c:2475
int append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
Definition relay.c:3528
STATIC int resolved_cell_parse(const relay_msg_t *msg, smartlist_t *addresses_out, int *errcode_out)
Definition relay.c:1167
uint64_t stats_n_data_cells_received
Definition relay.c:2219
void packed_cell_free_(packed_cell_t *cell)
Definition relay.c:2703
STATIC int connection_edge_process_resolved_cell(edge_connection_t *conn, const relay_msg_t *msg)
Definition relay.c:1337
void destroy_cell_queue_clear(destroy_cell_queue_t *queue)
Definition relay.c:2809
void destroy_cell_queue_append(destroy_cell_queue_t *queue, circid_t circid, uint8_t reason)
Definition relay.c:2835
relay_cell_fmt_t circuit_get_relay_format(const circuit_t *circ, const crypt_path_t *cpath)
Definition relay.c:3622
void channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
Definition relay.c:3069
int append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan, cell_t *cell, cell_direction_t direction, streamid_t fromstream)
Definition relay.c:3437
void cell_queue_append_packed_copy(circuit_t *circ, cell_queue_t *queue, int exitward, const cell_t *cell, int wide_circ_ids, int use_stats)
Definition relay.c:2751
uint64_t oom_stats_n_bytes_removed_dns
Definition relay.c:2887
static packed_cell_t * destroy_cell_to_packed_cell(destroy_cell_t *inp, int wide_circ_ids)
Definition relay.c:2851
void dump_cell_pool_usage(int severity)
Definition relay.c:2713
STATIC int connection_edge_process_relay_cell(const relay_msg_t *msg, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint)
Definition relay.c:2076
void circuit_reset_sendme_randomness(circuit_t *circ)
Definition relay.c:2231
uint64_t stats_n_relay_cells_relayed
Definition relay.c:137
size_t circuit_max_relay_payload(const circuit_t *circ, const crypt_path_t *cpath, uint8_t relay_command)
Definition relay.c:3640
uint64_t stats_n_circ_max_cell_reached
Definition relay.c:144
#define MAX_RESOLVE_FAILURES
Definition relay.c:823
static void remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
Definition relay.c:1095
static int circuit_queue_streams_are_blocked(circuit_t *circ)
Definition relay.c:3609
static void connection_ap_handshake_socks_got_resolved_cell(entry_connection_t *conn, int error_code, smartlist_t *results)
Definition relay.c:1263
static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ, entry_connection_t *conn, node_t *node, const tor_addr_t *addr)
Definition relay.c:1060
static void circuit_update_channel_usage(circuit_t *circ, cell_t *cell)
Definition relay.c:158
uint64_t stats_n_data_cells_packaged
Definition relay.c:2213
STATIC packed_cell_t * packed_cell_new(void)
Definition relay.c:2695
void cell_queue_clear(cell_queue_t *queue)
Definition relay.c:2775
void circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
Definition relay.c:3582
void cell_queue_init(cell_queue_t *queue)
Definition relay.c:2767
int circuit_package_relay_cell(cell_t *cell, circuit_t *circ, cell_direction_t cell_direction, crypt_path_t *layer_hint, streamid_t on_stream, const char *filename, int lineno)
Definition relay.c:390
STATIC packed_cell_t * cell_queue_pop(cell_queue_t *queue)
Definition relay.c:2789
uint64_t stats_n_data_bytes_received
Definition relay.c:2223
circid_t packed_cell_get_circid(const packed_cell_t *cell, int wide_circ_ids)
Definition relay.c:3163
static int connection_edge_process_ordered_relay_cell(const relay_msg_t *msg, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint)
Definition relay.c:2177
const uint8_t * decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload, int payload_len)
Definition relay.c:3554
static uint32_t get_param_max_circuit_cell_queue_size(const networkstatus_t *ns)
Definition relay.c:3390
void update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction, const char *file, int lineno)
Definition relay.c:3024
STATIC destroy_cell_t * destroy_cell_queue_pop(destroy_cell_queue_t *queue)
Definition relay.c:2823
bool mainloop_must_free_memory
Definition relay.c:2893
uint8_t packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
Definition relay.c:3152
uint64_t stats_n_relay_cells_delivered
Definition relay.c:141
STATIC int cell_queues_check_size(void)
Definition relay.c:2991
STATIC int connected_cell_parse(const relay_msg_t *msg, tor_addr_t *addr_out, int *ttl_out)
Definition relay.c:1115
static size_t total_cells_allocated
Definition relay.c:2683
static int32_t max_circuit_cell_queue_size_out
Definition relay.c:3384
bool have_been_under_memory_pressure(void)
Definition relay.c:3013
int relay_send_command_from_edge_(streamid_t stream_id, circuit_t *orig_circ, uint8_t relay_command, const char *payload, size_t payload_len, crypt_path_t *cpath_layer, const char *filename, int lineno)
Definition relay.c:583
static void packed_cell_free_unchecked(packed_cell_t *cell)
Definition relay.c:2687
static int edge_reason_is_retriable(int reason)
Definition relay.c:828
STATIC size_t connection_edge_get_inbuf_bytes_to_package(size_t n_available, int package_partial, circuit_t *on_circuit, crypt_path_t *cpath)
Definition relay.c:2244
static void circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
Definition relay.c:2445
static void set_circuit_blocked_on_chan(circuit_t *circ, channel_t *chan, int block)
Definition relay.c:3088
STATIC void address_ttl_free_(address_ttl_t *addr)
Definition relay.c:1153
static uint32_t get_param_max_circuit_cell_queue_size_out(const networkstatus_t *ns)
Definition relay.c:3401
STATIC int handle_relay_msg(const relay_msg_t *msg, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint, int optimistic_data)
Definition relay.c:1639
static int process_sendme_cell(const relay_msg_t *msg, circuit_t *circ, edge_connection_t *conn, crypt_path_t *layer_hint, int domain)
Definition relay.c:1563
const char * relay_command_to_string(uint8_t command)
Definition relay.c:528
#define MEMORY_PRESSURE_INTERVAL
Definition relay.c:2881
static void set_block_state_for_streams(circuit_t *circ, edge_connection_t *stream_list, int block, streamid_t stream_id)
Definition relay.c:3111
void cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
Definition relay.c:2740
static edge_connection_t * relay_lookup_conn(circuit_t *circ, const relay_msg_t *msg, cell_direction_t cell_direction, crypt_path_t *layer_hint)
Definition relay.c:453
static packed_cell_t * packed_cell_copy(const cell_t *cell, int wide_circ_ids)
Definition relay.c:2731
int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ, cell_direction_t cell_direction)
Definition relay.c:236
int connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial, int *max_cells)
Definition relay.c:2315
int connection_edge_send_command(edge_connection_t *fromconn, uint8_t relay_command, const char *payload, size_t payload_len)
Definition relay.c:766
uint64_t stats_n_data_bytes_packaged
Definition relay.c:2217
size_t packed_cell_mem_cost(void)
Definition relay.c:2868
static int cell_queues_check_reclaim_impl(bool reclaim_immediately)
Definition relay.c:2900
static time_t last_time_under_memory_pressure
Definition relay.c:2884
static int circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
Definition relay.c:2650
Header file for relay.c.
Header for relay_crypto.c.
int relay_msg_encode_cell(relay_cell_fmt_t format, const relay_msg_t *msg, cell_t *cell_out)
Definition relay_msg.c:225
int relay_msg_decode_cell_in_place(relay_cell_fmt_t format, const cell_t *cell, relay_msg_t *msg_out)
Definition relay_msg.c:254
Header file for relay_msg.c.
static size_t relay_cell_max_payload_size(relay_cell_fmt_t format, uint8_t relay_command)
Definition relay_msg.h:65
A relay message which contains a relay command and parameters, if any, that is from a relay cell.
void rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint, int command, size_t length, const uint8_t *payload)
Definition rendcommon.c:34
Header file for rendcommon.c.
void rep_hist_note_overload(overload_type_t overload)
Definition rephist.c:541
Header file for rephist.c.
Router descriptor structure.
#define ROUTER_PURPOSE_GENERAL
Header file for routerlist.c.
void scheduler_channel_has_waiting_cells(channel_t *chan)
Definition scheduler.c:548
Header file for scheduler*.c.
void sendme_connection_edge_consider_sending(edge_connection_t *conn)
Definition sendme.c:417
void sendme_circuit_consider_sending(circuit_t *circ, crypt_path_t *layer_hint)
Definition sendme.c:464
Header file for sendme.c.
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition smartlist.c:279
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
#define SMARTLIST_DEL_CURRENT(sl, var)
Client request structure.
#define SOCKS_COMMAND_RESOLVE_PTR
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition cell_st.h:21
uint8_t command
Definition cell_st.h:19
circid_t circ_id
Definition cell_st.h:18
unsigned int num_n_circuits
Definition channel.h:411
uint64_t dirreq_id
Definition channel.h:459
channel_usage_info_t channel_usage
Definition channel.h:229
circuitmux_t * cmux
Definition channel.h:398
int marked_for_close_reason
Definition circuit_st.h:217
uint8_t state
Definition circuit_st.h:111
unsigned int circuit_blocked_on_n_chan
Definition circuit_st.h:92
uint16_t send_randomness_after_n_cells
Definition circuit_st.h:128
struct create_cell_t * n_chan_create_cell
Definition circuit_st.h:173
unsigned int circuit_blocked_on_p_chan
Definition circuit_st.h:95
unsigned int have_sent_sufficiently_random_cell
Definition circuit_st.h:109
uint64_t dirreq_id
Definition circuit_st.h:224
cell_queue_t n_chan_cells
Definition circuit_st.h:82
uint16_t marked_for_close
Definition circuit_st.h:209
struct conflux_t * conflux
Definition circuit_st.h:282
uint8_t purpose
Definition circuit_st.h:112
const char * marked_for_close_file
Definition circuit_st.h:212
int package_window
Definition circuit_st.h:117
smartlist_t * testing_cell_stats
Definition circuit_st.h:232
struct timeval timestamp_created
Definition circuit_st.h:188
channel_t * n_chan
Definition circuit_st.h:70
extend_info_t * n_hop
Definition circuit_st.h:88
circid_t n_circ_id
Definition circuit_st.h:79
relay_msg_t * msg
Definition conflux.h:42
time_t timestamp_last_read_allowed
struct connection_t * linked_conn
unsigned int type
uint16_t marked_for_close
const char * marked_for_close_file
unsigned int purpose
tor_socket_t s
struct event * read_event
extend_info_t * chosen_exit
relay_cell_fmt_t relay_cell_format
struct crypt_path_t * cpath_layer
struct edge_connection_t * next_stream
unsigned int edge_has_sent_end
struct circuit_t * on_circuit
socks_request_t * socks_request
unsigned int chosen_exit_optional
unsigned int chosen_exit_retries
struct buf_t * pending_optimistic_data
char identity_digest[DIGEST_LEN]
created_cell_t created_cell
Definition onion.h:71
ed25519_public_key_t identity_pk
Definition hs_ident.h:112
uint16_t orig_virtual_port
Definition hs_ident.h:117
uint64_t total_cell_waiting_time
channel_t * p_chan
uint32_t n_cells_discarded_at_end
relay_cell_fmt_t relay_cell_format
circid_t p_circ_id
cell_queue_t p_chan_cells
struct or_circuit_t * rend_splice
edge_connection_t * n_streams
uint32_t processed_cells
edge_connection_t * p_streams
uint8_t relay_early_commands[MAX_RELAY_EARLY_CELLS_PER_CIRCUIT]
unsigned int remaining_relay_early_cells
path_state_bitfield_t path_state
smartlist_t * prepend_policy
crypt_path_t * cpath
cpath_build_state_t * build_state
smartlist_t * half_streams
uint32_t inserted_timestamp
char body[CELL_MAX_NETWORK_SIZE]
unsigned int has_finished
char address[MAX_SOCKS_ADDR_LEN]
Definition or.h:923
uint8_t command
Definition or.h:924
unsigned int waiting_time
Definition or.h:929
unsigned int exitward
Definition or.h:931
unsigned int removed
Definition or.h:930
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
#define tor_assert(expr)
Definition util_bug.h:103