Forward port changelog
[tor.git] / src / or / relay.c
blob39ef56caa29e7f7bd67add20c96fb150acc646a4
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char relay_c_id[] = "$Id$";
8 /**
9 * \file relay.c
10 * \brief Handle relay cell encryption/decryption, plus packaging and
11 * receiving from circuits.
12 **/
14 #include "or.h"
16 static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
17 crypt_path_t **layer_hint, char *recognized);
18 static connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction);
20 static int
21 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
22 connection_t *conn,
23 crypt_path_t *layer_hint);
24 static void
25 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
26 static void
27 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
28 static int
29 circuit_resume_edge_reading_helper(connection_t *conn,
30 circuit_t *circ,
31 crypt_path_t *layer_hint);
32 static int
33 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
35 /** Stats: how many relay cells have originated at this hop, or have
36 * been relayed onward (not recognized at this hop)?
38 unsigned long stats_n_relay_cells_relayed = 0;
39 /** Stats: how many relay cells have been delivered to streams at this
40 * hop?
42 unsigned long stats_n_relay_cells_delivered = 0;
44 /** Update digest from the payload of cell. Assign integrity part to
45 * cell.
47 static void relay_set_digest(crypto_digest_env_t *digest, cell_t *cell) {
48 char integrity[4];
49 relay_header_t rh;
51 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
52 crypto_digest_get_digest(digest, integrity, 4);
53 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
54 // integrity[0], integrity[1], integrity[2], integrity[3]);
55 relay_header_unpack(&rh, cell->payload);
56 memcpy(rh.integrity, integrity, 4);
57 relay_header_pack(cell->payload, &rh);
60 /** Does the digest for this circuit indicate that this cell is for us?
62 * Update digest from the payload of cell (with the integrity part set
63 * to 0). If the integrity part is valid, return 1, else restore digest
64 * and cell to their original state and return 0.
66 static int relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell) {
67 char received_integrity[4], calculated_integrity[4];
68 relay_header_t rh;
69 crypto_digest_env_t *backup_digest=NULL;
71 backup_digest = crypto_digest_dup(digest);
73 relay_header_unpack(&rh, cell->payload);
74 memcpy(received_integrity, rh.integrity, 4);
75 memset(rh.integrity, 0, 4);
76 relay_header_pack(cell->payload, &rh);
78 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
79 // received_integrity[0], received_integrity[1],
80 // received_integrity[2], received_integrity[3]);
82 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
83 crypto_digest_get_digest(digest, calculated_integrity, 4);
85 if (memcmp(received_integrity, calculated_integrity, 4)) {
86 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
87 // (%d vs %d).", received_integrity, calculated_integrity);
88 /* restore digest to its old form */
89 crypto_digest_assign(digest, backup_digest);
90 /* restore the relay header */
91 memcpy(rh.integrity, received_integrity, 4);
92 relay_header_pack(cell->payload, &rh);
93 crypto_free_digest_env(backup_digest);
94 return 0;
96 crypto_free_digest_env(backup_digest);
97 return 1;
100 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
101 * (in place).
103 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
105 * Return -1 if the crypto fails, else return 0.
107 static int relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
108 int encrypt_mode) {
109 char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
110 relay_header_t rh;
112 relay_header_unpack(&rh, in);
113 // log_fn(LOG_DEBUG,"before crypt: %d",rh.recognized);
114 if (( encrypt_mode && crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE)) ||
115 (!encrypt_mode && crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE))) {
116 log_fn(LOG_WARN,"Error during relay encryption");
117 return -1;
119 memcpy(in,out,CELL_PAYLOAD_SIZE);
120 relay_header_unpack(&rh, in);
121 // log_fn(LOG_DEBUG,"after crypt: %d",rh.recognized);
122 return 0;
125 /** Receive a relay cell:
126 * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
127 * - Check if recognized (if exitward).
128 * - If recognized and the digest checks out, then find if there's
129 * a conn that the cell is intended for, and deliver it to·
130 * connection_edge.
131 * - Else connection_or_write_cell_to_buf to the conn on the other
132 * side of the circuit.
134 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
135 int cell_direction) {
136 connection_t *conn=NULL;
137 crypt_path_t *layer_hint=NULL;
138 char recognized=0;
140 tor_assert(cell);
141 tor_assert(circ);
142 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
143 cell_direction == CELL_DIRECTION_IN);
144 if (circ->marked_for_close)
145 return 0;
147 if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
148 log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
149 return -1;
152 if (recognized) {
153 conn = relay_lookup_conn(circ, cell, cell_direction);
154 if (cell_direction == CELL_DIRECTION_OUT) {
155 ++stats_n_relay_cells_delivered;
156 log_fn(LOG_DEBUG,"Sending away from origin.");
157 if (connection_edge_process_relay_cell(cell, circ, conn, NULL) < 0) {
158 log_fn(LOG_WARN,"connection_edge_process_relay_cell (away from origin) failed.");
159 return -1;
162 if (cell_direction == CELL_DIRECTION_IN) {
163 ++stats_n_relay_cells_delivered;
164 log_fn(LOG_DEBUG,"Sending to origin.");
165 if (connection_edge_process_relay_cell(cell, circ, conn, layer_hint) < 0) {
166 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at origin) failed.");
167 return -1;
170 return 0;
173 /* not recognized. pass it on. */
174 if (cell_direction == CELL_DIRECTION_OUT) {
175 cell->circ_id = circ->n_circ_id; /* switch it */
176 conn = circ->n_conn;
177 } else {
178 cell->circ_id = circ->p_circ_id; /* switch it */
179 conn = circ->p_conn;
182 if (!conn) {
183 if (circ->rend_splice && cell_direction == CELL_DIRECTION_OUT) {
184 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
185 tor_assert(circ->rend_splice->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
186 cell->circ_id = circ->rend_splice->p_circ_id;
187 if (circuit_receive_relay_cell(cell, circ->rend_splice, CELL_DIRECTION_IN)<0) {
188 log_fn(LOG_WARN, "Error relaying cell across rendezvous; closing circuits");
189 circuit_mark_for_close(circ); /* XXXX Do this here, or just return -1? */
190 return -1;
192 return 0;
194 log_fn(LOG_WARN,"Didn't recognize cell, but circ stops here! Closing circ.");
195 return -1;
198 log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
199 ++stats_n_relay_cells_relayed;
200 connection_or_write_cell_to_buf(cell, conn);
201 return 0;
204 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
205 * <b>circ</b> in direction <b>cell_direction</b>.
207 * If cell_direction == CELL_DIRECTION_IN:
208 * - If we're at the origin (we're the OP), for hops 1..N,
209 * decrypt cell. If recognized, stop.
210 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
212 * If cell_direction == CELL_DIRECTION_OUT:
213 * - decrypt one hop. Check if recognized.
215 * If cell is recognized, set *recognized to 1, and set
216 * *layer_hint to the hop that recognized it.
218 * Return -1 to indicate that we should mark the circuit for close,
219 * else return 0.
221 /* wrap this into receive_relay_cell one day */
222 static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
223 crypt_path_t **layer_hint, char *recognized) {
224 crypt_path_t *thishop;
225 relay_header_t rh;
227 tor_assert(circ);
228 tor_assert(cell);
229 tor_assert(recognized);
230 tor_assert(cell_direction == CELL_DIRECTION_IN ||
231 cell_direction == CELL_DIRECTION_OUT);
233 if (cell_direction == CELL_DIRECTION_IN) {
234 if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
235 We'll want to do layered decrypts. */
236 tor_assert(circ->cpath);
237 thishop = circ->cpath;
238 if (thishop->state != CPATH_STATE_OPEN) {
239 log_fn(LOG_WARN,"Relay cell before first created cell? Closing.");
240 return -1;
242 do { /* Remember: cpath is in forward order, that is, first hop first. */
243 tor_assert(thishop);
245 if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
246 return -1;
248 relay_header_unpack(&rh, cell->payload);
249 if (rh.recognized == 0) {
250 /* it's possibly recognized. have to check digest to be sure. */
251 if (relay_digest_matches(thishop->b_digest, cell)) {
252 *recognized = 1;
253 *layer_hint = thishop;
254 return 0;
258 thishop = thishop->next;
259 } while (thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
260 log_fn(LOG_WARN,"in-cell at OP not recognized. Closing.");
261 return -1;
262 } else { /* we're in the middle. Just one crypt. */
263 if (relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
264 return -1;
265 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
267 } else /* cell_direction == CELL_DIRECTION_OUT */ {
268 /* we're in the middle. Just one crypt. */
270 if (relay_crypt_one_payload(circ->n_crypto, cell->payload, 0) < 0)
271 return -1;
273 relay_header_unpack(&rh, cell->payload);
274 if (rh.recognized == 0) {
275 /* it's possibly recognized. have to check digest to be sure. */
276 if (relay_digest_matches(circ->n_digest, cell)) {
277 *recognized = 1;
278 return 0;
282 return 0;
285 /** Package a relay cell:
286 * - Encrypt it to the right layer
287 * - connection_or_write_cell_to_buf to the right conn
289 static int
290 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
291 int cell_direction,
292 crypt_path_t *layer_hint)
294 connection_t *conn; /* where to send the cell */
295 crypt_path_t *thishop; /* counter for repeated crypts */
297 if (cell_direction == CELL_DIRECTION_OUT) {
298 conn = circ->n_conn;
299 if (!conn) {
300 log_fn(LOG_WARN,"outgoing relay cell has n_conn==NULL. Dropping.");
301 return 0; /* just drop it */
303 relay_set_digest(layer_hint->f_digest, cell);
305 thishop = layer_hint;
306 /* moving from farthest to nearest hop */
307 do {
308 tor_assert(thishop);
310 log_fn(LOG_DEBUG,"crypting a layer of the relay cell.");
311 if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
312 return -1;
315 thishop = thishop->prev;
316 } while (thishop != circ->cpath->prev);
318 } else { /* incoming cell */
319 conn = circ->p_conn;
320 if (!conn) {
321 log_fn(LOG_WARN,"incoming relay cell has p_conn==NULL. Dropping.");
322 return 0; /* just drop it */
324 relay_set_digest(circ->p_digest, cell);
325 if (relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
326 return -1;
328 ++stats_n_relay_cells_relayed;
329 connection_or_write_cell_to_buf(cell, conn);
330 return 0;
333 /** If cell's stream_id matches the stream_id of any conn that's
334 * attached to circ, return that conn, else return NULL.
336 static connection_t *
337 relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
339 connection_t *tmpconn;
340 relay_header_t rh;
342 relay_header_unpack(&rh, cell->payload);
344 if (!rh.stream_id)
345 return NULL;
347 /* IN or OUT cells could have come from either direction, now
348 * that we allow rendezvous *to* an OP.
351 for (tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
352 if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
353 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
354 if (cell_direction == CELL_DIRECTION_OUT ||
355 connection_edge_is_rendezvous_stream(tmpconn))
356 return tmpconn;
359 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
360 if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
361 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
362 return tmpconn;
365 for (tmpconn = circ->resolving_streams; tmpconn; tmpconn=tmpconn->next_stream) {
366 if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
367 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
368 return tmpconn;
371 return NULL; /* probably a begin relay cell */
374 /** Pack the relay_header_t host-order structure <b>src</b> into
375 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
376 * about the wire format.
378 void relay_header_pack(char *dest, const relay_header_t *src) {
379 *(uint8_t*)(dest) = src->command;
381 set_uint16(dest+1, htons(src->recognized));
382 set_uint16(dest+3, htons(src->stream_id));
383 memcpy(dest+5, src->integrity, 4);
384 set_uint16(dest+9, htons(src->length));
387 /** Unpack the network-order buffer <b>src</b> into a host-order
388 * relay_header_t structure <b>dest</b>.
390 void relay_header_unpack(relay_header_t *dest, const char *src) {
391 dest->command = *(uint8_t*)(src);
393 dest->recognized = ntohs(get_uint16(src+1));
394 dest->stream_id = ntohs(get_uint16(src+3));
395 memcpy(dest->integrity, src+5, 4);
396 dest->length = ntohs(get_uint16(src+9));
399 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
400 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
401 * that's sending the relay cell, or NULL if it's a control cell.
402 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
403 * for OP->OR cells.
405 * If you can't send the cell, mark the circuit for close and
406 * return -1. Else return 0.
408 int connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
409 int relay_command, const char *payload,
410 size_t payload_len, crypt_path_t *cpath_layer) {
411 cell_t cell;
412 relay_header_t rh;
413 int cell_direction;
415 if (!circ) {
416 log_fn(LOG_WARN,"no circ. Closing conn.");
417 tor_assert(fromconn);
418 fromconn->has_sent_end = 1; /* no circ to send to */
419 connection_mark_for_close(fromconn);
420 return -1;
423 memset(&cell, 0, sizeof(cell_t));
424 cell.command = CELL_RELAY;
425 if (cpath_layer) {
426 cell.circ_id = circ->n_circ_id;
427 cell_direction = CELL_DIRECTION_OUT;
428 } else {
429 cell.circ_id = circ->p_circ_id;
430 cell_direction = CELL_DIRECTION_IN;
433 memset(&rh, 0, sizeof(rh));
434 rh.command = relay_command;
435 if (fromconn)
436 rh.stream_id = fromconn->stream_id; /* else it's 0 */
437 rh.length = payload_len;
438 relay_header_pack(cell.payload, &rh);
439 if (payload_len)
440 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
442 log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
443 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
445 if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
446 log_fn(LOG_WARN,"circuit_package_relay_cell failed. Closing.");
447 circuit_mark_for_close(circ);
448 return -1;
450 return 0;
453 /** Translate the <b>payload</b> of length <b>length</b>, which
454 * came from a relay 'end' cell, into a static const string describing
455 * why the stream is closing.
457 static const char *
458 connection_edge_end_reason(char *payload, uint16_t length) {
459 if (length < 1) {
460 log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
461 return "MALFORMED";
463 if (*payload < _MIN_END_STREAM_REASON || *payload > _MAX_END_STREAM_REASON) {
464 log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",*payload);
465 return "MALFORMED";
467 switch (*payload) {
468 case END_STREAM_REASON_MISC: return "misc error";
469 case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
470 case END_STREAM_REASON_CONNECTFAILED: return "connect failed";
471 case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
472 case END_STREAM_REASON_DESTROY: return "destroyed";
473 case END_STREAM_REASON_DONE: return "closed normally";
474 case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
476 tor_assert(0);
477 return "";
480 /** How many times will I retry a stream that fails due to DNS
481 * resolve failure?
483 #define MAX_RESOLVE_FAILURES 3
485 /** An incoming relay cell has arrived from circuit <b>circ</b> to
486 * stream <b>conn</b>.
488 * The arguments here are the same as in
489 * connection_edge_process_relay_cell() below; this function is called
490 * from there when <b>conn</b> is defined and not in an open state.
492 static int
493 connection_edge_process_relay_cell_not_open(
494 relay_header_t *rh, cell_t *cell, circuit_t *circ,
495 connection_t *conn, crypt_path_t *layer_hint) {
496 uint32_t addr;
497 int reason;
498 routerinfo_t *exitrouter;
500 if (rh->command == RELAY_COMMAND_END) {
501 reason = *(cell->payload+RELAY_HEADER_SIZE);
502 /* We have to check this here, since we aren't connected yet. */
503 if (rh->length >= 5 && reason == END_STREAM_REASON_EXITPOLICY) {
504 if (conn->type != CONN_TYPE_AP) {
505 log_fn(LOG_WARN,"Got an end because of exitpolicy, but we're not an AP. Closing.");
506 return -1;
508 addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
509 if (addr) {
510 log_fn(LOG_INFO,"Address '%s' refused due to exit policy. Retrying.",
511 conn->socks_request->address);
512 } else {
513 log_fn(LOG_INFO,"Address '%s' resolved to 0.0.0.0. Closing,",
514 conn->socks_request->address);
515 conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
516 connection_mark_for_close(conn);
517 return 0;
519 client_dns_set_entry(conn->socks_request->address, addr);
521 /* check if he *ought* to have allowed it */
522 exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
523 if (!exitrouter) {
524 log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
525 return 0; /* this circuit is screwed and doesn't know it yet */
527 if (connection_ap_can_use_exit(conn, exitrouter)) {
528 log_fn(LOG_NOTICE,"Exitrouter '%s' seems to be more restrictive than its exit policy. Not using this router as exit for now.", exitrouter->nickname);
529 addr_policy_free(exitrouter->exit_policy);
530 exitrouter->exit_policy =
531 router_parse_addr_policy_from_string("reject *:*");
534 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
535 circuit_detach_stream(circ,conn);
536 if (connection_ap_handshake_attach_circuit(conn) >= 0)
537 return 0;
538 log_fn(LOG_INFO,"Giving up on retrying (from exitpolicy); conn can't be handled.");
539 /* else, conn will get closed below */
540 } else if (rh->length && reason == END_STREAM_REASON_RESOLVEFAILED) {
541 if (conn->type != CONN_TYPE_AP) {
542 log_fn(LOG_WARN,"Got an end because of resolvefailed, but we're not an AP. Closing.");
543 return -1;
545 if (client_dns_incr_failures(conn->socks_request->address)
546 < MAX_RESOLVE_FAILURES) {
547 /* We haven't retried too many times; reattach the connection. */
548 log_fn(LOG_INFO,"Resolve of '%s' failed, trying again.",
549 conn->socks_request->address);
550 circuit_log_path(LOG_INFO,circ);
551 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
552 circuit_detach_stream(circ,conn);
553 tor_assert(circ->timestamp_dirty);
554 circ->timestamp_dirty -= get_options()->MaxCircuitDirtiness;
555 /* make sure not to expire/retry the stream quite yet */
556 conn->timestamp_lastread = time(NULL);
557 if (connection_ap_handshake_attach_circuit(conn) >= 0)
558 return 0;
559 /* else, conn will get closed below */
560 log_fn(LOG_INFO,"Giving up on retrying (from resolvefailed); conn can't be handled.");
561 } else {
562 log_fn(LOG_NOTICE,"Have tried resolving address '%s' at %d different places. Giving up.",
563 conn->socks_request->address, MAX_RESOLVE_FAILURES);
566 log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
567 connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh->length));
568 if (CIRCUIT_IS_ORIGIN(circ))
569 circuit_log_path(LOG_INFO,circ);
570 conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
571 connection_mark_for_close(conn);
572 return 0;
575 if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
576 if (conn->state != AP_CONN_STATE_CONNECT_WAIT) {
577 log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
578 return 0;
580 // log_fn(LOG_INFO,"Connected! Notifying application.");
581 conn->state = AP_CONN_STATE_OPEN;
582 log_fn(LOG_INFO,"'connected' received after %d seconds.",
583 (int)(time(NULL) - conn->timestamp_lastread));
584 if (rh->length >= 4) {
585 addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
586 if (!addr) {
587 log_fn(LOG_INFO,"...but it claims the IP address was 0.0.0.0. Closing.");
588 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
589 connection_mark_for_close(conn);
590 return 0;
592 client_dns_set_entry(conn->socks_request->address, addr);
594 circuit_log_path(LOG_INFO,circ);
595 connection_ap_handshake_socks_reply(conn, NULL, 0, 1);
596 conn->socks_request->has_finished = 1;
597 /* handle anything that might have queued */
598 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
599 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
600 connection_mark_for_close(conn);
601 return 0;
603 return 0;
605 if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_RESOLVED) {
606 if (conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
607 log_fn(LOG_WARN,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
608 return 0;
610 tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
611 if (rh->length < 2 || cell->payload[RELAY_HEADER_SIZE+1]+2>rh->length) {
612 log_fn(LOG_WARN, "Dropping malformed 'resolved' cell");
613 conn->has_sent_end = 1;
614 connection_mark_for_close(conn);
615 return 0;
617 connection_ap_handshake_socks_resolved(conn,
618 cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
619 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
620 cell->payload+RELAY_HEADER_SIZE+2); /* answer */
621 conn->has_sent_end = 1;
622 connection_mark_for_close(conn);
623 conn->hold_open_until_flushed = 1;
624 return 0;
627 log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
628 rh->command, conn->state, conn_state_to_string[conn->type][conn->state]);
629 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
630 connection_mark_for_close(conn);
631 return -1;
634 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
635 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
636 * destined for <b>conn</b>.
638 * If <b>layer_hint</b> is defined, then we're the origin of the
639 * circuit, and it specifies the hop that packaged <b>cell</b>.
641 * Return -1 if you want to tear down the circuit, else 0.
643 static int
644 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
645 connection_t *conn,
646 crypt_path_t *layer_hint)
648 static int num_seen=0;
649 relay_header_t rh;
651 tor_assert(cell);
652 tor_assert(circ);
654 relay_header_unpack(&rh, cell->payload);
655 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
656 num_seen++;
657 log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
659 /* either conn is NULL, in which case we've got a control cell, or else
660 * conn points to the recognized stream. */
662 if (conn &&
663 conn->state != AP_CONN_STATE_OPEN &&
664 conn->state != EXIT_CONN_STATE_OPEN) {
665 return connection_edge_process_relay_cell_not_open(
666 &rh, cell, circ, conn, layer_hint);
669 switch (rh.command) {
670 case RELAY_COMMAND_DROP:
671 log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
672 return 0;
673 case RELAY_COMMAND_BEGIN:
674 if (layer_hint &&
675 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
676 log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
677 return 0;
679 if (conn) {
680 log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
681 return 0;
683 connection_exit_begin_conn(cell, circ);
684 return 0;
685 case RELAY_COMMAND_DATA:
686 ++stats_n_data_cells_received;
687 if (( layer_hint && --layer_hint->deliver_window < 0) ||
688 (!layer_hint && --circ->deliver_window < 0)) {
689 log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
690 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
691 connection_mark_for_close(conn);
692 return -1;
694 log_fn(LOG_DEBUG,"circ deliver_window now %d.", layer_hint ?
695 layer_hint->deliver_window : circ->deliver_window);
697 circuit_consider_sending_sendme(circ, layer_hint);
699 if (!conn) {
700 log_fn(LOG_INFO,"data cell dropped, unknown stream.");
701 return 0;
704 if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
705 log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
706 return -1; /* somebody's breaking protocol. kill the whole circuit. */
709 stats_n_data_bytes_received += rh.length;
710 if (conn->type == CONN_TYPE_AP) {
711 conn->stream_size += rh.length;
712 log_fn(LOG_DEBUG,"%d: stream size now %d.", conn->s, (int)conn->stream_size);
714 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
715 rh.length, conn);
716 connection_edge_consider_sending_sendme(conn);
717 return 0;
718 case RELAY_COMMAND_END:
719 if (!conn) {
720 log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
721 connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length));
722 return 0;
724 /* XXX add to this log_fn the exit node's nickname? */
725 log_fn(LOG_INFO,"%d: end cell (%s) for stream %d. Removing stream. Size %d.",
726 conn->s,
727 connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length),
728 conn->stream_id, (int)conn->stream_size);
730 #ifdef HALF_OPEN
731 conn->done_sending = 1;
732 shutdown(conn->s, 1); /* XXX check return; refactor NM */
733 if (conn->done_receiving) {
734 /* We just *got* an end; no reason to send one. */
735 conn->has_sent_end = 1;
736 connection_mark_for_close(conn);
737 conn->hold_open_until_flushed = 1;
739 #else
740 /* We just *got* an end; no reason to send one. */
741 conn->has_sent_end = 1;
742 if (!conn->marked_for_close) {
743 /* only mark it if not already marked. it's possible to
744 * get the 'end' right around when the client hangs up on us. */
745 connection_mark_for_close(conn);
746 conn->hold_open_until_flushed = 1;
748 #endif
749 return 0;
750 case RELAY_COMMAND_EXTEND:
751 if (conn) {
752 log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
753 return 0;
755 return circuit_extend(cell, circ);
756 case RELAY_COMMAND_EXTENDED:
757 if (!layer_hint) {
758 log_fn(LOG_WARN,"'extended' unsupported at non-origin. Dropping.");
759 return 0;
761 log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
762 if (circuit_finish_handshake(circ, cell->payload+RELAY_HEADER_SIZE) < 0) {
763 log_fn(LOG_WARN,"circuit_finish_handshake failed.");
764 return -1;
766 if (circuit_send_next_onion_skin(circ)<0) {
767 log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
768 return -1;
770 return 0;
771 case RELAY_COMMAND_TRUNCATE:
772 if (layer_hint) {
773 log_fn(LOG_WARN,"'truncate' unsupported at origin. Dropping.");
774 return 0;
776 if (circ->n_conn) {
777 connection_send_destroy(circ->n_circ_id, circ->n_conn);
778 circ->n_conn = NULL;
780 log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
781 connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
782 NULL, 0, NULL);
783 return 0;
784 case RELAY_COMMAND_TRUNCATED:
785 if (!layer_hint) {
786 log_fn(LOG_WARN,"'truncated' unsupported at non-origin. Dropping.");
787 return 0;
789 circuit_truncated(circ, layer_hint);
790 return 0;
791 case RELAY_COMMAND_CONNECTED:
792 if (conn) {
793 log_fn(LOG_WARN,"'connected' unsupported while open. Closing circ.");
794 return -1;
796 log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
797 return 0;
798 case RELAY_COMMAND_SENDME:
799 if (!conn) {
800 if (layer_hint) {
801 layer_hint->package_window += CIRCWINDOW_INCREMENT;
802 log_fn(LOG_DEBUG,"circ-level sendme at origin, packagewindow %d.",
803 layer_hint->package_window);
804 circuit_resume_edge_reading(circ, layer_hint);
805 } else {
806 circ->package_window += CIRCWINDOW_INCREMENT;
807 log_fn(LOG_DEBUG,"circ-level sendme at non-origin, packagewindow %d.",
808 circ->package_window);
809 circuit_resume_edge_reading(circ, layer_hint);
811 return 0;
813 conn->package_window += STREAMWINDOW_INCREMENT;
814 log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
815 connection_start_reading(conn);
816 connection_edge_package_raw_inbuf(conn, 1); /* handle whatever might still be on the inbuf */
817 return 0;
818 case RELAY_COMMAND_RESOLVE:
819 if (layer_hint) {
820 log_fn(LOG_WARN,"resolve request unsupported at AP; dropping.");
821 return 0;
822 } else if (conn) {
823 log_fn(LOG_WARN, "resolve request for known stream; dropping.");
824 return 0;
825 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
826 log_fn(LOG_WARN, "resolve request on circ with purpose %d; dropping",
827 circ->purpose);
828 return 0;
830 connection_exit_begin_resolve(cell, circ);
831 return 0;
832 case RELAY_COMMAND_RESOLVED:
833 if (conn) {
834 log_fn(LOG_WARN,"'resolved' unsupported while open. Closing circ.");
835 return -1;
837 log_fn(LOG_INFO,"'resolved' received, no conn attached anymore. Ignoring.");
838 return 0;
839 case RELAY_COMMAND_ESTABLISH_INTRO:
840 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
841 case RELAY_COMMAND_INTRODUCE1:
842 case RELAY_COMMAND_INTRODUCE2:
843 case RELAY_COMMAND_INTRODUCE_ACK:
844 case RELAY_COMMAND_RENDEZVOUS1:
845 case RELAY_COMMAND_RENDEZVOUS2:
846 case RELAY_COMMAND_INTRO_ESTABLISHED:
847 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
848 rend_process_relay_cell(circ, rh.command, rh.length,
849 cell->payload+RELAY_HEADER_SIZE);
850 return 0;
852 log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
853 return -1;
856 uint64_t stats_n_data_cells_packaged = 0;
857 uint64_t stats_n_data_bytes_packaged = 0;
858 uint64_t stats_n_data_cells_received = 0;
859 uint64_t stats_n_data_bytes_received = 0;
861 /** While conn->inbuf has an entire relay payload of bytes on it,
862 * and the appropriate package windows aren't empty, grab a cell
863 * and send it down the circuit.
865 * Return -1 if conn should be marked for close, else return 0.
867 int connection_edge_package_raw_inbuf(connection_t *conn, int package_partial) {
868 size_t amount_to_process, length;
869 char payload[CELL_PAYLOAD_SIZE];
870 circuit_t *circ;
872 tor_assert(conn);
873 tor_assert(!connection_speaks_cells(conn));
875 repeat_connection_edge_package_raw_inbuf:
877 circ = circuit_get_by_conn(conn);
878 if (!circ) {
879 log_fn(LOG_INFO,"conn has no circuits! Closing.");
880 return -1;
883 if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
884 return 0;
886 if (conn->package_window <= 0) {
887 log_fn(LOG_INFO,"called with package_window %d. Skipping.", conn->package_window);
888 connection_stop_reading(conn);
889 return 0;
892 amount_to_process = buf_datalen(conn->inbuf);
894 if (!amount_to_process)
895 return 0;
897 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
898 return 0;
900 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
901 length = RELAY_PAYLOAD_SIZE;
902 } else {
903 length = amount_to_process;
905 stats_n_data_bytes_packaged += length;
906 stats_n_data_cells_packaged += 1;
908 connection_fetch_from_buf(payload, length, conn);
910 log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s,
911 (int)length, (int)buf_datalen(conn->inbuf));
912 if (conn->type == CONN_TYPE_EXIT) {
913 conn->stream_size += length;
914 log_fn(LOG_DEBUG,"%d: Stream size now %d.", conn->s, (int)conn->stream_size);
917 if (connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
918 payload, length, conn->cpath_layer) < 0)
919 return 0; /* circuit is closed, don't continue */
921 if (!conn->cpath_layer) { /* non-rendezvous exit */
922 tor_assert(circ->package_window > 0);
923 circ->package_window--;
924 } else { /* we're an AP, or an exit on a rendezvous circ */
925 tor_assert(conn->cpath_layer->package_window > 0);
926 conn->cpath_layer->package_window--;
929 if (--conn->package_window <= 0) { /* is it 0 after decrement? */
930 connection_stop_reading(conn);
931 log_fn(LOG_DEBUG,"conn->package_window reached 0.");
932 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
933 return 0; /* don't process the inbuf any more */
935 log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
937 /* handle more if there's more, or return 0 if there isn't */
938 goto repeat_connection_edge_package_raw_inbuf;
941 /** Called when we've just received a relay data cell, or when
942 * we've just finished flushing all bytes to stream <b>conn</b>.
944 * If conn->outbuf is not too full, and our deliver window is
945 * low, send back a suitable number of stream-level sendme cells.
947 void connection_edge_consider_sending_sendme(connection_t *conn) {
948 circuit_t *circ;
950 if (connection_outbuf_too_full(conn))
951 return;
953 circ = circuit_get_by_conn(conn);
954 if (!circ) {
955 /* this can legitimately happen if the destroy has already
956 * arrived and torn down the circuit */
957 log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
958 return;
961 while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
962 log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", (int)conn->outbuf_flushlen);
963 conn->deliver_window += STREAMWINDOW_INCREMENT;
964 if (connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
965 NULL, 0, conn->cpath_layer) < 0) {
966 log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
967 return; /* the circuit's closed, don't continue */
972 /** The circuit <b>circ</b> has received a circuit-level sendme
973 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
974 * attached streams and let them resume reading and packaging, if
975 * their stream windows allow it.
977 static void
978 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
981 log_fn(LOG_DEBUG,"resuming");
983 /* have to check both n_streams and p_streams, to handle rendezvous */
984 if (circuit_resume_edge_reading_helper(circ->n_streams, circ, layer_hint) >= 0)
985 circuit_resume_edge_reading_helper(circ->p_streams, circ, layer_hint);
988 /** A helper function for circuit_resume_edge_reading() above.
989 * The arguments are the same, except that <b>conn</b> is the head
990 * of a linked list of edge streams that should each be considered.
992 static int
993 circuit_resume_edge_reading_helper(connection_t *conn,
994 circuit_t *circ,
995 crypt_path_t *layer_hint) {
997 for ( ; conn; conn=conn->next_stream) {
998 if ((!layer_hint && conn->package_window > 0) ||
999 (layer_hint && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
1000 connection_start_reading(conn);
1001 /* handle whatever might still be on the inbuf */
1002 connection_edge_package_raw_inbuf(conn, 1);
1004 /* If the circuit won't accept any more data, return without looking
1005 * at any more of the streams. Any connections that should be stopped
1006 * have already been stopped by connection_edge_package_raw_inbuf. */
1007 if (circuit_consider_stop_edge_reading(circ, layer_hint))
1008 return -1;
1011 return 0;
1014 /** Check if the package window for <b>circ</b> is empty (at
1015 * hop <b>layer_hint</b> if it's defined).
1017 * If yes, tell edge streams to stop reading and return 1.
1018 * Else return 0.
1020 static int
1021 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1023 connection_t *conn = NULL;
1025 if (!layer_hint) {
1026 log_fn(LOG_DEBUG,"considering circ->package_window %d", circ->package_window);
1027 if (circ->package_window <= 0) {
1028 log_fn(LOG_DEBUG,"yes, not-at-origin. stopped.");
1029 for (conn = circ->n_streams; conn; conn=conn->next_stream)
1030 connection_stop_reading(conn);
1031 return 1;
1033 return 0;
1035 /* else, layer hint is defined, use it */
1036 log_fn(LOG_DEBUG,"considering layer_hint->package_window %d", layer_hint->package_window);
1037 if (layer_hint->package_window <= 0) {
1038 log_fn(LOG_DEBUG,"yes, at-origin. stopped.");
1039 for (conn = circ->n_streams; conn; conn=conn->next_stream)
1040 if (conn->cpath_layer == layer_hint)
1041 connection_stop_reading(conn);
1042 for (conn = circ->p_streams; conn; conn=conn->next_stream)
1043 if (conn->cpath_layer == layer_hint)
1044 connection_stop_reading(conn);
1045 return 1;
1047 return 0;
1050 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1051 * <b>layer_hint</b> if it's defined) is low enough that we should
1052 * send a circuit-level sendme back down the circuit. If so, send
1053 * enough sendmes that the window would be overfull if we sent any
1054 * more.
1056 static void
1057 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1059 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1060 // layer_hint ? "defined" : "null");
1061 while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
1062 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1063 log_fn(LOG_DEBUG,"Queueing circuit sendme.");
1064 if (layer_hint)
1065 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1066 else
1067 circ->deliver_window += CIRCWINDOW_INCREMENT;
1068 if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
1069 NULL, 0, layer_hint) < 0) {
1070 log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
1071 return; /* the circuit's closed, don't continue */