when we get an unrecognized relay streamid, log it
[tor/rransom.git] / src / or / relay.c
blobb4592e85f8758f210f0a2520533d8ca5b226a639
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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file relay.c
9 * \brief Handle relay cell encryption/decryption, plus packaging and
10 * receiving from circuits, plus queueing on circuits.
11 **/
13 #include "or.h"
14 #include "mempool.h"
16 static int relay_crypt(circuit_t *circ, cell_t *cell,
17 cell_direction_t cell_direction,
18 crypt_path_t **layer_hint, char *recognized);
19 static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
20 cell_direction_t cell_direction,
21 crypt_path_t *layer_hint);
23 static int
24 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
25 edge_connection_t *conn,
26 crypt_path_t *layer_hint);
27 static void
28 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
29 static void
30 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
31 static int
32 circuit_resume_edge_reading_helper(edge_connection_t *conn,
33 circuit_t *circ,
34 crypt_path_t *layer_hint);
35 static int
36 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
38 /** Stats: how many relay cells have originated at this hop, or have
39 * been relayed onward (not recognized at this hop)?
41 uint64_t stats_n_relay_cells_relayed = 0;
42 /** Stats: how many relay cells have been delivered to streams at this
43 * hop?
45 uint64_t stats_n_relay_cells_delivered = 0;
47 /** Update digest from the payload of cell. Assign integrity part to
48 * cell.
50 static void
51 relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
53 char integrity[4];
54 relay_header_t rh;
56 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
57 crypto_digest_get_digest(digest, integrity, 4);
58 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
59 // integrity[0], integrity[1], integrity[2], integrity[3]);
60 relay_header_unpack(&rh, cell->payload);
61 memcpy(rh.integrity, integrity, 4);
62 relay_header_pack(cell->payload, &rh);
65 /** Does the digest for this circuit indicate that this cell is for us?
67 * Update digest from the payload of cell (with the integrity part set
68 * to 0). If the integrity part is valid, return 1, else restore digest
69 * and cell to their original state and return 0.
71 static int
72 relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
74 char received_integrity[4], calculated_integrity[4];
75 relay_header_t rh;
76 crypto_digest_env_t *backup_digest=NULL;
78 backup_digest = crypto_digest_dup(digest);
80 relay_header_unpack(&rh, cell->payload);
81 memcpy(received_integrity, rh.integrity, 4);
82 memset(rh.integrity, 0, 4);
83 relay_header_pack(cell->payload, &rh);
85 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
86 // received_integrity[0], received_integrity[1],
87 // received_integrity[2], received_integrity[3]);
89 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
90 crypto_digest_get_digest(digest, calculated_integrity, 4);
92 if (memcmp(received_integrity, calculated_integrity, 4)) {
93 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
94 // (%d vs %d).", received_integrity, calculated_integrity);
95 /* restore digest to its old form */
96 crypto_digest_assign(digest, backup_digest);
97 /* restore the relay header */
98 memcpy(rh.integrity, received_integrity, 4);
99 relay_header_pack(cell->payload, &rh);
100 crypto_free_digest_env(backup_digest);
101 return 0;
103 crypto_free_digest_env(backup_digest);
104 return 1;
107 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
108 * (in place).
110 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
112 * Return -1 if the crypto fails, else return 0.
114 static int
115 relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
116 int encrypt_mode)
118 int r;
119 (void)encrypt_mode;
120 r = crypto_cipher_crypt_inplace(cipher, in, CELL_PAYLOAD_SIZE);
122 if (r) {
123 log_warn(LD_BUG,"Error during relay encryption");
124 return -1;
126 return 0;
129 /** Receive a relay cell:
130 * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
131 * origin; decrypt if we're headed toward the exit).
132 * - Check if recognized (if exitward).
133 * - If recognized and the digest checks out, then find if there's a stream
134 * that the cell is intended for, and deliver it to the right
135 * connection_edge.
136 * - If not recognized, then we need to relay it: append it to the appropriate
137 * cell_queue on <b>circ</b>.
139 * Return -<b>reason</b> on failure.
142 circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
143 cell_direction_t cell_direction)
145 or_connection_t *or_conn=NULL;
146 crypt_path_t *layer_hint=NULL;
147 char recognized=0;
148 int reason;
150 tor_assert(cell);
151 tor_assert(circ);
152 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
153 cell_direction == CELL_DIRECTION_IN);
154 if (circ->marked_for_close)
155 return 0;
157 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
158 log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
159 return -END_CIRC_REASON_INTERNAL;
162 if (recognized) {
163 edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
164 layer_hint);
165 if (cell_direction == CELL_DIRECTION_OUT) {
166 ++stats_n_relay_cells_delivered;
167 log_debug(LD_OR,"Sending away from origin.");
168 if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
169 < 0) {
170 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
171 "connection_edge_process_relay_cell (away from origin) "
172 "failed.");
173 return reason;
176 if (cell_direction == CELL_DIRECTION_IN) {
177 ++stats_n_relay_cells_delivered;
178 log_debug(LD_OR,"Sending to origin.");
179 if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
180 layer_hint)) < 0) {
181 log_warn(LD_OR,
182 "connection_edge_process_relay_cell (at origin) failed.");
183 return reason;
186 return 0;
189 /* not recognized. pass it on. */
190 if (cell_direction == CELL_DIRECTION_OUT) {
191 cell->circ_id = circ->n_circ_id; /* switch it */
192 or_conn = circ->n_conn;
193 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
194 cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
195 or_conn = TO_OR_CIRCUIT(circ)->p_conn;
196 } else {
197 log_fn(LOG_PROTOCOL_WARN, LD_OR,
198 "Dropping unrecognized inbound cell on origin circuit.");
199 return 0;
202 if (!or_conn) {
203 // XXXX Can this splice stuff be done more cleanly?
204 if (! CIRCUIT_IS_ORIGIN(circ) &&
205 TO_OR_CIRCUIT(circ)->rend_splice &&
206 cell_direction == CELL_DIRECTION_OUT) {
207 or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
208 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
209 tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
210 cell->circ_id = splice->p_circ_id;
211 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
212 CELL_DIRECTION_IN)) < 0) {
213 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
214 "circuits");
215 /* XXXX Do this here, or just return -1? */
216 circuit_mark_for_close(circ, -reason);
217 return reason;
219 return 0;
221 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
222 "Didn't recognize cell, but circ stops here! Closing circ.");
223 return -END_CIRC_REASON_TORPROTOCOL;
226 log_debug(LD_OR,"Passing on unrecognized cell.");
228 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
229 * we might kill the circ before we relay
230 * the cells. */
232 append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
233 return 0;
236 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
237 * <b>circ</b> in direction <b>cell_direction</b>.
239 * If cell_direction == CELL_DIRECTION_IN:
240 * - If we're at the origin (we're the OP), for hops 1..N,
241 * decrypt cell. If recognized, stop.
242 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
244 * If cell_direction == CELL_DIRECTION_OUT:
245 * - decrypt one hop. Check if recognized.
247 * If cell is recognized, set *recognized to 1, and set
248 * *layer_hint to the hop that recognized it.
250 * Return -1 to indicate that we should mark the circuit for close,
251 * else return 0.
253 static int
254 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
255 crypt_path_t **layer_hint, char *recognized)
257 relay_header_t rh;
259 tor_assert(circ);
260 tor_assert(cell);
261 tor_assert(recognized);
262 tor_assert(cell_direction == CELL_DIRECTION_IN ||
263 cell_direction == CELL_DIRECTION_OUT);
265 if (cell_direction == CELL_DIRECTION_IN) {
266 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
267 * We'll want to do layered decrypts. */
268 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
269 thishop = cpath;
270 if (thishop->state != CPATH_STATE_OPEN) {
271 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
272 "Relay cell before first created cell? Closing.");
273 return -1;
275 do { /* Remember: cpath is in forward order, that is, first hop first. */
276 tor_assert(thishop);
278 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
279 return -1;
281 relay_header_unpack(&rh, cell->payload);
282 if (rh.recognized == 0) {
283 /* it's possibly recognized. have to check digest to be sure. */
284 if (relay_digest_matches(thishop->b_digest, cell)) {
285 *recognized = 1;
286 *layer_hint = thishop;
287 return 0;
291 thishop = thishop->next;
292 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
293 log_fn(LOG_PROTOCOL_WARN, LD_OR,
294 "Incoming cell at client not recognized. Closing.");
295 return -1;
296 } else { /* we're in the middle. Just one crypt. */
297 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
298 cell->payload, 1) < 0)
299 return -1;
300 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
301 // "the client.");
303 } else /* cell_direction == CELL_DIRECTION_OUT */ {
304 /* we're in the middle. Just one crypt. */
306 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
307 cell->payload, 0) < 0)
308 return -1;
310 relay_header_unpack(&rh, cell->payload);
311 if (rh.recognized == 0) {
312 /* it's possibly recognized. have to check digest to be sure. */
313 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
314 *recognized = 1;
315 return 0;
319 return 0;
322 /** Package a relay cell from an edge:
323 * - Encrypt it to the right layer
324 * - Append it to the appropriate cell_queue on <b>circ</b>.
326 static int
327 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
328 cell_direction_t cell_direction,
329 crypt_path_t *layer_hint)
331 or_connection_t *conn; /* where to send the cell */
333 if (cell_direction == CELL_DIRECTION_OUT) {
334 crypt_path_t *thishop; /* counter for repeated crypts */
335 conn = circ->n_conn;
336 if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
337 log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
338 return 0; /* just drop it */
341 relay_set_digest(layer_hint->f_digest, cell);
343 thishop = layer_hint;
344 /* moving from farthest to nearest hop */
345 do {
346 tor_assert(thishop);
347 /* XXXX RD This is a bug, right? */
348 log_debug(LD_OR,"crypting a layer of the relay cell.");
349 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
350 return -1;
353 thishop = thishop->prev;
354 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
356 } else { /* incoming cell */
357 or_circuit_t *or_circ;
358 if (CIRCUIT_IS_ORIGIN(circ)) {
359 /* We should never package an _incoming_ cell from the circuit
360 * origin; that means we messed up somewhere. */
361 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
362 assert_circuit_ok(circ);
363 return 0; /* just drop it */
365 or_circ = TO_OR_CIRCUIT(circ);
366 conn = or_circ->p_conn;
367 relay_set_digest(or_circ->p_digest, cell);
368 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
369 return -1;
371 ++stats_n_relay_cells_relayed;
373 append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
374 return 0;
377 /** If cell's stream_id matches the stream_id of any conn that's
378 * attached to circ, return that conn, else return NULL.
380 static edge_connection_t *
381 relay_lookup_conn(circuit_t *circ, cell_t *cell,
382 cell_direction_t cell_direction, crypt_path_t *layer_hint)
384 edge_connection_t *tmpconn;
385 relay_header_t rh;
387 relay_header_unpack(&rh, cell->payload);
389 if (!rh.stream_id)
390 return NULL;
392 /* IN or OUT cells could have come from either direction, now
393 * that we allow rendezvous *to* an OP.
396 if (CIRCUIT_IS_ORIGIN(circ)) {
397 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
398 tmpconn=tmpconn->next_stream) {
399 if (rh.stream_id == tmpconn->stream_id &&
400 !tmpconn->_base.marked_for_close &&
401 tmpconn->cpath_layer == layer_hint) {
402 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
403 return tmpconn;
406 } else {
407 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
408 tmpconn=tmpconn->next_stream) {
409 if (rh.stream_id == tmpconn->stream_id &&
410 !tmpconn->_base.marked_for_close) {
411 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
412 if (cell_direction == CELL_DIRECTION_OUT ||
413 connection_edge_is_rendezvous_stream(tmpconn))
414 return tmpconn;
417 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
418 tmpconn=tmpconn->next_stream) {
419 if (rh.stream_id == tmpconn->stream_id &&
420 !tmpconn->_base.marked_for_close) {
421 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
422 return tmpconn;
426 return NULL; /* probably a begin relay cell */
429 /** Pack the relay_header_t host-order structure <b>src</b> into
430 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
431 * about the wire format.
433 void
434 relay_header_pack(char *dest, const relay_header_t *src)
436 *(uint8_t*)(dest) = src->command;
438 set_uint16(dest+1, htons(src->recognized));
439 set_uint16(dest+3, htons(src->stream_id));
440 memcpy(dest+5, src->integrity, 4);
441 set_uint16(dest+9, htons(src->length));
444 /** Unpack the network-order buffer <b>src</b> into a host-order
445 * relay_header_t structure <b>dest</b>.
447 void
448 relay_header_unpack(relay_header_t *dest, const char *src)
450 dest->command = *(uint8_t*)(src);
452 dest->recognized = ntohs(get_uint16(src+1));
453 dest->stream_id = ntohs(get_uint16(src+3));
454 memcpy(dest->integrity, src+5, 4);
455 dest->length = ntohs(get_uint16(src+9));
458 /** Convert the relay <b>command</b> into a human-readable string. */
459 static const char *
460 relay_command_to_string(uint8_t command)
462 switch (command) {
463 case RELAY_COMMAND_BEGIN: return "BEGIN";
464 case RELAY_COMMAND_DATA: return "DATA";
465 case RELAY_COMMAND_END: return "END";
466 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
467 case RELAY_COMMAND_SENDME: return "SENDME";
468 case RELAY_COMMAND_EXTEND: return "EXTEND";
469 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
470 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
471 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
472 case RELAY_COMMAND_DROP: return "DROP";
473 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
474 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
475 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
476 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
477 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
478 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
479 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
480 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
481 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
482 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
483 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
484 return "RENDEZVOUS_ESTABLISHED";
485 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
486 default: return "(unrecognized)";
490 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
491 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
492 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
493 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
494 * destination hop for OP->OR cells.
496 * If you can't send the cell, mark the circuit for close and return -1. Else
497 * return 0.
500 relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
501 uint8_t relay_command, const char *payload,
502 size_t payload_len, crypt_path_t *cpath_layer)
504 cell_t cell;
505 relay_header_t rh;
506 cell_direction_t cell_direction;
507 /* XXXX NM Split this function into a separate versions per circuit type? */
509 tor_assert(circ);
510 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
512 memset(&cell, 0, sizeof(cell_t));
513 cell.command = CELL_RELAY;
514 if (cpath_layer) {
515 cell.circ_id = circ->n_circ_id;
516 cell_direction = CELL_DIRECTION_OUT;
517 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
518 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
519 cell_direction = CELL_DIRECTION_IN;
520 } else {
521 return -1;
524 memset(&rh, 0, sizeof(rh));
525 rh.command = relay_command;
526 rh.stream_id = stream_id;
527 rh.length = payload_len;
528 relay_header_pack(cell.payload, &rh);
529 if (payload_len)
530 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
532 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
533 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
535 if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
536 /* if we're using relaybandwidthrate, this conn wants priority */
537 circ->n_conn->client_used = approx_time();
540 if (cell_direction == CELL_DIRECTION_OUT) {
541 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
542 if (origin_circ->remaining_relay_early_cells > 0 &&
543 (relay_command == RELAY_COMMAND_EXTEND ||
544 cpath_layer != origin_circ->cpath)) {
545 /* If we've got any relay_early cells left, and we're sending a relay
546 * cell or we're not talking to the first hop, use one of them. Don't
547 * worry about the conn protocol version: append_cell_to_circuit_queue
548 * will fix it up. */
549 cell.command = CELL_RELAY_EARLY;
550 --origin_circ->remaining_relay_early_cells;
551 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
552 (int)origin_circ->remaining_relay_early_cells);
553 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
554 * task 878. */
555 origin_circ->relay_early_commands[
556 origin_circ->relay_early_cells_sent++] = relay_command;
557 } else if (relay_command == RELAY_COMMAND_EXTEND) {
558 /* If no RELAY_EARLY cells can be sent over this circuit, log which
559 * commands have been sent as RELAY_EARLY cells before; helps debug
560 * task 878. */
561 smartlist_t *commands_list = smartlist_create();
562 int i = 0;
563 char *commands = NULL;
564 for (; i < origin_circ->relay_early_cells_sent; i++)
565 smartlist_add(commands_list, (char *)
566 relay_command_to_string(origin_circ->relay_early_commands[i]));
567 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
568 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
569 "but we have run out of RELAY_EARLY cells on that circuit. "
570 "Commands sent before: %s", commands);
571 tor_free(commands);
572 smartlist_free(commands_list);
576 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
577 < 0) {
578 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
579 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
580 return -1;
582 return 0;
585 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
586 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
587 * that's sending the relay cell, or NULL if it's a control cell.
588 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
589 * for OP->OR cells.
591 * If you can't send the cell, mark the circuit for close and
592 * return -1. Else return 0.
595 connection_edge_send_command(edge_connection_t *fromconn,
596 uint8_t relay_command, const char *payload,
597 size_t payload_len)
599 /* XXXX NM Split this function into a separate versions per circuit type? */
600 circuit_t *circ;
601 tor_assert(fromconn);
602 circ = fromconn->on_circuit;
604 if (fromconn->_base.marked_for_close) {
605 log_warn(LD_BUG,
606 "called on conn that's already marked for close at %s:%d.",
607 fromconn->_base.marked_for_close_file,
608 fromconn->_base.marked_for_close);
609 return 0;
612 if (!circ) {
613 if (fromconn->_base.type == CONN_TYPE_AP) {
614 log_info(LD_APP,"no circ. Closing conn.");
615 connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
616 } else {
617 log_info(LD_EXIT,"no circ. Closing conn.");
618 fromconn->edge_has_sent_end = 1; /* no circ to send to */
619 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
620 connection_mark_for_close(TO_CONN(fromconn));
622 return -1;
625 return relay_send_command_from_edge(fromconn->stream_id, circ,
626 relay_command, payload,
627 payload_len, fromconn->cpath_layer);
630 /** How many times will I retry a stream that fails due to DNS
631 * resolve failure or misc error?
633 #define MAX_RESOLVE_FAILURES 3
635 /** Return 1 if reason is something that you should retry if you
636 * get the end cell before you've connected; else return 0. */
637 static int
638 edge_reason_is_retriable(int reason)
640 return reason == END_STREAM_REASON_HIBERNATING ||
641 reason == END_STREAM_REASON_RESOURCELIMIT ||
642 reason == END_STREAM_REASON_EXITPOLICY ||
643 reason == END_STREAM_REASON_RESOLVEFAILED ||
644 reason == END_STREAM_REASON_MISC;
647 /** Called when we receive an END cell on a stream that isn't open yet,
648 * from the client side.
649 * Arguments are as for connection_edge_process_relay_cell().
651 static int
652 connection_ap_process_end_not_open(
653 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
654 edge_connection_t *conn, crypt_path_t *layer_hint)
656 struct in_addr in;
657 routerinfo_t *exitrouter;
658 int reason = *(cell->payload+RELAY_HEADER_SIZE);
659 int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
660 (void) layer_hint; /* unused */
662 if (rh->length > 0 && edge_reason_is_retriable(reason) &&
663 !connection_edge_is_rendezvous_stream(conn) /* avoid retry if rend */
665 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
666 safe_str(conn->socks_request->address),
667 stream_end_reason_to_string(reason));
668 exitrouter =
669 router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
670 switch (reason) {
671 case END_STREAM_REASON_EXITPOLICY:
672 if (rh->length >= 5) {
673 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
674 int ttl;
675 if (!addr) {
676 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
677 safe_str(conn->socks_request->address));
678 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
679 return 0;
681 if (rh->length >= 9)
682 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
683 else
684 ttl = -1;
686 if (get_options()->ClientDNSRejectInternalAddresses &&
687 is_internal_IP(addr, 0)) {
688 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
689 safe_str(conn->socks_request->address));
690 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
691 return 0;
693 client_dns_set_addressmap(conn->socks_request->address, addr,
694 conn->chosen_exit_name, ttl);
696 /* check if he *ought* to have allowed it */
697 if (exitrouter &&
698 (rh->length < 5 ||
699 (tor_inet_aton(conn->socks_request->address, &in) &&
700 !conn->chosen_exit_name))) {
701 log_info(LD_APP,
702 "Exitrouter '%s' seems to be more restrictive than its exit "
703 "policy. Not using this router as exit for now.",
704 exitrouter->nickname);
705 policies_set_router_exitpolicy_to_reject_all(exitrouter);
707 /* rewrite it to an IP if we learned one. */
708 if (addressmap_rewrite(conn->socks_request->address,
709 sizeof(conn->socks_request->address),
710 NULL)) {
711 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
713 if (conn->chosen_exit_optional ||
714 conn->chosen_exit_retries) {
715 /* stop wanting a specific exit */
716 conn->chosen_exit_optional = 0;
717 /* A non-zero chosen_exit_retries can happen if we set a
718 * TrackHostExits for this address under a port that the exit
719 * relay allows, but then try the same address with a different
720 * port that it doesn't allow to exit. We shouldn't unregister
721 * the mapping, since it is probably still wanted on the
722 * original port. But now we give away to the exit relay that
723 * we probably have a TrackHostExits on it. So be it. */
724 conn->chosen_exit_retries = 0;
725 tor_free(conn->chosen_exit_name); /* clears it */
727 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
728 return 0;
729 /* else, conn will get closed below */
730 break;
731 case END_STREAM_REASON_CONNECTREFUSED:
732 if (!conn->chosen_exit_optional)
733 break; /* break means it'll close, below */
734 /* Else fall through: expire this circuit, clear the
735 * chosen_exit_name field, and try again. */
736 case END_STREAM_REASON_RESOLVEFAILED:
737 case END_STREAM_REASON_TIMEOUT:
738 case END_STREAM_REASON_MISC:
739 if (client_dns_incr_failures(conn->socks_request->address)
740 < MAX_RESOLVE_FAILURES) {
741 /* We haven't retried too many times; reattach the connection. */
742 circuit_log_path(LOG_INFO,LD_APP,circ);
743 tor_assert(circ->_base.timestamp_dirty);
744 circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
746 if (conn->chosen_exit_optional) {
747 /* stop wanting a specific exit */
748 conn->chosen_exit_optional = 0;
749 tor_free(conn->chosen_exit_name); /* clears it */
751 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
752 return 0;
753 /* else, conn will get closed below */
754 } else {
755 log_notice(LD_APP,
756 "Have tried resolving or connecting to address '%s' "
757 "at %d different places. Giving up.",
758 safe_str(conn->socks_request->address),
759 MAX_RESOLVE_FAILURES);
760 /* clear the failures, so it will have a full try next time */
761 client_dns_clear_failures(conn->socks_request->address);
763 break;
764 case END_STREAM_REASON_HIBERNATING:
765 case END_STREAM_REASON_RESOURCELIMIT:
766 if (exitrouter) {
767 policies_set_router_exitpolicy_to_reject_all(exitrouter);
769 if (conn->chosen_exit_optional) {
770 /* stop wanting a specific exit */
771 conn->chosen_exit_optional = 0;
772 tor_free(conn->chosen_exit_name); /* clears it */
774 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
775 return 0;
776 /* else, will close below */
777 break;
778 } /* end switch */
779 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
782 log_info(LD_APP,
783 "Edge got end (%s) before we're connected. Marking for close.",
784 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
785 circuit_log_path(LOG_INFO,LD_APP,circ);
786 /* need to test because of detach_retriable*/
787 if (!conn->_base.marked_for_close)
788 connection_mark_unattached_ap(conn, control_reason);
789 return 0;
792 /** Helper: change the socks_request-&gt;address field on conn to the
793 * dotted-quad representation of <b>new_addr</b> (given in host order),
794 * and send an appropriate REMAP event. */
795 static void
796 remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
798 struct in_addr in;
800 in.s_addr = htonl(new_addr);
801 tor_inet_ntoa(&in, conn->socks_request->address,
802 sizeof(conn->socks_request->address));
803 control_event_stream_status(conn, STREAM_EVENT_REMAP,
804 REMAP_STREAM_SOURCE_EXIT);
807 /** An incoming relay cell has arrived from circuit <b>circ</b> to
808 * stream <b>conn</b>.
810 * The arguments here are the same as in
811 * connection_edge_process_relay_cell() below; this function is called
812 * from there when <b>conn</b> is defined and not in an open state.
814 static int
815 connection_edge_process_relay_cell_not_open(
816 relay_header_t *rh, cell_t *cell, circuit_t *circ,
817 edge_connection_t *conn, crypt_path_t *layer_hint)
819 if (rh->command == RELAY_COMMAND_END) {
820 if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
821 return connection_ap_process_end_not_open(rh, cell,
822 TO_ORIGIN_CIRCUIT(circ), conn,
823 layer_hint);
824 } else {
825 /* we just got an 'end', don't need to send one */
826 conn->edge_has_sent_end = 1;
827 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
828 END_STREAM_REASON_FLAG_REMOTE;
829 connection_mark_for_close(TO_CONN(conn));
830 return 0;
834 if (conn->_base.type == CONN_TYPE_AP &&
835 rh->command == RELAY_COMMAND_CONNECTED) {
836 tor_assert(CIRCUIT_IS_ORIGIN(circ));
837 if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
838 log_fn(LOG_PROTOCOL_WARN, LD_APP,
839 "Got 'connected' while not in state connect_wait. Dropping.");
840 return 0;
842 conn->_base.state = AP_CONN_STATE_OPEN;
843 log_info(LD_APP,"'connected' received after %d seconds.",
844 (int)(time(NULL) - conn->_base.timestamp_lastread));
845 if (rh->length >= 4) {
846 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
847 int ttl;
848 if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
849 is_internal_IP(addr, 0))) {
850 char buf[INET_NTOA_BUF_LEN];
851 struct in_addr a;
852 a.s_addr = htonl(addr);
853 tor_inet_ntoa(&a, buf, sizeof(buf));
854 log_info(LD_APP,
855 "...but it claims the IP address was %s. Closing.", buf);
856 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
857 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
858 return 0;
860 if (rh->length >= 8)
861 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
862 else
863 ttl = -1;
864 client_dns_set_addressmap(conn->socks_request->address, addr,
865 conn->chosen_exit_name, ttl);
867 remap_event_helper(conn, addr);
869 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
870 /* don't send a socks reply to transparent conns */
871 if (!conn->socks_request->has_finished)
872 connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
874 /* Was it a linked dir conn? If so, a dir request just started to
875 * fetch something; this could be a bootstrap status milestone. */
876 log_debug(LD_APP, "considering");
877 if (TO_CONN(conn)->linked_conn &&
878 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
879 connection_t *dirconn = TO_CONN(conn)->linked_conn;
880 log_debug(LD_APP, "it is! %d", dirconn->purpose);
881 switch (dirconn->purpose) {
882 case DIR_PURPOSE_FETCH_CERTIFICATE:
883 if (consensus_is_waiting_for_certs())
884 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
885 break;
886 case DIR_PURPOSE_FETCH_CONSENSUS:
887 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
888 break;
889 case DIR_PURPOSE_FETCH_SERVERDESC:
890 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
891 count_loading_descriptors_progress());
892 break;
896 /* handle anything that might have queued */
897 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
898 /* (We already sent an end cell if possible) */
899 connection_mark_for_close(TO_CONN(conn));
900 return 0;
902 return 0;
904 if (conn->_base.type == CONN_TYPE_AP &&
905 rh->command == RELAY_COMMAND_RESOLVED) {
906 int ttl;
907 int answer_len;
908 uint8_t answer_type;
909 if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
910 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
911 "not in state resolve_wait. Dropping.");
912 return 0;
914 tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
915 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
916 if (rh->length < 2 || answer_len+2>rh->length) {
917 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
918 "Dropping malformed 'resolved' cell");
919 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
920 return 0;
922 answer_type = cell->payload[RELAY_HEADER_SIZE];
923 if (rh->length >= answer_len+6)
924 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
925 2+answer_len));
926 else
927 ttl = -1;
928 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
929 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
930 if (get_options()->ClientDNSRejectInternalAddresses &&
931 is_internal_IP(addr, 0)) {
932 char buf[INET_NTOA_BUF_LEN];
933 struct in_addr a;
934 a.s_addr = htonl(addr);
935 tor_inet_ntoa(&a, buf, sizeof(buf));
936 log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
937 connection_ap_handshake_socks_resolved(conn,
938 RESOLVED_TYPE_ERROR_TRANSIENT,
939 0, NULL, 0, TIME_MAX);
940 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
941 return 0;
944 connection_ap_handshake_socks_resolved(conn,
945 answer_type,
946 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
947 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
948 ttl,
949 -1);
950 if (answer_type == RESOLVED_TYPE_IPV4) {
951 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
952 remap_event_helper(conn, addr);
954 connection_mark_unattached_ap(conn,
955 END_STREAM_REASON_DONE |
956 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
957 return 0;
960 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
961 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
962 rh->command, conn->_base.state,
963 conn_state_to_string(conn->_base.type, conn->_base.state));
964 return 0; /* for forward compatibility, don't kill the circuit */
965 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
966 // connection_mark_for_close(conn);
967 // return -1;
970 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
971 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
972 * destined for <b>conn</b>.
974 * If <b>layer_hint</b> is defined, then we're the origin of the
975 * circuit, and it specifies the hop that packaged <b>cell</b>.
977 * Return -reason if you want to warn and tear down the circuit, else 0.
979 static int
980 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
981 edge_connection_t *conn,
982 crypt_path_t *layer_hint)
984 static int num_seen=0;
985 relay_header_t rh;
986 unsigned domain = layer_hint?LD_APP:LD_EXIT;
987 int reason;
989 tor_assert(cell);
990 tor_assert(circ);
992 relay_header_unpack(&rh, cell->payload);
993 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
994 num_seen++;
995 log_debug(domain, "Now seen %d relay cells here.", num_seen);
997 if (rh.length > RELAY_PAYLOAD_SIZE) {
998 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
999 "Relay cell length field too long. Closing circuit.");
1000 return - END_CIRC_REASON_TORPROTOCOL;
1003 /* either conn is NULL, in which case we've got a control cell, or else
1004 * conn points to the recognized stream. */
1006 if (conn && !connection_state_is_open(TO_CONN(conn)))
1007 return connection_edge_process_relay_cell_not_open(
1008 &rh, cell, circ, conn, layer_hint);
1010 switch (rh.command) {
1011 case RELAY_COMMAND_DROP:
1012 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1013 return 0;
1014 case RELAY_COMMAND_BEGIN:
1015 case RELAY_COMMAND_BEGIN_DIR:
1016 if (layer_hint &&
1017 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1018 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1019 "Relay begin request unsupported at AP. Dropping.");
1020 return 0;
1022 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1023 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1024 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1025 "Relay begin request to Hidden Service "
1026 "from intermediary node. Dropping.");
1027 return 0;
1029 if (conn) {
1030 log_fn(LOG_PROTOCOL_WARN, domain,
1031 "Begin cell for known stream. Dropping.");
1032 return 0;
1034 return connection_exit_begin_conn(cell, circ);
1035 case RELAY_COMMAND_DATA:
1036 ++stats_n_data_cells_received;
1037 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1038 (!layer_hint && --circ->deliver_window < 0)) {
1039 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1040 "(relay data) circ deliver_window below 0. Killing.");
1041 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1042 connection_mark_for_close(TO_CONN(conn));
1043 return -END_CIRC_REASON_TORPROTOCOL;
1045 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1046 layer_hint->deliver_window : circ->deliver_window);
1048 circuit_consider_sending_sendme(circ, layer_hint);
1050 if (!conn) {
1051 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1052 rh.stream_id);
1053 return 0;
1056 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1057 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1058 "(relay data) conn deliver_window below 0. Killing.");
1059 return -END_CIRC_REASON_TORPROTOCOL;
1062 stats_n_data_bytes_received += rh.length;
1063 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
1064 rh.length, TO_CONN(conn));
1065 connection_edge_consider_sending_sendme(conn);
1066 return 0;
1067 case RELAY_COMMAND_END:
1068 reason = rh.length > 0 ?
1069 *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1070 if (!conn) {
1071 log_info(domain,"end cell (%s) dropped, unknown stream.",
1072 stream_end_reason_to_string(reason));
1073 return 0;
1075 /* XXX add to this log_fn the exit node's nickname? */
1076 log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
1077 conn->_base.s,
1078 stream_end_reason_to_string(reason),
1079 conn->stream_id);
1080 if (conn->socks_request && !conn->socks_request->has_finished)
1081 log_warn(LD_BUG,
1082 "open stream hasn't sent socks answer yet? Closing.");
1083 /* We just *got* an end; no reason to send one. */
1084 conn->edge_has_sent_end = 1;
1085 if (!conn->end_reason)
1086 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1087 if (!conn->_base.marked_for_close) {
1088 /* only mark it if not already marked. it's possible to
1089 * get the 'end' right around when the client hangs up on us. */
1090 connection_mark_for_close(TO_CONN(conn));
1091 conn->_base.hold_open_until_flushed = 1;
1093 return 0;
1094 case RELAY_COMMAND_EXTEND:
1095 if (conn) {
1096 log_fn(LOG_PROTOCOL_WARN, domain,
1097 "'extend' cell received for non-zero stream. Dropping.");
1098 return 0;
1100 return circuit_extend(cell, circ);
1101 case RELAY_COMMAND_EXTENDED:
1102 if (!layer_hint) {
1103 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1104 "'extended' unsupported at non-origin. Dropping.");
1105 return 0;
1107 log_debug(domain,"Got an extended cell! Yay.");
1108 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1109 CELL_CREATED,
1110 cell->payload+RELAY_HEADER_SIZE)) < 0) {
1111 log_warn(domain,"circuit_finish_handshake failed.");
1112 return reason;
1114 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1115 log_info(domain,"circuit_send_next_onion_skin() failed.");
1116 return reason;
1118 return 0;
1119 case RELAY_COMMAND_TRUNCATE:
1120 if (layer_hint) {
1121 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1122 "'truncate' unsupported at origin. Dropping.");
1123 return 0;
1125 if (circ->n_conn) {
1126 uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
1127 connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
1128 trunc_reason);
1129 circuit_set_n_circid_orconn(circ, 0, NULL);
1131 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1133 char payload[1];
1134 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1135 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1136 payload, sizeof(payload), NULL);
1138 return 0;
1139 case RELAY_COMMAND_TRUNCATED:
1140 if (!layer_hint) {
1141 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1142 "'truncated' unsupported at non-origin. Dropping.");
1143 return 0;
1145 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
1146 return 0;
1147 case RELAY_COMMAND_CONNECTED:
1148 if (conn) {
1149 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1150 "'connected' unsupported while open. Closing circ.");
1151 return -END_CIRC_REASON_TORPROTOCOL;
1153 log_info(domain,
1154 "'connected' received, no conn attached anymore. Ignoring.");
1155 return 0;
1156 case RELAY_COMMAND_SENDME:
1157 if (!conn) {
1158 if (layer_hint) {
1159 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1160 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1161 layer_hint->package_window);
1162 circuit_resume_edge_reading(circ, layer_hint);
1163 } else {
1164 circ->package_window += CIRCWINDOW_INCREMENT;
1165 log_debug(LD_APP,
1166 "circ-level sendme at non-origin, packagewindow %d.",
1167 circ->package_window);
1168 circuit_resume_edge_reading(circ, layer_hint);
1170 return 0;
1172 conn->package_window += STREAMWINDOW_INCREMENT;
1173 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1174 conn->package_window);
1175 connection_start_reading(TO_CONN(conn));
1176 /* handle whatever might still be on the inbuf */
1177 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
1178 /* (We already sent an end cell if possible) */
1179 connection_mark_for_close(TO_CONN(conn));
1180 return 0;
1182 return 0;
1183 case RELAY_COMMAND_RESOLVE:
1184 if (layer_hint) {
1185 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1186 "resolve request unsupported at AP; dropping.");
1187 return 0;
1188 } else if (conn) {
1189 log_fn(LOG_PROTOCOL_WARN, domain,
1190 "resolve request for known stream; dropping.");
1191 return 0;
1192 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1193 log_fn(LOG_PROTOCOL_WARN, domain,
1194 "resolve request on circ with purpose %d; dropping",
1195 circ->purpose);
1196 return 0;
1198 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1199 return 0;
1200 case RELAY_COMMAND_RESOLVED:
1201 if (conn) {
1202 log_fn(LOG_PROTOCOL_WARN, domain,
1203 "'resolved' unsupported while open. Closing circ.");
1204 return -END_CIRC_REASON_TORPROTOCOL;
1206 log_info(domain,
1207 "'resolved' received, no conn attached anymore. Ignoring.");
1208 return 0;
1209 case RELAY_COMMAND_ESTABLISH_INTRO:
1210 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1211 case RELAY_COMMAND_INTRODUCE1:
1212 case RELAY_COMMAND_INTRODUCE2:
1213 case RELAY_COMMAND_INTRODUCE_ACK:
1214 case RELAY_COMMAND_RENDEZVOUS1:
1215 case RELAY_COMMAND_RENDEZVOUS2:
1216 case RELAY_COMMAND_INTRO_ESTABLISHED:
1217 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1218 rend_process_relay_cell(circ, layer_hint,
1219 rh.command, rh.length,
1220 cell->payload+RELAY_HEADER_SIZE);
1221 return 0;
1223 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1224 "Received unknown relay command %d. Perhaps the other side is using "
1225 "a newer version of Tor? Dropping.",
1226 rh.command);
1227 return 0; /* for forward compatibility, don't kill the circuit */
1230 /** How many relay_data cells have we built, ever? */
1231 uint64_t stats_n_data_cells_packaged = 0;
1232 /** How many bytes of data have we put in relay_data cells have we built,
1233 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1234 * every relay cell we ever sent were completely full of data. */
1235 uint64_t stats_n_data_bytes_packaged = 0;
1236 /** How many relay_data cells have we received, ever? */
1237 uint64_t stats_n_data_cells_received = 0;
1238 /** How many bytes of data have we received relay_data cells, ever? This would
1239 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1240 * ever received were completely full of data. */
1241 uint64_t stats_n_data_bytes_received = 0;
1243 /** While conn->inbuf has an entire relay payload of bytes on it,
1244 * and the appropriate package windows aren't empty, grab a cell
1245 * and send it down the circuit.
1247 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1248 * be marked for close, else return 0.
1251 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
1253 size_t amount_to_process, length;
1254 char payload[CELL_PAYLOAD_SIZE];
1255 circuit_t *circ;
1256 unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
1258 tor_assert(conn);
1260 if (conn->_base.marked_for_close) {
1261 log_warn(LD_BUG,
1262 "called on conn that's already marked for close at %s:%d.",
1263 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
1264 return 0;
1267 repeat_connection_edge_package_raw_inbuf:
1269 circ = circuit_get_by_edge_conn(conn);
1270 if (!circ) {
1271 log_info(domain,"conn has no circuit! Closing.");
1272 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1273 return -1;
1276 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
1277 return 0;
1279 if (conn->package_window <= 0) {
1280 log_info(domain,"called with package_window %d. Skipping.",
1281 conn->package_window);
1282 connection_stop_reading(TO_CONN(conn));
1283 return 0;
1286 amount_to_process = buf_datalen(conn->_base.inbuf);
1288 if (!amount_to_process)
1289 return 0;
1291 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
1292 return 0;
1294 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
1295 length = RELAY_PAYLOAD_SIZE;
1296 } else {
1297 length = amount_to_process;
1299 stats_n_data_bytes_packaged += length;
1300 stats_n_data_cells_packaged += 1;
1302 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1304 log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
1305 (int)length, (int)buf_datalen(conn->_base.inbuf));
1307 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1308 payload, length) < 0 )
1309 /* circuit got marked for close, don't continue, don't need to mark conn */
1310 return 0;
1312 if (!conn->cpath_layer) { /* non-rendezvous exit */
1313 tor_assert(circ->package_window > 0);
1314 circ->package_window--;
1315 } else { /* we're an AP, or an exit on a rendezvous circ */
1316 tor_assert(conn->cpath_layer->package_window > 0);
1317 conn->cpath_layer->package_window--;
1320 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1321 connection_stop_reading(TO_CONN(conn));
1322 log_debug(domain,"conn->package_window reached 0.");
1323 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
1324 return 0; /* don't process the inbuf any more */
1326 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1328 /* handle more if there's more, or return 0 if there isn't */
1329 goto repeat_connection_edge_package_raw_inbuf;
1332 /** Called when we've just received a relay data cell, or when
1333 * we've just finished flushing all bytes to stream <b>conn</b>.
1335 * If conn->outbuf is not too full, and our deliver window is
1336 * low, send back a suitable number of stream-level sendme cells.
1338 void
1339 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1341 circuit_t *circ;
1343 if (connection_outbuf_too_full(TO_CONN(conn)))
1344 return;
1346 circ = circuit_get_by_edge_conn(conn);
1347 if (!circ) {
1348 /* this can legitimately happen if the destroy has already
1349 * arrived and torn down the circuit */
1350 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1351 return;
1354 while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1355 log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
1356 "Outbuf %d, Queueing stream sendme.",
1357 (int)conn->_base.outbuf_flushlen);
1358 conn->deliver_window += STREAMWINDOW_INCREMENT;
1359 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
1360 NULL, 0) < 0) {
1361 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
1362 return; /* the circuit's closed, don't continue */
1367 /** The circuit <b>circ</b> has received a circuit-level sendme
1368 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1369 * attached streams and let them resume reading and packaging, if
1370 * their stream windows allow it.
1372 static void
1373 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1376 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1378 if (CIRCUIT_IS_ORIGIN(circ))
1379 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
1380 circ, layer_hint);
1381 else
1382 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
1383 circ, layer_hint);
1386 /** A helper function for circuit_resume_edge_reading() above.
1387 * The arguments are the same, except that <b>conn</b> is the head
1388 * of a linked list of edge streams that should each be considered.
1390 static int
1391 circuit_resume_edge_reading_helper(edge_connection_t *conn,
1392 circuit_t *circ,
1393 crypt_path_t *layer_hint)
1395 for ( ; conn; conn=conn->next_stream) {
1396 if (conn->_base.marked_for_close)
1397 continue;
1398 if ((!layer_hint && conn->package_window > 0) ||
1399 (layer_hint && conn->package_window > 0 &&
1400 conn->cpath_layer == layer_hint)) {
1401 connection_start_reading(TO_CONN(conn));
1402 /* handle whatever might still be on the inbuf */
1403 if (connection_edge_package_raw_inbuf(conn, 1)<0) {
1404 /* (We already sent an end cell if possible) */
1405 connection_mark_for_close(TO_CONN(conn));
1406 continue;
1409 /* If the circuit won't accept any more data, return without looking
1410 * at any more of the streams. Any connections that should be stopped
1411 * have already been stopped by connection_edge_package_raw_inbuf. */
1412 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1413 return -1;
1416 return 0;
1419 /** Check if the package window for <b>circ</b> is empty (at
1420 * hop <b>layer_hint</b> if it's defined).
1422 * If yes, tell edge streams to stop reading and return 1.
1423 * Else return 0.
1425 static int
1426 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1428 edge_connection_t *conn = NULL;
1429 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1431 if (!layer_hint) {
1432 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1433 log_debug(domain,"considering circ->package_window %d",
1434 circ->package_window);
1435 if (circ->package_window <= 0) {
1436 log_debug(domain,"yes, not-at-origin. stopped.");
1437 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
1438 connection_stop_reading(TO_CONN(conn));
1439 return 1;
1441 return 0;
1443 /* else, layer hint is defined, use it */
1444 log_debug(domain,"considering layer_hint->package_window %d",
1445 layer_hint->package_window);
1446 if (layer_hint->package_window <= 0) {
1447 log_debug(domain,"yes, at-origin. stopped.");
1448 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
1449 conn=conn->next_stream)
1450 if (conn->cpath_layer == layer_hint)
1451 connection_stop_reading(TO_CONN(conn));
1452 return 1;
1454 return 0;
1457 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1458 * <b>layer_hint</b> if it's defined) is low enough that we should
1459 * send a circuit-level sendme back down the circuit. If so, send
1460 * enough sendmes that the window would be overfull if we sent any
1461 * more.
1463 static void
1464 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1466 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1467 // layer_hint ? "defined" : "null");
1468 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
1469 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1470 log_debug(LD_CIRC,"Queueing circuit sendme.");
1471 if (layer_hint)
1472 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1473 else
1474 circ->deliver_window += CIRCWINDOW_INCREMENT;
1475 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
1476 NULL, 0, layer_hint) < 0) {
1477 log_warn(LD_CIRC,
1478 "relay_send_command_from_edge failed. Circuit's closed.");
1479 return; /* the circuit's closed, don't continue */
1484 /** Stop reading on edge connections when we have this many cells
1485 * waiting on the appropriate queue. */
1486 #define CELL_QUEUE_HIGHWATER_SIZE 256
1487 /** Start reading from edge connections again when we get down to this many
1488 * cells. */
1489 #define CELL_QUEUE_LOWWATER_SIZE 64
1491 #ifdef ACTIVE_CIRCUITS_PARANOIA
1492 #define assert_active_circuits_ok_paranoid(conn) \
1493 assert_active_circuits_ok(conn)
1494 #else
1495 #define assert_active_circuits_ok_paranoid(conn)
1496 #endif
1498 /** The total number of cells we have allocated from the memory pool. */
1499 static int total_cells_allocated = 0;
1501 /** A memory pool to allocate packed_cell_t objects. */
1502 static mp_pool_t *cell_pool = NULL;
1504 /** Allocate structures to hold cells. */
1505 void
1506 init_cell_pool(void)
1508 tor_assert(!cell_pool);
1509 cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
1512 /** Free all storage used to hold cells. */
1513 void
1514 free_cell_pool(void)
1516 /* Maybe we haven't called init_cell_pool yet; need to check for it. */
1517 if (cell_pool) {
1518 mp_pool_destroy(cell_pool);
1519 cell_pool = NULL;
1523 /** Free excess storage in cell pool. */
1524 void
1525 clean_cell_pool(void)
1527 tor_assert(cell_pool);
1528 mp_pool_clean(cell_pool, 0, 1);
1531 /** Release storage held by <b>cell</b>. */
1532 static INLINE void
1533 packed_cell_free(packed_cell_t *cell)
1535 --total_cells_allocated;
1536 mp_pool_release(cell);
1539 /** Allocate and return a new packed_cell_t. */
1540 static INLINE packed_cell_t *
1541 packed_cell_alloc(void)
1543 ++total_cells_allocated;
1544 return mp_pool_get(cell_pool);
1547 /** Log current statistics for cell pool allocation at log level
1548 * <b>severity</b>. */
1549 void
1550 dump_cell_pool_usage(int severity)
1552 circuit_t *c;
1553 int n_circs = 0;
1554 int n_cells = 0;
1555 for (c = _circuit_get_global_list(); c; c = c->next) {
1556 n_cells += c->n_conn_cells.n;
1557 if (!CIRCUIT_IS_ORIGIN(c))
1558 n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
1559 ++n_circs;
1561 log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
1562 n_cells, n_circs, total_cells_allocated - n_cells);
1563 mp_pool_log_status(cell_pool, severity);
1566 /** Allocate a new copy of packed <b>cell</b>. */
1567 static INLINE packed_cell_t *
1568 packed_cell_copy(const cell_t *cell)
1570 packed_cell_t *c = packed_cell_alloc();
1571 cell_pack(c, cell);
1572 c->next = NULL;
1573 return c;
1576 /** Append <b>cell</b> to the end of <b>queue</b>. */
1577 void
1578 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
1580 if (queue->tail) {
1581 tor_assert(!queue->tail->next);
1582 queue->tail->next = cell;
1583 } else {
1584 queue->head = cell;
1586 queue->tail = cell;
1587 cell->next = NULL;
1588 ++queue->n;
1591 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
1592 void
1593 cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
1595 cell_queue_append(queue, packed_cell_copy(cell));
1598 /** Remove and free every cell in <b>queue</b>. */
1599 void
1600 cell_queue_clear(cell_queue_t *queue)
1602 packed_cell_t *cell, *next;
1603 cell = queue->head;
1604 while (cell) {
1605 next = cell->next;
1606 packed_cell_free(cell);
1607 cell = next;
1609 queue->head = queue->tail = NULL;
1610 queue->n = 0;
1613 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
1614 * <b>queue</b> is empty. */
1615 static INLINE packed_cell_t *
1616 cell_queue_pop(cell_queue_t *queue)
1618 packed_cell_t *cell = queue->head;
1619 if (!cell)
1620 return NULL;
1621 queue->head = cell->next;
1622 if (cell == queue->tail) {
1623 tor_assert(!queue->head);
1624 queue->tail = NULL;
1626 --queue->n;
1627 return cell;
1630 /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
1631 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1632 static INLINE circuit_t **
1633 next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1635 tor_assert(circ);
1636 tor_assert(conn);
1637 if (conn == circ->n_conn) {
1638 return &circ->next_active_on_n_conn;
1639 } else {
1640 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1641 tor_assert(conn == orcirc->p_conn);
1642 return &orcirc->next_active_on_p_conn;
1646 /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
1647 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1648 static INLINE circuit_t **
1649 prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1651 tor_assert(circ);
1652 tor_assert(conn);
1653 if (conn == circ->n_conn) {
1654 return &circ->prev_active_on_n_conn;
1655 } else {
1656 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1657 tor_assert(conn == orcirc->p_conn);
1658 return &orcirc->prev_active_on_p_conn;
1662 /** Add <b>circ</b> to the list of circuits with pending cells on
1663 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1664 void
1665 make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
1667 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1668 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1670 if (*nextp && *prevp) {
1671 /* Already active. */
1672 return;
1675 if (! conn->active_circuits) {
1676 conn->active_circuits = circ;
1677 *prevp = *nextp = circ;
1678 } else {
1679 circuit_t *head = conn->active_circuits;
1680 circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
1681 *next_circ_on_conn_p(old_tail, conn) = circ;
1682 *nextp = head;
1683 *prev_circ_on_conn_p(head, conn) = circ;
1684 *prevp = old_tail;
1686 assert_active_circuits_ok_paranoid(conn);
1689 /** Remove <b>circ</b> to the list of circuits with pending cells on
1690 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1691 void
1692 make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
1694 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1695 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1696 circuit_t *next = *nextp, *prev = *prevp;
1698 if (!next && !prev) {
1699 /* Already inactive. */
1700 return;
1703 tor_assert(next && prev);
1704 tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
1705 tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
1707 if (next == circ) {
1708 conn->active_circuits = NULL;
1709 } else {
1710 *prev_circ_on_conn_p(next, conn) = prev;
1711 *next_circ_on_conn_p(prev, conn) = next;
1712 if (conn->active_circuits == circ)
1713 conn->active_circuits = next;
1715 *prevp = *nextp = NULL;
1716 assert_active_circuits_ok_paranoid(conn);
1719 /** Remove all circuits from the list of circuits with pending cells on
1720 * <b>conn</b>. */
1721 void
1722 connection_or_unlink_all_active_circs(or_connection_t *orconn)
1724 circuit_t *head = orconn->active_circuits;
1725 circuit_t *cur = head;
1726 if (! head)
1727 return;
1728 do {
1729 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1730 *prev_circ_on_conn_p(cur, orconn) = NULL;
1731 *next_circ_on_conn_p(cur, orconn) = NULL;
1732 cur = next;
1733 } while (cur != head);
1734 orconn->active_circuits = NULL;
1737 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
1738 * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
1739 * and start or stop reading as appropriate. */
1740 static void
1741 set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
1742 int block)
1744 edge_connection_t *edge = NULL;
1745 if (circ->n_conn == orconn) {
1746 circ->streams_blocked_on_n_conn = block;
1747 if (CIRCUIT_IS_ORIGIN(circ))
1748 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
1749 } else {
1750 circ->streams_blocked_on_p_conn = block;
1751 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1752 edge = TO_OR_CIRCUIT(circ)->n_streams;
1755 for (; edge; edge = edge->next_stream) {
1756 connection_t *conn = TO_CONN(edge);
1757 edge->edge_blocked_on_circ = block;
1759 if (!conn->read_event) {
1760 /* This connection is a placeholder for something; probably a DNS
1761 * request. It can't actually stop or start reading.*/
1762 continue;
1765 if (block) {
1766 if (connection_is_reading(conn))
1767 connection_stop_reading(conn);
1768 } else {
1769 /* Is this right? */
1770 if (!connection_is_reading(conn))
1771 connection_start_reading(conn);
1776 /** Pull as many cells as possible (but no more than <b>max</b>) from the
1777 * queue of the first active circuit on <b>conn</b>, and write then to
1778 * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
1779 * the active circuit pointer to the next active circuit in the ring. */
1781 connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
1782 time_t now)
1784 int n_flushed;
1785 cell_queue_t *queue;
1786 circuit_t *circ;
1787 int streams_blocked;
1788 circ = conn->active_circuits;
1789 if (!circ) return 0;
1790 assert_active_circuits_ok_paranoid(conn);
1791 if (circ->n_conn == conn) {
1792 queue = &circ->n_conn_cells;
1793 streams_blocked = circ->streams_blocked_on_n_conn;
1794 } else {
1795 queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
1796 streams_blocked = circ->streams_blocked_on_p_conn;
1798 tor_assert(*next_circ_on_conn_p(circ,conn));
1800 for (n_flushed = 0; n_flushed < max && queue->head; ) {
1801 packed_cell_t *cell = cell_queue_pop(queue);
1802 tor_assert(*next_circ_on_conn_p(circ,conn));
1804 connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
1806 packed_cell_free(cell);
1807 ++n_flushed;
1808 if (circ != conn->active_circuits) {
1809 /* If this happens, the current circuit just got made inactive by
1810 * a call in connection_write_to_buf(). That's nothing to worry about:
1811 * circuit_make_inactive_on_conn() already advanced conn->active_circuits
1812 * for us.
1814 assert_active_circuits_ok_paranoid(conn);
1815 goto done;
1818 tor_assert(*next_circ_on_conn_p(circ,conn));
1819 assert_active_circuits_ok_paranoid(conn);
1820 conn->active_circuits = *next_circ_on_conn_p(circ, conn);
1822 /* Is the cell queue low enough to unblock all the streams that are waiting
1823 * to write to this circuit? */
1824 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
1825 set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
1827 /* Did we just ran out of cells on this queue? */
1828 if (queue->n == 0) {
1829 log_debug(LD_GENERAL, "Made a circuit inactive.");
1830 make_circuit_inactive_on_conn(circ, conn);
1832 done:
1833 if (n_flushed)
1834 conn->timestamp_last_added_nonpadding = now;
1835 return n_flushed;
1838 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
1839 * transmitting in <b>direction</b>. */
1840 void
1841 append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
1842 cell_t *cell, cell_direction_t direction)
1844 cell_queue_t *queue;
1845 int streams_blocked;
1846 if (direction == CELL_DIRECTION_OUT) {
1847 queue = &circ->n_conn_cells;
1848 streams_blocked = circ->streams_blocked_on_n_conn;
1849 } else {
1850 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1851 queue = &orcirc->p_conn_cells;
1852 streams_blocked = circ->streams_blocked_on_p_conn;
1854 if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
1855 /* V1 connections don't understand RELAY_EARLY. */
1856 cell->command = CELL_RELAY;
1859 cell_queue_append_packed_copy(queue, cell);
1861 /* If we have too many cells on the circuit, we should stop reading from
1862 * the edge streams for a while. */
1863 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
1864 set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
1866 if (queue->n == 1) {
1867 /* This was the first cell added to the queue. We need to make this
1868 * circuit active. */
1869 log_debug(LD_GENERAL, "Made a circuit active.");
1870 make_circuit_active_on_conn(circ, orconn);
1873 if (! buf_datalen(orconn->_base.outbuf)) {
1874 /* There is no data at all waiting to be sent on the outbuf. Add a
1875 * cell, so that we can notice when it gets flushed, flushed_some can
1876 * get called, and we can start putting more data onto the buffer then.
1878 log_debug(LD_GENERAL, "Primed a buffer.");
1879 connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
1883 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
1884 * have at least 18 bytes of free space. The encoding is, as specified in
1885 * tor-spec.txt:
1886 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
1887 * LENGTH [1 byte]
1888 * ADDRESS [length bytes]
1889 * Return the number of bytes added, or -1 on error */
1891 append_address_to_payload(char *payload_out, const tor_addr_t *addr)
1893 uint32_t a;
1894 switch (tor_addr_family(addr)) {
1895 case AF_INET:
1896 payload_out[0] = RESOLVED_TYPE_IPV4;
1897 payload_out[1] = 4;
1898 a = tor_addr_to_ipv4n(addr);
1899 memcpy(payload_out+2, &a, 4);
1900 return 6;
1901 case AF_INET6:
1902 payload_out[0] = RESOLVED_TYPE_IPV6;
1903 payload_out[1] = 16;
1904 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
1905 return 18;
1906 case AF_UNSPEC:
1907 default:
1908 return -1;
1912 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
1913 * encoded as by append_address_to_payload(), try to decode the address into
1914 * *<b>addr_out</b>. Return the next byte in the payload after the address on
1915 * success, or NULL on failure. */
1916 const char *
1917 decode_address_from_payload(tor_addr_t *addr_out, const char *payload,
1918 int payload_len)
1920 if (payload_len < 2)
1921 return NULL;
1922 if (payload_len < 2+(uint8_t)payload[1])
1923 return NULL;
1925 switch (payload[0]) {
1926 case RESOLVED_TYPE_IPV4:
1927 if (payload[1] != 4)
1928 return NULL;
1929 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
1930 break;
1931 case RESOLVED_TYPE_IPV6:
1932 if (payload[1] != 16)
1933 return NULL;
1934 tor_addr_from_ipv6_bytes(addr_out, payload+2);
1935 break;
1936 default:
1937 tor_addr_make_unspec(addr_out);
1938 break;
1940 return payload + 2 + (uint8_t)payload[1];
1943 /** Fail with an assert if the active circuits ring on <b>orconn</b> is
1944 * corrupt. */
1945 void
1946 assert_active_circuits_ok(or_connection_t *orconn)
1948 circuit_t *head = orconn->active_circuits;
1949 circuit_t *cur = head;
1950 if (! head)
1951 return;
1952 do {
1953 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1954 circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
1955 tor_assert(next);
1956 tor_assert(prev);
1957 tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
1958 tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
1959 cur = next;
1960 } while (cur != head);