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