Some tweaks to statistics.
[tor/rransom.git] / src / or / relay.c
blob098b95253e4846d769a6ccf75e40efa552bcb276
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-2009, 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 if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
212 CELL_DIRECTION_IN)) < 0) {
213 log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
214 "circuits");
215 /* XXXX Do this here, or just return -1? */
216 circuit_mark_for_close(circ, -reason);
217 return reason;
219 return 0;
221 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
222 "Didn't recognize cell, but circ stops here! Closing circ.");
223 return -END_CIRC_REASON_TORPROTOCOL;
226 log_debug(LD_OR,"Passing on unrecognized cell.");
228 ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
229 * we might kill the circ before we relay
230 * the cells. */
232 append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
233 return 0;
236 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
237 * <b>circ</b> in direction <b>cell_direction</b>.
239 * If cell_direction == CELL_DIRECTION_IN:
240 * - If we're at the origin (we're the OP), for hops 1..N,
241 * decrypt cell. If recognized, stop.
242 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
244 * If cell_direction == CELL_DIRECTION_OUT:
245 * - decrypt one hop. Check if recognized.
247 * If cell is recognized, set *recognized to 1, and set
248 * *layer_hint to the hop that recognized it.
250 * Return -1 to indicate that we should mark the circuit for close,
251 * else return 0.
253 static int
254 relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
255 crypt_path_t **layer_hint, char *recognized)
257 relay_header_t rh;
259 tor_assert(circ);
260 tor_assert(cell);
261 tor_assert(recognized);
262 tor_assert(cell_direction == CELL_DIRECTION_IN ||
263 cell_direction == CELL_DIRECTION_OUT);
265 if (cell_direction == CELL_DIRECTION_IN) {
266 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
267 * We'll want to do layered decrypts. */
268 crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
269 thishop = cpath;
270 if (thishop->state != CPATH_STATE_OPEN) {
271 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
272 "Relay cell before first created cell? Closing.");
273 return -1;
275 do { /* Remember: cpath is in forward order, that is, first hop first. */
276 tor_assert(thishop);
278 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
279 return -1;
281 relay_header_unpack(&rh, cell->payload);
282 if (rh.recognized == 0) {
283 /* it's possibly recognized. have to check digest to be sure. */
284 if (relay_digest_matches(thishop->b_digest, cell)) {
285 *recognized = 1;
286 *layer_hint = thishop;
287 return 0;
291 thishop = thishop->next;
292 } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
293 log_fn(LOG_PROTOCOL_WARN, LD_OR,
294 "Incoming cell at client not recognized. Closing.");
295 return -1;
296 } else { /* we're in the middle. Just one crypt. */
297 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
298 cell->payload, 1) < 0)
299 return -1;
300 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
301 // "the client.");
303 } else /* cell_direction == CELL_DIRECTION_OUT */ {
304 /* we're in the middle. Just one crypt. */
306 if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
307 cell->payload, 0) < 0)
308 return -1;
310 relay_header_unpack(&rh, cell->payload);
311 if (rh.recognized == 0) {
312 /* it's possibly recognized. have to check digest to be sure. */
313 if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
314 *recognized = 1;
315 return 0;
319 return 0;
322 /** Package a relay cell from an edge:
323 * - Encrypt it to the right layer
324 * - Append it to the appropriate cell_queue on <b>circ</b>.
326 static int
327 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
328 cell_direction_t cell_direction,
329 crypt_path_t *layer_hint)
331 or_connection_t *conn; /* where to send the cell */
333 if (cell_direction == CELL_DIRECTION_OUT) {
334 crypt_path_t *thishop; /* counter for repeated crypts */
335 conn = circ->n_conn;
336 if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
337 log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
338 return 0; /* just drop it */
341 relay_set_digest(layer_hint->f_digest, cell);
343 thishop = layer_hint;
344 /* moving from farthest to nearest hop */
345 do {
346 tor_assert(thishop);
347 /* XXXX RD This is a bug, right? */
348 log_debug(LD_OR,"crypting a layer of the relay cell.");
349 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
350 return -1;
353 thishop = thishop->prev;
354 } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
356 } else { /* incoming cell */
357 or_circuit_t *or_circ;
358 if (CIRCUIT_IS_ORIGIN(circ)) {
359 /* We should never package an _incoming_ cell from the circuit
360 * origin; that means we messed up somewhere. */
361 log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
362 assert_circuit_ok(circ);
363 return 0; /* just drop it */
365 or_circ = TO_OR_CIRCUIT(circ);
366 conn = or_circ->p_conn;
367 relay_set_digest(or_circ->p_digest, cell);
368 if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
369 return -1;
371 ++stats_n_relay_cells_relayed;
373 append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
374 return 0;
377 /** If cell's stream_id matches the stream_id of any conn that's
378 * attached to circ, return that conn, else return NULL.
380 static edge_connection_t *
381 relay_lookup_conn(circuit_t *circ, cell_t *cell,
382 cell_direction_t cell_direction, crypt_path_t *layer_hint)
384 edge_connection_t *tmpconn;
385 relay_header_t rh;
387 relay_header_unpack(&rh, cell->payload);
389 if (!rh.stream_id)
390 return NULL;
392 /* IN or OUT cells could have come from either direction, now
393 * that we allow rendezvous *to* an OP.
396 if (CIRCUIT_IS_ORIGIN(circ)) {
397 for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
398 tmpconn=tmpconn->next_stream) {
399 if (rh.stream_id == tmpconn->stream_id &&
400 !tmpconn->_base.marked_for_close &&
401 tmpconn->cpath_layer == layer_hint) {
402 log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
403 return tmpconn;
406 } else {
407 for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
408 tmpconn=tmpconn->next_stream) {
409 if (rh.stream_id == tmpconn->stream_id &&
410 !tmpconn->_base.marked_for_close) {
411 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
412 if (cell_direction == CELL_DIRECTION_OUT ||
413 connection_edge_is_rendezvous_stream(tmpconn))
414 return tmpconn;
417 for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
418 tmpconn=tmpconn->next_stream) {
419 if (rh.stream_id == tmpconn->stream_id &&
420 !tmpconn->_base.marked_for_close) {
421 log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
422 return tmpconn;
426 return NULL; /* probably a begin relay cell */
429 /** Pack the relay_header_t host-order structure <b>src</b> into
430 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
431 * about the wire format.
433 void
434 relay_header_pack(char *dest, const relay_header_t *src)
436 *(uint8_t*)(dest) = src->command;
438 set_uint16(dest+1, htons(src->recognized));
439 set_uint16(dest+3, htons(src->stream_id));
440 memcpy(dest+5, src->integrity, 4);
441 set_uint16(dest+9, htons(src->length));
444 /** Unpack the network-order buffer <b>src</b> into a host-order
445 * relay_header_t structure <b>dest</b>.
447 void
448 relay_header_unpack(relay_header_t *dest, const char *src)
450 dest->command = *(uint8_t*)(src);
452 dest->recognized = ntohs(get_uint16(src+1));
453 dest->stream_id = ntohs(get_uint16(src+3));
454 memcpy(dest->integrity, src+5, 4);
455 dest->length = ntohs(get_uint16(src+9));
458 /** Convert the relay <b>command</b> into a human-readable string. */
459 static const char *
460 relay_command_to_string(uint8_t command)
462 switch (command) {
463 case RELAY_COMMAND_BEGIN: return "BEGIN";
464 case RELAY_COMMAND_DATA: return "DATA";
465 case RELAY_COMMAND_END: return "END";
466 case RELAY_COMMAND_CONNECTED: return "CONNECTED";
467 case RELAY_COMMAND_SENDME: return "SENDME";
468 case RELAY_COMMAND_EXTEND: return "EXTEND";
469 case RELAY_COMMAND_EXTENDED: return "EXTENDED";
470 case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
471 case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
472 case RELAY_COMMAND_DROP: return "DROP";
473 case RELAY_COMMAND_RESOLVE: return "RESOLVE";
474 case RELAY_COMMAND_RESOLVED: return "RESOLVED";
475 case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
476 case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
477 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
478 case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
479 case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
480 case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
481 case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
482 case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
483 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
484 return "RENDEZVOUS_ESTABLISHED";
485 case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
486 default: return "(unrecognized)";
490 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
491 * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
492 * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
493 * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
494 * destination hop for OP->OR cells.
496 * If you can't send the cell, mark the circuit for close and return -1. Else
497 * return 0.
500 relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
501 uint8_t relay_command, const char *payload,
502 size_t payload_len, crypt_path_t *cpath_layer)
504 cell_t cell;
505 relay_header_t rh;
506 cell_direction_t cell_direction;
507 /* XXXX NM Split this function into a separate versions per circuit type? */
509 tor_assert(circ);
510 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
512 memset(&cell, 0, sizeof(cell_t));
513 cell.command = CELL_RELAY;
514 if (cpath_layer) {
515 cell.circ_id = circ->n_circ_id;
516 cell_direction = CELL_DIRECTION_OUT;
517 } else if (! CIRCUIT_IS_ORIGIN(circ)) {
518 cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
519 cell_direction = CELL_DIRECTION_IN;
520 } else {
521 return -1;
524 memset(&rh, 0, sizeof(rh));
525 rh.command = relay_command;
526 rh.stream_id = stream_id;
527 rh.length = payload_len;
528 relay_header_pack(cell.payload, &rh);
529 if (payload_len)
530 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
532 log_debug(LD_OR,"delivering %d cell %s.", relay_command,
533 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
535 #ifdef ENABLE_DIRREQ_STATS
536 /* If we are sending an END cell and this circuit is used for a tunneled
537 * directory request, advance its state. */
538 if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
539 geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
540 DIRREQ_END_CELL_SENT);
541 #endif
543 if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
544 /* if we're using relaybandwidthrate, this conn wants priority */
545 circ->n_conn->client_used = approx_time();
548 if (cell_direction == CELL_DIRECTION_OUT) {
549 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
550 if (origin_circ->remaining_relay_early_cells > 0 &&
551 (relay_command == RELAY_COMMAND_EXTEND ||
552 cpath_layer != origin_circ->cpath)) {
553 /* If we've got any relay_early cells left, and we're sending a relay
554 * cell or we're not talking to the first hop, use one of them. Don't
555 * worry about the conn protocol version: append_cell_to_circuit_queue
556 * will fix it up. */
557 cell.command = CELL_RELAY_EARLY;
558 --origin_circ->remaining_relay_early_cells;
559 log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
560 (int)origin_circ->remaining_relay_early_cells);
561 /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
562 * task 878. */
563 origin_circ->relay_early_commands[
564 origin_circ->relay_early_cells_sent++] = relay_command;
565 } else if (relay_command == RELAY_COMMAND_EXTEND) {
566 /* If no RELAY_EARLY cells can be sent over this circuit, log which
567 * commands have been sent as RELAY_EARLY cells before; helps debug
568 * task 878. */
569 smartlist_t *commands_list = smartlist_create();
570 int i = 0;
571 char *commands = NULL;
572 for (; i < origin_circ->relay_early_cells_sent; i++)
573 smartlist_add(commands_list, (char *)
574 relay_command_to_string(origin_circ->relay_early_commands[i]));
575 commands = smartlist_join_strings(commands_list, ",", 0, NULL);
576 log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
577 "but we have run out of RELAY_EARLY cells on that circuit. "
578 "Commands sent before: %s", commands);
579 tor_free(commands);
580 smartlist_free(commands_list);
584 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
585 < 0) {
586 log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
587 circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
588 return -1;
590 return 0;
593 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
594 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
595 * that's sending the relay cell, or NULL if it's a control cell.
596 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
597 * for OP->OR cells.
599 * If you can't send the cell, mark the circuit for close and
600 * return -1. Else return 0.
603 connection_edge_send_command(edge_connection_t *fromconn,
604 uint8_t relay_command, const char *payload,
605 size_t payload_len)
607 /* XXXX NM Split this function into a separate versions per circuit type? */
608 circuit_t *circ;
609 tor_assert(fromconn);
610 circ = fromconn->on_circuit;
612 if (fromconn->_base.marked_for_close) {
613 log_warn(LD_BUG,
614 "called on conn that's already marked for close at %s:%d.",
615 fromconn->_base.marked_for_close_file,
616 fromconn->_base.marked_for_close);
617 return 0;
620 if (!circ) {
621 if (fromconn->_base.type == CONN_TYPE_AP) {
622 log_info(LD_APP,"no circ. Closing conn.");
623 connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
624 } else {
625 log_info(LD_EXIT,"no circ. Closing conn.");
626 fromconn->edge_has_sent_end = 1; /* no circ to send to */
627 fromconn->end_reason = END_STREAM_REASON_INTERNAL;
628 connection_mark_for_close(TO_CONN(fromconn));
630 return -1;
633 return relay_send_command_from_edge(fromconn->stream_id, circ,
634 relay_command, payload,
635 payload_len, fromconn->cpath_layer);
638 /** How many times will I retry a stream that fails due to DNS
639 * resolve failure or misc error?
641 #define MAX_RESOLVE_FAILURES 3
643 /** Return 1 if reason is something that you should retry if you
644 * get the end cell before you've connected; else return 0. */
645 static int
646 edge_reason_is_retriable(int reason)
648 return reason == END_STREAM_REASON_HIBERNATING ||
649 reason == END_STREAM_REASON_RESOURCELIMIT ||
650 reason == END_STREAM_REASON_EXITPOLICY ||
651 reason == END_STREAM_REASON_RESOLVEFAILED ||
652 reason == END_STREAM_REASON_MISC;
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 if (client_dns_incr_failures(conn->socks_request->address)
748 < MAX_RESOLVE_FAILURES) {
749 /* We haven't retried too many times; reattach the connection. */
750 circuit_log_path(LOG_INFO,LD_APP,circ);
751 tor_assert(circ->_base.timestamp_dirty);
752 circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
754 if (conn->chosen_exit_optional) {
755 /* stop wanting a specific exit */
756 conn->chosen_exit_optional = 0;
757 tor_free(conn->chosen_exit_name); /* clears it */
759 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
760 return 0;
761 /* else, conn will get closed below */
762 } else {
763 log_notice(LD_APP,
764 "Have tried resolving or connecting to address '%s' "
765 "at %d different places. Giving up.",
766 safe_str(conn->socks_request->address),
767 MAX_RESOLVE_FAILURES);
768 /* clear the failures, so it will have a full try next time */
769 client_dns_clear_failures(conn->socks_request->address);
771 break;
772 case END_STREAM_REASON_HIBERNATING:
773 case END_STREAM_REASON_RESOURCELIMIT:
774 if (exitrouter) {
775 policies_set_router_exitpolicy_to_reject_all(exitrouter);
777 if (conn->chosen_exit_optional) {
778 /* stop wanting a specific exit */
779 conn->chosen_exit_optional = 0;
780 tor_free(conn->chosen_exit_name); /* clears it */
782 if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
783 return 0;
784 /* else, will close below */
785 break;
786 } /* end switch */
787 log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
790 log_info(LD_APP,
791 "Edge got end (%s) before we're connected. Marking for close.",
792 stream_end_reason_to_string(rh->length > 0 ? reason : -1));
793 circuit_log_path(LOG_INFO,LD_APP,circ);
794 /* need to test because of detach_retriable */
795 if (!conn->_base.marked_for_close)
796 connection_mark_unattached_ap(conn, control_reason);
797 return 0;
800 /** Helper: change the socks_request-&gt;address field on conn to the
801 * dotted-quad representation of <b>new_addr</b> (given in host order),
802 * and send an appropriate REMAP event. */
803 static void
804 remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
806 struct in_addr in;
808 in.s_addr = htonl(new_addr);
809 tor_inet_ntoa(&in, conn->socks_request->address,
810 sizeof(conn->socks_request->address));
811 control_event_stream_status(conn, STREAM_EVENT_REMAP,
812 REMAP_STREAM_SOURCE_EXIT);
815 /** An incoming relay cell has arrived from circuit <b>circ</b> to
816 * stream <b>conn</b>.
818 * The arguments here are the same as in
819 * connection_edge_process_relay_cell() below; this function is called
820 * from there when <b>conn</b> is defined and not in an open state.
822 static int
823 connection_edge_process_relay_cell_not_open(
824 relay_header_t *rh, cell_t *cell, circuit_t *circ,
825 edge_connection_t *conn, crypt_path_t *layer_hint)
827 if (rh->command == RELAY_COMMAND_END) {
828 if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
829 return connection_ap_process_end_not_open(rh, cell,
830 TO_ORIGIN_CIRCUIT(circ), conn,
831 layer_hint);
832 } else {
833 /* we just got an 'end', don't need to send one */
834 conn->edge_has_sent_end = 1;
835 conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
836 END_STREAM_REASON_FLAG_REMOTE;
837 connection_mark_for_close(TO_CONN(conn));
838 return 0;
842 if (conn->_base.type == CONN_TYPE_AP &&
843 rh->command == RELAY_COMMAND_CONNECTED) {
844 tor_assert(CIRCUIT_IS_ORIGIN(circ));
845 if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
846 log_fn(LOG_PROTOCOL_WARN, LD_APP,
847 "Got 'connected' while not in state connect_wait. Dropping.");
848 return 0;
850 conn->_base.state = AP_CONN_STATE_OPEN;
851 log_info(LD_APP,"'connected' received after %d seconds.",
852 (int)(time(NULL) - conn->_base.timestamp_lastread));
853 if (rh->length >= 4) {
854 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
855 int ttl;
856 if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
857 is_internal_IP(addr, 0))) {
858 char buf[INET_NTOA_BUF_LEN];
859 struct in_addr a;
860 a.s_addr = htonl(addr);
861 tor_inet_ntoa(&a, buf, sizeof(buf));
862 log_info(LD_APP,
863 "...but it claims the IP address was %s. Closing.", buf);
864 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
865 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
866 return 0;
868 if (rh->length >= 8)
869 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
870 else
871 ttl = -1;
872 client_dns_set_addressmap(conn->socks_request->address, addr,
873 conn->chosen_exit_name, ttl);
875 remap_event_helper(conn, addr);
877 circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
878 /* don't send a socks reply to transparent conns */
879 if (!conn->socks_request->has_finished)
880 connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
882 /* Was it a linked dir conn? If so, a dir request just started to
883 * fetch something; this could be a bootstrap status milestone. */
884 log_debug(LD_APP, "considering");
885 if (TO_CONN(conn)->linked_conn &&
886 TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
887 connection_t *dirconn = TO_CONN(conn)->linked_conn;
888 log_debug(LD_APP, "it is! %d", dirconn->purpose);
889 switch (dirconn->purpose) {
890 case DIR_PURPOSE_FETCH_CERTIFICATE:
891 if (consensus_is_waiting_for_certs())
892 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
893 break;
894 case DIR_PURPOSE_FETCH_CONSENSUS:
895 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
896 break;
897 case DIR_PURPOSE_FETCH_SERVERDESC:
898 control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
899 count_loading_descriptors_progress());
900 break;
904 /* handle anything that might have queued */
905 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
906 /* (We already sent an end cell if possible) */
907 connection_mark_for_close(TO_CONN(conn));
908 return 0;
910 return 0;
912 if (conn->_base.type == CONN_TYPE_AP &&
913 rh->command == RELAY_COMMAND_RESOLVED) {
914 int ttl;
915 int answer_len;
916 uint8_t answer_type;
917 if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
918 log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
919 "not in state resolve_wait. Dropping.");
920 return 0;
922 tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
923 answer_len = cell->payload[RELAY_HEADER_SIZE+1];
924 if (rh->length < 2 || answer_len+2>rh->length) {
925 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
926 "Dropping malformed 'resolved' cell");
927 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
928 return 0;
930 answer_type = cell->payload[RELAY_HEADER_SIZE];
931 if (rh->length >= answer_len+6)
932 ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
933 2+answer_len));
934 else
935 ttl = -1;
936 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
937 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
938 if (get_options()->ClientDNSRejectInternalAddresses &&
939 is_internal_IP(addr, 0)) {
940 char buf[INET_NTOA_BUF_LEN];
941 struct in_addr a;
942 a.s_addr = htonl(addr);
943 tor_inet_ntoa(&a, buf, sizeof(buf));
944 log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
945 connection_ap_handshake_socks_resolved(conn,
946 RESOLVED_TYPE_ERROR_TRANSIENT,
947 0, NULL, 0, TIME_MAX);
948 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
949 return 0;
952 connection_ap_handshake_socks_resolved(conn,
953 answer_type,
954 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
955 cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
956 ttl,
957 -1);
958 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
959 uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
960 remap_event_helper(conn, addr);
962 connection_mark_unattached_ap(conn,
963 END_STREAM_REASON_DONE |
964 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
965 return 0;
968 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
969 "Got an unexpected relay command %d, in state %d (%s). Dropping.",
970 rh->command, conn->_base.state,
971 conn_state_to_string(conn->_base.type, conn->_base.state));
972 return 0; /* for forward compatibility, don't kill the circuit */
973 // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
974 // connection_mark_for_close(conn);
975 // return -1;
978 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
979 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
980 * destined for <b>conn</b>.
982 * If <b>layer_hint</b> is defined, then we're the origin of the
983 * circuit, and it specifies the hop that packaged <b>cell</b>.
985 * Return -reason if you want to warn and tear down the circuit, else 0.
987 static int
988 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
989 edge_connection_t *conn,
990 crypt_path_t *layer_hint)
992 static int num_seen=0;
993 relay_header_t rh;
994 unsigned domain = layer_hint?LD_APP:LD_EXIT;
995 int reason;
997 tor_assert(cell);
998 tor_assert(circ);
1000 relay_header_unpack(&rh, cell->payload);
1001 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
1002 num_seen++;
1003 log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
1004 num_seen, rh.command, rh.stream_id);
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 #ifdef ENABLE_DIRREQ_STATS
1044 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
1045 /* Assign this circuit and its app-ward OR connection a unique ID,
1046 * so that we can measure download times. The local edge and dir
1047 * connection will be assigned the same ID when they are created
1048 * and linked. */
1049 static uint64_t next_id = 0;
1050 circ->dirreq_id = ++next_id;
1051 TO_CONN(TO_OR_CIRCUIT(circ)->p_conn)->dirreq_id = circ->dirreq_id;
1053 #endif
1055 return connection_exit_begin_conn(cell, circ);
1056 case RELAY_COMMAND_DATA:
1057 ++stats_n_data_cells_received;
1058 if (( layer_hint && --layer_hint->deliver_window < 0) ||
1059 (!layer_hint && --circ->deliver_window < 0)) {
1060 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1061 "(relay data) circ deliver_window below 0. Killing.");
1062 connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
1063 connection_mark_for_close(TO_CONN(conn));
1064 return -END_CIRC_REASON_TORPROTOCOL;
1066 log_debug(domain,"circ deliver_window now %d.", layer_hint ?
1067 layer_hint->deliver_window : circ->deliver_window);
1069 circuit_consider_sending_sendme(circ, layer_hint);
1071 if (!conn) {
1072 log_info(domain,"data cell dropped, unknown stream (streamid %d).",
1073 rh.stream_id);
1074 return 0;
1077 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
1078 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1079 "(relay data) conn deliver_window below 0. Killing.");
1080 return -END_CIRC_REASON_TORPROTOCOL;
1083 stats_n_data_bytes_received += rh.length;
1084 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
1085 rh.length, TO_CONN(conn));
1086 connection_edge_consider_sending_sendme(conn);
1087 return 0;
1088 case RELAY_COMMAND_END:
1089 reason = rh.length > 0 ?
1090 *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
1091 if (!conn) {
1092 log_info(domain,"end cell (%s) dropped, unknown stream.",
1093 stream_end_reason_to_string(reason));
1094 return 0;
1096 /* XXX add to this log_fn the exit node's nickname? */
1097 log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
1098 conn->_base.s,
1099 stream_end_reason_to_string(reason),
1100 conn->stream_id);
1101 if (conn->socks_request && !conn->socks_request->has_finished)
1102 log_warn(LD_BUG,
1103 "open stream hasn't sent socks answer yet? Closing.");
1104 /* We just *got* an end; no reason to send one. */
1105 conn->edge_has_sent_end = 1;
1106 if (!conn->end_reason)
1107 conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
1108 if (!conn->_base.marked_for_close) {
1109 /* only mark it if not already marked. it's possible to
1110 * get the 'end' right around when the client hangs up on us. */
1111 connection_mark_for_close(TO_CONN(conn));
1112 conn->_base.hold_open_until_flushed = 1;
1114 return 0;
1115 case RELAY_COMMAND_EXTEND:
1116 if (conn) {
1117 log_fn(LOG_PROTOCOL_WARN, domain,
1118 "'extend' cell received for non-zero stream. Dropping.");
1119 return 0;
1121 return circuit_extend(cell, circ);
1122 case RELAY_COMMAND_EXTENDED:
1123 if (!layer_hint) {
1124 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1125 "'extended' unsupported at non-origin. Dropping.");
1126 return 0;
1128 log_debug(domain,"Got an extended cell! Yay.");
1129 if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
1130 CELL_CREATED,
1131 cell->payload+RELAY_HEADER_SIZE)) < 0) {
1132 log_warn(domain,"circuit_finish_handshake failed.");
1133 return reason;
1135 if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
1136 log_info(domain,"circuit_send_next_onion_skin() failed.");
1137 return reason;
1139 return 0;
1140 case RELAY_COMMAND_TRUNCATE:
1141 if (layer_hint) {
1142 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1143 "'truncate' unsupported at origin. Dropping.");
1144 return 0;
1146 if (circ->n_conn) {
1147 uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
1148 connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
1149 trunc_reason);
1150 circuit_set_n_circid_orconn(circ, 0, NULL);
1152 log_debug(LD_EXIT, "Processed 'truncate', replying.");
1154 char payload[1];
1155 payload[0] = (char)END_CIRC_REASON_REQUESTED;
1156 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
1157 payload, sizeof(payload), NULL);
1159 return 0;
1160 case RELAY_COMMAND_TRUNCATED:
1161 if (!layer_hint) {
1162 log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
1163 "'truncated' unsupported at non-origin. Dropping.");
1164 return 0;
1166 circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
1167 return 0;
1168 case RELAY_COMMAND_CONNECTED:
1169 if (conn) {
1170 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1171 "'connected' unsupported while open. Closing circ.");
1172 return -END_CIRC_REASON_TORPROTOCOL;
1174 log_info(domain,
1175 "'connected' received, no conn attached anymore. Ignoring.");
1176 return 0;
1177 case RELAY_COMMAND_SENDME:
1178 if (!conn) {
1179 if (layer_hint) {
1180 layer_hint->package_window += CIRCWINDOW_INCREMENT;
1181 log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
1182 layer_hint->package_window);
1183 circuit_resume_edge_reading(circ, layer_hint);
1184 } else {
1185 circ->package_window += CIRCWINDOW_INCREMENT;
1186 log_debug(LD_APP,
1187 "circ-level sendme at non-origin, packagewindow %d.",
1188 circ->package_window);
1189 circuit_resume_edge_reading(circ, layer_hint);
1191 return 0;
1193 conn->package_window += STREAMWINDOW_INCREMENT;
1194 log_debug(domain,"stream-level sendme, packagewindow now %d.",
1195 conn->package_window);
1196 connection_start_reading(TO_CONN(conn));
1197 /* handle whatever might still be on the inbuf */
1198 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
1199 /* (We already sent an end cell if possible) */
1200 connection_mark_for_close(TO_CONN(conn));
1201 return 0;
1203 return 0;
1204 case RELAY_COMMAND_RESOLVE:
1205 if (layer_hint) {
1206 log_fn(LOG_PROTOCOL_WARN, LD_APP,
1207 "resolve request unsupported at AP; dropping.");
1208 return 0;
1209 } else if (conn) {
1210 log_fn(LOG_PROTOCOL_WARN, domain,
1211 "resolve request for known stream; dropping.");
1212 return 0;
1213 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
1214 log_fn(LOG_PROTOCOL_WARN, domain,
1215 "resolve request on circ with purpose %d; dropping",
1216 circ->purpose);
1217 return 0;
1219 connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
1220 return 0;
1221 case RELAY_COMMAND_RESOLVED:
1222 if (conn) {
1223 log_fn(LOG_PROTOCOL_WARN, domain,
1224 "'resolved' unsupported while open. Closing circ.");
1225 return -END_CIRC_REASON_TORPROTOCOL;
1227 log_info(domain,
1228 "'resolved' received, no conn attached anymore. Ignoring.");
1229 return 0;
1230 case RELAY_COMMAND_ESTABLISH_INTRO:
1231 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
1232 case RELAY_COMMAND_INTRODUCE1:
1233 case RELAY_COMMAND_INTRODUCE2:
1234 case RELAY_COMMAND_INTRODUCE_ACK:
1235 case RELAY_COMMAND_RENDEZVOUS1:
1236 case RELAY_COMMAND_RENDEZVOUS2:
1237 case RELAY_COMMAND_INTRO_ESTABLISHED:
1238 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
1239 rend_process_relay_cell(circ, layer_hint,
1240 rh.command, rh.length,
1241 cell->payload+RELAY_HEADER_SIZE);
1242 return 0;
1244 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1245 "Received unknown relay command %d. Perhaps the other side is using "
1246 "a newer version of Tor? Dropping.",
1247 rh.command);
1248 return 0; /* for forward compatibility, don't kill the circuit */
1251 /** How many relay_data cells have we built, ever? */
1252 uint64_t stats_n_data_cells_packaged = 0;
1253 /** How many bytes of data have we put in relay_data cells have we built,
1254 * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
1255 * every relay cell we ever sent were completely full of data. */
1256 uint64_t stats_n_data_bytes_packaged = 0;
1257 /** How many relay_data cells have we received, ever? */
1258 uint64_t stats_n_data_cells_received = 0;
1259 /** How many bytes of data have we received relay_data cells, ever? This would
1260 * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
1261 * ever received were completely full of data. */
1262 uint64_t stats_n_data_bytes_received = 0;
1264 /** While conn->inbuf has an entire relay payload of bytes on it,
1265 * and the appropriate package windows aren't empty, grab a cell
1266 * and send it down the circuit.
1268 * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
1269 * be marked for close, else return 0.
1272 connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
1274 size_t amount_to_process, length;
1275 char payload[CELL_PAYLOAD_SIZE];
1276 circuit_t *circ;
1277 unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
1279 tor_assert(conn);
1281 if (conn->_base.marked_for_close) {
1282 log_warn(LD_BUG,
1283 "called on conn that's already marked for close at %s:%d.",
1284 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
1285 return 0;
1288 repeat_connection_edge_package_raw_inbuf:
1290 circ = circuit_get_by_edge_conn(conn);
1291 if (!circ) {
1292 log_info(domain,"conn has no circuit! Closing.");
1293 conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
1294 return -1;
1297 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
1298 return 0;
1300 if (conn->package_window <= 0) {
1301 log_info(domain,"called with package_window %d. Skipping.",
1302 conn->package_window);
1303 connection_stop_reading(TO_CONN(conn));
1304 return 0;
1307 amount_to_process = buf_datalen(conn->_base.inbuf);
1309 if (!amount_to_process)
1310 return 0;
1312 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
1313 return 0;
1315 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
1316 length = RELAY_PAYLOAD_SIZE;
1317 } else {
1318 length = amount_to_process;
1320 stats_n_data_bytes_packaged += length;
1321 stats_n_data_cells_packaged += 1;
1323 connection_fetch_from_buf(payload, length, TO_CONN(conn));
1325 log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
1326 (int)length, (int)buf_datalen(conn->_base.inbuf));
1328 if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
1329 payload, length) < 0 )
1330 /* circuit got marked for close, don't continue, don't need to mark conn */
1331 return 0;
1333 if (!conn->cpath_layer) { /* non-rendezvous exit */
1334 tor_assert(circ->package_window > 0);
1335 circ->package_window--;
1336 } else { /* we're an AP, or an exit on a rendezvous circ */
1337 tor_assert(conn->cpath_layer->package_window > 0);
1338 conn->cpath_layer->package_window--;
1341 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
1342 connection_stop_reading(TO_CONN(conn));
1343 log_debug(domain,"conn->package_window reached 0.");
1344 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
1345 return 0; /* don't process the inbuf any more */
1347 log_debug(domain,"conn->package_window is now %d",conn->package_window);
1349 /* handle more if there's more, or return 0 if there isn't */
1350 goto repeat_connection_edge_package_raw_inbuf;
1353 /** Called when we've just received a relay data cell, or when
1354 * we've just finished flushing all bytes to stream <b>conn</b>.
1356 * If conn->outbuf is not too full, and our deliver window is
1357 * low, send back a suitable number of stream-level sendme cells.
1359 void
1360 connection_edge_consider_sending_sendme(edge_connection_t *conn)
1362 circuit_t *circ;
1364 if (connection_outbuf_too_full(TO_CONN(conn)))
1365 return;
1367 circ = circuit_get_by_edge_conn(conn);
1368 if (!circ) {
1369 /* this can legitimately happen if the destroy has already
1370 * arrived and torn down the circuit */
1371 log_info(LD_APP,"No circuit associated with conn. Skipping.");
1372 return;
1375 while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
1376 log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
1377 "Outbuf %d, Queuing stream sendme.",
1378 (int)conn->_base.outbuf_flushlen);
1379 conn->deliver_window += STREAMWINDOW_INCREMENT;
1380 if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
1381 NULL, 0) < 0) {
1382 log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
1383 return; /* the circuit's closed, don't continue */
1388 /** The circuit <b>circ</b> has received a circuit-level sendme
1389 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
1390 * attached streams and let them resume reading and packaging, if
1391 * their stream windows allow it.
1393 static void
1394 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1397 log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
1399 if (CIRCUIT_IS_ORIGIN(circ))
1400 circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
1401 circ, layer_hint);
1402 else
1403 circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
1404 circ, layer_hint);
1407 /** A helper function for circuit_resume_edge_reading() above.
1408 * The arguments are the same, except that <b>conn</b> is the head
1409 * of a linked list of edge streams that should each be considered.
1411 static int
1412 circuit_resume_edge_reading_helper(edge_connection_t *conn,
1413 circuit_t *circ,
1414 crypt_path_t *layer_hint)
1416 for ( ; conn; conn=conn->next_stream) {
1417 if (conn->_base.marked_for_close)
1418 continue;
1419 if ((!layer_hint && conn->package_window > 0) ||
1420 (layer_hint && conn->package_window > 0 &&
1421 conn->cpath_layer == layer_hint)) {
1422 connection_start_reading(TO_CONN(conn));
1423 /* handle whatever might still be on the inbuf */
1424 if (connection_edge_package_raw_inbuf(conn, 1)<0) {
1425 /* (We already sent an end cell if possible) */
1426 connection_mark_for_close(TO_CONN(conn));
1427 continue;
1430 /* If the circuit won't accept any more data, return without looking
1431 * at any more of the streams. Any connections that should be stopped
1432 * have already been stopped by connection_edge_package_raw_inbuf. */
1433 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1434 return -1;
1437 return 0;
1440 /** Check if the package window for <b>circ</b> is empty (at
1441 * hop <b>layer_hint</b> if it's defined).
1443 * If yes, tell edge streams to stop reading and return 1.
1444 * Else return 0.
1446 static int
1447 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1449 edge_connection_t *conn = NULL;
1450 unsigned domain = layer_hint ? LD_APP : LD_EXIT;
1452 if (!layer_hint) {
1453 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1454 log_debug(domain,"considering circ->package_window %d",
1455 circ->package_window);
1456 if (circ->package_window <= 0) {
1457 log_debug(domain,"yes, not-at-origin. stopped.");
1458 for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
1459 connection_stop_reading(TO_CONN(conn));
1460 return 1;
1462 return 0;
1464 /* else, layer hint is defined, use it */
1465 log_debug(domain,"considering layer_hint->package_window %d",
1466 layer_hint->package_window);
1467 if (layer_hint->package_window <= 0) {
1468 log_debug(domain,"yes, at-origin. stopped.");
1469 for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
1470 conn=conn->next_stream)
1471 if (conn->cpath_layer == layer_hint)
1472 connection_stop_reading(TO_CONN(conn));
1473 return 1;
1475 return 0;
1478 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1479 * <b>layer_hint</b> if it's defined) is low enough that we should
1480 * send a circuit-level sendme back down the circuit. If so, send
1481 * enough sendmes that the window would be overfull if we sent any
1482 * more.
1484 static void
1485 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1487 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1488 // layer_hint ? "defined" : "null");
1489 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
1490 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1491 log_debug(LD_CIRC,"Queuing circuit sendme.");
1492 if (layer_hint)
1493 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1494 else
1495 circ->deliver_window += CIRCWINDOW_INCREMENT;
1496 if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
1497 NULL, 0, layer_hint) < 0) {
1498 log_warn(LD_CIRC,
1499 "relay_send_command_from_edge failed. Circuit's closed.");
1500 return; /* the circuit's closed, don't continue */
1505 /** Stop reading on edge connections when we have this many cells
1506 * waiting on the appropriate queue. */
1507 #define CELL_QUEUE_HIGHWATER_SIZE 256
1508 /** Start reading from edge connections again when we get down to this many
1509 * cells. */
1510 #define CELL_QUEUE_LOWWATER_SIZE 64
1512 #ifdef ACTIVE_CIRCUITS_PARANOIA
1513 #define assert_active_circuits_ok_paranoid(conn) \
1514 assert_active_circuits_ok(conn)
1515 #else
1516 #define assert_active_circuits_ok_paranoid(conn)
1517 #endif
1519 /** The total number of cells we have allocated from the memory pool. */
1520 static int total_cells_allocated = 0;
1522 /** A memory pool to allocate packed_cell_t objects. */
1523 static mp_pool_t *cell_pool = NULL;
1525 /** Allocate structures to hold cells. */
1526 void
1527 init_cell_pool(void)
1529 tor_assert(!cell_pool);
1530 cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
1533 /** Free all storage used to hold cells. */
1534 void
1535 free_cell_pool(void)
1537 /* Maybe we haven't called init_cell_pool yet; need to check for it. */
1538 if (cell_pool) {
1539 mp_pool_destroy(cell_pool);
1540 cell_pool = NULL;
1544 /** Free excess storage in cell pool. */
1545 void
1546 clean_cell_pool(void)
1548 tor_assert(cell_pool);
1549 mp_pool_clean(cell_pool, 0, 1);
1552 /** Release storage held by <b>cell</b>. */
1553 static INLINE void
1554 packed_cell_free(packed_cell_t *cell)
1556 --total_cells_allocated;
1557 mp_pool_release(cell);
1560 /** Allocate and return a new packed_cell_t. */
1561 static INLINE packed_cell_t *
1562 packed_cell_alloc(void)
1564 ++total_cells_allocated;
1565 return mp_pool_get(cell_pool);
1568 /** Log current statistics for cell pool allocation at log level
1569 * <b>severity</b>. */
1570 void
1571 dump_cell_pool_usage(int severity)
1573 circuit_t *c;
1574 int n_circs = 0;
1575 int n_cells = 0;
1576 for (c = _circuit_get_global_list(); c; c = c->next) {
1577 n_cells += c->n_conn_cells.n;
1578 if (!CIRCUIT_IS_ORIGIN(c))
1579 n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
1580 ++n_circs;
1582 log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
1583 n_cells, n_circs, total_cells_allocated - n_cells);
1584 mp_pool_log_status(cell_pool, severity);
1587 /** Allocate a new copy of packed <b>cell</b>. */
1588 static INLINE packed_cell_t *
1589 packed_cell_copy(const cell_t *cell)
1591 packed_cell_t *c = packed_cell_alloc();
1592 cell_pack(c, cell);
1593 c->next = NULL;
1594 return c;
1597 /** Append <b>cell</b> to the end of <b>queue</b>. */
1598 void
1599 cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
1601 if (queue->tail) {
1602 tor_assert(!queue->tail->next);
1603 queue->tail->next = cell;
1604 } else {
1605 queue->head = cell;
1607 queue->tail = cell;
1608 cell->next = NULL;
1609 ++queue->n;
1612 /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
1613 void
1614 cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
1616 packed_cell_t *copy = packed_cell_copy(cell);
1617 #ifdef ENABLE_BUFFER_STATS
1618 /* Remember the exact time when this cell was put in the queue. */
1619 if (get_options()->CellStatistics)
1620 tor_gettimeofday(&copy->packed_timeval);
1621 #endif
1622 cell_queue_append(queue, copy);
1625 /** Remove and free every cell in <b>queue</b>. */
1626 void
1627 cell_queue_clear(cell_queue_t *queue)
1629 packed_cell_t *cell, *next;
1630 cell = queue->head;
1631 while (cell) {
1632 next = cell->next;
1633 packed_cell_free(cell);
1634 cell = next;
1636 queue->head = queue->tail = NULL;
1637 queue->n = 0;
1640 /** Extract and return the cell at the head of <b>queue</b>; return NULL if
1641 * <b>queue</b> is empty. */
1642 static INLINE packed_cell_t *
1643 cell_queue_pop(cell_queue_t *queue)
1645 packed_cell_t *cell = queue->head;
1646 if (!cell)
1647 return NULL;
1648 queue->head = cell->next;
1649 if (cell == queue->tail) {
1650 tor_assert(!queue->head);
1651 queue->tail = NULL;
1653 --queue->n;
1654 return cell;
1657 /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
1658 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1659 static INLINE circuit_t **
1660 next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1662 tor_assert(circ);
1663 tor_assert(conn);
1664 if (conn == circ->n_conn) {
1665 return &circ->next_active_on_n_conn;
1666 } else {
1667 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1668 tor_assert(conn == orcirc->p_conn);
1669 return &orcirc->next_active_on_p_conn;
1673 /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
1674 * depending on whether <b>conn</b> matches n_conn or p_conn. */
1675 static INLINE circuit_t **
1676 prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
1678 tor_assert(circ);
1679 tor_assert(conn);
1680 if (conn == circ->n_conn) {
1681 return &circ->prev_active_on_n_conn;
1682 } else {
1683 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1684 tor_assert(conn == orcirc->p_conn);
1685 return &orcirc->prev_active_on_p_conn;
1689 /** Add <b>circ</b> to the list of circuits with pending cells on
1690 * <b>conn</b>. No effect if <b>circ</b> is already linked. */
1691 void
1692 make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
1694 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1695 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1697 if (*nextp && *prevp) {
1698 /* Already active. */
1699 return;
1702 if (! conn->active_circuits) {
1703 conn->active_circuits = circ;
1704 *prevp = *nextp = circ;
1705 } else {
1706 circuit_t *head = conn->active_circuits;
1707 circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
1708 *next_circ_on_conn_p(old_tail, conn) = circ;
1709 *nextp = head;
1710 *prev_circ_on_conn_p(head, conn) = circ;
1711 *prevp = old_tail;
1713 assert_active_circuits_ok_paranoid(conn);
1716 /** Remove <b>circ</b> from the list of circuits with pending cells on
1717 * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
1718 void
1719 make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
1721 circuit_t **nextp = next_circ_on_conn_p(circ, conn);
1722 circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
1723 circuit_t *next = *nextp, *prev = *prevp;
1725 if (!next && !prev) {
1726 /* Already inactive. */
1727 return;
1730 tor_assert(next && prev);
1731 tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
1732 tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
1734 if (next == circ) {
1735 conn->active_circuits = NULL;
1736 } else {
1737 *prev_circ_on_conn_p(next, conn) = prev;
1738 *next_circ_on_conn_p(prev, conn) = next;
1739 if (conn->active_circuits == circ)
1740 conn->active_circuits = next;
1742 *prevp = *nextp = NULL;
1743 assert_active_circuits_ok_paranoid(conn);
1746 /** Remove all circuits from the list of circuits with pending cells on
1747 * <b>conn</b>. */
1748 void
1749 connection_or_unlink_all_active_circs(or_connection_t *orconn)
1751 circuit_t *head = orconn->active_circuits;
1752 circuit_t *cur = head;
1753 if (! head)
1754 return;
1755 do {
1756 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
1757 *prev_circ_on_conn_p(cur, orconn) = NULL;
1758 *next_circ_on_conn_p(cur, orconn) = NULL;
1759 cur = next;
1760 } while (cur != head);
1761 orconn->active_circuits = NULL;
1764 /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
1765 * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
1766 * and start or stop reading as appropriate. */
1767 static void
1768 set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
1769 int block)
1771 edge_connection_t *edge = NULL;
1772 if (circ->n_conn == orconn) {
1773 circ->streams_blocked_on_n_conn = block;
1774 if (CIRCUIT_IS_ORIGIN(circ))
1775 edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
1776 } else {
1777 circ->streams_blocked_on_p_conn = block;
1778 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1779 edge = TO_OR_CIRCUIT(circ)->n_streams;
1782 for (; edge; edge = edge->next_stream) {
1783 connection_t *conn = TO_CONN(edge);
1784 edge->edge_blocked_on_circ = block;
1786 if (!conn->read_event) {
1787 /* This connection is a placeholder for something; probably a DNS
1788 * request. It can't actually stop or start reading.*/
1789 continue;
1792 if (block) {
1793 if (connection_is_reading(conn))
1794 connection_stop_reading(conn);
1795 } else {
1796 /* Is this right? */
1797 if (!connection_is_reading(conn))
1798 connection_start_reading(conn);
1803 /** Pull as many cells as possible (but no more than <b>max</b>) from the
1804 * queue of the first active circuit on <b>conn</b>, and write then to
1805 * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
1806 * the active circuit pointer to the next active circuit in the ring. */
1808 connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
1809 time_t now)
1811 int n_flushed;
1812 cell_queue_t *queue;
1813 circuit_t *circ;
1814 int streams_blocked;
1815 circ = conn->active_circuits;
1816 if (!circ) return 0;
1817 assert_active_circuits_ok_paranoid(conn);
1818 if (circ->n_conn == conn) {
1819 queue = &circ->n_conn_cells;
1820 streams_blocked = circ->streams_blocked_on_n_conn;
1821 } else {
1822 queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
1823 streams_blocked = circ->streams_blocked_on_p_conn;
1825 tor_assert(*next_circ_on_conn_p(circ,conn));
1827 for (n_flushed = 0; n_flushed < max && queue->head; ) {
1828 packed_cell_t *cell = cell_queue_pop(queue);
1829 tor_assert(*next_circ_on_conn_p(circ,conn));
1831 #ifdef ENABLE_BUFFER_STATS
1832 /* Calculate the exact time that this cell has spent in the queue. */
1833 if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
1834 struct timeval flushed_from_queue;
1835 uint32_t cell_waiting_time;
1836 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1837 tor_gettimeofday(&flushed_from_queue);
1838 cell_waiting_time = (uint32_t)
1839 (tv_udiff(&cell->packed_timeval, &flushed_from_queue) / 1000);
1840 orcirc->total_cell_waiting_time += cell_waiting_time;
1841 orcirc->processed_cells++;
1843 #endif
1844 #ifdef ENABLE_DIRREQ_STATS
1845 /* If we just flushed our queue and this circuit is used for a
1846 * tunneled directory request, possibly advance its state. */
1847 if (queue->n == 0 && TO_CONN(conn)->dirreq_id)
1848 geoip_change_dirreq_state(TO_CONN(conn)->dirreq_id,
1849 DIRREQ_TUNNELED,
1850 DIRREQ_CIRC_QUEUE_FLUSHED);
1851 #endif
1853 connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
1855 packed_cell_free(cell);
1856 ++n_flushed;
1857 if (circ != conn->active_circuits) {
1858 /* If this happens, the current circuit just got made inactive by
1859 * a call in connection_write_to_buf(). That's nothing to worry about:
1860 * circuit_make_inactive_on_conn() already advanced conn->active_circuits
1861 * for us.
1863 assert_active_circuits_ok_paranoid(conn);
1864 goto done;
1867 tor_assert(*next_circ_on_conn_p(circ,conn));
1868 assert_active_circuits_ok_paranoid(conn);
1869 conn->active_circuits = *next_circ_on_conn_p(circ, conn);
1871 /* Is the cell queue low enough to unblock all the streams that are waiting
1872 * to write to this circuit? */
1873 if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
1874 set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
1876 /* Did we just ran out of cells on this queue? */
1877 if (queue->n == 0) {
1878 log_debug(LD_GENERAL, "Made a circuit inactive.");
1879 make_circuit_inactive_on_conn(circ, conn);
1881 done:
1882 if (n_flushed)
1883 conn->timestamp_last_added_nonpadding = now;
1884 return n_flushed;
1887 /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
1888 * transmitting in <b>direction</b>. */
1889 void
1890 append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
1891 cell_t *cell, cell_direction_t direction)
1893 cell_queue_t *queue;
1894 int streams_blocked;
1895 if (direction == CELL_DIRECTION_OUT) {
1896 queue = &circ->n_conn_cells;
1897 streams_blocked = circ->streams_blocked_on_n_conn;
1898 } else {
1899 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
1900 queue = &orcirc->p_conn_cells;
1901 streams_blocked = circ->streams_blocked_on_p_conn;
1903 if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
1904 /* V1 connections don't understand RELAY_EARLY. */
1905 cell->command = CELL_RELAY;
1908 cell_queue_append_packed_copy(queue, cell);
1910 /* If we have too many cells on the circuit, we should stop reading from
1911 * the edge streams for a while. */
1912 if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
1913 set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
1915 if (queue->n == 1) {
1916 /* This was the first cell added to the queue. We need to make this
1917 * circuit active. */
1918 log_debug(LD_GENERAL, "Made a circuit active.");
1919 make_circuit_active_on_conn(circ, orconn);
1922 if (! buf_datalen(orconn->_base.outbuf)) {
1923 /* There is no data at all waiting to be sent on the outbuf. Add a
1924 * cell, so that we can notice when it gets flushed, flushed_some can
1925 * get called, and we can start putting more data onto the buffer then.
1927 log_debug(LD_GENERAL, "Primed a buffer.");
1928 connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
1932 /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
1933 * have at least 18 bytes of free space. The encoding is, as specified in
1934 * tor-spec.txt:
1935 * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
1936 * LENGTH [1 byte]
1937 * ADDRESS [length bytes]
1938 * Return the number of bytes added, or -1 on error */
1940 append_address_to_payload(char *payload_out, const tor_addr_t *addr)
1942 uint32_t a;
1943 switch (tor_addr_family(addr)) {
1944 case AF_INET:
1945 payload_out[0] = RESOLVED_TYPE_IPV4;
1946 payload_out[1] = 4;
1947 a = tor_addr_to_ipv4n(addr);
1948 memcpy(payload_out+2, &a, 4);
1949 return 6;
1950 case AF_INET6:
1951 payload_out[0] = RESOLVED_TYPE_IPV6;
1952 payload_out[1] = 16;
1953 memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
1954 return 18;
1955 case AF_UNSPEC:
1956 default:
1957 return -1;
1961 /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
1962 * encoded as by append_address_to_payload(), try to decode the address into
1963 * *<b>addr_out</b>. Return the next byte in the payload after the address on
1964 * success, or NULL on failure. */
1965 const char *
1966 decode_address_from_payload(tor_addr_t *addr_out, const char *payload,
1967 int payload_len)
1969 if (payload_len < 2)
1970 return NULL;
1971 if (payload_len < 2+(uint8_t)payload[1])
1972 return NULL;
1974 switch (payload[0]) {
1975 case RESOLVED_TYPE_IPV4:
1976 if (payload[1] != 4)
1977 return NULL;
1978 tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
1979 break;
1980 case RESOLVED_TYPE_IPV6:
1981 if (payload[1] != 16)
1982 return NULL;
1983 tor_addr_from_ipv6_bytes(addr_out, payload+2);
1984 break;
1985 default:
1986 tor_addr_make_unspec(addr_out);
1987 break;
1989 return payload + 2 + (uint8_t)payload[1];
1992 /** Fail with an assert if the active circuits ring on <b>orconn</b> is
1993 * corrupt. */
1994 void
1995 assert_active_circuits_ok(or_connection_t *orconn)
1997 circuit_t *head = orconn->active_circuits;
1998 circuit_t *cur = head;
1999 if (! head)
2000 return;
2001 do {
2002 circuit_t *next = *next_circ_on_conn_p(cur, orconn);
2003 circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
2004 tor_assert(next);
2005 tor_assert(prev);
2006 tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
2007 tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
2008 cur = next;
2009 } while (cur != head);