1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char connection_edge_c_id
[] = "$Id$";
9 * \file connection_edge.c
10 * \brief Handle edge streams.
16 static addr_policy_t
*socks_policy
= NULL
;
17 /* List of exit_redirect_t */
18 static smartlist_t
*redirect_exit_list
= NULL
;
20 static int connection_ap_handshake_process_socks(connection_t
*conn
);
22 /** There was an EOF. Send an end and mark the connection for close.
24 int connection_edge_reached_eof(connection_t
*conn
) {
26 /* eof reached; we're done reading, but we might want to write more. */
27 conn
->done_receiving
= 1;
28 shutdown(conn
->s
, 0); /* XXX check return, refactor NM */
29 if (conn
->done_sending
) {
30 connection_edge_end(conn
, END_STREAM_REASON_DONE
, conn
->cpath_layer
);
31 connection_mark_for_close(conn
);
33 connection_edge_send_command(conn
, circuit_get_by_conn(conn
), RELAY_COMMAND_END
,
34 NULL
, 0, conn
->cpath_layer
);
38 if (buf_datalen(conn
->inbuf
) && connection_state_is_open(conn
)) {
39 /* it still has stuff to process. don't let it die yet. */
42 log_fn(LOG_INFO
,"conn (fd %d) reached eof (stream size %d). Closing.", conn
->s
, (int)conn
->stream_size
);
43 if (!conn
->marked_for_close
) {
44 /* only mark it if not already marked. it's possible to
45 * get the 'end' right around when the client hangs up on us. */
46 connection_edge_end(conn
, END_STREAM_REASON_DONE
, conn
->cpath_layer
);
47 connection_mark_for_close(conn
);
48 // conn->hold_open_until_flushed = 1; /* just because we shouldn't read
49 // doesn't mean we shouldn't write */
55 /** Handle new bytes on conn->inbuf based on state:
56 * - If it's waiting for socks info, try to read another step of the
57 * socks handshake out of conn->inbuf.
58 * - If it's open, then package more relay cells from the stream.
59 * - Else, leave the bytes on inbuf alone for now.
61 * Mark and return -1 if there was an unexpected error with the conn,
64 int connection_edge_process_inbuf(connection_t
*conn
, int package_partial
) {
67 tor_assert(conn
->type
== CONN_TYPE_AP
|| conn
->type
== CONN_TYPE_EXIT
);
69 switch (conn
->state
) {
70 case AP_CONN_STATE_SOCKS_WAIT
:
71 if (connection_ap_handshake_process_socks(conn
) < 0) {
72 conn
->has_sent_end
= 1; /* no circ yet */
73 connection_mark_for_close(conn
);
74 conn
->hold_open_until_flushed
= 1; /* redundant but shouldn't hurt */
78 case AP_CONN_STATE_OPEN
:
79 case EXIT_CONN_STATE_OPEN
:
80 if (connection_edge_package_raw_inbuf(conn
, package_partial
) < 0) {
81 connection_edge_end(conn
, END_STREAM_REASON_MISC
, conn
->cpath_layer
);
82 connection_mark_for_close(conn
);
86 case EXIT_CONN_STATE_CONNECTING
:
87 case AP_CONN_STATE_RENDDESC_WAIT
:
88 case AP_CONN_STATE_CIRCUIT_WAIT
:
89 case AP_CONN_STATE_CONNECT_WAIT
:
90 case AP_CONN_STATE_RESOLVE_WAIT
:
91 log_fn(LOG_INFO
,"data from edge while in '%s' state. Leaving it on buffer.",
92 conn_state_to_string
[conn
->type
][conn
->state
]);
95 log_fn(LOG_WARN
,"Bug: Got unexpected state %d. Closing.",conn
->state
);
99 connection_edge_end(conn
, END_STREAM_REASON_MISC
, conn
->cpath_layer
);
100 connection_mark_for_close(conn
);
104 /** This edge needs to be closed, because its circuit has closed.
105 * Mark it for close and return 0.
107 int connection_edge_destroy(uint16_t circ_id
, connection_t
*conn
) {
108 tor_assert(conn
->type
== CONN_TYPE_AP
|| conn
->type
== CONN_TYPE_EXIT
);
110 if (conn
->marked_for_close
)
111 return 0; /* already marked; probably got an 'end' */
112 log_fn(LOG_INFO
,"CircID %d: At an edge. Marking connection for close.",
114 conn
->has_sent_end
= 1; /* we're closing the circuit, nothing to send to */
115 connection_mark_for_close(conn
);
116 conn
->hold_open_until_flushed
= 1;
120 /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
121 * with a destination of cpath_layer. (If cpath_layer is NULL, the
122 * destination is the circuit's origin.) Mark the relay end cell as
123 * closing because of <b>reason</b>.
125 * Return -1 if this function has already been called on this conn,
129 connection_edge_end(connection_t
*conn
, char reason
, crypt_path_t
*cpath_layer
)
132 size_t payload_len
=1;
135 if (conn
->has_sent_end
) {
136 log_fn(LOG_WARN
,"Bug: Calling connection_edge_end on an already ended stream?");
144 if (reason
== END_STREAM_REASON_EXITPOLICY
) {
145 /* this is safe even for rend circs, because they never fail
146 * because of exitpolicy */
147 set_uint32(payload
+1, htonl(conn
->addr
));
151 circ
= circuit_get_by_conn(conn
);
152 if (circ
&& !circ
->marked_for_close
) {
153 log_fn(LOG_DEBUG
,"Marking conn (fd %d) and sending end.",conn
->s
);
154 connection_edge_send_command(conn
, circ
, RELAY_COMMAND_END
,
155 payload
, payload_len
, cpath_layer
);
157 log_fn(LOG_DEBUG
,"Marking conn (fd %d); no circ to send end.",conn
->s
);
160 conn
->has_sent_end
= 1;
164 /** Connection <b>conn</b> has finished writing and has no bytes left on
167 * If it's in state 'open', stop writing, consider responding with a
168 * sendme, and return.
169 * Otherwise, stop writing and return.
171 * If <b>conn</b> is broken, mark it for close and return -1, else
174 int connection_edge_finished_flushing(connection_t
*conn
) {
176 tor_assert(conn
->type
== CONN_TYPE_AP
|| conn
->type
== CONN_TYPE_EXIT
);
178 switch (conn
->state
) {
179 case AP_CONN_STATE_OPEN
:
180 case EXIT_CONN_STATE_OPEN
:
181 connection_stop_writing(conn
);
182 connection_edge_consider_sending_sendme(conn
);
184 case AP_CONN_STATE_SOCKS_WAIT
:
185 case AP_CONN_STATE_RENDDESC_WAIT
:
186 case AP_CONN_STATE_CIRCUIT_WAIT
:
187 case AP_CONN_STATE_CONNECT_WAIT
:
188 connection_stop_writing(conn
);
191 log_fn(LOG_WARN
,"BUG: called in unexpected state %d.", conn
->state
);
200 /** Connected handler for exit connections: start writing pending
201 * data, deliver 'CONNECTED' relay cells as appropriate, and check
202 * any pending data that may have been received. */
203 int connection_edge_finished_connecting(connection_t
*conn
)
205 unsigned char connected_payload
[4];
208 tor_assert(conn
->type
== CONN_TYPE_EXIT
);
209 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
211 log_fn(LOG_INFO
,"Exit connection to %s:%u established.",
212 conn
->address
,conn
->port
);
214 conn
->state
= EXIT_CONN_STATE_OPEN
;
215 connection_watch_events(conn
, EV_READ
); /* stop writing, continue reading */
216 if (connection_wants_to_flush(conn
)) /* in case there are any queued relay cells */
217 connection_start_writing(conn
);
218 /* deliver a 'connected' relay cell back through the circuit. */
219 if (connection_edge_is_rendezvous_stream(conn
)) {
220 if (connection_edge_send_command(conn
, circuit_get_by_conn(conn
),
221 RELAY_COMMAND_CONNECTED
, NULL
, 0, conn
->cpath_layer
) < 0)
222 return 0; /* circuit is closed, don't continue */
224 *(uint32_t*)connected_payload
= htonl(conn
->addr
);
225 if (connection_edge_send_command(conn
, circuit_get_by_conn(conn
),
226 RELAY_COMMAND_CONNECTED
, connected_payload
, 4, conn
->cpath_layer
) < 0)
227 return 0; /* circuit is closed, don't continue */
229 tor_assert(conn
->package_window
> 0);
230 /* in case the server has written anything */
231 return connection_edge_process_inbuf(conn
, 1);
234 /** Find all general-purpose AP streams waiting for a response that sent
235 * their begin/resolve cell >=15 seconds ago. Detach from their current circuit,
236 * and mark their current circuit as unsuitable for new streams. Then call
237 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
238 * available) or launch a new one.
240 * For rendezvous streams, simply give up after 45 seconds (with no
243 void connection_ap_expire_beginning(void) {
244 connection_t
**carray
;
248 time_t now
= time(NULL
);
249 or_options_t
*options
= get_options();
251 get_connection_array(&carray
, &n
);
253 for (i
= 0; i
< n
; ++i
) {
255 if (conn
->type
!= CONN_TYPE_AP
)
257 if (conn
->state
!= AP_CONN_STATE_RESOLVE_WAIT
&&
258 conn
->state
!= AP_CONN_STATE_CONNECT_WAIT
)
260 if (now
- conn
->timestamp_lastread
< 15)
262 circ
= circuit_get_by_conn(conn
);
263 if (!circ
) { /* it's vanished? */
264 log_fn(LOG_INFO
,"Conn is waiting (address %s), but lost its circ.",
265 conn
->socks_request
->address
);
266 connection_mark_for_close(conn
);
269 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
270 if (now
- conn
->timestamp_lastread
> 45) {
271 log_fn(LOG_NOTICE
,"Rend stream is %d seconds late. Giving up on address '%s'.",
272 (int)(now
- conn
->timestamp_lastread
), conn
->socks_request
->address
);
273 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
, conn
->cpath_layer
);
274 connection_mark_for_close(conn
);
278 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
279 log_fn(LOG_NOTICE
,"Stream is %d seconds late on address '%s'. Retrying.",
280 (int)(now
- conn
->timestamp_lastread
), conn
->socks_request
->address
);
281 circuit_log_path(LOG_NOTICE
, circ
);
282 /* send an end down the circuit */
283 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
, conn
->cpath_layer
);
284 /* un-mark it as ending, since we're going to reuse it */
285 conn
->has_sent_end
= 0;
286 /* move it back into 'pending' state. */
287 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
288 circuit_detach_stream(circ
, conn
);
289 /* kludge to make us not try this circuit again, yet to allow
290 * current streams on it to survive if they can: make it
291 * unattractive to use for new streams */
292 tor_assert(circ
->timestamp_dirty
);
293 circ
->timestamp_dirty
-= options
->MaxCircuitDirtiness
;
294 /* give our stream another 15 seconds to try */
295 conn
->timestamp_lastread
+= 15;
296 /* attaching to a dirty circuit is fine */
297 if (connection_ap_handshake_attach_circuit(conn
)<0) {
298 /* it will never work */
299 /* Don't need to send end -- we're not connected */
300 conn
->has_sent_end
= 1;
301 connection_mark_for_close(conn
);
306 /** Tell any AP streams that are waiting for a new circuit that one is
309 void connection_ap_attach_pending(void)
311 connection_t
**carray
;
315 get_connection_array(&carray
, &n
);
317 for (i
= 0; i
< n
; ++i
) {
319 if (conn
->marked_for_close
||
320 conn
->type
!= CONN_TYPE_AP
||
321 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
323 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
324 /* -1 means it will never work */
325 /* Don't send end; there is no 'other side' yet */
326 conn
->has_sent_end
= 1;
327 connection_mark_for_close(conn
);
332 /** Return 1 if <b>address</b> has funny characters in it like
333 * colons. Return 0 if it's fine.
336 address_is_invalid_destination(const char *address
) {
337 /* FFFF should flesh this out */
338 if (strchr(address
,':'))
343 /** connection_edge_process_inbuf() found a conn in state
344 * socks_wait. See if conn->inbuf has the right bytes to proceed with
345 * the socks handshake.
347 * If the handshake is complete, and it's for a general circuit, then
348 * try to attach it to a circuit (or launch one as needed). If it's for
349 * a rendezvous circuit, then fetch a rendezvous descriptor first (or
350 * attach/launch a circuit if the rendezvous descriptor is already here
353 * Return -1 if an unexpected error with conn (and it should be marked
354 * for close), else return 0.
356 static int connection_ap_handshake_process_socks(connection_t
*conn
) {
357 socks_request_t
*socks
;
359 hostname_type_t addresstype
;
362 tor_assert(conn
->type
== CONN_TYPE_AP
);
363 tor_assert(conn
->state
== AP_CONN_STATE_SOCKS_WAIT
);
364 tor_assert(conn
->socks_request
);
365 socks
= conn
->socks_request
;
367 log_fn(LOG_DEBUG
,"entered.");
369 sockshere
= fetch_from_buf_socks(conn
->inbuf
, socks
);
370 if (sockshere
== -1 || sockshere
== 0) {
371 if (socks
->replylen
) { /* we should send reply back */
372 log_fn(LOG_DEBUG
,"reply is already set for us. Using it.");
373 connection_ap_handshake_socks_reply(conn
, socks
->reply
, socks
->replylen
, 0);
374 socks
->replylen
= 0; /* zero it out so we can do another round of negotiation */
375 } else if (sockshere
== -1) { /* send normal reject */
376 log_fn(LOG_WARN
,"Fetching socks handshake failed. Closing.");
377 connection_ap_handshake_socks_reply(conn
, NULL
, 0, -1);
379 log_fn(LOG_DEBUG
,"socks handshake not all here yet.");
382 socks
->has_finished
= 1;
384 } /* else socks handshake is done, continue processing */
386 /* Parse the address provided by SOCKS. Modify it in-place if it
387 * specifies a hidden-service (.onion) or particular exit node (.exit).
389 addresstype
= parse_extended_hostname(socks
->address
);
391 if (addresstype
== EXIT_HOSTNAME
) {
392 /* .exit -- modify conn to specify the exit node. */
393 char *s
= strrchr(socks
->address
,'.');
394 if (!s
|| s
[1] == '\0') {
395 log_fn(LOG_WARN
,"Malformed exit address '%s'. Refusing.", socks
->address
);
398 conn
->chosen_exit_name
= tor_strdup(s
+1);
402 if (addresstype
!= ONION_HOSTNAME
) {
403 /* not a hidden-service request (i.e. normal or .exit) */
405 if (address_is_invalid_destination(socks
->address
)) {
406 log_fn(LOG_WARN
,"Destination '%s' seems to be an invalid hostname. Failing.", socks
->address
);
410 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
413 /* Reply to resolves immediately if we can. */
414 if (strlen(socks
->address
) > RELAY_PAYLOAD_SIZE
) {
415 log_fn(LOG_WARN
,"Address to be resolved is too large. Failing.");
416 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,0,NULL
);
419 if (tor_inet_aton(socks
->address
, &in
)) /* see if it's an IP already */
421 if (!answer
&& !conn
->chosen_exit_name
) /* if it's not .exit, check cache */
422 answer
= htonl(client_dns_lookup_entry(socks
->address
));
424 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
426 conn
->has_sent_end
= 1;
427 connection_mark_for_close(conn
);
428 conn
->hold_open_until_flushed
= 1;
431 rep_hist_note_used_resolve(time(NULL
)); /* help predict this next time */
432 } else { /* socks->command == SOCKS_COMMAND_CONNECT */
433 if (socks
->port
== 0) {
434 log_fn(LOG_NOTICE
,"Application asked to connect to port 0. Refusing.");
437 rep_hist_note_used_port(socks
->port
, time(NULL
)); /* help predict this next time */
439 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
440 return connection_ap_handshake_attach_circuit(conn
);
442 /* it's a hidden-service request */
443 rend_cache_entry_t
*entry
;
446 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
447 /* if it's a resolve request, fail it right now, rather than
448 * building all the circuits and then realizing it won't work. */
449 log_fn(LOG_WARN
,"Resolve requests to hidden services not allowed. Failing.");
450 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,0,NULL
);
454 strlcpy(conn
->rend_query
, socks
->address
, sizeof(conn
->rend_query
));
455 log_fn(LOG_INFO
,"Got a hidden service request for ID '%s'", conn
->rend_query
);
456 /* see if we already have it cached */
457 r
= rend_cache_lookup_entry(conn
->rend_query
, &entry
);
459 log_fn(LOG_WARN
,"Invalid service descriptor %s", conn
->rend_query
);
463 conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
464 log_fn(LOG_INFO
, "Unknown descriptor %s. Fetching.", conn
->rend_query
);
465 rend_client_refetch_renddesc(conn
->rend_query
);
469 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
470 if (time(NULL
) - entry
->received
< NUM_SECONDS_BEFORE_REFETCH
) {
471 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
472 log_fn(LOG_INFO
, "Descriptor is here and fresh enough. Great.");
473 return connection_ap_handshake_attach_circuit(conn
);
475 conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
476 log_fn(LOG_INFO
, "Stale descriptor %s. Refetching.", conn
->rend_query
);
477 rend_client_refetch_renddesc(conn
->rend_query
);
482 return 0; /* unreached but keeps the compiler happy */
485 /** Iterate over the two bytes of stream_id until we get one that is not
486 * already in use; return it. Return 0 if can't get a unique stream_id.
488 static uint16_t get_unique_stream_id_by_circ(circuit_t
*circ
) {
489 connection_t
*tmpconn
;
490 uint16_t test_stream_id
;
494 test_stream_id
= circ
->next_stream_id
++;
495 if (++attempts
> 1<<16) {
496 /* Make sure we don't loop forever if all stream_id's are used. */
497 log_fn(LOG_WARN
,"No unused stream IDs. Failing.");
500 if (test_stream_id
== 0)
502 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
503 if (tmpconn
->stream_id
== test_stream_id
)
505 return test_stream_id
;
508 /** Write a relay begin cell, using destaddr and destport from ap_conn's
509 * socks_request field, and send it down circ.
511 * If ap_conn is broken, mark it for close and return -1. Else return 0.
513 int connection_ap_handshake_send_begin(connection_t
*ap_conn
, circuit_t
*circ
)
515 char payload
[CELL_PAYLOAD_SIZE
];
518 const char *string_addr
;
520 tor_assert(ap_conn
->type
== CONN_TYPE_AP
);
521 tor_assert(ap_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
522 tor_assert(ap_conn
->socks_request
);
524 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
525 if (ap_conn
->stream_id
==0) {
526 /* Don't send end: there is no 'other side' yet */
527 ap_conn
->has_sent_end
= 1;
528 connection_mark_for_close(ap_conn
);
529 circuit_mark_for_close(circ
);
533 if (circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
534 in
.s_addr
= htonl(client_dns_lookup_entry(ap_conn
->socks_request
->address
));
535 string_addr
= in
.s_addr
? inet_ntoa(in
) : NULL
;
537 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
,
539 string_addr
? string_addr
: ap_conn
->socks_request
->address
,
540 ap_conn
->socks_request
->port
);
542 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
,
543 ":%d", ap_conn
->socks_request
->port
);
545 payload_len
= strlen(payload
)+1;
547 log_fn(LOG_DEBUG
,"Sending relay cell to begin stream %d.",ap_conn
->stream_id
);
549 if (connection_edge_send_command(ap_conn
, circ
, RELAY_COMMAND_BEGIN
,
550 payload
, payload_len
, ap_conn
->cpath_layer
) < 0)
551 return -1; /* circuit is closed, don't continue */
553 ap_conn
->package_window
= STREAMWINDOW_START
;
554 ap_conn
->deliver_window
= STREAMWINDOW_START
;
555 ap_conn
->state
= AP_CONN_STATE_CONNECT_WAIT
;
556 log_fn(LOG_INFO
,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn
->s
,circ
->n_circ_id
);
557 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
);
561 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
562 * socks_request field, and send it down circ.
564 * If ap_conn is broken, mark it for close and return -1. Else return 0.
566 int connection_ap_handshake_send_resolve(connection_t
*ap_conn
, circuit_t
*circ
)
569 const char *string_addr
;
571 tor_assert(ap_conn
->type
== CONN_TYPE_AP
);
572 tor_assert(ap_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
573 tor_assert(ap_conn
->socks_request
);
574 tor_assert(ap_conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE
);
575 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
577 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
578 if (ap_conn
->stream_id
==0) {
579 /* Don't send end: there is no 'other side' yet */
580 ap_conn
->has_sent_end
= 1;
581 connection_mark_for_close(ap_conn
);
582 circuit_mark_for_close(circ
);
586 string_addr
= ap_conn
->socks_request
->address
;
587 payload_len
= strlen(string_addr
);
588 tor_assert(strlen(string_addr
) <= RELAY_PAYLOAD_SIZE
);
590 log_fn(LOG_DEBUG
,"Sending relay cell to begin stream %d.",ap_conn
->stream_id
);
592 if (connection_edge_send_command(ap_conn
, circ
, RELAY_COMMAND_RESOLVE
,
593 string_addr
, payload_len
, ap_conn
->cpath_layer
) < 0)
594 return -1; /* circuit is closed, don't continue */
596 ap_conn
->state
= AP_CONN_STATE_RESOLVE_WAIT
;
597 log_fn(LOG_INFO
,"Address sent for resolve, ap socket %d, n_circ_id %d",ap_conn
->s
,circ
->n_circ_id
);
598 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
);
602 /** Make an AP connection_t, do a socketpair and attach one side
603 * to the conn, connection_add it, initialize it to circuit_wait,
604 * and call connection_ap_handshake_attach_circuit(conn) on it.
606 * Return the other end of the socketpair, or -1 if error.
608 int connection_ap_make_bridge(char *address
, uint16_t port
) {
612 log_fn(LOG_INFO
,"Making AP bridge to %s:%d ...",address
,port
);
614 if (tor_socketpair(AF_UNIX
, SOCK_STREAM
, 0, fd
) < 0) {
615 log(LOG_WARN
,"Couldn't construct socketpair (%s). Network down? Delaying.",
616 tor_socket_strerror(tor_socket_errno(-1)));
620 set_socket_nonblocking(fd
[0]);
621 set_socket_nonblocking(fd
[1]);
623 conn
= connection_new(CONN_TYPE_AP
);
626 /* populate conn->socks_request */
628 /* leave version at zero, so the socks_reply is empty */
629 conn
->socks_request
->socks_version
= 0;
630 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
631 strlcpy(conn
->socks_request
->address
, address
,
632 sizeof(conn
->socks_request
->address
));
633 conn
->socks_request
->port
= port
;
634 conn
->socks_request
->command
= SOCKS_COMMAND_CONNECT
;
636 conn
->address
= tor_strdup("(local bridge)");
640 if (connection_add(conn
) < 0) { /* no space, forget it */
641 connection_free(conn
); /* this closes fd[0] */
642 tor_close_socket(fd
[1]);
646 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
647 connection_start_reading(conn
);
649 /* attaching to a dirty circuit is fine */
650 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
651 conn
->has_sent_end
= 1; /* no circ to send to */
652 connection_mark_for_close(conn
);
653 tor_close_socket(fd
[1]);
657 log_fn(LOG_INFO
,"... AP bridge created and connected.");
662 void connection_ap_handshake_socks_resolved(connection_t
*conn
,
670 if (answer_type
== RESOLVED_TYPE_IPV4
) {
671 uint32_t a
= get_uint32(answer
);
673 client_dns_set_entry(conn
->socks_request
->address
, ntohl(a
));
676 if (conn
->socks_request
->socks_version
== 4) {
677 buf
[0] = 0x00; /* version */
678 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
679 buf
[1] = 90; /* "Granted" */
680 set_uint16(buf
+2, 0);
681 memcpy(buf
+4, answer
, 4); /* address */
682 replylen
= SOCKS4_NETWORK_LEN
;
684 buf
[1] = 91; /* "error" */
686 replylen
= SOCKS4_NETWORK_LEN
;
690 buf
[0] = 0x05; /* version */
691 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
692 buf
[1] = 0; /* succeeded */
693 buf
[2] = 0; /* reserved */
694 buf
[3] = 0x01; /* IPv4 address type */
695 memcpy(buf
+4, answer
, 4); /* address */
696 set_uint16(buf
+8, 0); /* port == 0. */
698 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
699 buf
[1] = 0; /* succeeded */
700 buf
[2] = 0; /* reserved */
701 buf
[3] = 0x04; /* IPv6 address type */
702 memcpy(buf
+4, answer
, 16); /* address */
703 set_uint16(buf
+20, 0); /* port == 0. */
706 buf
[1] = 0x04; /* host unreachable */
711 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
712 (answer_type
== RESOLVED_TYPE_IPV4
||
713 answer_type
== RESOLVED_TYPE_IPV6
) ? 1 : -1);
714 conn
->socks_request
->has_finished
= 1;
717 /** Send a socks reply to stream <b>conn</b>, using the appropriate
718 * socks version, etc.
720 * Status can be 1 (succeeded), -1 (failed), or 0 (not sure yet).
722 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
723 * to conn and return, else reply based on <b>status</b>.
725 * If <b>reply</b> is undefined, <b>status</b> can't be 0.
727 void connection_ap_handshake_socks_reply(connection_t
*conn
, char *reply
,
728 size_t replylen
, int status
) {
731 if (status
) /* it's either 1 or -1 */
732 control_event_stream_status(conn
,
733 status
==1 ? STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
);
735 if (replylen
) { /* we already have a reply in mind */
736 connection_write_to_buf(reply
, replylen
, conn
);
739 tor_assert(conn
->socks_request
);
740 tor_assert(status
== 1 || status
== -1);
741 if (conn
->socks_request
->socks_version
== 4) {
742 memset(buf
,0,SOCKS4_NETWORK_LEN
);
743 #define SOCKS4_GRANTED 90
744 #define SOCKS4_REJECT 91
745 buf
[1] = (status
==1 ? SOCKS4_GRANTED
: SOCKS4_REJECT
);
746 /* leave version, destport, destip zero */
747 connection_write_to_buf(buf
, SOCKS4_NETWORK_LEN
, conn
);
749 if (conn
->socks_request
->socks_version
== 5) {
750 buf
[0] = 5; /* version 5 */
751 #define SOCKS5_SUCCESS 0
752 #define SOCKS5_GENERIC_ERROR 1
753 buf
[1] = status
==1 ? SOCKS5_SUCCESS
: SOCKS5_GENERIC_ERROR
;
755 buf
[3] = 1; /* ipv4 addr */
756 memset(buf
+4,0,6); /* Set external addr/port to 0.
757 The spec doesn't seem to say what to do here. -RD */
758 connection_write_to_buf(buf
,10,conn
);
760 /* If socks_version isn't 4 or 5, don't send anything.
761 * This can happen in the case of AP bridges. */
765 /** A relay 'begin' cell has arrived, and either we are an exit hop
766 * for the circuit, or we are the origin and it is a rendezvous begin.
768 * Launch a new exit connection and initialize things appropriately.
770 * If it's a rendezvous stream, call connection_exit_connect() on
773 * For general streams, call dns_resolve() on it first, and only call
774 * connection_exit_connect() if the dns answer is already known.
776 * Note that we don't call connection_add() on the new stream! We wait
777 * for connection_exit_connect() to do that.
779 * Return -1 if we want to tear down <b>circ</b>. Else return 0.
781 int connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
) {
782 connection_t
*n_stream
;
787 assert_circuit_ok(circ
);
788 relay_header_unpack(&rh
, cell
->payload
);
790 /* XXX currently we don't send an end cell back if we drop the
791 * begin because it's malformed.
794 if (!memchr(cell
->payload
+RELAY_HEADER_SIZE
, 0, rh
.length
)) {
795 log_fn(LOG_WARN
,"relay begin cell has no \\0. Dropping.");
798 if (parse_addr_port(cell
->payload
+RELAY_HEADER_SIZE
,&address
,NULL
,&port
)<0) {
799 log_fn(LOG_WARN
,"Unable to parse addr:port in relay begin cell. Dropping.");
803 log_fn(LOG_WARN
,"Missing port in relay begin cell. Dropping.");
808 log_fn(LOG_DEBUG
,"Creating new exit connection.");
809 n_stream
= connection_new(CONN_TYPE_EXIT
);
810 n_stream
->purpose
= EXIT_PURPOSE_CONNECT
;
812 n_stream
->stream_id
= rh
.stream_id
;
813 n_stream
->port
= port
;
814 /* leave n_stream->s at -1, because it's not yet valid */
815 n_stream
->package_window
= STREAMWINDOW_START
;
816 n_stream
->deliver_window
= STREAMWINDOW_START
;
818 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
819 log_fn(LOG_DEBUG
,"begin is for rendezvous. configuring stream.");
820 n_stream
->address
= tor_strdup("(rendezvous)");
821 n_stream
->state
= EXIT_CONN_STATE_CONNECTING
;
822 strlcpy(n_stream
->rend_query
, circ
->rend_query
,
823 sizeof(n_stream
->rend_query
));
824 tor_assert(connection_edge_is_rendezvous_stream(n_stream
));
825 assert_circuit_ok(circ
);
826 if (rend_service_set_connection_addr_port(n_stream
, circ
) < 0) {
827 log_fn(LOG_INFO
,"Didn't find rendezvous service (port %d)",n_stream
->port
);
828 connection_edge_end(n_stream
, END_STREAM_REASON_EXITPOLICY
, n_stream
->cpath_layer
);
829 connection_free(n_stream
);
830 circuit_mark_for_close(circ
); /* knock the whole thing down, somebody screwed up */
834 assert_circuit_ok(circ
);
835 log_fn(LOG_DEBUG
,"Finished assigning addr/port");
836 n_stream
->cpath_layer
= circ
->cpath
->prev
; /* link it */
838 /* add it into the linked list of n_streams on this circuit */
839 n_stream
->next_stream
= circ
->n_streams
;
840 circ
->n_streams
= n_stream
;
841 assert_circuit_ok(circ
);
843 connection_exit_connect(n_stream
);
847 n_stream
->address
= address
;
848 n_stream
->state
= EXIT_CONN_STATE_RESOLVEFAILED
;
849 /* default to failed, change in dns_resolve if it turns out not to fail */
851 if (we_are_hibernating()) {
852 connection_edge_end(n_stream
, END_STREAM_REASON_EXITPOLICY
, n_stream
->cpath_layer
);
853 connection_free(n_stream
);
857 /* send it off to the gethostbyname farm */
858 switch (dns_resolve(n_stream
)) {
859 case 1: /* resolve worked */
861 /* add it into the linked list of n_streams on this circuit */
862 n_stream
->next_stream
= circ
->n_streams
;
863 circ
->n_streams
= n_stream
;
864 assert_circuit_ok(circ
);
866 connection_exit_connect(n_stream
);
868 case -1: /* resolve failed */
869 log_fn(LOG_INFO
,"Resolve failed (%s).", n_stream
->address
);
870 if (!n_stream
->marked_for_close
) {
871 connection_edge_end(n_stream
, END_STREAM_REASON_RESOLVEFAILED
,
872 n_stream
->cpath_layer
);
874 connection_free(n_stream
);
876 case 0: /* resolve added to pending list */
877 /* add it into the linked list of resolving_streams on this circuit */
878 n_stream
->next_stream
= circ
->resolving_streams
;
879 circ
->resolving_streams
= n_stream
;
880 assert_circuit_ok(circ
);
887 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
888 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
890 int connection_exit_begin_resolve(cell_t
*cell
, circuit_t
*circ
) {
891 connection_t
*dummy_conn
;
894 assert_circuit_ok(circ
);
895 relay_header_unpack(&rh
, cell
->payload
);
897 /* This 'dummy_conn' only exists to remember the stream ID
898 * associated with the resolve request; and to make the
899 * implementation of dns.c more uniform. (We really only need to
900 * remember the circuit, the stream ID, and the hostname to be
901 * resolved; but if we didn't store them in a connection like this,
902 * the housekeeping in dns.c would get way more complicated.)
904 dummy_conn
= connection_new(CONN_TYPE_EXIT
);
905 dummy_conn
->stream_id
= rh
.stream_id
;
906 dummy_conn
->address
= tor_strndup(cell
->payload
+RELAY_HEADER_SIZE
,
908 dummy_conn
->port
= 0;
909 dummy_conn
->state
= EXIT_CONN_STATE_RESOLVEFAILED
;
910 dummy_conn
->purpose
= EXIT_PURPOSE_RESOLVE
;
912 dummy_conn
->next_stream
= circ
->resolving_streams
;
913 circ
->resolving_streams
= dummy_conn
;
915 /* send it off to the gethostbyname farm */
916 switch (dns_resolve(dummy_conn
)) {
917 case 1: /* The result was cached; a resolved cell was sent. */
919 circuit_detach_stream(circuit_get_by_conn(dummy_conn
), dummy_conn
);
920 connection_free(dummy_conn
);
922 case 0: /* resolve added to pending list */
923 assert_circuit_ok(circ
);
929 /** Connect to conn's specified addr and port. If it worked, conn
930 * has now been added to the connection_array.
932 * Send back a connected cell. Include the resolved IP of the destination
933 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
934 * streams must not reveal what IP they connected to.)
937 connection_exit_connect(connection_t
*conn
) {
938 unsigned char connected_payload
[4];
942 if (!connection_edge_is_rendezvous_stream(conn
) &&
943 router_compare_to_my_exit_policy(conn
) == ADDR_POLICY_REJECTED
) {
944 log_fn(LOG_INFO
,"%s:%d failed exit policy. Closing.", conn
->address
, conn
->port
);
945 connection_edge_end(conn
, END_STREAM_REASON_EXITPOLICY
, conn
->cpath_layer
);
946 circuit_detach_stream(circuit_get_by_conn(conn
), conn
);
947 connection_free(conn
);
953 if (redirect_exit_list
) {
954 SMARTLIST_FOREACH(redirect_exit_list
, exit_redirect_t
*, r
,
956 if ((addr
&r
->mask
)==(r
->addr
&r
->mask
) &&
957 (r
->port_min
<= port
) && (port
<= r
->port_max
)) {
959 if (r
->is_redirect
) {
962 in
.s_addr
= htonl(addr
);
963 log_fn(LOG_DEBUG
, "Redirecting connection from %s:%d to %s:%d",
964 conn
->address
, conn
->port
, inet_ntoa(in
), port
);
971 log_fn(LOG_DEBUG
,"about to try connecting");
972 switch (connection_connect(conn
, conn
->address
, addr
, port
)) {
974 connection_edge_end(conn
, END_STREAM_REASON_CONNECTFAILED
, conn
->cpath_layer
);
975 circuit_detach_stream(circuit_get_by_conn(conn
), conn
);
976 connection_free(conn
);
979 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
981 connection_watch_events(conn
, EV_WRITE
| EV_READ
);
982 /* writable indicates finish, readable indicates broken link,
983 error indicates broken link in windowsland. */
985 /* case 1: fall through */
988 conn
->state
= EXIT_CONN_STATE_OPEN
;
989 if (connection_wants_to_flush(conn
)) { /* in case there are any queued data cells */
990 log_fn(LOG_WARN
,"Bug: newly connected conn had data waiting!");
991 // connection_start_writing(conn);
993 connection_watch_events(conn
, EV_READ
);
995 /* also, deliver a 'connected' cell back through the circuit. */
996 if (connection_edge_is_rendezvous_stream(conn
)) { /* rendezvous stream */
997 /* don't send an address back! */
998 connection_edge_send_command(conn
, circuit_get_by_conn(conn
), RELAY_COMMAND_CONNECTED
,
999 NULL
, 0, conn
->cpath_layer
);
1000 } else { /* normal stream */
1001 /* This must be the original address, not the redirected address. */
1002 *(uint32_t*)connected_payload
= htonl(conn
->addr
);
1003 connection_edge_send_command(conn
, circuit_get_by_conn(conn
), RELAY_COMMAND_CONNECTED
,
1004 connected_payload
, 4, conn
->cpath_layer
);
1008 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
1009 * it is a general stream.
1011 int connection_edge_is_rendezvous_stream(connection_t
*conn
) {
1013 if (*conn
->rend_query
) /* XXX */
1018 /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
1019 * to exit from it, or 0 if it definitely will not allow it.
1020 * (We might be uncertain if conn's destination address has not yet been
1023 int connection_ap_can_use_exit(connection_t
*conn
, routerinfo_t
*exit
)
1028 tor_assert(conn
->type
== CONN_TYPE_AP
);
1029 tor_assert(conn
->socks_request
);
1032 log_fn(LOG_DEBUG
,"considering nickname %s, for address %s / port %d:",
1033 exit
->nickname
, conn
->socks_request
->address
,
1034 conn
->socks_request
->port
);
1036 /* If a particular exit node has been requested for the new connection,
1037 * make sure the exit node of the existing circuit matches exactly.
1039 if (conn
->chosen_exit_name
) {
1040 if (router_get_by_nickname(conn
->chosen_exit_name
) != exit
) {
1042 log_fn(LOG_DEBUG
,"Requested node '%s', considering node '%s'. No.",
1043 conn
->chosen_exit_name
, exit
->nickname
);
1048 if (conn
->socks_request
->command
!= SOCKS_COMMAND_RESOLVE
) {
1049 addr
= client_dns_lookup_entry(conn
->socks_request
->address
);
1050 if (router_compare_addr_to_addr_policy(addr
, conn
->socks_request
->port
,
1051 exit
->exit_policy
) == ADDR_POLICY_REJECTED
)
1057 /** A helper function for socks_policy_permits_address() below.
1059 * Parse options->SocksPolicy in the same way that the exit policy
1060 * is parsed, and put the processed version in &socks_policy.
1061 * Ignore port specifiers.
1064 parse_socks_policy(void)
1068 addr_policy_free(socks_policy
);
1069 socks_policy
= NULL
;
1071 config_parse_addr_policy(get_options()->SocksPolicy
, &socks_policy
);
1072 /* ports aren't used. */
1073 for (n
=socks_policy
; n
; n
= n
->next
) {
1079 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1080 * based on <b>socks_policy</b>. Else return 0.
1082 int socks_policy_permits_address(uint32_t addr
)
1086 if (!socks_policy
) /* 'no socks policy' means 'accept' */
1088 a
= router_compare_addr_to_addr_policy(addr
, 1, socks_policy
);
1094 log_fn(LOG_WARN
, "Bug: Got unexpected 'maybe' answer from socks policy");
1098 /* ***** Client DNS code ***** */
1100 /* XXX Perhaps this should get merged with the dns.c code somehow. */
1101 /* XXX But we can't just merge them, because then nodes that act as
1102 * both OR and OP could be attacked: people could rig the dns cache
1103 * by answering funny things to stream begin requests, and later
1104 * other clients would reuse those funny addr's. Hm.
1107 /** A client-side struct to remember the resolved IP (addr) for
1108 * a given address. These structs make up a tree, with client_dns_map
1109 * below as its root.
1111 struct client_dns_entry
{
1112 uint32_t addr
; /**< The resolved IP of this entry. */
1113 time_t expires
; /**< At what second does addr expire? */
1114 int n_failures
; /**< How many times has this entry failed to resolve so far? */
1117 /** How many elements are in the client dns cache currently? */
1118 static int client_dns_size
= 0;
1119 /** The tree of client-side cached DNS resolves. */
1120 static strmap_t
*client_dns_map
= NULL
;
1122 /** Initialize client_dns_map and client_dns_size. */
1123 void client_dns_init(void) {
1124 client_dns_map
= strmap_new();
1125 client_dns_size
= 0;
1128 /** Return the client_dns_entry that corresponds to <b>address</b>.
1129 * If it's not there, allocate and return a new entry for <b>address</b>.
1131 static struct client_dns_entry
*
1132 _get_or_create_ent(const char *address
)
1134 struct client_dns_entry
*ent
;
1135 ent
= strmap_get_lc(client_dns_map
,address
);
1137 ent
= tor_malloc_zero(sizeof(struct client_dns_entry
));
1138 ent
->expires
= time(NULL
)+MAX_DNS_ENTRY_AGE
;
1139 strmap_set_lc(client_dns_map
,address
,ent
);
1145 /** Return the IP associated with <b>address</b>, if we know it
1146 * and it's still fresh enough. Otherwise return 0.
1148 uint32_t client_dns_lookup_entry(const char *address
)
1150 struct client_dns_entry
*ent
;
1154 tor_assert(address
);
1156 if (tor_inet_aton(address
, &in
)) {
1157 log_fn(LOG_DEBUG
, "Using static address %s (%08lX)", address
,
1158 (unsigned long)ntohl(in
.s_addr
));
1159 return ntohl(in
.s_addr
);
1161 ent
= strmap_get_lc(client_dns_map
,address
);
1162 if (!ent
|| !ent
->addr
) {
1163 log_fn(LOG_DEBUG
, "No entry found for address %s", address
);
1167 if (ent
->expires
< now
) {
1168 log_fn(LOG_DEBUG
, "Expired entry found for address %s", address
);
1169 strmap_remove_lc(client_dns_map
,address
);
1174 in
.s_addr
= htonl(ent
->addr
);
1175 log_fn(LOG_DEBUG
, "Found cached entry for address %s: %s", address
,
1181 /** An attempt to resolve <b>address</b> failed at some OR.
1182 * Increment the number of resolve failures we have on record
1183 * for it, and then return that number.
1185 int client_dns_incr_failures(const char *address
)
1187 struct client_dns_entry
*ent
;
1188 ent
= _get_or_create_ent(address
);
1190 log_fn(LOG_DEBUG
,"Address %s now has %d resolve failures.",
1191 address
, ent
->n_failures
);
1192 return ent
->n_failures
;
1195 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1196 * We can now use this in subsequent streams in client_dns_lookup_entry(),
1197 * so we can more correctly choose a router that will allow <b>address</b>
1200 void client_dns_set_entry(const char *address
, uint32_t val
)
1202 struct client_dns_entry
*ent
;
1206 tor_assert(address
);
1209 if (tor_inet_aton(address
, &in
))
1212 ent
= _get_or_create_ent(address
);
1213 in
.s_addr
= htonl(val
);
1214 log_fn(LOG_DEBUG
, "Updating entry for address %s: %s", address
,
1217 ent
->expires
= now
+MAX_DNS_ENTRY_AGE
;
1218 ent
->n_failures
= 0;
1221 /** A helper function for client_dns_clean() below. If ent is too old,
1222 * then remove it from the tree and return NULL, else return ent.
1224 static void* _remove_if_expired(const char *addr
,
1225 struct client_dns_entry
*ent
,
1228 if (ent
->expires
< *nowp
) {
1237 /** Clean out entries from the client-side DNS cache that were
1238 * resolved long enough ago that they are no longer valid.
1240 void client_dns_clean(void)
1244 if (!client_dns_size
)
1247 strmap_foreach(client_dns_map
, (strmap_foreach_fn
)_remove_if_expired
, &now
);
1250 /** Make connection redirection follow the provided list of
1251 * exit_redirect_t */
1253 set_exit_redirects(smartlist_t
*lst
)
1255 if (redirect_exit_list
) {
1256 SMARTLIST_FOREACH(redirect_exit_list
, exit_redirect_t
*, p
, tor_free(p
));
1257 smartlist_free(redirect_exit_list
);
1259 redirect_exit_list
= lst
;
1262 /** If address is of the form "y.onion" with a well-formed handle y:
1263 * Put a '\0' after y, lower-case it, and return ONION_HOSTNAME.
1265 * If address is of the form "y.exit":
1266 * Put a '\0' after y and return EXIT_HOSTNAME.
1269 * Return NORMAL_HOSTNAME and change nothing.
1272 parse_extended_hostname(char *address
) {
1274 char query
[REND_SERVICE_ID_LEN
+1];
1276 s
= strrchr(address
,'.');
1277 if (!s
) return 0; /* no dot, thus normal */
1278 if (!strcasecmp(s
+1,"exit")) {
1279 *s
= 0; /* null-terminate it */
1280 return EXIT_HOSTNAME
; /* .exit */
1282 if (strcasecmp(s
+1,"onion"))
1283 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
1285 /* so it is .onion */
1286 *s
= 0; /* null-terminate it */
1287 if (strlcpy(query
, address
, REND_SERVICE_ID_LEN
+1) >= REND_SERVICE_ID_LEN
+1)
1289 tor_strlower(query
);
1290 if (rend_valid_service_id(query
)) {
1291 tor_strlower(address
);
1292 return ONION_HOSTNAME
; /* success */
1295 /* otherwise, return to previous state and return 0 */
1297 return NORMAL_HOSTNAME
;