Disable logging to control port connections in buf_shrink_freelists.
[tor/rransom.git] / src / or / relay.c
blobb3d2fbb026d6f861743b3b928eafab849fe547c7
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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file relay.c
9 * \brief Handle relay cell encryption/decryption, plus packaging and
10 * receiving from circuits, plus queuing on circuits.
11 **/
13 #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 cell->command = CELL_RELAY; /* can't be relay_early anyway */
212 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
213 CELL_DIRECTION_IN)) < 0) {
214 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
215 "circuits");
216 /* XXXX Do this here, or just return -1? */
217 circuit_mark_for_close(circ, -reason);
218 return reason;
220 return 0;
222 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
223 "Didn't recognize cell, but circ stops here! Closing circ.");
224 return -END_CIRC_REASON_TORPROTOCOL;
227 log_debug(LD_OR,"Passing on unrecognized cell.");
229 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
230 * we might kill the circ before we relay
231 * the cells. */
233 append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
234 return 0;
237 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
238 * <b>circ</b> in direction <b>cell_direction</b>.
240 * If cell_direction == CELL_DIRECTION_IN:
241 * - If we're at the origin (we're the OP), for hops 1..N,
242 * decrypt cell. If recognized, stop.
243 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
245 * If cell_direction == CELL_DIRECTION_OUT:
246 * - decrypt one hop. Check if recognized.
248 * If cell is recognized, set *recognized to 1, and set
249 * *layer_hint to the hop that recognized it.
251 * Return -1 to indicate that we should mark the circuit for close,
252 * else return 0.
254 static int
255 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
256 crypt_path_t **layer_hint, char *recognized)
258 relay_header_t rh;
260 tor_assert(circ);
261 tor_assert(cell);
262 tor_assert(recognized);
263 tor_assert(cell_direction == CELL_DIRECTION_IN ||
264 cell_direction == CELL_DIRECTION_OUT);
266 if (cell_direction == CELL_DIRECTION_IN) {
267 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
268 * We'll want to do layered decrypts. */
269 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
270 thishop = cpath;
271 if (thishop->state != CPATH_STATE_OPEN) {
272 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
273 "Relay cell before first created cell? Closing.");
274 return -1;
276 do { /* Remember: cpath is in forward order, that is, first hop first. */
277 tor_assert(thishop);
279 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
280 return -1;
282 relay_header_unpack(&rh, cell->payload);
283 if (rh.recognized == 0) {
284 /* it's possibly recognized. have to check digest to be sure. */
285 if (relay_digest_matches(thishop->b_digest, cell)) {
286 *recognized = 1;
287 *layer_hint = thishop;
288 return 0;
292 thishop = thishop->next;
293 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
294 log_fn(LOG_PROTOCOL_WARN, LD_OR,
295 "Incoming cell at client not recognized. Closing.");
296 return -1;
297 } else { /* we're in the middle. Just one crypt. */
298 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
299 cell->payload, 1) < 0)
300 return -1;
301 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
302 // "the client.");
304 } else /* cell_direction == CELL_DIRECTION_OUT */ {
305 /* we're in the middle. Just one crypt. */
307 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
308 cell->payload, 0) < 0)
309 return -1;
311 relay_header_unpack(&rh, cell->payload);
312 if (rh.recognized == 0) {
313 /* it's possibly recognized. have to check digest to be sure. */
314 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
315 *recognized = 1;
316 return 0;
320 return 0;
323 /** Package a relay cell from an edge:
324 * - Encrypt it to the right layer
325 * - Append it to the appropriate cell_queue on <b>circ</b>.
327 static int
328 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
329 cell_direction_t cell_direction,
330 crypt_path_t *layer_hint)
332 or_connection_t *conn; /* where to send the cell */
334 if (cell_direction == CELL_DIRECTION_OUT) {
335 crypt_path_t *thishop; /* counter for repeated crypts */
336 conn = circ->n_conn;
337 if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
338 log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
339 return 0; /* just drop it */
342 relay_set_digest(layer_hint->f_digest, cell);
344 thishop = layer_hint;
345 /* moving from farthest to nearest hop */
346 do {
347 tor_assert(thishop);
348 /* XXXX RD This is a bug, right? */
349 log_debug(LD_OR,"crypting a layer of the relay cell.");
350 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
351 return -1;
354 thishop = thishop->prev;
355 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
357 } else { /* incoming cell */
358 or_circuit_t *or_circ;
359 if (CIRCUIT_IS_ORIGIN(circ)) {
360 /* We should never package an _incoming_ cell from the circuit
361 * origin; that means we messed up somewhere. */
362 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
363 assert_circuit_ok(circ);
364 return 0; /* just drop it */
366 or_circ = TO_OR_CIRCUIT(circ);
367 conn = or_circ->p_conn;
368 relay_set_digest(or_circ->p_digest, cell);
369 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
370 return -1;
372 ++stats_n_relay_cells_relayed;
374 append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
375 return 0;
378 /** If cell's stream_id matches the stream_id of any conn that's
379 * attached to circ, return that conn, else return NULL.
381 static edge_connection_t *
382 relay_lookup_conn(circuit_t *circ, cell_t *cell,
383 cell_direction_t cell_direction, crypt_path_t *layer_hint)
385 edge_connection_t *tmpconn;
386 relay_header_t rh;
388 relay_header_unpack(&rh, cell->payload);
390 if (!rh.stream_id)
391 return NULL;
393 /* IN or OUT cells could have come from either direction, now
394 * that we allow rendezvous *to* an OP.
397 if (CIRCUIT_IS_ORIGIN(circ)) {
398 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
399 tmpconn=tmpconn->next_stream) {
400 if (rh.stream_id == tmpconn->stream_id &&
401 !tmpconn->_base.marked_for_close &&
402 tmpconn->cpath_layer == layer_hint) {
403 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
404 return tmpconn;
407 } else {
408 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
409 tmpconn=tmpconn->next_stream) {
410 if (rh.stream_id == tmpconn->stream_id &&
411 !tmpconn->_base.marked_for_close) {
412 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
413 if (cell_direction == CELL_DIRECTION_OUT ||
414 connection_edge_is_rendezvous_stream(tmpconn))
415 return tmpconn;
418 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
419 tmpconn=tmpconn->next_stream) {
420 if (rh.stream_id == tmpconn->stream_id &&
421 !tmpconn->_base.marked_for_close) {
422 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
423 return tmpconn;
427 return NULL; /* probably a begin relay cell */
430 /** Pack the relay_header_t host-order structure <b>src</b> into
431 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
432 * about the wire format.
434 void
435 relay_header_pack(char *dest, const relay_header_t *src)
437 *(uint8_t*)(dest) = src->command;
439 set_uint16(dest+1, htons(src->recognized));
440 set_uint16(dest+3, htons(src->stream_id));
441 memcpy(dest+5, src->integrity, 4);
442 set_uint16(dest+9, htons(src->length));
445 /** Unpack the network-order buffer <b>src</b> into a host-order
446 * relay_header_t structure <b>dest</b>.
448 void
449 relay_header_unpack(relay_header_t *dest, const char *src)
451 dest->command = *(uint8_t*)(src);
453 dest->recognized = ntohs(get_uint16(src+1));
454 dest->stream_id = ntohs(get_uint16(src+3));
455 memcpy(dest->integrity, src+5, 4);
456 dest->length = ntohs(get_uint16(src+9));
459 /** Convert the relay <b>command</b> into a human-readable string. */
460 static const char *
461 relay_command_to_string(uint8_t command)
463 switch (command) {
464 case RELAY_COMMAND_BEGIN: return "BEGIN";
465 case RELAY_COMMAND_DATA: return "DATA";
466 case RELAY_COMMAND_END: return "END";
467 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
468 case RELAY_COMMAND_SENDME: return "SENDME";
469 case RELAY_COMMAND_EXTEND: return "EXTEND";
470 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
471 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
472 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
473 case RELAY_COMMAND_DROP: return "DROP";
474 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
475 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
476 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
477 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
478 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
479 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
480 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
481 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
482 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
483 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
484 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
485 return "RENDEZVOUS_ESTABLISHED";
486 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
487 default: return "(unrecognized)";
491 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
492 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
493 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
494 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
495 * destination hop for OP->OR cells.
497 * If you can't send the cell, mark the circuit for close and return -1. Else
498 * return 0.
501 relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
502 uint8_t relay_command, const char *payload,
503 size_t payload_len, crypt_path_t *cpath_layer)
505 cell_t cell;
506 relay_header_t rh;
507 cell_direction_t cell_direction;
508 /* XXXX NM Split this function into a separate versions per circuit type? */
510 tor_assert(circ);
511 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
513 memset(&cell, 0, sizeof(cell_t));
514 cell.command = CELL_RELAY;
515 if (cpath_layer) {
516 cell.circ_id = circ->n_circ_id;
517 cell_direction = CELL_DIRECTION_OUT;
518 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
519 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
520 cell_direction = CELL_DIRECTION_IN;
521 } else {
522 return -1;
525 memset(&rh, 0, sizeof(rh));
526 rh.command = relay_command;
527 rh.stream_id = stream_id;
528 rh.length = payload_len;
529 relay_header_pack(cell.payload, &rh);
530 if (payload_len)
531 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
533 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
534 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
536 if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
537 /* if we're using relaybandwidthrate, this conn wants priority */
538 circ->n_conn->client_used = approx_time();
541 if (cell_direction == CELL_DIRECTION_OUT) {
542 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
543 if (origin_circ->remaining_relay_early_cells > 0 &&
544 (relay_command == RELAY_COMMAND_EXTEND ||
545 (cpath_layer != origin_circ->cpath &&
546 !CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(circ->purpose)))) {
547 /* If we've got any relay_early cells left, and we're sending
548 * an extend cell or (we're not talking to the first hop and we're
549 * not talking to a rendezvous circuit), use one of them.
550 * Don't worry about the conn protocol version:
551 * append_cell_to_circuit_queue will fix it up. */
552 /* XXX For now, clients don't use RELAY_EARLY cells when sending
553 * relay cells on rendezvous circuits. See bug 1038. Eventually,
554 * we can take this behavior away in favor of having clients avoid
555 * rendezvous points running 0.2.1.3-alpha through 0.2.1.18. -RD */
556 cell.command = CELL_RELAY_EARLY;
557 --origin_circ->remaining_relay_early_cells;
558 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
559 (int)origin_circ->remaining_relay_early_cells);
560 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
561 * task 878. */
562 origin_circ->relay_early_commands[
563 origin_circ->relay_early_cells_sent++] = relay_command;
564 } else if (relay_command == RELAY_COMMAND_EXTEND) {
565 /* If no RELAY_EARLY cells can be sent over this circuit, log which
566 * commands have been sent as RELAY_EARLY cells before; helps debug
567 * task 878. */
568 smartlist_t *commands_list = smartlist_create();
569 int i = 0;
570 char *commands = NULL;
571 for (; i < origin_circ->relay_early_cells_sent; i++)
572 smartlist_add(commands_list, (char *)
573 relay_command_to_string(origin_circ->relay_early_commands[i]));
574 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
575 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
576 "but we have run out of RELAY_EARLY cells on that circuit. "
577 "Commands sent before: %s", commands);
578 tor_free(commands);
579 smartlist_free(commands_list);
583 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
584 < 0) {
585 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
586 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
587 return -1;
589 return 0;
592 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
593 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
594 * that's sending the relay cell, or NULL if it's a control cell.
595 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
596 * for OP->OR cells.
598 * If you can't send the cell, mark the circuit for close and
599 * return -1. Else return 0.
602 connection_edge_send_command(edge_connection_t *fromconn,
603 uint8_t relay_command, const char *payload,
604 size_t payload_len)
606 /* XXXX NM Split this function into a separate versions per circuit type? */
607 circuit_t *circ;
608 tor_assert(fromconn);
609 circ = fromconn->on_circuit;
611 if (fromconn->_base.marked_for_close) {
612 log_warn(LD_BUG,
613 "called on conn that's already marked for close at %s:%d.",
614 fromconn->_base.marked_for_close_file,
615 fromconn->_base.marked_for_close);
616 return 0;
619 if (!circ) {
620 if (fromconn->_base.type == CONN_TYPE_AP) {
621 log_info(LD_APP,"no circ. Closing conn.");
622 connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
623 } else {
624 log_info(LD_EXIT,"no circ. Closing conn.");
625 fromconn->edge_has_sent_end = 1; /* no circ to send to */
626 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
627 connection_mark_for_close(TO_CONN(fromconn));
629 return -1;
632 return relay_send_command_from_edge(fromconn->stream_id, circ,
633 relay_command, payload,
634 payload_len, fromconn->cpath_layer);
637 /** How many times will I retry a stream that fails due to DNS
638 * resolve failure or misc error?
640 #define MAX_RESOLVE_FAILURES 3
642 /** Return 1 if reason is something that you should retry if you
643 * get the end cell before you've connected; else return 0. */
644 static int
645 edge_reason_is_retriable(int reason)
647 return reason == END_STREAM_REASON_HIBERNATING ||
648 reason == END_STREAM_REASON_RESOURCELIMIT ||
649 reason == END_STREAM_REASON_EXITPOLICY ||
650 reason == END_STREAM_REASON_RESOLVEFAILED ||
651 reason == END_STREAM_REASON_MISC ||
652 reason == END_STREAM_REASON_NOROUTE;
655 /** Called when we receive an END cell on a stream that isn't open yet,
656 * from the client side.
657 * Arguments are as for connection_edge_process_relay_cell().
659 static int
660 connection_ap_process_end_not_open(
661 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
662 edge_connection_t *conn, crypt_path_t *layer_hint)
664 struct in_addr in;
665 routerinfo_t *exitrouter;
666 int reason = *(cell->payload+RELAY_HEADER_SIZE);
667 int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
668 (void) layer_hint; /* unused */
670 if (rh->length > 0 && edge_reason_is_retriable(reason) &&
671 !connection_edge_is_rendezvous_stream(conn) /* avoid retry if rend */
673 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
674 safe_str(conn->socks_request->address),
675 stream_end_reason_to_string(reason));
676 exitrouter =
677 router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
678 switch (reason) {
679 case END_STREAM_REASON_EXITPOLICY:
680 if (rh->length >= 5) {
681 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
682 int ttl;
683 if (!addr) {
684 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
685 safe_str(conn->socks_request->address));
686 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
687 return 0;
689 if (rh->length >= 9)
690 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
691 else
692 ttl = -1;
694 if (get_options()->ClientDNSRejectInternalAddresses &&
695 is_internal_IP(addr, 0)) {
696 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
697 safe_str(conn->socks_request->address));
698 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
699 return 0;
701 client_dns_set_addressmap(conn->socks_request->address, addr,
702 conn->chosen_exit_name, ttl);
704 /* check if he *ought* to have allowed it */
705 if (exitrouter &&
706 (rh->length < 5 ||
707 (tor_inet_aton(conn->socks_request->address, &in) &&
708 !conn->chosen_exit_name))) {
709 log_info(LD_APP,
710 "Exitrouter '%s' seems to be more restrictive than its exit "
711 "policy. Not using this router as exit for now.",
712 exitrouter->nickname);
713 policies_set_router_exitpolicy_to_reject_all(exitrouter);
715 /* rewrite it to an IP if we learned one. */
716 if (addressmap_rewrite(conn->socks_request->address,
717 sizeof(conn->socks_request->address),
718 NULL)) {
719 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
721 if (conn->chosen_exit_optional ||
722 conn->chosen_exit_retries) {
723 /* stop wanting a specific exit */
724 conn->chosen_exit_optional = 0;
725 /* A non-zero chosen_exit_retries can happen if we set a
726 * TrackHostExits for this address under a port that the exit
727 * relay allows, but then try the same address with a different
728 * port that it doesn't allow to exit. We shouldn't unregister
729 * the mapping, since it is probably still wanted on the
730 * original port. But now we give away to the exit relay that
731 * we probably have a TrackHostExits on it. So be it. */
732 conn->chosen_exit_retries = 0;
733 tor_free(conn->chosen_exit_name); /* clears it */
735 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
736 return 0;
737 /* else, conn will get closed below */
738 break;
739 case END_STREAM_REASON_CONNECTREFUSED:
740 if (!conn->chosen_exit_optional)
741 break; /* break means it'll close, below */
742 /* Else fall through: expire this circuit, clear the
743 * chosen_exit_name field, and try again. */
744 case END_STREAM_REASON_RESOLVEFAILED:
745 case END_STREAM_REASON_TIMEOUT:
746 case END_STREAM_REASON_MISC:
747 case END_STREAM_REASON_NOROUTE:
748 if (client_dns_incr_failures(conn->socks_request->address)
749 < MAX_RESOLVE_FAILURES) {
750 /* We haven't retried too many times; reattach the connection. */
751 circuit_log_path(LOG_INFO,LD_APP,circ);
752 tor_assert(circ->_base.timestamp_dirty);
753 circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
755 if (conn->chosen_exit_optional) {
756 /* stop wanting a specific exit */
757 conn->chosen_exit_optional = 0;
758 tor_free(conn->chosen_exit_name); /* clears it */
760 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
761 return 0;
762 /* else, conn will get closed below */
763 } else {
764 log_notice(LD_APP,
765 "Have tried resolving or connecting to address '%s' "
766 "at %d different places. Giving up.",
767 safe_str(conn->socks_request->address),
768 MAX_RESOLVE_FAILURES);
769 /* clear the failures, so it will have a full try next time */
770 client_dns_clear_failures(conn->socks_request->address);
772 break;
773 case END_STREAM_REASON_HIBERNATING:
774 case END_STREAM_REASON_RESOURCELIMIT:
775 if (exitrouter) {
776 policies_set_router_exitpolicy_to_reject_all(exitrouter);
778 if (conn->chosen_exit_optional) {
779 /* stop wanting a specific exit */
780 conn->chosen_exit_optional = 0;
781 tor_free(conn->chosen_exit_name); /* clears it */
783 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
784 return 0;
785 /* else, will close below */
786 break;
787 } /* end switch */
788 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
791 log_info(LD_APP,
792 "Edge got end (%s) before we're connected. Marking for close.",
793 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
794 circuit_log_path(LOG_INFO,LD_APP,circ);
795 /* need to test because of detach_retriable */
796 if (!conn->_base.marked_for_close)
797 connection_mark_unattached_ap(conn, control_reason);
798 return 0;
801 /** Helper: change the socks_request-&gt;address field on conn to the
802 * dotted-quad representation of <b>new_addr</b> (given in host order),
803 * and send an appropriate REMAP event. */
804 static void
805 remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
807 struct in_addr in;
809 in.s_addr = htonl(new_addr);
810 tor_inet_ntoa(&in, conn->socks_request->address,
811 sizeof(conn->socks_request->address));
812 control_event_stream_status(conn, STREAM_EVENT_REMAP,
813 REMAP_STREAM_SOURCE_EXIT);
816 /** An incoming relay cell has arrived from circuit <b>circ</b> to
817 * stream <b>conn</b>.
819 * The arguments here are the same as in
820 * connection_edge_process_relay_cell() below; this function is called
821 * from there when <b>conn</b> is defined and not in an open state.
823 static int
824 connection_edge_process_relay_cell_not_open(
825 relay_header_t *rh, cell_t *cell, circuit_t *circ,
826 edge_connection_t *conn, crypt_path_t *layer_hint)
828 if (rh->command == RELAY_COMMAND_END) {
829 if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
830 return connection_ap_process_end_not_open(rh, cell,
831 TO_ORIGIN_CIRCUIT(circ), conn,
832 layer_hint);
833 } else {
834 /* we just got an 'end', don't need to send one */
835 conn->edge_has_sent_end = 1;
836 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
837 END_STREAM_REASON_FLAG_REMOTE;
838 connection_mark_for_close(TO_CONN(conn));
839 return 0;
843 if (conn->_base.type == CONN_TYPE_AP &&
844 rh->command == RELAY_COMMAND_CONNECTED) {
845 tor_assert(CIRCUIT_IS_ORIGIN(circ));
846 if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
847 log_fn(LOG_PROTOCOL_WARN, LD_APP,
848 "Got 'connected' while not in state connect_wait. Dropping.");
849 return 0;
851 conn->_base.state = AP_CONN_STATE_OPEN;
852 log_info(LD_APP,"'connected' received after %d seconds.",
853 (int)(time(NULL) - conn->_base.timestamp_lastread));
854 if (rh->length >= 4) {
855 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
856 int ttl;
857 if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
858 is_internal_IP(addr, 0))) {
859 char buf[INET_NTOA_BUF_LEN];
860 struct in_addr a;
861 a.s_addr = htonl(addr);
862 tor_inet_ntoa(&a, buf, sizeof(buf));
863 log_info(LD_APP,
864 "...but it claims the IP address was %s. Closing.", buf);
865 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
866 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
867 return 0;
869 if (rh->length >= 8)
870 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
871 else
872 ttl = -1;
873 client_dns_set_addressmap(conn->socks_request->address, addr,
874 conn->chosen_exit_name, ttl);
876 remap_event_helper(conn, addr);
878 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
879 /* don't send a socks reply to transparent conns */
880 if (!conn->socks_request->has_finished)
881 connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
883 /* Was it a linked dir conn? If so, a dir request just started to
884 * fetch something; this could be a bootstrap status milestone. */
885 log_debug(LD_APP, "considering");
886 if (TO_CONN(conn)->linked_conn &&
887 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
888 connection_t *dirconn = TO_CONN(conn)->linked_conn;
889 log_debug(LD_APP, "it is! %d", dirconn->purpose);
890 switch (dirconn->purpose) {
891 case DIR_PURPOSE_FETCH_CERTIFICATE:
892 if (consensus_is_waiting_for_certs())
893 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
894 break;
895 case DIR_PURPOSE_FETCH_CONSENSUS:
896 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
897 break;
898 case DIR_PURPOSE_FETCH_SERVERDESC:
899 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
900 count_loading_descriptors_progress());
901 break;
905 /* handle anything that might have queued */
906 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
907 /* (We already sent an end cell if possible) */
908 connection_mark_for_close(TO_CONN(conn));
909 return 0;
911 return 0;
913 if (conn->_base.type == CONN_TYPE_AP &&
914 rh->command == RELAY_COMMAND_RESOLVED) {
915 int ttl;
916 int answer_len;
917 uint8_t answer_type;
918 if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
919 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
920 "not in state resolve_wait. Dropping.");
921 return 0;
923 tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
924 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
925 if (rh->length < 2 || answer_len+2>rh->length) {
926 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
927 "Dropping malformed 'resolved' cell");
928 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
929 return 0;
931 answer_type = cell->payload[RELAY_HEADER_SIZE];
932 if (rh->length >= answer_len+6)
933 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
934 2+answer_len));
935 else
936 ttl = -1;
937 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
938 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
939 if (get_options()->ClientDNSRejectInternalAddresses &&
940 is_internal_IP(addr, 0)) {
941 char buf[INET_NTOA_BUF_LEN];
942 struct in_addr a;
943 a.s_addr = htonl(addr);
944 tor_inet_ntoa(&a, buf, sizeof(buf));
945 log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
946 connection_ap_handshake_socks_resolved(conn,
947 RESOLVED_TYPE_ERROR_TRANSIENT,
948 0, NULL, 0, TIME_MAX);
949 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
950 return 0;
953 connection_ap_handshake_socks_resolved(conn,
954 answer_type,
955 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
956 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
957 ttl,
958 -1);
959 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
960 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
961 remap_event_helper(conn, addr);
963 connection_mark_unattached_ap(conn,
964 END_STREAM_REASON_DONE |
965 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
966 return 0;
969 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
970 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
971 rh->command, conn->_base.state,
972 conn_state_to_string(conn->_base.type, conn->_base.state));
973 return 0; /* for forward compatibility, don't kill the circuit */
974 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
975 // connection_mark_for_close(conn);
976 // return -1;
979 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
980 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
981 * destined for <b>conn</b>.
983 * If <b>layer_hint</b> is defined, then we're the origin of the
984 * circuit, and it specifies the hop that packaged <b>cell</b>.
986 * Return -reason if you want to warn and tear down the circuit, else 0.
988 static int
989 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
990 edge_connection_t *conn,
991 crypt_path_t *layer_hint)
993 static int num_seen=0;
994 relay_header_t rh;
995 unsigned domain = layer_hint?LD_APP:LD_EXIT;
996 int reason;
998 tor_assert(cell);
999 tor_assert(circ);
1001 relay_header_unpack(&rh, cell->payload);
1002 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1003 num_seen++;
1004 log_debug(domain, "Now seen %d relay cells here.", num_seen);
1006 if (rh.length > RELAY_PAYLOAD_SIZE) {
1007 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1008 "Relay cell length field too long. Closing circuit.");
1009 return - END_CIRC_REASON_TORPROTOCOL;
1012 /* either conn is NULL, in which case we've got a control cell, or else
1013 * conn points to the recognized stream. */
1015 if (conn && !connection_state_is_open(TO_CONN(conn)))
1016 return connection_edge_process_relay_cell_not_open(
1017 &rh, cell, circ, conn, layer_hint);
1019 switch (rh.command) {
1020 case RELAY_COMMAND_DROP:
1021 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1022 return 0;
1023 case RELAY_COMMAND_BEGIN:
1024 case RELAY_COMMAND_BEGIN_DIR:
1025 if (layer_hint &&
1026 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1027 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1028 "Relay begin request unsupported at AP. Dropping.");
1029 return 0;
1031 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1032 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1033 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1034 "Relay begin request to Hidden Service "
1035 "from intermediary node. Dropping.");
1036 return 0;
1038 if (conn) {
1039 log_fn(LOG_PROTOCOL_WARN, domain,
1040 "Begin cell for known stream. Dropping.");
1041 return 0;
1043 return connection_exit_begin_conn(cell, circ);
1044 case RELAY_COMMAND_DATA:
1045 ++stats_n_data_cells_received;
1046 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1047 (!layer_hint && --circ->deliver_window < 0)) {
1048 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1049 "(relay data) circ deliver_window below 0. Killing.");
1050 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1051 connection_mark_for_close(TO_CONN(conn));
1052 return -END_CIRC_REASON_TORPROTOCOL;
1054 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1055 layer_hint->deliver_window : circ->deliver_window);
1057 circuit_consider_sending_sendme(circ, layer_hint);
1059 if (!conn) {
1060 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1061 rh.stream_id);
1062 return 0;
1065 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1066 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1067 "(relay data) conn deliver_window below 0. Killing.");
1068 return -END_CIRC_REASON_TORPROTOCOL;
1071 stats_n_data_bytes_received += rh.length;
1072 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
1073 rh.length, TO_CONN(conn));
1074 connection_edge_consider_sending_sendme(conn);
1075 return 0;
1076 case RELAY_COMMAND_END:
1077 reason = rh.length > 0 ?
1078 *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1079 if (!conn) {
1080 log_info(domain,"end cell (%s) dropped, unknown stream.",
1081 stream_end_reason_to_string(reason));
1082 return 0;
1084 /* XXX add to this log_fn the exit node's nickname? */
1085 log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
1086 conn->_base.s,
1087 stream_end_reason_to_string(reason),
1088 conn->stream_id);
1089 if (conn->socks_request && !conn->socks_request->has_finished)
1090 log_warn(LD_BUG,
1091 "open stream hasn't sent socks answer yet? Closing.");
1092 /* We just *got* an end; no reason to send one. */
1093 conn->edge_has_sent_end = 1;
1094 if (!conn->end_reason)
1095 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1096 if (!conn->_base.marked_for_close) {
1097 /* only mark it if not already marked. it's possible to
1098 * get the 'end' right around when the client hangs up on us. */
1099 connection_mark_for_close(TO_CONN(conn));
1100 conn->_base.hold_open_until_flushed = 1;
1102 return 0;
1103 case RELAY_COMMAND_EXTEND:
1104 if (conn) {
1105 log_fn(LOG_PROTOCOL_WARN, domain,
1106 "'extend' cell received for non-zero stream. Dropping.");
1107 return 0;
1109 return circuit_extend(cell, circ);
1110 case RELAY_COMMAND_EXTENDED:
1111 if (!layer_hint) {
1112 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1113 "'extended' unsupported at non-origin. Dropping.");
1114 return 0;
1116 log_debug(domain,"Got an extended cell! Yay.");
1117 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1118 CELL_CREATED,
1119 cell->payload+RELAY_HEADER_SIZE)) < 0) {
1120 log_warn(domain,"circuit_finish_handshake failed.");
1121 return reason;
1123 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1124 log_info(domain,"circuit_send_next_onion_skin() failed.");
1125 return reason;
1127 return 0;
1128 case RELAY_COMMAND_TRUNCATE:
1129 if (layer_hint) {
1130 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1131 "'truncate' unsupported at origin. Dropping.");
1132 return 0;
1134 if (circ->n_conn) {
1135 uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
1136 connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
1137 trunc_reason);
1138 circuit_set_n_circid_orconn(circ, 0, NULL);
1140 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1142 char payload[1];
1143 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1144 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1145 payload, sizeof(payload), NULL);
1147 return 0;
1148 case RELAY_COMMAND_TRUNCATED:
1149 if (!layer_hint) {
1150 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1151 "'truncated' unsupported at non-origin. Dropping.");
1152 return 0;
1154 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
1155 return 0;
1156 case RELAY_COMMAND_CONNECTED:
1157 if (conn) {
1158 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1159 "'connected' unsupported while open. Closing circ.");
1160 return -END_CIRC_REASON_TORPROTOCOL;
1162 log_info(domain,
1163 "'connected' received, no conn attached anymore. Ignoring.");
1164 return 0;
1165 case RELAY_COMMAND_SENDME:
1166 if (!conn) {
1167 if (layer_hint) {
1168 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1169 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1170 layer_hint->package_window);
1171 circuit_resume_edge_reading(circ, layer_hint);
1172 } else {
1173 circ->package_window += CIRCWINDOW_INCREMENT;
1174 log_debug(LD_APP,
1175 "circ-level sendme at non-origin, packagewindow %d.",
1176 circ->package_window);
1177 circuit_resume_edge_reading(circ, layer_hint);
1179 return 0;
1181 conn->package_window += STREAMWINDOW_INCREMENT;
1182 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1183 conn->package_window);
1184 connection_start_reading(TO_CONN(conn));
1185 /* handle whatever might still be on the inbuf */
1186 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
1187 /* (We already sent an end cell if possible) */
1188 connection_mark_for_close(TO_CONN(conn));
1189 return 0;
1191 return 0;
1192 case RELAY_COMMAND_RESOLVE:
1193 if (layer_hint) {
1194 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1195 "resolve request unsupported at AP; dropping.");
1196 return 0;
1197 } else if (conn) {
1198 log_fn(LOG_PROTOCOL_WARN, domain,
1199 "resolve request for known stream; dropping.");
1200 return 0;
1201 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1202 log_fn(LOG_PROTOCOL_WARN, domain,
1203 "resolve request on circ with purpose %d; dropping",
1204 circ->purpose);
1205 return 0;
1207 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1208 return 0;
1209 case RELAY_COMMAND_RESOLVED:
1210 if (conn) {
1211 log_fn(LOG_PROTOCOL_WARN, domain,
1212 "'resolved' unsupported while open. Closing circ.");
1213 return -END_CIRC_REASON_TORPROTOCOL;
1215 log_info(domain,
1216 "'resolved' received, no conn attached anymore. Ignoring.");
1217 return 0;
1218 case RELAY_COMMAND_ESTABLISH_INTRO:
1219 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1220 case RELAY_COMMAND_INTRODUCE1:
1221 case RELAY_COMMAND_INTRODUCE2:
1222 case RELAY_COMMAND_INTRODUCE_ACK:
1223 case RELAY_COMMAND_RENDEZVOUS1:
1224 case RELAY_COMMAND_RENDEZVOUS2:
1225 case RELAY_COMMAND_INTRO_ESTABLISHED:
1226 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1227 rend_process_relay_cell(circ, layer_hint,
1228 rh.command, rh.length,
1229 cell->payload+RELAY_HEADER_SIZE);
1230 return 0;
1232 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1233 "Received unknown relay command %d. Perhaps the other side is using "
1234 "a newer version of Tor? Dropping.",
1235 rh.command);
1236 return 0; /* for forward compatibility, don't kill the circuit */
1239 /** How many relay_data cells have we built, ever? */
1240 uint64_t stats_n_data_cells_packaged = 0;
1241 /** How many bytes of data have we put in relay_data cells have we built,
1242 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1243 * every relay cell we ever sent were completely full of data. */
1244 uint64_t stats_n_data_bytes_packaged = 0;
1245 /** How many relay_data cells have we received, ever? */
1246 uint64_t stats_n_data_cells_received = 0;
1247 /** How many bytes of data have we received relay_data cells, ever? This would
1248 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1249 * ever received were completely full of data. */
1250 uint64_t stats_n_data_bytes_received = 0;
1252 /** While conn->inbuf has an entire relay payload of bytes on it,
1253 * and the appropriate package windows aren't empty, grab a cell
1254 * and send it down the circuit.
1256 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1257 * be marked for close, else return 0.
1260 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
1262 size_t amount_to_process, length;
1263 char payload[CELL_PAYLOAD_SIZE];
1264 circuit_t *circ;
1265 unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
1267 tor_assert(conn);
1269 if (conn->_base.marked_for_close) {
1270 log_warn(LD_BUG,
1271 "called on conn that's already marked for close at %s:%d.",
1272 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
1273 return 0;
1276 repeat_connection_edge_package_raw_inbuf:
1278 circ = circuit_get_by_edge_conn(conn);
1279 if (!circ) {
1280 log_info(domain,"conn has no circuit! Closing.");
1281 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1282 return -1;
1285 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
1286 return 0;
1288 if (conn->package_window <= 0) {
1289 log_info(domain,"called with package_window %d. Skipping.",
1290 conn->package_window);
1291 connection_stop_reading(TO_CONN(conn));
1292 return 0;
1295 amount_to_process = buf_datalen(conn->_base.inbuf);
1297 if (!amount_to_process)
1298 return 0;
1300 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
1301 return 0;
1303 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
1304 length = RELAY_PAYLOAD_SIZE;
1305 } else {
1306 length = amount_to_process;
1308 stats_n_data_bytes_packaged += length;
1309 stats_n_data_cells_packaged += 1;
1311 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1313 log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
1314 (int)length, (int)buf_datalen(conn->_base.inbuf));
1316 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1317 payload, length) < 0 )
1318 /* circuit got marked for close, don't continue, don't need to mark conn */
1319 return 0;
1321 if (!conn->cpath_layer) { /* non-rendezvous exit */
1322 tor_assert(circ->package_window > 0);
1323 circ->package_window--;
1324 } else { /* we're an AP, or an exit on a rendezvous circ */
1325 tor_assert(conn->cpath_layer->package_window > 0);
1326 conn->cpath_layer->package_window--;
1329 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1330 connection_stop_reading(TO_CONN(conn));
1331 log_debug(domain,"conn->package_window reached 0.");
1332 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
1333 return 0; /* don't process the inbuf any more */
1335 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1337 /* handle more if there's more, or return 0 if there isn't */
1338 goto repeat_connection_edge_package_raw_inbuf;
1341 /** Called when we've just received a relay data cell, or when
1342 * we've just finished flushing all bytes to stream <b>conn</b>.
1344 * If conn->outbuf is not too full, and our deliver window is
1345 * low, send back a suitable number of stream-level sendme cells.
1347 void
1348 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1350 circuit_t *circ;
1352 if (connection_outbuf_too_full(TO_CONN(conn)))
1353 return;
1355 circ = circuit_get_by_edge_conn(conn);
1356 if (!circ) {
1357 /* this can legitimately happen if the destroy has already
1358 * arrived and torn down the circuit */
1359 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1360 return;
1363 while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1364 log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
1365 "Outbuf %d, Queuing stream sendme.",
1366 (int)conn->_base.outbuf_flushlen);
1367 conn->deliver_window += STREAMWINDOW_INCREMENT;
1368 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
1369 NULL, 0) < 0) {
1370 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
1371 return; /* the circuit's closed, don't continue */
1376 /** The circuit <b>circ</b> has received a circuit-level sendme
1377 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1378 * attached streams and let them resume reading and packaging, if
1379 * their stream windows allow it.
1381 static void
1382 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1385 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1387 if (CIRCUIT_IS_ORIGIN(circ))
1388 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
1389 circ, layer_hint);
1390 else
1391 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
1392 circ, layer_hint);
1395 /** A helper function for circuit_resume_edge_reading() above.
1396 * The arguments are the same, except that <b>conn</b> is the head
1397 * of a linked list of edge streams that should each be considered.
1399 static int
1400 circuit_resume_edge_reading_helper(edge_connection_t *conn,
1401 circuit_t *circ,
1402 crypt_path_t *layer_hint)
1404 for ( ; conn; conn=conn->next_stream) {
1405 if (conn->_base.marked_for_close)
1406 continue;
1407 if ((!layer_hint && conn->package_window > 0) ||
1408 (layer_hint && conn->package_window > 0 &&
1409 conn->cpath_layer == layer_hint)) {
1410 connection_start_reading(TO_CONN(conn));
1411 /* handle whatever might still be on the inbuf */
1412 if (connection_edge_package_raw_inbuf(conn, 1)<0) {
1413 /* (We already sent an end cell if possible) */
1414 connection_mark_for_close(TO_CONN(conn));
1415 continue;
1418 /* If the circuit won't accept any more data, return without looking
1419 * at any more of the streams. Any connections that should be stopped
1420 * have already been stopped by connection_edge_package_raw_inbuf. */
1421 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1422 return -1;
1425 return 0;
1428 /** Check if the package window for <b>circ</b> is empty (at
1429 * hop <b>layer_hint</b> if it's defined).
1431 * If yes, tell edge streams to stop reading and return 1.
1432 * Else return 0.
1434 static int
1435 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1437 edge_connection_t *conn = NULL;
1438 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1440 if (!layer_hint) {
1441 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1442 log_debug(domain,"considering circ->package_window %d",
1443 circ->package_window);
1444 if (circ->package_window <= 0) {
1445 log_debug(domain,"yes, not-at-origin. stopped.");
1446 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
1447 connection_stop_reading(TO_CONN(conn));
1448 return 1;
1450 return 0;
1452 /* else, layer hint is defined, use it */
1453 log_debug(domain,"considering layer_hint->package_window %d",
1454 layer_hint->package_window);
1455 if (layer_hint->package_window <= 0) {
1456 log_debug(domain,"yes, at-origin. stopped.");
1457 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
1458 conn=conn->next_stream)
1459 if (conn->cpath_layer == layer_hint)
1460 connection_stop_reading(TO_CONN(conn));
1461 return 1;
1463 return 0;
1466 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1467 * <b>layer_hint</b> if it's defined) is low enough that we should
1468 * send a circuit-level sendme back down the circuit. If so, send
1469 * enough sendmes that the window would be overfull if we sent any
1470 * more.
1472 static void
1473 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1475 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1476 // layer_hint ? "defined" : "null");
1477 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
1478 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1479 log_debug(LD_CIRC,"Queuing circuit sendme.");
1480 if (layer_hint)
1481 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1482 else
1483 circ->deliver_window += CIRCWINDOW_INCREMENT;
1484 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
1485 NULL, 0, layer_hint) < 0) {
1486 log_warn(LD_CIRC,
1487 "relay_send_command_from_edge failed. Circuit's closed.");
1488 return; /* the circuit's closed, don't continue */
1493 /** Stop reading on edge connections when we have this many cells
1494 * waiting on the appropriate queue. */
1495 #define CELL_QUEUE_HIGHWATER_SIZE 256
1496 /** Start reading from edge connections again when we get down to this many
1497 * cells. */
1498 #define CELL_QUEUE_LOWWATER_SIZE 64
1500 #ifdef ACTIVE_CIRCUITS_PARANOIA
1501 #define assert_active_circuits_ok_paranoid(conn) \
1502 assert_active_circuits_ok(conn)
1503 #else
1504 #define assert_active_circuits_ok_paranoid(conn)
1505 #endif
1507 /** The total number of cells we have allocated from the memory pool. */
1508 static int total_cells_allocated = 0;
1510 /** A memory pool to allocate packed_cell_t objects. */
1511 static mp_pool_t *cell_pool = NULL;
1513 /** Allocate structures to hold cells. */
1514 void
1515 init_cell_pool(void)
1517 tor_assert(!cell_pool);
1518 cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
1521 /** Free all storage used to hold cells. */
1522 void
1523 free_cell_pool(void)
1525 /* Maybe we haven't called init_cell_pool yet; need to check for it. */
1526 if (cell_pool) {
1527 mp_pool_destroy(cell_pool);
1528 cell_pool = NULL;
1532 /** Free excess storage in cell pool. */
1533 void
1534 clean_cell_pool(void)
1536 tor_assert(cell_pool);
1537 mp_pool_clean(cell_pool, 0, 1);
1540 /** Release storage held by <b>cell</b>. */
1541 static INLINE void
1542 packed_cell_free(packed_cell_t *cell)
1544 --total_cells_allocated;
1545 mp_pool_release(cell);
1548 /** Allocate and return a new packed_cell_t. */
1549 static INLINE packed_cell_t *
1550 packed_cell_alloc(void)
1552 ++total_cells_allocated;
1553 return mp_pool_get(cell_pool);
1556 /** Log current statistics for cell pool allocation at log level
1557 * <b>severity</b>. */
1558 void
1559 dump_cell_pool_usage(int severity)
1561 circuit_t *c;
1562 int n_circs = 0;
1563 int n_cells = 0;
1564 for (c = _circuit_get_global_list(); c; c = c->next) {
1565 n_cells += c->n_conn_cells.n;
1566 if (!CIRCUIT_IS_ORIGIN(c))
1567 n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
1568 ++n_circs;
1570 log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
1571 n_cells, n_circs, total_cells_allocated - n_cells);
1572 mp_pool_log_status(cell_pool, severity);
1575 /** Allocate a new copy of packed <b>cell</b>. */
1576 static INLINE packed_cell_t *
1577 packed_cell_copy(const cell_t *cell)
1579 packed_cell_t *c = packed_cell_alloc();
1580 cell_pack(c, cell);
1581 c->next = NULL;
1582 return c;
1585 /** Append <b>cell</b> to the end of <b>queue</b>. */
1586 void
1587 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
1589 if (queue->tail) {
1590 tor_assert(!queue->tail->next);
1591 queue->tail->next = cell;
1592 } else {
1593 queue->head = cell;
1595 queue->tail = cell;
1596 cell->next = NULL;
1597 ++queue->n;
1600 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
1601 void
1602 cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
1604 cell_queue_append(queue, packed_cell_copy(cell));
1607 /** Remove and free every cell in <b>queue</b>. */
1608 void
1609 cell_queue_clear(cell_queue_t *queue)
1611 packed_cell_t *cell, *next;
1612 cell = queue->head;
1613 while (cell) {
1614 next = cell->next;
1615 packed_cell_free(cell);
1616 cell = next;
1618 queue->head = queue->tail = NULL;
1619 queue->n = 0;
1622 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
1623 * <b>queue</b> is empty. */
1624 static INLINE packed_cell_t *
1625 cell_queue_pop(cell_queue_t *queue)
1627 packed_cell_t *cell = queue->head;
1628 if (!cell)
1629 return NULL;
1630 queue->head = cell->next;
1631 if (cell == queue->tail) {
1632 tor_assert(!queue->head);
1633 queue->tail = NULL;
1635 --queue->n;
1636 return cell;
1639 /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
1640 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1641 static INLINE circuit_t **
1642 next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1644 tor_assert(circ);
1645 tor_assert(conn);
1646 if (conn == circ->n_conn) {
1647 return &circ->next_active_on_n_conn;
1648 } else {
1649 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1650 tor_assert(conn == orcirc->p_conn);
1651 return &orcirc->next_active_on_p_conn;
1655 /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
1656 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1657 static INLINE circuit_t **
1658 prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1660 tor_assert(circ);
1661 tor_assert(conn);
1662 if (conn == circ->n_conn) {
1663 return &circ->prev_active_on_n_conn;
1664 } else {
1665 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1666 tor_assert(conn == orcirc->p_conn);
1667 return &orcirc->prev_active_on_p_conn;
1671 /** Add <b>circ</b> to the list of circuits with pending cells on
1672 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1673 void
1674 make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
1676 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1677 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1679 if (*nextp && *prevp) {
1680 /* Already active. */
1681 return;
1684 if (! conn->active_circuits) {
1685 conn->active_circuits = circ;
1686 *prevp = *nextp = circ;
1687 } else {
1688 circuit_t *head = conn->active_circuits;
1689 circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
1690 *next_circ_on_conn_p(old_tail, conn) = circ;
1691 *nextp = head;
1692 *prev_circ_on_conn_p(head, conn) = circ;
1693 *prevp = old_tail;
1695 assert_active_circuits_ok_paranoid(conn);
1698 /** Remove <b>circ</b> to the list of circuits with pending cells on
1699 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1700 void
1701 make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
1703 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1704 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1705 circuit_t *next = *nextp, *prev = *prevp;
1707 if (!next && !prev) {
1708 /* Already inactive. */
1709 return;
1712 tor_assert(next && prev);
1713 tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
1714 tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
1716 if (next == circ) {
1717 conn->active_circuits = NULL;
1718 } else {
1719 *prev_circ_on_conn_p(next, conn) = prev;
1720 *next_circ_on_conn_p(prev, conn) = next;
1721 if (conn->active_circuits == circ)
1722 conn->active_circuits = next;
1724 *prevp = *nextp = NULL;
1725 assert_active_circuits_ok_paranoid(conn);
1728 /** Remove all circuits from the list of circuits with pending cells on
1729 * <b>conn</b>. */
1730 void
1731 connection_or_unlink_all_active_circs(or_connection_t *orconn)
1733 circuit_t *head = orconn->active_circuits;
1734 circuit_t *cur = head;
1735 if (! head)
1736 return;
1737 do {
1738 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1739 *prev_circ_on_conn_p(cur, orconn) = NULL;
1740 *next_circ_on_conn_p(cur, orconn) = NULL;
1741 cur = next;
1742 } while (cur != head);
1743 orconn->active_circuits = NULL;
1746 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
1747 * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
1748 * and start or stop reading as appropriate. */
1749 static void
1750 set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
1751 int block)
1753 edge_connection_t *edge = NULL;
1754 if (circ->n_conn == orconn) {
1755 circ->streams_blocked_on_n_conn = block;
1756 if (CIRCUIT_IS_ORIGIN(circ))
1757 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
1758 } else {
1759 circ->streams_blocked_on_p_conn = block;
1760 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1761 edge = TO_OR_CIRCUIT(circ)->n_streams;
1764 for (; edge; edge = edge->next_stream) {
1765 connection_t *conn = TO_CONN(edge);
1766 edge->edge_blocked_on_circ = block;
1768 if (!conn->read_event) {
1769 /* This connection is a placeholder for something; probably a DNS
1770 * request. It can't actually stop or start reading.*/
1771 continue;
1774 if (block) {
1775 if (connection_is_reading(conn))
1776 connection_stop_reading(conn);
1777 } else {
1778 /* Is this right? */
1779 if (!connection_is_reading(conn))
1780 connection_start_reading(conn);
1785 /** Pull as many cells as possible (but no more than <b>max</b>) from the
1786 * queue of the first active circuit on <b>conn</b>, and write then to
1787 * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
1788 * the active circuit pointer to the next active circuit in the ring. */
1790 connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
1791 time_t now)
1793 int n_flushed;
1794 cell_queue_t *queue;
1795 circuit_t *circ;
1796 int streams_blocked;
1797 circ = conn->active_circuits;
1798 if (!circ) return 0;
1799 assert_active_circuits_ok_paranoid(conn);
1800 if (circ->n_conn == conn) {
1801 queue = &circ->n_conn_cells;
1802 streams_blocked = circ->streams_blocked_on_n_conn;
1803 } else {
1804 queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
1805 streams_blocked = circ->streams_blocked_on_p_conn;
1807 tor_assert(*next_circ_on_conn_p(circ,conn));
1809 for (n_flushed = 0; n_flushed < max && queue->head; ) {
1810 packed_cell_t *cell = cell_queue_pop(queue);
1811 tor_assert(*next_circ_on_conn_p(circ,conn));
1813 connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
1815 packed_cell_free(cell);
1816 ++n_flushed;
1817 if (circ != conn->active_circuits) {
1818 /* If this happens, the current circuit just got made inactive by
1819 * a call in connection_write_to_buf(). That's nothing to worry about:
1820 * circuit_make_inactive_on_conn() already advanced conn->active_circuits
1821 * for us.
1823 assert_active_circuits_ok_paranoid(conn);
1824 goto done;
1827 tor_assert(*next_circ_on_conn_p(circ,conn));
1828 assert_active_circuits_ok_paranoid(conn);
1829 conn->active_circuits = *next_circ_on_conn_p(circ, conn);
1831 /* Is the cell queue low enough to unblock all the streams that are waiting
1832 * to write to this circuit? */
1833 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
1834 set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
1836 /* Did we just ran out of cells on this queue? */
1837 if (queue->n == 0) {
1838 log_debug(LD_GENERAL, "Made a circuit inactive.");
1839 make_circuit_inactive_on_conn(circ, conn);
1841 done:
1842 if (n_flushed)
1843 conn->timestamp_last_added_nonpadding = now;
1844 return n_flushed;
1847 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
1848 * transmitting in <b>direction</b>. */
1849 void
1850 append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
1851 cell_t *cell, cell_direction_t direction)
1853 cell_queue_t *queue;
1854 int streams_blocked;
1855 if (direction == CELL_DIRECTION_OUT) {
1856 queue = &circ->n_conn_cells;
1857 streams_blocked = circ->streams_blocked_on_n_conn;
1858 } else {
1859 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1860 queue = &orcirc->p_conn_cells;
1861 streams_blocked = circ->streams_blocked_on_p_conn;
1863 if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
1864 /* V1 connections don't understand RELAY_EARLY. */
1865 cell->command = CELL_RELAY;
1868 cell_queue_append_packed_copy(queue, cell);
1870 /* If we have too many cells on the circuit, we should stop reading from
1871 * the edge streams for a while. */
1872 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
1873 set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
1875 if (queue->n == 1) {
1876 /* This was the first cell added to the queue. We need to make this
1877 * circuit active. */
1878 log_debug(LD_GENERAL, "Made a circuit active.");
1879 make_circuit_active_on_conn(circ, orconn);
1882 if (! buf_datalen(orconn->_base.outbuf)) {
1883 /* There is no data at all waiting to be sent on the outbuf. Add a
1884 * cell, so that we can notice when it gets flushed, flushed_some can
1885 * get called, and we can start putting more data onto the buffer then.
1887 log_debug(LD_GENERAL, "Primed a buffer.");
1888 connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
1892 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
1893 * have at least 18 bytes of free space. The encoding is, as specified in
1894 * tor-spec.txt:
1895 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
1896 * LENGTH [1 byte]
1897 * ADDRESS [length bytes]
1898 * Return the number of bytes added, or -1 on error */
1900 append_address_to_payload(char *payload_out, const tor_addr_t *addr)
1902 uint32_t a;
1903 switch (tor_addr_family(addr)) {
1904 case AF_INET:
1905 payload_out[0] = RESOLVED_TYPE_IPV4;
1906 payload_out[1] = 4;
1907 a = tor_addr_to_ipv4n(addr);
1908 memcpy(payload_out+2, &a, 4);
1909 return 6;
1910 case AF_INET6:
1911 payload_out[0] = RESOLVED_TYPE_IPV6;
1912 payload_out[1] = 16;
1913 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
1914 return 18;
1915 case AF_UNSPEC:
1916 default:
1917 return -1;
1921 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
1922 * encoded as by append_address_to_payload(), try to decode the address into
1923 * *<b>addr_out</b>. Return the next byte in the payload after the address on
1924 * success, or NULL on failure. */
1925 const char *
1926 decode_address_from_payload(tor_addr_t *addr_out, const char *payload,
1927 int payload_len)
1929 if (payload_len < 2)
1930 return NULL;
1931 if (payload_len < 2+(uint8_t)payload[1])
1932 return NULL;
1934 switch (payload[0]) {
1935 case RESOLVED_TYPE_IPV4:
1936 if (payload[1] != 4)
1937 return NULL;
1938 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
1939 break;
1940 case RESOLVED_TYPE_IPV6:
1941 if (payload[1] != 16)
1942 return NULL;
1943 tor_addr_from_ipv6_bytes(addr_out, payload+2);
1944 break;
1945 default:
1946 tor_addr_make_unspec(addr_out);
1947 break;
1949 return payload + 2 + (uint8_t)payload[1];
1952 /** Fail with an assert if the active circuits ring on <b>orconn</b> is
1953 * corrupt. */
1954 void
1955 assert_active_circuits_ok(or_connection_t *orconn)
1957 circuit_t *head = orconn->active_circuits;
1958 circuit_t *cur = head;
1959 if (! head)
1960 return;
1961 do {
1962 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1963 circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
1964 tor_assert(next);
1965 tor_assert(prev);
1966 tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
1967 tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
1968 cur = next;
1969 } while (cur != head);