connect() on win32 can do more things than we thought?
[tor.git] / src / or / relay.c
blob4e3534baa1ab07f0a375bd6dc638edead70ca17f
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$ */
7 /**
8 * \file relay.c
9 * \brief Handle relay cell encryption/decryption, plus packaging and
10 * receiving from circuits.
11 **/
13 #include "or.h"
15 static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
16 crypt_path_t **layer_hint, char *recognized);
17 static connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction);
19 static int
20 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
21 connection_t *conn,
22 crypt_path_t *layer_hint);
23 static void
24 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
25 static void
26 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
27 static int
28 circuit_resume_edge_reading_helper(connection_t *conn,
29 circuit_t *circ,
30 crypt_path_t *layer_hint);
31 static int
32 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
34 /** Stats: how many relay cells have originated at this hop, or have
35 * been relayed onward (not recognized at this hop)?
37 unsigned long stats_n_relay_cells_relayed = 0;
38 /** Stats: how many relay cells have been delivered to streams at this
39 * hop?
41 unsigned long stats_n_relay_cells_delivered = 0;
43 /** Update digest from the payload of cell. Assign integrity part to
44 * cell.
46 static void relay_set_digest(crypto_digest_env_t *digest, cell_t *cell) {
47 char integrity[4];
48 relay_header_t rh;
50 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
51 crypto_digest_get_digest(digest, integrity, 4);
52 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
53 // integrity[0], integrity[1], integrity[2], integrity[3]);
54 relay_header_unpack(&rh, cell->payload);
55 memcpy(rh.integrity, integrity, 4);
56 relay_header_pack(cell->payload, &rh);
59 /** Does the digest for this circuit indicate that this cell is for us?
61 * Update digest from the payload of cell (with the integrity part set
62 * to 0). If the integrity part is valid, return 1, else restore digest
63 * and cell to their original state and return 0.
65 static int relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell) {
66 char received_integrity[4], calculated_integrity[4];
67 relay_header_t rh;
68 crypto_digest_env_t *backup_digest=NULL;
70 backup_digest = crypto_digest_dup(digest);
72 relay_header_unpack(&rh, cell->payload);
73 memcpy(received_integrity, rh.integrity, 4);
74 memset(rh.integrity, 0, 4);
75 relay_header_pack(cell->payload, &rh);
77 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
78 // received_integrity[0], received_integrity[1],
79 // received_integrity[2], received_integrity[3]);
81 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
82 crypto_digest_get_digest(digest, calculated_integrity, 4);
84 if(memcmp(received_integrity, calculated_integrity, 4)) {
85 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
86 // (%d vs %d).", received_integrity, calculated_integrity);
87 /* restore digest to its old form */
88 crypto_digest_assign(digest, backup_digest);
89 /* restore the relay header */
90 memcpy(rh.integrity, received_integrity, 4);
91 relay_header_pack(cell->payload, &rh);
92 crypto_free_digest_env(backup_digest);
93 return 0;
95 crypto_free_digest_env(backup_digest);
96 return 1;
99 /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
100 * (in place).
102 * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
104 * Return -1 if the crypto fails, else return 0.
106 static int relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
107 int encrypt_mode) {
108 char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
109 relay_header_t rh;
111 relay_header_unpack(&rh, in);
112 // log_fn(LOG_DEBUG,"before crypt: %d",rh.recognized);
113 if(( encrypt_mode && crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE)) ||
114 (!encrypt_mode && crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE))) {
115 log_fn(LOG_WARN,"Error during relay encryption");
116 return -1;
118 memcpy(in,out,CELL_PAYLOAD_SIZE);
119 relay_header_unpack(&rh, in);
120 // log_fn(LOG_DEBUG,"after crypt: %d",rh.recognized);
121 return 0;
124 /** Receive a relay cell:
125 * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
126 * - Check if recognized (if exitward).
127 * - If recognized and the digest checks out, then find if there's
128 * a conn that the cell is intended for, and deliver it to·
129 * connection_edge.
130 * - Else connection_or_write_cell_to_buf to the conn on the other
131 * side of the circuit.
133 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
134 int cell_direction) {
135 connection_t *conn=NULL;
136 crypt_path_t *layer_hint=NULL;
137 char recognized=0;
139 tor_assert(cell);
140 tor_assert(circ);
141 tor_assert(cell_direction == CELL_DIRECTION_OUT ||
142 cell_direction == CELL_DIRECTION_IN);
143 if (circ->marked_for_close)
144 return 0;
146 if(relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
147 log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
148 return -1;
151 if(recognized) {
152 conn = relay_lookup_conn(circ, cell, cell_direction);
153 if(cell_direction == CELL_DIRECTION_OUT) {
154 ++stats_n_relay_cells_delivered;
155 log_fn(LOG_DEBUG,"Sending away from origin.");
156 if (connection_edge_process_relay_cell(cell, circ, conn, NULL) < 0) {
157 log_fn(LOG_WARN,"connection_edge_process_relay_cell (away from origin) failed.");
158 return -1;
161 if(cell_direction == CELL_DIRECTION_IN) {
162 ++stats_n_relay_cells_delivered;
163 log_fn(LOG_DEBUG,"Sending to origin.");
164 if (connection_edge_process_relay_cell(cell, circ, conn, layer_hint) < 0) {
165 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at origin) failed.");
166 return -1;
169 return 0;
172 /* not recognized. pass it on. */
173 if(cell_direction == CELL_DIRECTION_OUT) {
174 cell->circ_id = circ->n_circ_id; /* switch it */
175 conn = circ->n_conn;
176 } else {
177 cell->circ_id = circ->p_circ_id; /* switch it */
178 conn = circ->p_conn;
181 if(!conn) {
182 if (circ->rend_splice && cell_direction == CELL_DIRECTION_OUT) {
183 tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
184 tor_assert(circ->rend_splice->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
185 cell->circ_id = circ->rend_splice->p_circ_id;
186 if (circuit_receive_relay_cell(cell, circ->rend_splice, CELL_DIRECTION_IN)<0) {
187 log_fn(LOG_WARN, "Error relaying cell across rendezvous; closing circuits");
188 circuit_mark_for_close(circ); /* XXXX Do this here, or just return -1? */
189 return -1;
191 return 0;
193 log_fn(LOG_WARN,"Didn't recognize cell, but circ stops here! Closing circ.");
194 return -1;
197 log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
198 ++stats_n_relay_cells_relayed;
199 connection_or_write_cell_to_buf(cell, conn);
200 return 0;
203 /** Do the appropriate en/decryptions for <b>cell</b> arriving on
204 * <b>circ</b> in direction <b>cell_direction</b>.
206 * If cell_direction == CELL_DIRECTION_IN:
207 * - If we're at the origin (we're the OP), for hops 1..N,
208 * decrypt cell. If recognized, stop.
209 * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
211 * If cell_direction == CELL_DIRECTION_OUT:
212 * - decrypt one hop. Check if recognized.
214 * If cell is recognized, set *recognized to 1, and set
215 * *layer_hint to the hop that recognized it.
217 * Return -1 to indicate that we should mark the circuit for close,
218 * else return 0.
220 /* wrap this into receive_relay_cell one day */
221 static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
222 crypt_path_t **layer_hint, char *recognized) {
223 crypt_path_t *thishop;
224 relay_header_t rh;
226 tor_assert(circ);
227 tor_assert(cell);
228 tor_assert(recognized);
229 tor_assert(cell_direction == CELL_DIRECTION_IN ||
230 cell_direction == CELL_DIRECTION_OUT);
232 if(cell_direction == CELL_DIRECTION_IN) {
233 if(CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
234 We'll want to do layered decrypts. */
235 tor_assert(circ->cpath);
236 thishop = circ->cpath;
237 if(thishop->state != CPATH_STATE_OPEN) {
238 log_fn(LOG_WARN,"Relay cell before first created cell? Closing.");
239 return -1;
241 do { /* Remember: cpath is in forward order, that is, first hop first. */
242 tor_assert(thishop);
244 if(relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
245 return -1;
247 relay_header_unpack(&rh, cell->payload);
248 if(rh.recognized == 0) {
249 /* it's possibly recognized. have to check digest to be sure. */
250 if(relay_digest_matches(thishop->b_digest, cell)) {
251 *recognized = 1;
252 *layer_hint = thishop;
253 return 0;
257 thishop = thishop->next;
258 } while(thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
259 log_fn(LOG_WARN,"in-cell at OP not recognized. Closing.");
260 return -1;
261 } else { /* we're in the middle. Just one crypt. */
262 if(relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
263 return -1;
264 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
266 } else /* cell_direction == CELL_DIRECTION_OUT */ {
267 /* we're in the middle. Just one crypt. */
269 if(relay_crypt_one_payload(circ->n_crypto, cell->payload, 0) < 0)
270 return -1;
272 relay_header_unpack(&rh, cell->payload);
273 if (rh.recognized == 0) {
274 /* it's possibly recognized. have to check digest to be sure. */
275 if(relay_digest_matches(circ->n_digest, cell)) {
276 *recognized = 1;
277 return 0;
281 return 0;
284 /** Package a relay cell:
285 * - Encrypt it to the right layer
286 * - connection_or_write_cell_to_buf to the right conn
288 static int
289 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
290 int cell_direction,
291 crypt_path_t *layer_hint)
293 connection_t *conn; /* where to send the cell */
294 crypt_path_t *thishop; /* counter for repeated crypts */
296 if(cell_direction == CELL_DIRECTION_OUT) {
297 conn = circ->n_conn;
298 if(!conn) {
299 log_fn(LOG_WARN,"outgoing relay cell has n_conn==NULL. Dropping.");
300 return 0; /* just drop it */
302 relay_set_digest(layer_hint->f_digest, cell);
304 thishop = layer_hint;
305 /* moving from farthest to nearest hop */
306 do {
307 tor_assert(thishop);
309 log_fn(LOG_DEBUG,"crypting a layer of the relay cell.");
310 if(relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
311 return -1;
314 thishop = thishop->prev;
315 } while (thishop != circ->cpath->prev);
317 } else { /* incoming cell */
318 conn = circ->p_conn;
319 if(!conn) {
320 log_fn(LOG_WARN,"incoming relay cell has p_conn==NULL. Dropping.");
321 return 0; /* just drop it */
323 relay_set_digest(circ->p_digest, cell);
324 if(relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
325 return -1;
327 ++stats_n_relay_cells_relayed;
328 connection_or_write_cell_to_buf(cell, conn);
329 return 0;
332 /** If cell's stream_id matches the stream_id of any conn that's
333 * attached to circ, return that conn, else return NULL.
335 static connection_t *
336 relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
338 connection_t *tmpconn;
339 relay_header_t rh;
341 relay_header_unpack(&rh, cell->payload);
343 if(!rh.stream_id)
344 return NULL;
346 /* IN or OUT cells could have come from either direction, now
347 * that we allow rendezvous *to* an OP.
350 for(tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
351 if(rh.stream_id == tmpconn->stream_id) {
352 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
353 if(cell_direction == CELL_DIRECTION_OUT ||
354 connection_edge_is_rendezvous_stream(tmpconn))
355 return tmpconn;
358 for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
359 if(rh.stream_id == tmpconn->stream_id) {
360 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
361 return tmpconn;
364 for(tmpconn = circ->resolving_streams; tmpconn; tmpconn=tmpconn->next_stream) {
365 if(rh.stream_id == tmpconn->stream_id) {
366 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
367 return tmpconn;
370 return NULL; /* probably a begin relay cell */
373 /** Pack the relay_header_t host-order structure <b>src</b> into
374 * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
375 * about the wire format.
377 void relay_header_pack(char *dest, const relay_header_t *src) {
378 *(uint8_t*)(dest) = src->command;
380 set_uint16(dest+1, htons(src->recognized));
381 set_uint16(dest+3, htons(src->stream_id));
382 memcpy(dest+5, src->integrity, 4);
383 set_uint16(dest+9, htons(src->length));
386 /** Unpack the network-order buffer <b>src</b> into a host-order
387 * relay_header_t structure <b>dest</b>.
389 void relay_header_unpack(relay_header_t *dest, const char *src) {
390 dest->command = *(uint8_t*)(src);
392 dest->recognized = ntohs(get_uint16(src+1));
393 dest->stream_id = ntohs(get_uint16(src+3));
394 memcpy(dest->integrity, src+5, 4);
395 dest->length = ntohs(get_uint16(src+9));
398 /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
399 * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
400 * that's sending the relay cell, or NULL if it's a control cell.
401 * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
402 * for OP->OR cells.
404 * If you can't send the cell, mark the circuit for close and
405 * return -1. Else return 0.
407 int connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
408 int relay_command, const char *payload,
409 size_t payload_len, crypt_path_t *cpath_layer) {
410 cell_t cell;
411 relay_header_t rh;
412 int cell_direction;
414 if(!circ) {
415 log_fn(LOG_WARN,"no circ. Closing conn.");
416 tor_assert(fromconn);
417 fromconn->has_sent_end = 1; /* no circ to send to */
418 connection_mark_for_close(fromconn);
419 return -1;
422 memset(&cell, 0, sizeof(cell_t));
423 cell.command = CELL_RELAY;
424 if(cpath_layer) {
425 cell.circ_id = circ->n_circ_id;
426 cell_direction = CELL_DIRECTION_OUT;
427 } else {
428 cell.circ_id = circ->p_circ_id;
429 cell_direction = CELL_DIRECTION_IN;
432 memset(&rh, 0, sizeof(rh));
433 rh.command = relay_command;
434 if(fromconn)
435 rh.stream_id = fromconn->stream_id; /* else it's 0 */
436 rh.length = payload_len;
437 relay_header_pack(cell.payload, &rh);
438 if(payload_len)
439 memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
441 log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
442 cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
444 if(circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
445 log_fn(LOG_WARN,"circuit_package_relay_cell failed. Closing.");
446 circuit_mark_for_close(circ);
447 return -1;
449 return 0;
452 /** Translate the <b>payload</b> of length <b>length</b>, which
453 * came from a relay 'end' cell, into a static const string describing
454 * why the stream is closing.
456 static const char *
457 connection_edge_end_reason(char *payload, uint16_t length) {
458 if(length < 1) {
459 log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
460 return "MALFORMED";
462 if(*payload < _MIN_END_STREAM_REASON || *payload > _MAX_END_STREAM_REASON) {
463 log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",*payload);
464 return "MALFORMED";
466 switch(*payload) {
467 case END_STREAM_REASON_MISC: return "misc error";
468 case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
469 case END_STREAM_REASON_CONNECTFAILED: return "connect failed";
470 case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
471 case END_STREAM_REASON_DESTROY: return "destroyed";
472 case END_STREAM_REASON_DONE: return "closed normally";
473 case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
475 tor_assert(0);
476 return "";
479 /** How many times will I retry a stream that fails due to DNS
480 * resolve failure?
482 #define MAX_RESOLVE_FAILURES 3
484 /** An incoming relay cell has arrived from circuit <b>circ</b> to
485 * stream <b>conn</b>.
487 * The arguments here are the same as in
488 * connection_edge_process_relay_cell() below; this function is called
489 * from there when <b>conn</b> is defined and not in an open state.
491 static int
492 connection_edge_process_relay_cell_not_open(
493 relay_header_t *rh, cell_t *cell, circuit_t *circ,
494 connection_t *conn, crypt_path_t *layer_hint) {
495 uint32_t addr;
496 int reason;
497 routerinfo_t *exitrouter;
499 if(rh->command == RELAY_COMMAND_END) {
500 reason = *(cell->payload+RELAY_HEADER_SIZE);
501 /* We have to check this here, since we aren't connected yet. */
502 if (rh->length >= 5 && reason == END_STREAM_REASON_EXITPOLICY) {
503 if(conn->type != CONN_TYPE_AP) {
504 log_fn(LOG_WARN,"Got an end because of exitpolicy, but we're not an AP. Closing.");
505 return -1;
507 addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
508 if(addr) {
509 log_fn(LOG_INFO,"Address %s refused due to exit policy. Retrying.",
510 conn->socks_request->address);
511 } else {
512 log_fn(LOG_INFO,"Address %s resolved to 0.0.0.0. Closing,",
513 conn->socks_request->address);
514 conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
515 connection_mark_for_close(conn);
516 return 0;
518 client_dns_set_entry(conn->socks_request->address, addr);
520 /* check if he *ought* to have allowed it */
521 exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
522 if(!exitrouter) {
523 log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
524 return 0; /* this circuit is screwed and doesn't know it yet */
526 if(connection_ap_can_use_exit(conn, exitrouter)) {
527 log_fn(LOG_WARN,"Exitrouter %s seems to be more restrictive than its exit policy. Not using this router as exit for now,", exitrouter->nickname);
528 addr_policy_free(exitrouter->exit_policy);
529 exitrouter->exit_policy =
530 router_parse_addr_policy_from_string("reject *:*");
533 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
534 circuit_detach_stream(circ,conn);
535 if(connection_ap_handshake_attach_circuit(conn) >= 0)
536 return 0;
537 log_fn(LOG_INFO,"Giving up on retrying (from exitpolicy); conn can't be handled.");
538 /* else, conn will get closed below */
539 } else if (rh->length && reason == END_STREAM_REASON_RESOLVEFAILED) {
540 if (client_dns_incr_failures(conn->socks_request->address)
541 < MAX_RESOLVE_FAILURES) {
542 /* We haven't retried too many times; reattach the connection. */
543 log_fn(LOG_INFO,"Resolve of '%s' failed, trying again.",
544 conn->socks_request->address);
545 circuit_log_path(LOG_INFO,circ);
546 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
547 circuit_detach_stream(circ,conn);
548 tor_assert(circ->timestamp_dirty);
549 circ->timestamp_dirty -= get_options()->NewCircuitPeriod;
550 /* make sure not to expire/retry the stream quite yet */
551 conn->timestamp_lastread = time(NULL);
552 if(connection_ap_handshake_attach_circuit(conn) >= 0)
553 return 0;
554 /* else, conn will get closed below */
555 log_fn(LOG_INFO,"Giving up on retrying (from resolvefailed); conn can't be handled.");
556 } else {
557 log_fn(LOG_WARN,"Have tried resolving address %s at %d different places. Giving up.",
558 conn->socks_request->address, MAX_RESOLVE_FAILURES);
561 log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
562 connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh->length));
563 if(CIRCUIT_IS_ORIGIN(circ))
564 circuit_log_path(LOG_INFO,circ);
565 conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
566 connection_mark_for_close(conn);
567 return 0;
570 if(conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
571 if(conn->state != AP_CONN_STATE_CONNECT_WAIT) {
572 log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
573 return 0;
575 // log_fn(LOG_INFO,"Connected! Notifying application.");
576 conn->state = AP_CONN_STATE_OPEN;
577 log_fn(LOG_INFO,"'connected' received after %d seconds.",
578 (int)(time(NULL) - conn->timestamp_lastread));
579 if (rh->length >= 4) {
580 addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
581 if(!addr) {
582 log_fn(LOG_INFO,"...but it claims the IP address was 0.0.0.0. Closing.");
583 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
584 connection_mark_for_close(conn);
585 return 0;
587 client_dns_set_entry(conn->socks_request->address, addr);
589 circuit_log_path(LOG_INFO,circ);
590 connection_ap_handshake_socks_reply(conn, NULL, 0, 1);
591 conn->socks_request->has_finished = 1;
592 /* handle anything that might have queued */
593 if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
594 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
595 connection_mark_for_close(conn);
596 return 0;
598 return 0;
600 if(conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_RESOLVED) {
601 if (conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
602 log_fn(LOG_WARN,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
603 return 0;
605 tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
606 if (rh->length < 2 || cell->payload[RELAY_HEADER_SIZE+1]+2>rh->length) {
607 log_fn(LOG_WARN, "Dropping malformed 'resolved' cell");
608 conn->has_sent_end = 1;
609 connection_mark_for_close(conn);
610 return 0;
612 connection_ap_handshake_socks_resolved(conn,
613 cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
614 cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
615 cell->payload+RELAY_HEADER_SIZE+2); /* answer */
616 conn->has_sent_end = 1;
617 connection_mark_for_close(conn);
618 conn->hold_open_until_flushed = 1;
619 return 0;
622 log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
623 rh->command, conn->state, conn_state_to_string[conn->type][conn->state]);
624 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
625 connection_mark_for_close(conn);
626 return -1;
629 /** An incoming relay cell has arrived on circuit <b>circ</b>. If
630 * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
631 * destined for <b>conn</b>.
633 * If <b>layer_hint</b> is defined, then we're the origin of the
634 * circuit, and it specifies the hop that packaged <b>cell</b>.
636 * Return -1 if you want to tear down the circuit, else 0.
638 static int
639 connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
640 connection_t *conn,
641 crypt_path_t *layer_hint)
643 static int num_seen=0;
644 relay_header_t rh;
646 tor_assert(cell);
647 tor_assert(circ);
649 relay_header_unpack(&rh, cell->payload);
650 // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
651 num_seen++;
652 log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
654 /* either conn is NULL, in which case we've got a control cell, or else
655 * conn points to the recognized stream. */
657 if(conn &&
658 conn->state != AP_CONN_STATE_OPEN &&
659 conn->state != EXIT_CONN_STATE_OPEN) {
660 return connection_edge_process_relay_cell_not_open(
661 &rh, cell, circ, conn, layer_hint);
664 switch(rh.command) {
665 case RELAY_COMMAND_DROP:
666 log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
667 return 0;
668 case RELAY_COMMAND_BEGIN:
669 if (layer_hint &&
670 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
671 log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
672 return 0;
674 if(conn) {
675 log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
676 return 0;
678 connection_exit_begin_conn(cell, circ);
679 return 0;
680 case RELAY_COMMAND_DATA:
681 ++stats_n_data_cells_received;
682 if((layer_hint && --layer_hint->deliver_window < 0) ||
683 (!layer_hint && --circ->deliver_window < 0)) {
684 log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
685 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
686 connection_mark_for_close(conn);
687 return -1;
689 log_fn(LOG_DEBUG,"circ deliver_window now %d.", layer_hint ?
690 layer_hint->deliver_window : circ->deliver_window);
692 circuit_consider_sending_sendme(circ, layer_hint);
694 if(!conn) {
695 log_fn(LOG_INFO,"data cell dropped, unknown stream.");
696 return 0;
699 if(--conn->deliver_window < 0) { /* is it below 0 after decrement? */
700 log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
701 return -1; /* somebody's breaking protocol. kill the whole circuit. */
704 stats_n_data_bytes_received += rh.length;
705 if(conn->type == CONN_TYPE_AP) {
706 log_fn(LOG_DEBUG,"%d: stream size now %d.", conn->s, (int)conn->stream_size);
707 conn->stream_size += rh.length;
709 connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
710 rh.length, conn);
711 connection_edge_consider_sending_sendme(conn);
712 return 0;
713 case RELAY_COMMAND_END:
714 if(!conn) {
715 log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
716 connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length));
717 return 0;
719 /* XXX add to this log_fn the exit node's nickname? */
720 log_fn(LOG_INFO,"%d: end cell (%s) for stream %d. Removing stream. Size %d.",
721 conn->s,
722 connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length),
723 conn->stream_id, (int)conn->stream_size);
725 #ifdef HALF_OPEN
726 conn->done_sending = 1;
727 shutdown(conn->s, 1); /* XXX check return; refactor NM */
728 if (conn->done_receiving) {
729 /* We just *got* an end; no reason to send one. */
730 conn->has_sent_end = 1;
731 connection_mark_for_close(conn);
732 conn->hold_open_until_flushed = 1;
734 #else
735 /* We just *got* an end; no reason to send one. */
736 conn->has_sent_end = 1;
737 if(!conn->marked_for_close) {
738 /* only mark it if not already marked. it's possible to
739 * get the 'end' right around when the client hangs up on us. */
740 connection_mark_for_close(conn);
742 conn->hold_open_until_flushed = 1;
743 #endif
744 return 0;
745 case RELAY_COMMAND_EXTEND:
746 if(conn) {
747 log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
748 return 0;
750 return circuit_extend(cell, circ);
751 case RELAY_COMMAND_EXTENDED:
752 if(!layer_hint) {
753 log_fn(LOG_WARN,"'extended' unsupported at non-origin. Dropping.");
754 return 0;
756 log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
757 if(circuit_finish_handshake(circ, cell->payload+RELAY_HEADER_SIZE) < 0) {
758 log_fn(LOG_WARN,"circuit_finish_handshake failed.");
759 return -1;
761 if (circuit_send_next_onion_skin(circ)<0) {
762 log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
763 return -1;
765 return 0;
766 case RELAY_COMMAND_TRUNCATE:
767 if(layer_hint) {
768 log_fn(LOG_WARN,"'truncate' unsupported at origin. Dropping.");
769 return 0;
771 if(circ->n_conn) {
772 connection_send_destroy(circ->n_circ_id, circ->n_conn);
773 circ->n_conn = NULL;
775 log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
776 connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
777 NULL, 0, NULL);
778 return 0;
779 case RELAY_COMMAND_TRUNCATED:
780 if(!layer_hint) {
781 log_fn(LOG_WARN,"'truncated' unsupported at non-origin. Dropping.");
782 return 0;
784 circuit_truncated(circ, layer_hint);
785 return 0;
786 case RELAY_COMMAND_CONNECTED:
787 if(conn) {
788 log_fn(LOG_WARN,"'connected' unsupported while open. Closing circ.");
789 return -1;
791 log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
792 return 0;
793 case RELAY_COMMAND_SENDME:
794 if(!conn) {
795 if(layer_hint) {
796 layer_hint->package_window += CIRCWINDOW_INCREMENT;
797 log_fn(LOG_DEBUG,"circ-level sendme at origin, packagewindow %d.",
798 layer_hint->package_window);
799 circuit_resume_edge_reading(circ, layer_hint);
800 } else {
801 circ->package_window += CIRCWINDOW_INCREMENT;
802 log_fn(LOG_DEBUG,"circ-level sendme at non-origin, packagewindow %d.",
803 circ->package_window);
804 circuit_resume_edge_reading(circ, layer_hint);
806 return 0;
808 conn->package_window += STREAMWINDOW_INCREMENT;
809 log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
810 connection_start_reading(conn);
811 connection_edge_package_raw_inbuf(conn, 1); /* handle whatever might still be on the inbuf */
812 return 0;
813 case RELAY_COMMAND_RESOLVE:
814 if (layer_hint) {
815 log_fn(LOG_WARN,"resolve request unsupported at AP; dropping.");
816 return 0;
817 } else if (conn) {
818 log_fn(LOG_WARN, "resolve request for known stream; dropping.");
819 return 0;
820 } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
821 log_fn(LOG_WARN, "resolve request on circ with purpose %d; dropping",
822 circ->purpose);
823 return 0;
825 connection_exit_begin_resolve(cell, circ);
826 return 0;
827 case RELAY_COMMAND_RESOLVED:
828 if(conn) {
829 log_fn(LOG_WARN,"'resolved' unsupported while open. Closing circ.");
830 return -1;
832 log_fn(LOG_INFO,"'resolved' received, no conn attached anymore. Ignoring.");
833 return 0;
834 case RELAY_COMMAND_ESTABLISH_INTRO:
835 case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
836 case RELAY_COMMAND_INTRODUCE1:
837 case RELAY_COMMAND_INTRODUCE2:
838 case RELAY_COMMAND_INTRODUCE_ACK:
839 case RELAY_COMMAND_RENDEZVOUS1:
840 case RELAY_COMMAND_RENDEZVOUS2:
841 case RELAY_COMMAND_INTRO_ESTABLISHED:
842 case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
843 rend_process_relay_cell(circ, rh.command, rh.length,
844 cell->payload+RELAY_HEADER_SIZE);
845 return 0;
847 log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
848 return -1;
851 uint64_t stats_n_data_cells_packaged = 0;
852 uint64_t stats_n_data_bytes_packaged = 0;
853 uint64_t stats_n_data_cells_received = 0;
854 uint64_t stats_n_data_bytes_received = 0;
856 /** While conn->inbuf has an entire relay payload of bytes on it,
857 * and the appropriate package windows aren't empty, grab a cell
858 * and send it down the circuit.
860 * Return -1 if conn should be marked for close, else return 0.
862 int connection_edge_package_raw_inbuf(connection_t *conn, int package_partial) {
863 size_t amount_to_process, length;
864 char payload[CELL_PAYLOAD_SIZE];
865 circuit_t *circ;
867 tor_assert(conn);
868 tor_assert(!connection_speaks_cells(conn));
870 repeat_connection_edge_package_raw_inbuf:
872 circ = circuit_get_by_conn(conn);
873 if(!circ) {
874 log_fn(LOG_INFO,"conn has no circuits! Closing.");
875 return -1;
878 if(circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
879 return 0;
881 if(conn->package_window <= 0) {
882 log_fn(LOG_INFO,"called with package_window %d. Skipping.", conn->package_window);
883 connection_stop_reading(conn);
884 return 0;
887 amount_to_process = buf_datalen(conn->inbuf);
889 if (!amount_to_process)
890 return 0;
892 if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
893 return 0;
895 if (amount_to_process > RELAY_PAYLOAD_SIZE) {
896 length = RELAY_PAYLOAD_SIZE;
897 } else {
898 length = amount_to_process;
900 stats_n_data_bytes_packaged += length;
901 stats_n_data_cells_packaged += 1;
903 connection_fetch_from_buf(payload, length, conn);
905 log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s,
906 (int)length, (int)buf_datalen(conn->inbuf));
907 if (conn->type == CONN_TYPE_EXIT) {
908 conn->stream_size += length;
909 log_fn(LOG_DEBUG,"%d: Stream size now %d.", conn->s, (int)conn->stream_size);
912 if(connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
913 payload, length, conn->cpath_layer) < 0)
914 return 0; /* circuit is closed, don't continue */
916 if(!conn->cpath_layer) { /* non-rendezvous exit */
917 tor_assert(circ->package_window > 0);
918 circ->package_window--;
919 } else { /* we're an AP, or an exit on a rendezvous circ */
920 tor_assert(conn->cpath_layer->package_window > 0);
921 conn->cpath_layer->package_window--;
924 if(--conn->package_window <= 0) { /* is it 0 after decrement? */
925 connection_stop_reading(conn);
926 log_fn(LOG_DEBUG,"conn->package_window reached 0.");
927 circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
928 return 0; /* don't process the inbuf any more */
930 log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
932 /* handle more if there's more, or return 0 if there isn't */
933 goto repeat_connection_edge_package_raw_inbuf;
936 /** Called when we've just received a relay data cell, or when
937 * we've just finished flushing all bytes to stream <b>conn</b>.
939 * If conn->outbuf is not too full, and our deliver window is
940 * low, send back a suitable number of stream-level sendme cells.
942 void connection_edge_consider_sending_sendme(connection_t *conn) {
943 circuit_t *circ;
945 if(connection_outbuf_too_full(conn))
946 return;
948 circ = circuit_get_by_conn(conn);
949 if(!circ) {
950 /* this can legitimately happen if the destroy has already
951 * arrived and torn down the circuit */
952 log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
953 return;
956 while(conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
957 log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", (int)conn->outbuf_flushlen);
958 conn->deliver_window += STREAMWINDOW_INCREMENT;
959 if(connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
960 NULL, 0, conn->cpath_layer) < 0) {
961 log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
962 return; /* the circuit's closed, don't continue */
967 /** The circuit <b>circ</b> has received a circuit-level sendme
968 * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
969 * attached streams and let them resume reading and packaging, if
970 * their stream windows allow it.
972 static void
973 circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
976 log_fn(LOG_DEBUG,"resuming");
978 /* have to check both n_streams and p_streams, to handle rendezvous */
979 if(circuit_resume_edge_reading_helper(circ->n_streams, circ, layer_hint) >= 0)
980 circuit_resume_edge_reading_helper(circ->p_streams, circ, layer_hint);
983 /** A helper function for circuit_resume_edge_reading() above.
984 * The arguments are the same, except that <b>conn</b> is the head
985 * of a linked list of edge streams that should each be considered.
987 static int
988 circuit_resume_edge_reading_helper(connection_t *conn,
989 circuit_t *circ,
990 crypt_path_t *layer_hint) {
992 for( ; conn; conn=conn->next_stream) {
993 if((!layer_hint && conn->package_window > 0) ||
994 (layer_hint && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
995 connection_start_reading(conn);
996 /* handle whatever might still be on the inbuf */
997 connection_edge_package_raw_inbuf(conn, 1);
999 /* If the circuit won't accept any more data, return without looking
1000 * at any more of the streams. Any connections that should be stopped
1001 * have already been stopped by connection_edge_package_raw_inbuf. */
1002 if(circuit_consider_stop_edge_reading(circ, layer_hint))
1003 return -1;
1006 return 0;
1009 /** Check if the package window for <b>circ</b> is empty (at
1010 * hop <b>layer_hint</b> if it's defined).
1012 * If yes, tell edge streams to stop reading and return 1.
1013 * Else return 0.
1015 static int
1016 circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
1018 connection_t *conn = NULL;
1020 if (!layer_hint) {
1021 log_fn(LOG_DEBUG,"considering circ->package_window %d", circ->package_window);
1022 if (circ->package_window <= 0) {
1023 log_fn(LOG_DEBUG,"yes, not-at-origin. stopped.");
1024 for(conn = circ->n_streams; conn; conn=conn->next_stream)
1025 connection_stop_reading(conn);
1026 return 1;
1028 return 0;
1030 /* else, layer hint is defined, use it */
1031 log_fn(LOG_DEBUG,"considering layer_hint->package_window %d", layer_hint->package_window);
1032 if (layer_hint->package_window <= 0) {
1033 log_fn(LOG_DEBUG,"yes, at-origin. stopped.");
1034 for(conn = circ->n_streams; conn; conn=conn->next_stream)
1035 if(conn->cpath_layer == layer_hint)
1036 connection_stop_reading(conn);
1037 for(conn = circ->p_streams; conn; conn=conn->next_stream)
1038 if(conn->cpath_layer == layer_hint)
1039 connection_stop_reading(conn);
1040 return 1;
1042 return 0;
1045 /** Check if the deliver_window for circuit <b>circ</b> (at hop
1046 * <b>layer_hint</b> if it's defined) is low enough that we should
1047 * send a circuit-level sendme back down the circuit. If so, send
1048 * enough sendmes that the window would be overfull if we sent any
1049 * more.
1051 static void
1052 circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
1054 // log_fn(LOG_INFO,"Considering: layer_hint is %s",
1055 // layer_hint ? "defined" : "null");
1056 while((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
1057 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
1058 log_fn(LOG_DEBUG,"Queueing circuit sendme.");
1059 if(layer_hint)
1060 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
1061 else
1062 circ->deliver_window += CIRCWINDOW_INCREMENT;
1063 if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
1064 NULL, 0, layer_hint) < 0) {
1065 log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
1066 return; /* the circuit's closed, don't continue */