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