Make payloads into uint8_t.
[tor/rransom.git] / src / or / relay.c
blob02671473e6b47c64f642341809d0f1be8ffaf222
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, (char*)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, (char*) 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, uint8_t *in,
116 int encrypt_mode)
118 int r;
119 (void)encrypt_mode;
120 r = crypto_cipher_crypt_inplace(cipher, (char*) 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(uint8_t *dest, const relay_header_t *src)
437 set_uint8(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 uint8_t *src)
450 dest->command = get_uint8(src);
451 dest->recognized = ntohs(get_uint16(src+1));
452 dest->stream_id = ntohs(get_uint16(src+3));
453 memcpy(dest->integrity, src+5, 4);
454 dest->length = ntohs(get_uint16(src+9));
457 /** Convert the relay <b>command</b> into a human-readable string. */
458 static const char *
459 relay_command_to_string(uint8_t command)
461 switch (command) {
462 case RELAY_COMMAND_BEGIN: return "BEGIN";
463 case RELAY_COMMAND_DATA: return "DATA";
464 case RELAY_COMMAND_END: return "END";
465 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
466 case RELAY_COMMAND_SENDME: return "SENDME";
467 case RELAY_COMMAND_EXTEND: return "EXTEND";
468 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
469 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
470 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
471 case RELAY_COMMAND_DROP: return "DROP";
472 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
473 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
474 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
475 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
476 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
477 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
478 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
479 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
480 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
481 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
482 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
483 return "RENDEZVOUS_ESTABLISHED";
484 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
485 default: return "(unrecognized)";
489 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
490 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
491 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
492 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
493 * destination hop for OP->OR cells.
495 * If you can't send the cell, mark the circuit for close and return -1. Else
496 * return 0.
499 relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
500 uint8_t relay_command, const char *payload,
501 size_t payload_len, crypt_path_t *cpath_layer)
503 cell_t cell;
504 relay_header_t rh;
505 cell_direction_t cell_direction;
506 /* XXXX NM Split this function into a separate versions per circuit type? */
508 tor_assert(circ);
509 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
511 memset(&cell, 0, sizeof(cell_t));
512 cell.command = CELL_RELAY;
513 if (cpath_layer) {
514 cell.circ_id = circ->n_circ_id;
515 cell_direction = CELL_DIRECTION_OUT;
516 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
517 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
518 cell_direction = CELL_DIRECTION_IN;
519 } else {
520 return -1;
523 memset(&rh, 0, sizeof(rh));
524 rh.command = relay_command;
525 rh.stream_id = stream_id;
526 rh.length = payload_len;
527 relay_header_pack(cell.payload, &rh);
528 if (payload_len)
529 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
531 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
532 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
534 if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
535 /* if we're using relaybandwidthrate, this conn wants priority */
536 circ->n_conn->client_used = approx_time();
539 if (cell_direction == CELL_DIRECTION_OUT) {
540 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
541 if (origin_circ->remaining_relay_early_cells > 0 &&
542 (relay_command == RELAY_COMMAND_EXTEND ||
543 (cpath_layer != origin_circ->cpath &&
544 !CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(circ->purpose)))) {
545 /* If we've got any relay_early cells left, and we're sending
546 * an extend cell or (we're not talking to the first hop and we're
547 * not talking to a rendezvous circuit), use one of them.
548 * Don't worry about the conn protocol version:
549 * append_cell_to_circuit_queue will fix it up. */
550 /* XXX For now, clients don't use RELAY_EARLY cells when sending
551 * relay cells on rendezvous circuits. See bug 1038. Eventually,
552 * we can take this behavior away in favor of having clients avoid
553 * rendezvous points running 0.2.1.3-alpha through 0.2.1.18. -RD */
554 cell.command = CELL_RELAY_EARLY;
555 --origin_circ->remaining_relay_early_cells;
556 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
557 (int)origin_circ->remaining_relay_early_cells);
558 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
559 * task 878. */
560 origin_circ->relay_early_commands[
561 origin_circ->relay_early_cells_sent++] = relay_command;
562 } else if (relay_command == RELAY_COMMAND_EXTEND) {
563 /* If no RELAY_EARLY cells can be sent over this circuit, log which
564 * commands have been sent as RELAY_EARLY cells before; helps debug
565 * task 878. */
566 smartlist_t *commands_list = smartlist_create();
567 int i = 0;
568 char *commands = NULL;
569 for (; i < origin_circ->relay_early_cells_sent; i++)
570 smartlist_add(commands_list, (char *)
571 relay_command_to_string(origin_circ->relay_early_commands[i]));
572 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
573 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
574 "but we have run out of RELAY_EARLY cells on that circuit. "
575 "Commands sent before: %s", commands);
576 tor_free(commands);
577 smartlist_free(commands_list);
581 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
582 < 0) {
583 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
584 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
585 return -1;
587 return 0;
590 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
591 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
592 * that's sending the relay cell, or NULL if it's a control cell.
593 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
594 * for OP->OR cells.
596 * If you can't send the cell, mark the circuit for close and
597 * return -1. Else return 0.
600 connection_edge_send_command(edge_connection_t *fromconn,
601 uint8_t relay_command, const char *payload,
602 size_t payload_len)
604 /* XXXX NM Split this function into a separate versions per circuit type? */
605 circuit_t *circ;
606 tor_assert(fromconn);
607 circ = fromconn->on_circuit;
609 if (fromconn->_base.marked_for_close) {
610 log_warn(LD_BUG,
611 "called on conn that's already marked for close at %s:%d.",
612 fromconn->_base.marked_for_close_file,
613 fromconn->_base.marked_for_close);
614 return 0;
617 if (!circ) {
618 if (fromconn->_base.type == CONN_TYPE_AP) {
619 log_info(LD_APP,"no circ. Closing conn.");
620 connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
621 } else {
622 log_info(LD_EXIT,"no circ. Closing conn.");
623 fromconn->edge_has_sent_end = 1; /* no circ to send to */
624 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
625 connection_mark_for_close(TO_CONN(fromconn));
627 return -1;
630 return relay_send_command_from_edge(fromconn->stream_id, circ,
631 relay_command, payload,
632 payload_len, fromconn->cpath_layer);
635 /** How many times will I retry a stream that fails due to DNS
636 * resolve failure or misc error?
638 #define MAX_RESOLVE_FAILURES 3
640 /** Return 1 if reason is something that you should retry if you
641 * get the end cell before you've connected; else return 0. */
642 static int
643 edge_reason_is_retriable(int reason)
645 return reason == END_STREAM_REASON_HIBERNATING ||
646 reason == END_STREAM_REASON_RESOURCELIMIT ||
647 reason == END_STREAM_REASON_EXITPOLICY ||
648 reason == END_STREAM_REASON_RESOLVEFAILED ||
649 reason == END_STREAM_REASON_MISC ||
650 reason == END_STREAM_REASON_NOROUTE;
653 /** Called when we receive an END cell on a stream that isn't open yet,
654 * from the client side.
655 * Arguments are as for connection_edge_process_relay_cell().
657 static int
658 connection_ap_process_end_not_open(
659 relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
660 edge_connection_t *conn, crypt_path_t *layer_hint)
662 struct in_addr in;
663 routerinfo_t *exitrouter;
664 int reason = *(cell->payload+RELAY_HEADER_SIZE);
665 int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
666 (void) layer_hint; /* unused */
668 if (rh->length > 0 && edge_reason_is_retriable(reason) &&
669 !connection_edge_is_rendezvous_stream(conn) /* avoid retry if rend */
671 log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
672 safe_str(conn->socks_request->address),
673 stream_end_reason_to_string(reason));
674 exitrouter =
675 router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
676 switch (reason) {
677 case END_STREAM_REASON_EXITPOLICY:
678 if (rh->length >= 5) {
679 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
680 int ttl;
681 if (!addr) {
682 log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
683 safe_str(conn->socks_request->address));
684 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
685 return 0;
687 if (rh->length >= 9)
688 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
689 else
690 ttl = -1;
692 if (get_options()->ClientDNSRejectInternalAddresses &&
693 is_internal_IP(addr, 0)) {
694 log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
695 safe_str(conn->socks_request->address));
696 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
697 return 0;
699 client_dns_set_addressmap(conn->socks_request->address, addr,
700 conn->chosen_exit_name, ttl);
702 /* check if he *ought* to have allowed it */
703 if (exitrouter &&
704 (rh->length < 5 ||
705 (tor_inet_aton(conn->socks_request->address, &in) &&
706 !conn->chosen_exit_name))) {
707 log_info(LD_APP,
708 "Exitrouter '%s' seems to be more restrictive than its exit "
709 "policy. Not using this router as exit for now.",
710 exitrouter->nickname);
711 policies_set_router_exitpolicy_to_reject_all(exitrouter);
713 /* rewrite it to an IP if we learned one. */
714 if (addressmap_rewrite(conn->socks_request->address,
715 sizeof(conn->socks_request->address),
716 NULL)) {
717 control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
719 if (conn->chosen_exit_optional ||
720 conn->chosen_exit_retries) {
721 /* stop wanting a specific exit */
722 conn->chosen_exit_optional = 0;
723 /* A non-zero chosen_exit_retries can happen if we set a
724 * TrackHostExits for this address under a port that the exit
725 * relay allows, but then try the same address with a different
726 * port that it doesn't allow to exit. We shouldn't unregister
727 * the mapping, since it is probably still wanted on the
728 * original port. But now we give away to the exit relay that
729 * we probably have a TrackHostExits on it. So be it. */
730 conn->chosen_exit_retries = 0;
731 tor_free(conn->chosen_exit_name); /* clears it */
733 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
734 return 0;
735 /* else, conn will get closed below */
736 break;
737 case END_STREAM_REASON_CONNECTREFUSED:
738 if (!conn->chosen_exit_optional)
739 break; /* break means it'll close, below */
740 /* Else fall through: expire this circuit, clear the
741 * chosen_exit_name field, and try again. */
742 case END_STREAM_REASON_RESOLVEFAILED:
743 case END_STREAM_REASON_TIMEOUT:
744 case END_STREAM_REASON_MISC:
745 case END_STREAM_REASON_NOROUTE:
746 if (client_dns_incr_failures(conn->socks_request->address)
747 < MAX_RESOLVE_FAILURES) {
748 /* We haven't retried too many times; reattach the connection. */
749 circuit_log_path(LOG_INFO,LD_APP,circ);
750 tor_assert(circ->_base.timestamp_dirty);
751 circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
753 if (conn->chosen_exit_optional) {
754 /* stop wanting a specific exit */
755 conn->chosen_exit_optional = 0;
756 tor_free(conn->chosen_exit_name); /* clears it */
758 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
759 return 0;
760 /* else, conn will get closed below */
761 } else {
762 log_notice(LD_APP,
763 "Have tried resolving or connecting to address '%s' "
764 "at %d different places. Giving up.",
765 safe_str(conn->socks_request->address),
766 MAX_RESOLVE_FAILURES);
767 /* clear the failures, so it will have a full try next time */
768 client_dns_clear_failures(conn->socks_request->address);
770 break;
771 case END_STREAM_REASON_HIBERNATING:
772 case END_STREAM_REASON_RESOURCELIMIT:
773 if (exitrouter) {
774 policies_set_router_exitpolicy_to_reject_all(exitrouter);
776 if (conn->chosen_exit_optional) {
777 /* stop wanting a specific exit */
778 conn->chosen_exit_optional = 0;
779 tor_free(conn->chosen_exit_name); /* clears it */
781 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
782 return 0;
783 /* else, will close below */
784 break;
785 } /* end switch */
786 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
789 log_info(LD_APP,
790 "Edge got end (%s) before we're connected. Marking for close.",
791 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
792 circuit_log_path(LOG_INFO,LD_APP,circ);
793 /* need to test because of detach_retriable */
794 if (!conn->_base.marked_for_close)
795 connection_mark_unattached_ap(conn, control_reason);
796 return 0;
799 /** Helper: change the socks_request-&gt;address field on conn to the
800 * dotted-quad representation of <b>new_addr</b> (given in host order),
801 * and send an appropriate REMAP event. */
802 static void
803 remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
805 struct in_addr in;
807 in.s_addr = htonl(new_addr);
808 tor_inet_ntoa(&in, conn->socks_request->address,
809 sizeof(conn->socks_request->address));
810 control_event_stream_status(conn, STREAM_EVENT_REMAP,
811 REMAP_STREAM_SOURCE_EXIT);
814 /** An incoming relay cell has arrived from circuit <b>circ</b> to
815 * stream <b>conn</b>.
817 * The arguments here are the same as in
818 * connection_edge_process_relay_cell() below; this function is called
819 * from there when <b>conn</b> is defined and not in an open state.
821 static int
822 connection_edge_process_relay_cell_not_open(
823 relay_header_t *rh, cell_t *cell, circuit_t *circ,
824 edge_connection_t *conn, crypt_path_t *layer_hint)
826 if (rh->command == RELAY_COMMAND_END) {
827 if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
828 return connection_ap_process_end_not_open(rh, cell,
829 TO_ORIGIN_CIRCUIT(circ), conn,
830 layer_hint);
831 } else {
832 /* we just got an 'end', don't need to send one */
833 conn->edge_has_sent_end = 1;
834 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
835 END_STREAM_REASON_FLAG_REMOTE;
836 connection_mark_for_close(TO_CONN(conn));
837 return 0;
841 if (conn->_base.type == CONN_TYPE_AP &&
842 rh->command == RELAY_COMMAND_CONNECTED) {
843 tor_assert(CIRCUIT_IS_ORIGIN(circ));
844 if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
845 log_fn(LOG_PROTOCOL_WARN, LD_APP,
846 "Got 'connected' while not in state connect_wait. Dropping.");
847 return 0;
849 conn->_base.state = AP_CONN_STATE_OPEN;
850 log_info(LD_APP,"'connected' received after %d seconds.",
851 (int)(time(NULL) - conn->_base.timestamp_lastread));
852 if (rh->length >= 4) {
853 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
854 int ttl;
855 if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
856 is_internal_IP(addr, 0))) {
857 char buf[INET_NTOA_BUF_LEN];
858 struct in_addr a;
859 a.s_addr = htonl(addr);
860 tor_inet_ntoa(&a, buf, sizeof(buf));
861 log_info(LD_APP,
862 "...but it claims the IP address was %s. Closing.", buf);
863 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
864 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
865 return 0;
867 if (rh->length >= 8)
868 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
869 else
870 ttl = -1;
871 client_dns_set_addressmap(conn->socks_request->address, addr,
872 conn->chosen_exit_name, ttl);
874 remap_event_helper(conn, addr);
876 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
877 /* don't send a socks reply to transparent conns */
878 if (!conn->socks_request->has_finished)
879 connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
881 /* Was it a linked dir conn? If so, a dir request just started to
882 * fetch something; this could be a bootstrap status milestone. */
883 log_debug(LD_APP, "considering");
884 if (TO_CONN(conn)->linked_conn &&
885 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
886 connection_t *dirconn = TO_CONN(conn)->linked_conn;
887 log_debug(LD_APP, "it is! %d", dirconn->purpose);
888 switch (dirconn->purpose) {
889 case DIR_PURPOSE_FETCH_CERTIFICATE:
890 if (consensus_is_waiting_for_certs())
891 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
892 break;
893 case DIR_PURPOSE_FETCH_CONSENSUS:
894 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
895 break;
896 case DIR_PURPOSE_FETCH_SERVERDESC:
897 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
898 count_loading_descriptors_progress());
899 break;
903 /* handle anything that might have queued */
904 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
905 /* (We already sent an end cell if possible) */
906 connection_mark_for_close(TO_CONN(conn));
907 return 0;
909 return 0;
911 if (conn->_base.type == CONN_TYPE_AP &&
912 rh->command == RELAY_COMMAND_RESOLVED) {
913 int ttl;
914 int answer_len;
915 uint8_t answer_type;
916 if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
917 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
918 "not in state resolve_wait. Dropping.");
919 return 0;
921 tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
922 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
923 if (rh->length < 2 || answer_len+2>rh->length) {
924 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
925 "Dropping malformed 'resolved' cell");
926 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
927 return 0;
929 answer_type = cell->payload[RELAY_HEADER_SIZE];
930 if (rh->length >= answer_len+6)
931 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
932 2+answer_len));
933 else
934 ttl = -1;
935 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
936 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
937 if (get_options()->ClientDNSRejectInternalAddresses &&
938 is_internal_IP(addr, 0)) {
939 char buf[INET_NTOA_BUF_LEN];
940 struct in_addr a;
941 a.s_addr = htonl(addr);
942 tor_inet_ntoa(&a, buf, sizeof(buf));
943 log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
944 connection_ap_handshake_socks_resolved(conn,
945 RESOLVED_TYPE_ERROR_TRANSIENT,
946 0, NULL, 0, TIME_MAX);
947 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
948 return 0;
951 connection_ap_handshake_socks_resolved(conn,
952 answer_type,
953 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
954 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
955 ttl,
956 -1);
957 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
958 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
959 remap_event_helper(conn, addr);
961 connection_mark_unattached_ap(conn,
962 END_STREAM_REASON_DONE |
963 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
964 return 0;
967 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
968 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
969 rh->command, conn->_base.state,
970 conn_state_to_string(conn->_base.type, conn->_base.state));
971 return 0; /* for forward compatibility, don't kill the circuit */
972 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
973 // connection_mark_for_close(conn);
974 // return -1;
977 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
978 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
979 * destined for <b>conn</b>.
981 * If <b>layer_hint</b> is defined, then we're the origin of the
982 * circuit, and it specifies the hop that packaged <b>cell</b>.
984 * Return -reason if you want to warn and tear down the circuit, else 0.
986 static int
987 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
988 edge_connection_t *conn,
989 crypt_path_t *layer_hint)
991 static int num_seen=0;
992 relay_header_t rh;
993 unsigned domain = layer_hint?LD_APP:LD_EXIT;
994 int reason;
996 tor_assert(cell);
997 tor_assert(circ);
999 relay_header_unpack(&rh, cell->payload);
1000 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1001 num_seen++;
1002 log_debug(domain, "Now seen %d relay cells here.", num_seen);
1004 if (rh.length > RELAY_PAYLOAD_SIZE) {
1005 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1006 "Relay cell length field too long. Closing circuit.");
1007 return - END_CIRC_REASON_TORPROTOCOL;
1010 /* either conn is NULL, in which case we've got a control cell, or else
1011 * conn points to the recognized stream. */
1013 if (conn && !connection_state_is_open(TO_CONN(conn)))
1014 return connection_edge_process_relay_cell_not_open(
1015 &rh, cell, circ, conn, layer_hint);
1017 switch (rh.command) {
1018 case RELAY_COMMAND_DROP:
1019 // log_info(domain,"Got a relay-level padding cell. Dropping.");
1020 return 0;
1021 case RELAY_COMMAND_BEGIN:
1022 case RELAY_COMMAND_BEGIN_DIR:
1023 if (layer_hint &&
1024 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
1025 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1026 "Relay begin request unsupported at AP. Dropping.");
1027 return 0;
1029 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
1030 layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
1031 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1032 "Relay begin request to Hidden Service "
1033 "from intermediary node. Dropping.");
1034 return 0;
1036 if (conn) {
1037 log_fn(LOG_PROTOCOL_WARN, domain,
1038 "Begin cell for known stream. Dropping.");
1039 return 0;
1041 return connection_exit_begin_conn(cell, circ);
1042 case RELAY_COMMAND_DATA:
1043 ++stats_n_data_cells_received;
1044 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1045 (!layer_hint && --circ->deliver_window < 0)) {
1046 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1047 "(relay data) circ deliver_window below 0. Killing.");
1048 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1049 connection_mark_for_close(TO_CONN(conn));
1050 return -END_CIRC_REASON_TORPROTOCOL;
1052 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1053 layer_hint->deliver_window : circ->deliver_window);
1055 circuit_consider_sending_sendme(circ, layer_hint);
1057 if (!conn) {
1058 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1059 rh.stream_id);
1060 return 0;
1063 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1064 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1065 "(relay data) conn deliver_window below 0. Killing.");
1066 return -END_CIRC_REASON_TORPROTOCOL;
1069 stats_n_data_bytes_received += rh.length;
1070 connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
1071 rh.length, TO_CONN(conn));
1072 connection_edge_consider_sending_sendme(conn);
1073 return 0;
1074 case RELAY_COMMAND_END:
1075 reason = rh.length > 0 ?
1076 get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1077 if (!conn) {
1078 log_info(domain,"end cell (%s) dropped, unknown stream.",
1079 stream_end_reason_to_string(reason));
1080 return 0;
1082 /* XXX add to this log_fn the exit node's nickname? */
1083 log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
1084 conn->_base.s,
1085 stream_end_reason_to_string(reason),
1086 conn->stream_id);
1087 if (conn->socks_request && !conn->socks_request->has_finished)
1088 log_warn(LD_BUG,
1089 "open stream hasn't sent socks answer yet? Closing.");
1090 /* We just *got* an end; no reason to send one. */
1091 conn->edge_has_sent_end = 1;
1092 if (!conn->end_reason)
1093 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1094 if (!conn->_base.marked_for_close) {
1095 /* only mark it if not already marked. it's possible to
1096 * get the 'end' right around when the client hangs up on us. */
1097 connection_mark_for_close(TO_CONN(conn));
1098 conn->_base.hold_open_until_flushed = 1;
1100 return 0;
1101 case RELAY_COMMAND_EXTEND:
1102 if (conn) {
1103 log_fn(LOG_PROTOCOL_WARN, domain,
1104 "'extend' cell received for non-zero stream. Dropping.");
1105 return 0;
1107 return circuit_extend(cell, circ);
1108 case RELAY_COMMAND_EXTENDED:
1109 if (!layer_hint) {
1110 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1111 "'extended' unsupported at non-origin. Dropping.");
1112 return 0;
1114 log_debug(domain,"Got an extended cell! Yay.");
1115 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1116 CELL_CREATED,
1117 cell->payload+RELAY_HEADER_SIZE)) < 0) {
1118 log_warn(domain,"circuit_finish_handshake failed.");
1119 return reason;
1121 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1122 log_info(domain,"circuit_send_next_onion_skin() failed.");
1123 return reason;
1125 return 0;
1126 case RELAY_COMMAND_TRUNCATE:
1127 if (layer_hint) {
1128 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1129 "'truncate' unsupported at origin. Dropping.");
1130 return 0;
1132 if (circ->n_conn) {
1133 uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
1134 connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
1135 trunc_reason);
1136 circuit_set_n_circid_orconn(circ, 0, NULL);
1138 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1140 char payload[1];
1141 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1142 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1143 payload, sizeof(payload), NULL);
1145 return 0;
1146 case RELAY_COMMAND_TRUNCATED:
1147 if (!layer_hint) {
1148 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1149 "'truncated' unsupported at non-origin. Dropping.");
1150 return 0;
1152 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
1153 return 0;
1154 case RELAY_COMMAND_CONNECTED:
1155 if (conn) {
1156 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1157 "'connected' unsupported while open. Closing circ.");
1158 return -END_CIRC_REASON_TORPROTOCOL;
1160 log_info(domain,
1161 "'connected' received, no conn attached anymore. Ignoring.");
1162 return 0;
1163 case RELAY_COMMAND_SENDME:
1164 if (!conn) {
1165 if (layer_hint) {
1166 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1167 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1168 layer_hint->package_window);
1169 circuit_resume_edge_reading(circ, layer_hint);
1170 } else {
1171 circ->package_window += CIRCWINDOW_INCREMENT;
1172 log_debug(LD_APP,
1173 "circ-level sendme at non-origin, packagewindow %d.",
1174 circ->package_window);
1175 circuit_resume_edge_reading(circ, layer_hint);
1177 return 0;
1179 conn->package_window += STREAMWINDOW_INCREMENT;
1180 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1181 conn->package_window);
1182 connection_start_reading(TO_CONN(conn));
1183 /* handle whatever might still be on the inbuf */
1184 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
1185 /* (We already sent an end cell if possible) */
1186 connection_mark_for_close(TO_CONN(conn));
1187 return 0;
1189 return 0;
1190 case RELAY_COMMAND_RESOLVE:
1191 if (layer_hint) {
1192 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1193 "resolve request unsupported at AP; dropping.");
1194 return 0;
1195 } else if (conn) {
1196 log_fn(LOG_PROTOCOL_WARN, domain,
1197 "resolve request for known stream; dropping.");
1198 return 0;
1199 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1200 log_fn(LOG_PROTOCOL_WARN, domain,
1201 "resolve request on circ with purpose %d; dropping",
1202 circ->purpose);
1203 return 0;
1205 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1206 return 0;
1207 case RELAY_COMMAND_RESOLVED:
1208 if (conn) {
1209 log_fn(LOG_PROTOCOL_WARN, domain,
1210 "'resolved' unsupported while open. Closing circ.");
1211 return -END_CIRC_REASON_TORPROTOCOL;
1213 log_info(domain,
1214 "'resolved' received, no conn attached anymore. Ignoring.");
1215 return 0;
1216 case RELAY_COMMAND_ESTABLISH_INTRO:
1217 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1218 case RELAY_COMMAND_INTRODUCE1:
1219 case RELAY_COMMAND_INTRODUCE2:
1220 case RELAY_COMMAND_INTRODUCE_ACK:
1221 case RELAY_COMMAND_RENDEZVOUS1:
1222 case RELAY_COMMAND_RENDEZVOUS2:
1223 case RELAY_COMMAND_INTRO_ESTABLISHED:
1224 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1225 rend_process_relay_cell(circ, layer_hint,
1226 rh.command, rh.length,
1227 cell->payload+RELAY_HEADER_SIZE);
1228 return 0;
1230 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1231 "Received unknown relay command %d. Perhaps the other side is using "
1232 "a newer version of Tor? Dropping.",
1233 rh.command);
1234 return 0; /* for forward compatibility, don't kill the circuit */
1237 /** How many relay_data cells have we built, ever? */
1238 uint64_t stats_n_data_cells_packaged = 0;
1239 /** How many bytes of data have we put in relay_data cells have we built,
1240 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1241 * every relay cell we ever sent were completely full of data. */
1242 uint64_t stats_n_data_bytes_packaged = 0;
1243 /** How many relay_data cells have we received, ever? */
1244 uint64_t stats_n_data_cells_received = 0;
1245 /** How many bytes of data have we received relay_data cells, ever? This would
1246 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1247 * ever received were completely full of data. */
1248 uint64_t stats_n_data_bytes_received = 0;
1250 /** While conn->inbuf has an entire relay payload of bytes on it,
1251 * and the appropriate package windows aren't empty, grab a cell
1252 * and send it down the circuit.
1254 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1255 * be marked for close, else return 0.
1258 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
1260 size_t amount_to_process, length;
1261 char payload[CELL_PAYLOAD_SIZE];
1262 circuit_t *circ;
1263 unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
1265 tor_assert(conn);
1267 if (conn->_base.marked_for_close) {
1268 log_warn(LD_BUG,
1269 "called on conn that's already marked for close at %s:%d.",
1270 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
1271 return 0;
1274 repeat_connection_edge_package_raw_inbuf:
1276 circ = circuit_get_by_edge_conn(conn);
1277 if (!circ) {
1278 log_info(domain,"conn has no circuit! Closing.");
1279 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1280 return -1;
1283 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
1284 return 0;
1286 if (conn->package_window <= 0) {
1287 log_info(domain,"called with package_window %d. Skipping.",
1288 conn->package_window);
1289 connection_stop_reading(TO_CONN(conn));
1290 return 0;
1293 amount_to_process = buf_datalen(conn->_base.inbuf);
1295 if (!amount_to_process)
1296 return 0;
1298 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
1299 return 0;
1301 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
1302 length = RELAY_PAYLOAD_SIZE;
1303 } else {
1304 length = amount_to_process;
1306 stats_n_data_bytes_packaged += length;
1307 stats_n_data_cells_packaged += 1;
1309 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1311 log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
1312 (int)length, (int)buf_datalen(conn->_base.inbuf));
1314 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1315 payload, length) < 0 )
1316 /* circuit got marked for close, don't continue, don't need to mark conn */
1317 return 0;
1319 if (!conn->cpath_layer) { /* non-rendezvous exit */
1320 tor_assert(circ->package_window > 0);
1321 circ->package_window--;
1322 } else { /* we're an AP, or an exit on a rendezvous circ */
1323 tor_assert(conn->cpath_layer->package_window > 0);
1324 conn->cpath_layer->package_window--;
1327 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1328 connection_stop_reading(TO_CONN(conn));
1329 log_debug(domain,"conn->package_window reached 0.");
1330 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
1331 return 0; /* don't process the inbuf any more */
1333 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1335 /* handle more if there's more, or return 0 if there isn't */
1336 goto repeat_connection_edge_package_raw_inbuf;
1339 /** Called when we've just received a relay data cell, or when
1340 * we've just finished flushing all bytes to stream <b>conn</b>.
1342 * If conn->outbuf is not too full, and our deliver window is
1343 * low, send back a suitable number of stream-level sendme cells.
1345 void
1346 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1348 circuit_t *circ;
1350 if (connection_outbuf_too_full(TO_CONN(conn)))
1351 return;
1353 circ = circuit_get_by_edge_conn(conn);
1354 if (!circ) {
1355 /* this can legitimately happen if the destroy has already
1356 * arrived and torn down the circuit */
1357 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1358 return;
1361 while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1362 log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
1363 "Outbuf %d, Queuing stream sendme.",
1364 (int)conn->_base.outbuf_flushlen);
1365 conn->deliver_window += STREAMWINDOW_INCREMENT;
1366 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
1367 NULL, 0) < 0) {
1368 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
1369 return; /* the circuit's closed, don't continue */
1374 /** The circuit <b>circ</b> has received a circuit-level sendme
1375 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1376 * attached streams and let them resume reading and packaging, if
1377 * their stream windows allow it.
1379 static void
1380 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1383 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1385 if (CIRCUIT_IS_ORIGIN(circ))
1386 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
1387 circ, layer_hint);
1388 else
1389 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
1390 circ, layer_hint);
1393 /** A helper function for circuit_resume_edge_reading() above.
1394 * The arguments are the same, except that <b>conn</b> is the head
1395 * of a linked list of edge streams that should each be considered.
1397 static int
1398 circuit_resume_edge_reading_helper(edge_connection_t *conn,
1399 circuit_t *circ,
1400 crypt_path_t *layer_hint)
1402 for ( ; conn; conn=conn->next_stream) {
1403 if (conn->_base.marked_for_close)
1404 continue;
1405 if ((!layer_hint && conn->package_window > 0) ||
1406 (layer_hint && conn->package_window > 0 &&
1407 conn->cpath_layer == layer_hint)) {
1408 connection_start_reading(TO_CONN(conn));
1409 /* handle whatever might still be on the inbuf */
1410 if (connection_edge_package_raw_inbuf(conn, 1)<0) {
1411 /* (We already sent an end cell if possible) */
1412 connection_mark_for_close(TO_CONN(conn));
1413 continue;
1416 /* If the circuit won't accept any more data, return without looking
1417 * at any more of the streams. Any connections that should be stopped
1418 * have already been stopped by connection_edge_package_raw_inbuf. */
1419 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1420 return -1;
1423 return 0;
1426 /** Check if the package window for <b>circ</b> is empty (at
1427 * hop <b>layer_hint</b> if it's defined).
1429 * If yes, tell edge streams to stop reading and return 1.
1430 * Else return 0.
1432 static int
1433 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1435 edge_connection_t *conn = NULL;
1436 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1438 if (!layer_hint) {
1439 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1440 log_debug(domain,"considering circ->package_window %d",
1441 circ->package_window);
1442 if (circ->package_window <= 0) {
1443 log_debug(domain,"yes, not-at-origin. stopped.");
1444 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
1445 connection_stop_reading(TO_CONN(conn));
1446 return 1;
1448 return 0;
1450 /* else, layer hint is defined, use it */
1451 log_debug(domain,"considering layer_hint->package_window %d",
1452 layer_hint->package_window);
1453 if (layer_hint->package_window <= 0) {
1454 log_debug(domain,"yes, at-origin. stopped.");
1455 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
1456 conn=conn->next_stream)
1457 if (conn->cpath_layer == layer_hint)
1458 connection_stop_reading(TO_CONN(conn));
1459 return 1;
1461 return 0;
1464 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1465 * <b>layer_hint</b> if it's defined) is low enough that we should
1466 * send a circuit-level sendme back down the circuit. If so, send
1467 * enough sendmes that the window would be overfull if we sent any
1468 * more.
1470 static void
1471 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1473 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1474 // layer_hint ? "defined" : "null");
1475 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
1476 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1477 log_debug(LD_CIRC,"Queuing circuit sendme.");
1478 if (layer_hint)
1479 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1480 else
1481 circ->deliver_window += CIRCWINDOW_INCREMENT;
1482 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
1483 NULL, 0, layer_hint) < 0) {
1484 log_warn(LD_CIRC,
1485 "relay_send_command_from_edge failed. Circuit's closed.");
1486 return; /* the circuit's closed, don't continue */
1491 /** Stop reading on edge connections when we have this many cells
1492 * waiting on the appropriate queue. */
1493 #define CELL_QUEUE_HIGHWATER_SIZE 256
1494 /** Start reading from edge connections again when we get down to this many
1495 * cells. */
1496 #define CELL_QUEUE_LOWWATER_SIZE 64
1498 #ifdef ACTIVE_CIRCUITS_PARANOIA
1499 #define assert_active_circuits_ok_paranoid(conn) \
1500 assert_active_circuits_ok(conn)
1501 #else
1502 #define assert_active_circuits_ok_paranoid(conn)
1503 #endif
1505 /** The total number of cells we have allocated from the memory pool. */
1506 static int total_cells_allocated = 0;
1508 /** A memory pool to allocate packed_cell_t objects. */
1509 static mp_pool_t *cell_pool = NULL;
1511 /** Allocate structures to hold cells. */
1512 void
1513 init_cell_pool(void)
1515 tor_assert(!cell_pool);
1516 cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
1519 /** Free all storage used to hold cells. */
1520 void
1521 free_cell_pool(void)
1523 /* Maybe we haven't called init_cell_pool yet; need to check for it. */
1524 if (cell_pool) {
1525 mp_pool_destroy(cell_pool);
1526 cell_pool = NULL;
1530 /** Free excess storage in cell pool. */
1531 void
1532 clean_cell_pool(void)
1534 tor_assert(cell_pool);
1535 mp_pool_clean(cell_pool, 0, 1);
1538 /** Release storage held by <b>cell</b>. */
1539 static INLINE void
1540 packed_cell_free(packed_cell_t *cell)
1542 --total_cells_allocated;
1543 mp_pool_release(cell);
1546 /** Allocate and return a new packed_cell_t. */
1547 static INLINE packed_cell_t *
1548 packed_cell_alloc(void)
1550 ++total_cells_allocated;
1551 return mp_pool_get(cell_pool);
1554 /** Log current statistics for cell pool allocation at log level
1555 * <b>severity</b>. */
1556 void
1557 dump_cell_pool_usage(int severity)
1559 circuit_t *c;
1560 int n_circs = 0;
1561 int n_cells = 0;
1562 for (c = _circuit_get_global_list(); c; c = c->next) {
1563 n_cells += c->n_conn_cells.n;
1564 if (!CIRCUIT_IS_ORIGIN(c))
1565 n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
1566 ++n_circs;
1568 log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
1569 n_cells, n_circs, total_cells_allocated - n_cells);
1570 mp_pool_log_status(cell_pool, severity);
1573 /** Allocate a new copy of packed <b>cell</b>. */
1574 static INLINE packed_cell_t *
1575 packed_cell_copy(const cell_t *cell)
1577 packed_cell_t *c = packed_cell_alloc();
1578 cell_pack(c, cell);
1579 c->next = NULL;
1580 return c;
1583 /** Append <b>cell</b> to the end of <b>queue</b>. */
1584 void
1585 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
1587 if (queue->tail) {
1588 tor_assert(!queue->tail->next);
1589 queue->tail->next = cell;
1590 } else {
1591 queue->head = cell;
1593 queue->tail = cell;
1594 cell->next = NULL;
1595 ++queue->n;
1598 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
1599 void
1600 cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
1602 cell_queue_append(queue, packed_cell_copy(cell));
1605 /** Remove and free every cell in <b>queue</b>. */
1606 void
1607 cell_queue_clear(cell_queue_t *queue)
1609 packed_cell_t *cell, *next;
1610 cell = queue->head;
1611 while (cell) {
1612 next = cell->next;
1613 packed_cell_free(cell);
1614 cell = next;
1616 queue->head = queue->tail = NULL;
1617 queue->n = 0;
1620 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
1621 * <b>queue</b> is empty. */
1622 static INLINE packed_cell_t *
1623 cell_queue_pop(cell_queue_t *queue)
1625 packed_cell_t *cell = queue->head;
1626 if (!cell)
1627 return NULL;
1628 queue->head = cell->next;
1629 if (cell == queue->tail) {
1630 tor_assert(!queue->head);
1631 queue->tail = NULL;
1633 --queue->n;
1634 return cell;
1637 /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
1638 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1639 static INLINE circuit_t **
1640 next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1642 tor_assert(circ);
1643 tor_assert(conn);
1644 if (conn == circ->n_conn) {
1645 return &circ->next_active_on_n_conn;
1646 } else {
1647 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1648 tor_assert(conn == orcirc->p_conn);
1649 return &orcirc->next_active_on_p_conn;
1653 /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
1654 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1655 static INLINE circuit_t **
1656 prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1658 tor_assert(circ);
1659 tor_assert(conn);
1660 if (conn == circ->n_conn) {
1661 return &circ->prev_active_on_n_conn;
1662 } else {
1663 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1664 tor_assert(conn == orcirc->p_conn);
1665 return &orcirc->prev_active_on_p_conn;
1669 /** Add <b>circ</b> to the list of circuits with pending cells on
1670 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1671 void
1672 make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
1674 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1675 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1677 if (*nextp && *prevp) {
1678 /* Already active. */
1679 return;
1682 if (! conn->active_circuits) {
1683 conn->active_circuits = circ;
1684 *prevp = *nextp = circ;
1685 } else {
1686 circuit_t *head = conn->active_circuits;
1687 circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
1688 *next_circ_on_conn_p(old_tail, conn) = circ;
1689 *nextp = head;
1690 *prev_circ_on_conn_p(head, conn) = circ;
1691 *prevp = old_tail;
1693 assert_active_circuits_ok_paranoid(conn);
1696 /** Remove <b>circ</b> to the list of circuits with pending cells on
1697 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1698 void
1699 make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
1701 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1702 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1703 circuit_t *next = *nextp, *prev = *prevp;
1705 if (!next && !prev) {
1706 /* Already inactive. */
1707 return;
1710 tor_assert(next && prev);
1711 tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
1712 tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
1714 if (next == circ) {
1715 conn->active_circuits = NULL;
1716 } else {
1717 *prev_circ_on_conn_p(next, conn) = prev;
1718 *next_circ_on_conn_p(prev, conn) = next;
1719 if (conn->active_circuits == circ)
1720 conn->active_circuits = next;
1722 *prevp = *nextp = NULL;
1723 assert_active_circuits_ok_paranoid(conn);
1726 /** Remove all circuits from the list of circuits with pending cells on
1727 * <b>conn</b>. */
1728 void
1729 connection_or_unlink_all_active_circs(or_connection_t *orconn)
1731 circuit_t *head = orconn->active_circuits;
1732 circuit_t *cur = head;
1733 if (! head)
1734 return;
1735 do {
1736 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1737 *prev_circ_on_conn_p(cur, orconn) = NULL;
1738 *next_circ_on_conn_p(cur, orconn) = NULL;
1739 cur = next;
1740 } while (cur != head);
1741 orconn->active_circuits = NULL;
1744 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
1745 * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
1746 * and start or stop reading as appropriate. */
1747 static void
1748 set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
1749 int block)
1751 edge_connection_t *edge = NULL;
1752 if (circ->n_conn == orconn) {
1753 circ->streams_blocked_on_n_conn = block;
1754 if (CIRCUIT_IS_ORIGIN(circ))
1755 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
1756 } else {
1757 circ->streams_blocked_on_p_conn = block;
1758 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1759 edge = TO_OR_CIRCUIT(circ)->n_streams;
1762 for (; edge; edge = edge->next_stream) {
1763 connection_t *conn = TO_CONN(edge);
1764 edge->edge_blocked_on_circ = block;
1766 if (!conn->read_event) {
1767 /* This connection is a placeholder for something; probably a DNS
1768 * request. It can't actually stop or start reading.*/
1769 continue;
1772 if (block) {
1773 if (connection_is_reading(conn))
1774 connection_stop_reading(conn);
1775 } else {
1776 /* Is this right? */
1777 if (!connection_is_reading(conn))
1778 connection_start_reading(conn);
1783 /** Pull as many cells as possible (but no more than <b>max</b>) from the
1784 * queue of the first active circuit on <b>conn</b>, and write then to
1785 * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
1786 * the active circuit pointer to the next active circuit in the ring. */
1788 connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
1789 time_t now)
1791 int n_flushed;
1792 cell_queue_t *queue;
1793 circuit_t *circ;
1794 int streams_blocked;
1795 circ = conn->active_circuits;
1796 if (!circ) return 0;
1797 assert_active_circuits_ok_paranoid(conn);
1798 if (circ->n_conn == conn) {
1799 queue = &circ->n_conn_cells;
1800 streams_blocked = circ->streams_blocked_on_n_conn;
1801 } else {
1802 queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
1803 streams_blocked = circ->streams_blocked_on_p_conn;
1805 tor_assert(*next_circ_on_conn_p(circ,conn));
1807 for (n_flushed = 0; n_flushed < max && queue->head; ) {
1808 packed_cell_t *cell = cell_queue_pop(queue);
1809 tor_assert(*next_circ_on_conn_p(circ,conn));
1811 connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
1813 packed_cell_free(cell);
1814 ++n_flushed;
1815 if (circ != conn->active_circuits) {
1816 /* If this happens, the current circuit just got made inactive by
1817 * a call in connection_write_to_buf(). That's nothing to worry about:
1818 * circuit_make_inactive_on_conn() already advanced conn->active_circuits
1819 * for us.
1821 assert_active_circuits_ok_paranoid(conn);
1822 goto done;
1825 tor_assert(*next_circ_on_conn_p(circ,conn));
1826 assert_active_circuits_ok_paranoid(conn);
1827 conn->active_circuits = *next_circ_on_conn_p(circ, conn);
1829 /* Is the cell queue low enough to unblock all the streams that are waiting
1830 * to write to this circuit? */
1831 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
1832 set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
1834 /* Did we just ran out of cells on this queue? */
1835 if (queue->n == 0) {
1836 log_debug(LD_GENERAL, "Made a circuit inactive.");
1837 make_circuit_inactive_on_conn(circ, conn);
1839 done:
1840 if (n_flushed)
1841 conn->timestamp_last_added_nonpadding = now;
1842 return n_flushed;
1845 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
1846 * transmitting in <b>direction</b>. */
1847 void
1848 append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
1849 cell_t *cell, cell_direction_t direction)
1851 cell_queue_t *queue;
1852 int streams_blocked;
1853 if (direction == CELL_DIRECTION_OUT) {
1854 queue = &circ->n_conn_cells;
1855 streams_blocked = circ->streams_blocked_on_n_conn;
1856 } else {
1857 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1858 queue = &orcirc->p_conn_cells;
1859 streams_blocked = circ->streams_blocked_on_p_conn;
1861 if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
1862 /* V1 connections don't understand RELAY_EARLY. */
1863 cell->command = CELL_RELAY;
1866 cell_queue_append_packed_copy(queue, cell);
1868 /* If we have too many cells on the circuit, we should stop reading from
1869 * the edge streams for a while. */
1870 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
1871 set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
1873 if (queue->n == 1) {
1874 /* This was the first cell added to the queue. We need to make this
1875 * circuit active. */
1876 log_debug(LD_GENERAL, "Made a circuit active.");
1877 make_circuit_active_on_conn(circ, orconn);
1880 if (! buf_datalen(orconn->_base.outbuf)) {
1881 /* There is no data at all waiting to be sent on the outbuf. Add a
1882 * cell, so that we can notice when it gets flushed, flushed_some can
1883 * get called, and we can start putting more data onto the buffer then.
1885 log_debug(LD_GENERAL, "Primed a buffer.");
1886 connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
1890 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
1891 * have at least 18 bytes of free space. The encoding is, as specified in
1892 * tor-spec.txt:
1893 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
1894 * LENGTH [1 byte]
1895 * ADDRESS [length bytes]
1896 * Return the number of bytes added, or -1 on error */
1898 append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
1900 uint32_t a;
1901 switch (tor_addr_family(addr)) {
1902 case AF_INET:
1903 payload_out[0] = RESOLVED_TYPE_IPV4;
1904 payload_out[1] = 4;
1905 a = tor_addr_to_ipv4n(addr);
1906 memcpy(payload_out+2, &a, 4);
1907 return 6;
1908 case AF_INET6:
1909 payload_out[0] = RESOLVED_TYPE_IPV6;
1910 payload_out[1] = 16;
1911 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
1912 return 18;
1913 case AF_UNSPEC:
1914 default:
1915 return -1;
1919 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
1920 * encoded as by append_address_to_payload(), try to decode the address into
1921 * *<b>addr_out</b>. Return the next byte in the payload after the address on
1922 * success, or NULL on failure. */
1923 const uint8_t *
1924 decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
1925 int payload_len)
1927 if (payload_len < 2)
1928 return NULL;
1929 if (payload_len < 2+payload[1])
1930 return NULL;
1932 switch (payload[0]) {
1933 case RESOLVED_TYPE_IPV4:
1934 if (payload[1] != 4)
1935 return NULL;
1936 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
1937 break;
1938 case RESOLVED_TYPE_IPV6:
1939 if (payload[1] != 16)
1940 return NULL;
1941 tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
1942 break;
1943 default:
1944 tor_addr_make_unspec(addr_out);
1945 break;
1947 return payload + 2 + payload[1];
1950 /** Fail with an assert if the active circuits ring on <b>orconn</b> is
1951 * corrupt. */
1952 void
1953 assert_active_circuits_ok(or_connection_t *orconn)
1955 circuit_t *head = orconn->active_circuits;
1956 circuit_t *cur = head;
1957 if (! head)
1958 return;
1959 do {
1960 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1961 circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
1962 tor_assert(next);
1963 tor_assert(prev);
1964 tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
1965 tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
1966 cur = next;
1967 } while (cur != head);