Set chosen_exit_name to something we are not about to zero.
[tor.git] / src / or / connection_edge.c
blob786f2dbae0431b995e8122fa4f4a695dc42ed4ef
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char connection_edge_c_id[] = "$Id$";
8 /**
9 * \file connection_edge.c
10 * \brief Handle edge streams.
11 **/
13 #include "or.h"
15 static addr_policy_t *socks_policy = NULL;
16 /* List of exit_redirect_t */
17 static smartlist_t *redirect_exit_list = NULL;
19 static int connection_ap_handshake_process_socks(connection_t *conn);
21 /** An AP stream has failed/finished. If it hasn't already sent back
22 * a socks reply, send one now (based on endreason). Also set
23 * has_sent_end to 1, and mark the conn.
25 void
26 _connection_mark_unattached_ap(connection_t *conn, int endreason,
27 int line, const char *file)
29 tor_assert(conn->type == CONN_TYPE_AP);
30 conn->has_sent_end = 1; /* no circ yet */
32 if (conn->marked_for_close) {
33 /* This call will warn as appropriate. */
34 _connection_mark_for_close(conn, line, file);
35 return;
38 if (!conn->socks_request->has_finished) {
39 socks5_reply_status_t socksreason =
40 connection_edge_end_reason_socks5_response(endreason);
42 if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
43 warn(LD_BUG,"Bug: stream (marked at %s:%d) sending two socks replies?",
44 file, line);
46 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
47 connection_ap_handshake_socks_reply(conn, NULL, 0, socksreason);
48 else
49 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL,-1);
52 _connection_mark_for_close(conn, line, file);
53 conn->hold_open_until_flushed = 1;
56 /** There was an EOF. Send an end and mark the connection for close.
58 int
59 connection_edge_reached_eof(connection_t *conn)
61 #ifdef HALF_OPEN
62 /* eof reached; we're done reading, but we might want to write more. */
63 conn->done_receiving = 1;
64 shutdown(conn->s, 0); /* XXX check return, refactor NM */
65 if (conn->done_sending) {
66 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
67 connection_mark_for_close(conn);
68 } else {
69 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
70 RELAY_COMMAND_END,
71 NULL, 0, conn->cpath_layer);
73 return 0;
74 #else
75 if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
76 /* it still has stuff to process. don't let it die yet. */
77 return 0;
79 info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->s);
80 if (!conn->marked_for_close) {
81 /* only mark it if not already marked. it's possible to
82 * get the 'end' right around when the client hangs up on us. */
83 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
84 if (conn->socks_request) /* eof, so don't send a socks reply back */
85 conn->socks_request->has_finished = 1;
86 connection_mark_for_close(conn);
88 return 0;
89 #endif
92 /** Handle new bytes on conn->inbuf based on state:
93 * - If it's waiting for socks info, try to read another step of the
94 * socks handshake out of conn->inbuf.
95 * - If it's open, then package more relay cells from the stream.
96 * - Else, leave the bytes on inbuf alone for now.
98 * Mark and return -1 if there was an unexpected error with the conn,
99 * else return 0.
102 connection_edge_process_inbuf(connection_t *conn, int package_partial)
104 tor_assert(conn);
105 tor_assert(CONN_IS_EDGE(conn));
107 switch (conn->state) {
108 case AP_CONN_STATE_SOCKS_WAIT:
109 if (connection_ap_handshake_process_socks(conn) < 0) {
110 /* already marked */
111 return -1;
113 return 0;
114 case AP_CONN_STATE_OPEN:
115 case EXIT_CONN_STATE_OPEN:
116 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
117 /* (We already sent an end cell if possible) */
118 connection_mark_for_close(conn);
119 return -1;
121 return 0;
122 case EXIT_CONN_STATE_CONNECTING:
123 case AP_CONN_STATE_RENDDESC_WAIT:
124 case AP_CONN_STATE_CIRCUIT_WAIT:
125 case AP_CONN_STATE_CONNECT_WAIT:
126 case AP_CONN_STATE_RESOLVE_WAIT:
127 case AP_CONN_STATE_CONTROLLER_WAIT:
128 info(LD_EDGE,"data from edge while in '%s' state. Leaving it on buffer.",
129 conn_state_to_string(conn->type, conn->state));
130 return 0;
132 warn(LD_BUG,"Bug: Got unexpected state %d. Closing.",conn->state);
133 tor_fragile_assert();
134 connection_edge_end(conn, END_STREAM_REASON_INTERNAL, conn->cpath_layer);
135 connection_mark_for_close(conn);
136 return -1;
139 /** This edge needs to be closed, because its circuit has closed.
140 * Mark it for close and return 0.
143 connection_edge_destroy(uint16_t circ_id, connection_t *conn)
145 tor_assert(CONN_IS_EDGE(conn));
147 if (!conn->marked_for_close) {
148 info(LD_EDGE,
149 "CircID %d: At an edge. Marking connection for close.", circ_id);
150 if (conn->type == CONN_TYPE_AP) {
151 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
152 } else {
153 conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
154 connection_mark_for_close(conn);
155 conn->hold_open_until_flushed = 1;
158 conn->cpath_layer = NULL;
159 conn->on_circuit = NULL;
160 return 0;
163 /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
164 * with a destination of cpath_layer. (If cpath_layer is NULL, the
165 * destination is the circuit's origin.) Mark the relay end cell as
166 * closing because of <b>reason</b>.
168 * Return -1 if this function has already been called on this conn,
169 * else return 0.
172 connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
174 char payload[RELAY_PAYLOAD_SIZE];
175 size_t payload_len=1;
176 circuit_t *circ;
178 if (conn->has_sent_end) {
179 warn(LD_BUG,"Harmless bug: Calling connection_edge_end (reason %d) on an already ended stream?", reason);
180 tor_fragile_assert();
181 return -1;
184 if (conn->marked_for_close) {
185 warn(LD_BUG,"Bug: called on conn that's already marked for close at %s:%d.",
186 conn->marked_for_close_file, conn->marked_for_close);
187 return 0;
190 payload[0] = reason;
191 if (reason == END_STREAM_REASON_EXITPOLICY &&
192 !connection_edge_is_rendezvous_stream(conn)) {
193 set_uint32(payload+1, htonl(conn->addr));
194 set_uint32(payload+5, htonl(MAX_DNS_ENTRY_AGE)); /* XXXXfill with a real TTL*/
195 payload_len += 8;
198 circ = circuit_get_by_edge_conn(conn);
199 if (circ && !circ->marked_for_close) {
200 debug(LD_EDGE,"Marking conn (fd %d) and sending end.",conn->s);
201 connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
202 payload, payload_len, cpath_layer);
203 } else {
204 debug(LD_EDGE,"Marking conn (fd %d); no circ to send end.",conn->s);
207 conn->has_sent_end = 1;
208 return 0;
211 /** An error has just occured on an operation on an edge connection
212 * <b>conn</b>. Extract the errno; convert it to an end reason, and send
213 * an appropriate relay end cell to <b>cpath_layer</b>.
216 connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer)
218 uint8_t reason;
219 tor_assert(conn);
220 reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->s));
221 return connection_edge_end(conn, reason, cpath_layer);
224 /** Connection <b>conn</b> has finished writing and has no bytes left on
225 * its outbuf.
227 * If it's in state 'open', stop writing, consider responding with a
228 * sendme, and return.
229 * Otherwise, stop writing and return.
231 * If <b>conn</b> is broken, mark it for close and return -1, else
232 * return 0.
235 connection_edge_finished_flushing(connection_t *conn)
237 tor_assert(conn);
238 tor_assert(CONN_IS_EDGE(conn));
240 switch (conn->state) {
241 case AP_CONN_STATE_OPEN:
242 case EXIT_CONN_STATE_OPEN:
243 connection_stop_writing(conn);
244 connection_edge_consider_sending_sendme(conn);
245 return 0;
246 case AP_CONN_STATE_SOCKS_WAIT:
247 case AP_CONN_STATE_RENDDESC_WAIT:
248 case AP_CONN_STATE_CIRCUIT_WAIT:
249 case AP_CONN_STATE_CONNECT_WAIT:
250 case AP_CONN_STATE_CONTROLLER_WAIT:
251 connection_stop_writing(conn);
252 return 0;
253 default:
254 warn(LD_BUG,"BUG: called in unexpected state %d.", conn->state);
255 tor_fragile_assert();
256 return -1;
258 return 0;
261 /** Connected handler for exit connections: start writing pending
262 * data, deliver 'CONNECTED' relay cells as appropriate, and check
263 * any pending data that may have been received. */
265 connection_edge_finished_connecting(connection_t *conn)
267 char valbuf[INET_NTOA_BUF_LEN];
268 struct in_addr in;
270 tor_assert(conn);
271 tor_assert(conn->type == CONN_TYPE_EXIT);
272 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
274 in.s_addr = htonl(conn->addr);
275 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
276 info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
277 safe_str(conn->address),conn->port,safe_str(valbuf));
279 conn->state = EXIT_CONN_STATE_OPEN;
280 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
281 if (connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
282 connection_start_writing(conn);
283 /* deliver a 'connected' relay cell back through the circuit. */
284 if (connection_edge_is_rendezvous_stream(conn)) {
285 if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
286 RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
287 return 0; /* circuit is closed, don't continue */
288 } else {
289 char connected_payload[8];
290 set_uint32(connected_payload, htonl(conn->addr));
291 set_uint32(connected_payload+4,
292 htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
293 if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
294 RELAY_COMMAND_CONNECTED, connected_payload, 8, conn->cpath_layer) < 0)
295 return 0; /* circuit is closed, don't continue */
297 tor_assert(conn->package_window > 0);
298 /* in case the server has written anything */
299 return connection_edge_process_inbuf(conn, 1);
302 /** Find all general-purpose AP streams waiting for a response that sent
303 * their begin/resolve cell >=15 seconds ago. Detach from their current circuit,
304 * and mark their current circuit as unsuitable for new streams. Then call
305 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
306 * available) or launch a new one.
308 * For rendezvous streams, simply give up after 45 seconds (with no
309 * retry attempt).
311 void
312 connection_ap_expire_beginning(void)
314 connection_t **carray;
315 connection_t *conn;
316 circuit_t *circ;
317 int n, i;
318 time_t now = time(NULL);
319 or_options_t *options = get_options();
321 get_connection_array(&carray, &n);
323 for (i = 0; i < n; ++i) {
324 conn = carray[i];
325 if (conn->type != CONN_TYPE_AP)
326 continue;
327 if (conn->state == AP_CONN_STATE_CONTROLLER_WAIT) {
328 if (now - conn->timestamp_lastread >= 120) {
329 notice(LD_APP, "Closing unattached stream.");
330 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
332 continue;
335 else if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
336 conn->state != AP_CONN_STATE_CONNECT_WAIT)
337 continue;
338 if (now - conn->timestamp_lastread < 15)
339 continue;
340 circ = circuit_get_by_edge_conn(conn);
341 if (!circ) { /* it's vanished? */
342 info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
343 safe_str(conn->socks_request->address));
344 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
345 continue;
347 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
348 if (now - conn->timestamp_lastread > 45) {
349 notice(LD_REND,"Rend stream is %d seconds late. Giving up on address '%s.onion'.",
350 (int)(now - conn->timestamp_lastread),
351 safe_str(conn->socks_request->address));
352 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
353 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
355 continue;
357 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
358 notice(LD_APP,"We tried for %d seconds to connect to '%s'. Retrying on a new circuit.",
359 (int)(now - conn->timestamp_lastread),
360 safe_str(conn->socks_request->address));
361 /* send an end down the circuit */
362 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
363 /* un-mark it as ending, since we're going to reuse it */
364 conn->has_sent_end = 0;
365 /* kludge to make us not try this circuit again, yet to allow
366 * current streams on it to survive if they can: make it
367 * unattractive to use for new streams */
368 tor_assert(circ->timestamp_dirty);
369 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
370 /* give our stream another 15 seconds to try */
371 conn->timestamp_lastread += 15;
372 /* move it back into 'pending' state, and try to attach. */
373 if (connection_ap_detach_retriable(conn, circ)<0) {
374 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
376 } /* end for */
379 /** Tell any AP streams that are waiting for a new circuit that one is
380 * available.
382 void
383 connection_ap_attach_pending(void)
385 connection_t **carray;
386 connection_t *conn;
387 int n, i;
389 get_connection_array(&carray, &n);
391 for (i = 0; i < n; ++i) {
392 conn = carray[i];
393 if (conn->marked_for_close ||
394 conn->type != CONN_TYPE_AP ||
395 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
396 continue;
397 if (connection_ap_handshake_attach_circuit(conn) < 0) {
398 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
403 /** The AP connection <b>conn</b> has just failed while attaching or
404 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
405 * might work. Detach the circuit, and either reattach it, launch a
406 * new circuit, tell the controller, or give up as a appropriate.
408 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
411 connection_ap_detach_retriable(connection_t *conn, circuit_t *circ)
413 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE);
414 conn->timestamp_lastread = time(NULL);
415 if (! get_options()->LeaveStreamsUnattached) {
416 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
417 circuit_detach_stream(circ,conn);
418 return connection_ap_handshake_attach_circuit(conn);
419 } else {
420 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
421 circuit_detach_stream(circ,conn);
422 return 0;
426 /** A client-side struct to remember requests to rewrite addresses
427 * to new addresses. These structs are stored in the hash table
428 * "addressmap" below.
430 * There are 5 ways to set an address mapping:
431 * - A MapAddress command from the controller [permanent]
432 * - An AddressMap directive in the torrc [permanent]
433 * - When a TrackHostExits torrc directive is triggered [temporary]
434 * - When a dns resolve succeeds [temporary]
435 * - When a dns resolve fails [temporary]
437 * When an addressmap request is made but one is already registered,
438 * the new one is replaced only if the currently registered one has
439 * no "new_address" (that is, it's in the process of dns resolve),
440 * or if the new one is permanent (expires==0 or 1).
442 * (We overload the 'expires' field, using "0" for mappings set via
443 * the configuration file, "1" for mappings set from the control
444 * interface, and other values for DNS mappings that can expire.)
446 typedef struct {
447 char *new_address;
448 time_t expires;
449 int num_resolve_failures;
450 } addressmap_entry_t;
452 /** Entry for mapping addresses to which virtual address we mapped them to. */
453 typedef struct {
454 char *ipv4_address;
455 char *hostname_address;
456 } virtaddress_entry_t;
458 /** A hash table to store client-side address rewrite instructions. */
459 static strmap_t *addressmap=NULL;
461 * Table mapping addresses to which virtual address, if any, we
462 * assigned them to.
464 * We maintain the following invariant: if [A,B] is in
465 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
466 * must be in addressmap. We do not require that the converse hold:
467 * if it fails, then we could end up mapping two virtual addresses to
468 * the same address, which is no disaster.
470 static strmap_t *virtaddress_reversemap=NULL;
472 /** Initialize addressmap. */
473 void
474 addressmap_init(void)
476 addressmap = strmap_new();
477 virtaddress_reversemap = strmap_new();
480 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
481 static void
482 addressmap_ent_free(void *_ent)
484 addressmap_entry_t *ent = _ent;
485 tor_free(ent->new_address);
486 tor_free(ent);
489 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
490 static void
491 addressmap_virtaddress_ent_free(void *_ent)
493 virtaddress_entry_t *ent = _ent;
494 tor_free(ent->ipv4_address);
495 tor_free(ent->hostname_address);
496 tor_free(ent);
499 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
500 static void
501 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
503 if (ent && ent->new_address && address_is_in_virtual_range(ent->new_address)) {
504 virtaddress_entry_t *ve =
505 strmap_get(virtaddress_reversemap, ent->new_address);
506 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
507 if (ve) {
508 if (!strcmp(address, ve->ipv4_address))
509 tor_free(ve->ipv4_address);
510 if (!strcmp(address, ve->hostname_address))
511 tor_free(ve->hostname_address);
512 if (!ve->ipv4_address && !ve->hostname_address) {
513 tor_free(ve);
514 strmap_remove(virtaddress_reversemap, ent->new_address);
520 /* DOCDOC */
521 static void
522 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
524 addressmap_virtaddress_remove(address, ent);
525 addressmap_ent_free(ent);
528 /** Remove all entries from the addressmap that were set via the
529 * configuration file or the command line. */
530 void
531 addressmap_clear_configured(void)
533 addressmap_get_mappings(NULL, 0, 0);
536 /** Remove all entries from the addressmap that are set to expire, ever. */
537 void
538 addressmap_clear_transient(void)
540 addressmap_get_mappings(NULL, 2, TIME_MAX);
543 /** Clean out entries from the addressmap cache that were
544 * added long enough ago that they are no longer valid.
546 void
547 addressmap_clean(time_t now)
549 addressmap_get_mappings(NULL, 2, now);
552 /** Free all the elements in the addressmap, and free the addressmap
553 * itself. */
554 void
555 addressmap_free_all(void)
557 if (addressmap) {
558 strmap_free(addressmap, addressmap_ent_free);
559 addressmap = NULL;
561 if (virtaddress_reversemap) {
562 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
563 virtaddress_reversemap = NULL;
567 /** Look at address, and rewrite it until it doesn't want any
568 * more rewrites; but don't get into an infinite loop.
569 * Don't write more than maxlen chars into address.
571 void
572 addressmap_rewrite(char *address, size_t maxlen)
574 addressmap_entry_t *ent;
575 int rewrites;
577 for (rewrites = 0; rewrites < 16; rewrites++) {
578 ent = strmap_get(addressmap, address);
580 if (!ent || !ent->new_address)
581 return; /* done, no rewrite needed */
583 info(LD_APP, "Addressmap: rewriting '%s' to '%s'",
584 safe_str(address), safe_str(ent->new_address));
585 strlcpy(address, ent->new_address, maxlen);
587 warn(LD_CONFIG,"Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
588 safe_str(address));
589 /* it's fine to rewrite a rewrite, but don't loop forever */
592 /** Return 1 if <b>address</b> is already registered, else return 0 */
594 addressmap_already_mapped(const char *address)
596 return strmap_get(addressmap, address) ? 1 : 0;
599 /** Register a request to map <b>address</b> to <b>new_address</b>,
600 * which will expire on <b>expires</b> (or 0 if never expires from
601 * config file, 1 if never expires from controller, 2 if never expires
602 * (virtual address mapping) from the controller.)
604 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
605 * free as appropriate. We will leave address alone.
607 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
608 * any mappings that exist from <b>address</b>.
610 void
611 addressmap_register(const char *address, char *new_address, time_t expires)
613 addressmap_entry_t *ent;
615 ent = strmap_get(addressmap, address);
616 if (!new_address || !strcasecmp(address,new_address)) {
617 /* Remove the mapping, if any. */
618 tor_free(new_address);
619 if (ent) {
620 addressmap_ent_remove(address,ent);
621 strmap_remove(addressmap, address);
623 return;
625 if (!ent) { /* make a new one and register it */
626 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
627 strmap_set(addressmap, address, ent);
628 } else if (ent->new_address) { /* we need to clean up the old mapping. */
629 if (expires > 1) {
630 info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, since it's already mapped to '%s'",
631 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
632 tor_free(new_address);
633 return;
635 if (address_is_in_virtual_range(ent->new_address) &&
636 expires != 2) {
637 /* XXX This isn't the perfect test; we want to avoid removing
638 * mappings set from the control interface _as virtual mapping */
639 addressmap_virtaddress_remove(address, ent);
641 tor_free(ent->new_address);
642 } /* else { we have an in-progress resolve with no mapping. } */
644 ent->new_address = new_address;
645 ent->expires = expires==2 ? 1 : expires;
646 ent->num_resolve_failures = 0;
648 info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
649 safe_str(address), safe_str(ent->new_address));
650 control_event_address_mapped(address, ent->new_address, expires);
653 /** An attempt to resolve <b>address</b> failed at some OR.
654 * Increment the number of resolve failures we have on record
655 * for it, and then return that number.
658 client_dns_incr_failures(const char *address)
660 addressmap_entry_t *ent = strmap_get(addressmap, address);
661 if (!ent) {
662 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
663 ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
664 strmap_set(addressmap,address,ent);
666 ++ent->num_resolve_failures;
667 info(LD_APP, "Address %s now has %d resolve failures.",
668 safe_str(address), ent->num_resolve_failures);
669 return ent->num_resolve_failures;
672 /** If <b>address</b> is in the client dns addressmap, reset
673 * the number of resolve failures we have on record for it.
674 * This is used when we fail a stream because it won't resolve:
675 * otherwise future attempts on that address will only try once.
677 void
678 client_dns_clear_failures(const char *address)
680 addressmap_entry_t *ent = strmap_get(addressmap, address);
681 if (ent)
682 ent->num_resolve_failures = 0;
685 /** Record the fact that <b>address</b> resolved to <b>val</b>.
686 * We can now use this in subsequent streams via addressmap_rewrite()
687 * so we can more correctly choose an exit that will allow <b>address</b>.
689 * If <b>exitname</b> is defined, then append the addresses with
690 * ".exitname.exit" before registering the mapping.
692 * If <b>ttl</b> is nonnegative, the mapping will be valid for
693 * <b>ttl</b>seconds.
695 void
696 client_dns_set_addressmap(const char *address, uint32_t val, const char *exitname,
697 int ttl)
699 struct in_addr in;
700 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
701 char valbuf[INET_NTOA_BUF_LEN];
702 char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
704 tor_assert(address); tor_assert(val);
706 if (ttl<0 || ttl>MAX_DNS_ENTRY_AGE)
707 ttl = MAX_DNS_ENTRY_AGE;
709 if (tor_inet_aton(address, &in))
710 return; /* If address was an IP address already, don't add a mapping. */
711 in.s_addr = htonl(val);
712 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
713 if (exitname) {
714 tor_snprintf(extendedaddress, sizeof(extendedaddress),
715 "%s.%s.exit", address, exitname);
716 tor_snprintf(extendedval, sizeof(extendedval),
717 "%s.%s.exit", valbuf, exitname);
718 } else {
719 tor_snprintf(extendedaddress, sizeof(extendedaddress),
720 "%s", address);
721 tor_snprintf(extendedval, sizeof(extendedval),
722 "%s", valbuf);
724 addressmap_register(extendedaddress, tor_strdup(extendedval), time(NULL) + ttl);
727 /* Currently, we hand out 127.192.0.1 through 127.254.254.254.
728 * These addresses should map to localhost, so even if the
729 * application accidentally tried to connect to them directly (not
730 * via Tor), it wouldn't get too far astray.
732 * Eventually, we should probably make this configurable.
734 #define MIN_UNUSED_IPV4 0x7fc00001u
735 #define MAX_UNUSED_IPV4 0x7ffefefeu
738 * Return true iff <b>addr</b> is likely to have been returned by
739 * client_dns_get_unused_address.
742 address_is_in_virtual_range(const char *address)
744 struct in_addr in;
745 tor_assert(address);
746 if (!strcasecmpend(address, ".virtual")) {
747 return 1;
748 } else if (tor_inet_aton(address, &in)) {
749 uint32_t addr = ntohl(in.s_addr);
750 if (addr >= MIN_UNUSED_IPV4 && addr <= MAX_UNUSED_IPV4)
751 return 1;
753 return 0;
756 /** Return a newly allocated string holding an address of <b>type</b>
757 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
758 * and that is very unlikely to be the address of any real host.
760 static char *
761 addressmap_get_virtual_address(int type)
763 char buf[64];
764 static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
765 struct in_addr in;
767 if (type == RESOLVED_TYPE_HOSTNAME) {
768 char rand[10];
769 do {
770 crypto_rand(rand, sizeof(rand));
771 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
772 strlcat(buf, ".virtual", sizeof(buf));
773 } while (strmap_get(addressmap, buf));
774 return tor_strdup(buf);
775 } else if (type == RESOLVED_TYPE_IPV4) {
776 while (1) {
777 /* Don't hand out any .0 or .255 address. */
778 while ((next_ipv4 & 0xff) == 0 ||
779 (next_ipv4 & 0xff) == 0xff)
780 ++next_ipv4;
781 in.s_addr = htonl(next_ipv4);
782 tor_inet_ntoa(&in, buf, sizeof(buf));
783 if (!strmap_get(addressmap, buf))
784 break;
786 ++next_ipv4;
787 if (next_ipv4 > MAX_UNUSED_IPV4)
788 next_ipv4 = MIN_UNUSED_IPV4;
790 return tor_strdup(buf);
791 } else {
792 warn(LD_BUG, "Called with unsupported address type (%d)", type);
793 return NULL;
797 /** A controller has requested that we map some address of type
798 * <b>type</b> to the address <b>new_address</b>. Choose an address
799 * that is unlikely to be used, and map it, and return it in a newly
800 * allocated string. If another address of the same type is already
801 * mapped to <b>new_address</b>, try to return a copy of that address.
803 * The string in <b>new_address</b> may be freed, or inserted into a map
804 * as appropriate.
806 const char *
807 addressmap_register_virtual_address(int type, char *new_address)
809 char **addrp;
810 virtaddress_entry_t *vent;
812 tor_assert(new_address);
813 tor_assert(addressmap);
814 tor_assert(virtaddress_reversemap);
816 vent = strmap_get(virtaddress_reversemap, new_address);
817 if (!vent) {
818 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
819 strmap_set(virtaddress_reversemap, new_address, vent);
822 addrp = (type == RESOLVED_TYPE_IPV4) ?
823 &vent->ipv4_address : &vent->hostname_address;
824 if (*addrp) {
825 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
826 if (ent && ent->new_address && !strcasecmp(new_address, ent->new_address)) {
827 tor_free(new_address);
828 return tor_strdup(*addrp);
829 } else
830 warn(LD_BUG, "Internal confusion: I thought that '%s' was mapped to by '%s', but '%s' really maps to '%s'. This is a harmless bug.",
831 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
832 ent?safe_str(ent->new_address):"(nothing)");
835 tor_free(*addrp);
836 *addrp = addressmap_get_virtual_address(type);
837 addressmap_register(*addrp, new_address, 2);
839 #if 0
841 /* Try to catch possible bugs */
842 addressmap_entry_t *ent;
843 ent = strmap_get(addressmap, *addrp);
844 tor_assert(ent);
845 tor_assert(!strcasecmp(ent->new_address,new_address));
846 vent = strmap_get(virtaddress_reversemap, new_address);
847 tor_assert(vent);
848 tor_assert(!strcasecmp(*addrp,
849 (type == RESOLVED_TYPE_IPV4) ?
850 vent->ipv4_address : vent->hostname_address));
851 log_fn(LOG_INFO, "Map from %s to %s okay.",
852 safe_str(*addrp),safe_str(new_address));
854 #endif
856 return *addrp;
859 /** Return 1 if <b>address</b> has funny characters in it like
860 * colons. Return 0 if it's fine.
862 static int
863 address_is_invalid_destination(const char *address)
865 /* FFFF should flesh this out */
866 if (strchr(address,':'))
867 return 1;
868 return 0;
871 /** Iterate over all address mapings which have expiry times between
872 * min_expires and max_expires, inclusive. If sl is provided, add an
873 * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
874 * remove the mappings.
876 void
877 addressmap_get_mappings(smartlist_t *sl, time_t min_expires, time_t max_expires)
879 strmap_iter_t *iter;
880 const char *key;
881 void *_val;
882 addressmap_entry_t *val;
884 if (!addressmap)
885 addressmap_init();
887 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
888 strmap_iter_get(iter, &key, &_val);
889 val = _val;
890 if (val->expires >= min_expires && val->expires <= max_expires) {
891 if (!sl) {
892 iter = strmap_iter_next_rmv(addressmap,iter);
893 addressmap_ent_remove(key, val);
894 continue;
895 } else if (val->new_address) {
896 size_t len = strlen(key)+strlen(val->new_address)+2;
897 char *line = tor_malloc(len);
898 tor_snprintf(line, len, "%s %s", key, val->new_address);
899 smartlist_add(sl, line);
902 iter = strmap_iter_next(addressmap,iter);
906 /** connection_edge_process_inbuf() found a conn in state
907 * socks_wait. See if conn->inbuf has the right bytes to proceed with
908 * the socks handshake.
910 * If the handshake is complete, and it's for a general circuit, then
911 * try to attach it to a circuit (or launch one as needed). If it's for
912 * a rendezvous circuit, then fetch a rendezvous descriptor first (or
913 * attach/launch a circuit if the rendezvous descriptor is already here
914 * and fresh enough).
916 * Return -1 if an unexpected error with conn (and it should be marked
917 * for close), else return 0.
919 static int
920 connection_ap_handshake_process_socks(connection_t *conn)
922 socks_request_t *socks;
923 int sockshere;
924 hostname_type_t addresstype;
925 or_options_t *options = get_options();
926 int tor_should_handle_stream = !options->LeaveStreamsUnattached;
928 tor_assert(conn);
929 tor_assert(conn->type == CONN_TYPE_AP);
930 tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
931 tor_assert(conn->socks_request);
932 socks = conn->socks_request;
934 debug(LD_APP,"entered.");
936 sockshere = fetch_from_buf_socks(conn->inbuf, socks, options->TestSocks);
937 if (sockshere == 0) {
938 if (socks->replylen) {
939 connection_write_to_buf(socks->reply, socks->replylen, conn);
940 socks->replylen = 0; /* zero it out so we can do another round of negotiation */
941 } else {
942 debug(LD_APP,"socks handshake not all here yet.");
944 return 0;
945 } else if (sockshere == -1) {
946 if (socks->replylen) { /* we should send reply back */
947 debug(LD_APP,"reply is already set for us. Using it.");
948 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
949 SOCKS5_GENERAL_ERROR);
950 } else {
951 warn(LD_APP,"Fetching socks handshake failed. Closing.");
952 connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
954 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
955 return -1;
956 } /* else socks handshake is done, continue processing */
958 tor_strlower(socks->address); /* normalize it */
959 debug(LD_APP,"Client asked for %s:%d", safe_str(socks->address),
960 socks->port);
962 /* For address map controls, remap the address */
963 addressmap_rewrite(socks->address, sizeof(socks->address));
965 if (tor_should_handle_stream &&
966 address_is_in_virtual_range(socks->address)) {
967 /* This address was probably handed out by client_dns_get_unmapped_address,
968 * but the mapping was discarded for some reason. We *don't* want to send
969 * the address through tor; that's likely to fail, and may leak
970 * information.
972 warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
973 socks->address); /* don't safe_str() this yet. */
974 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
975 return -1;
978 /* Parse the address provided by SOCKS. Modify it in-place if it
979 * specifies a hidden-service (.onion) or particular exit node (.exit).
981 addresstype = parse_extended_hostname(socks->address);
983 if (tor_should_handle_stream && addresstype == BAD_HOSTNAME) {
984 warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
985 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
986 return -1;
989 if (addresstype == EXIT_HOSTNAME) {
990 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
991 * node, and conn->address to hold only the address portion.*/
992 char *s = strrchr(socks->address,'.');
993 if (s) {
994 if (s[1] != '\0') {
995 conn->chosen_exit_name = tor_strdup(s+1);
996 *s = 0;
997 } else {
998 warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
999 safe_str(socks->address));
1000 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1001 return -1;
1003 } else {
1004 struct in_addr in;
1005 conn->chosen_exit_name = tor_strdup(socks->address);
1006 *socks->address = 0;
1007 routerinfo_t *r = router_get_by_nickname(conn->chosen_exit_name, 1);
1008 if (r) {
1009 /* XXXX Should this use server->address instead? */
1010 in.s_addr = htonl(r->addr);
1011 strlcpy(socks->address, inet_ntoa(in), sizeof(socks->address));
1012 } else if (tor_should_handle_stream) {
1013 warn(LD_APP,
1014 "Unrecognized server in exit address '%s.exit'. Refusing.",
1015 safe_str(socks->address));
1016 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1017 return -1;
1022 if (addresstype != ONION_HOSTNAME) {
1023 /* not a hidden-service request (i.e. normal or .exit) */
1025 if (tor_should_handle_stream &&
1026 address_is_invalid_destination(socks->address)) {
1027 warn(LD_APP,"Destination '%s' seems to be an invalid hostname. Failing.",
1028 safe_str(socks->address));
1029 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1030 return -1;
1033 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1034 uint32_t answer;
1035 struct in_addr in;
1036 /* Reply to resolves immediately if we can. */
1037 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1038 warn(LD_APP,"Address to be resolved is too large. Failing.");
1039 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL,-1);
1040 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1041 return -1;
1043 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1044 answer = in.s_addr; /* leave it in network order */
1045 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1046 (char*)&answer,-1);
1047 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1048 return 0;
1050 rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
1051 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE);
1052 } else { /* socks->command == SOCKS_COMMAND_CONNECT */
1053 if (socks->port == 0) {
1054 notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1055 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1056 return -1;
1059 if (!conn->chosen_exit_name) {
1060 /* see if we can find a suitable enclave exit */
1061 routerinfo_t *r =
1062 router_find_exact_exit_enclave(socks->address, socks->port);
1063 if (r) {
1064 info(LD_APP,"Redirecting address %s to exit at enclave router %s",
1065 safe_str(socks->address), r->nickname);
1066 /* use the hex digest, not nickname, in case there are two
1067 routers with this nickname */
1068 conn->chosen_exit_name =
1069 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1073 rep_hist_note_used_port(socks->port, time(NULL)); /* help predict this next time */
1074 control_event_stream_status(conn, STREAM_EVENT_NEW);
1076 if (!tor_should_handle_stream) {
1077 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
1078 } else {
1079 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1080 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1081 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1082 return -1;
1085 return 0;
1086 } else {
1087 /* it's a hidden-service request */
1088 rend_cache_entry_t *entry;
1089 int r;
1091 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1092 /* if it's a resolve request, fail it right now, rather than
1093 * building all the circuits and then realizing it won't work. */
1094 warn(LD_APP,"Resolve requests to hidden services not allowed. Failing.");
1095 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL,-1);
1096 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1097 return -1;
1100 strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
1101 info(LD_REND,"Got a hidden service request for ID '%s'",
1102 safe_str(conn->rend_query));
1103 /* see if we already have it cached */
1104 r = rend_cache_lookup_entry(conn->rend_query, -1, &entry);
1105 if (r<0) {
1106 warn(LD_REND,"Invalid service descriptor %s",
1107 safe_str(conn->rend_query));
1108 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1109 return -1;
1111 if (r==0) {
1112 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1113 info(LD_REND, "Unknown descriptor %s. Fetching.",
1114 safe_str(conn->rend_query));
1115 rend_client_refetch_renddesc(conn->rend_query);
1116 return 0;
1118 if (r>0) {
1119 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
1120 if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
1121 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1122 info(LD_REND, "Descriptor is here and fresh enough. Great.");
1123 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1124 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1125 return -1;
1127 return 0;
1128 } else {
1129 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1130 info(LD_REND, "Stale descriptor %s. Refetching.",
1131 safe_str(conn->rend_query));
1132 rend_client_refetch_renddesc(conn->rend_query);
1133 return 0;
1137 return 0; /* unreached but keeps the compiler happy */
1140 /** Iterate over the two bytes of stream_id until we get one that is not
1141 * already in use; return it. Return 0 if can't get a unique stream_id.
1143 static uint16_t
1144 get_unique_stream_id_by_circ(circuit_t *circ)
1146 connection_t *tmpconn;
1147 uint16_t test_stream_id;
1148 uint32_t attempts=0;
1150 again:
1151 test_stream_id = circ->next_stream_id++;
1152 if (++attempts > 1<<16) {
1153 /* Make sure we don't loop forever if all stream_id's are used. */
1154 warn(LD_APP,"No unused stream IDs. Failing.");
1155 return 0;
1157 if (test_stream_id == 0)
1158 goto again;
1159 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
1160 if (tmpconn->stream_id == test_stream_id)
1161 goto again;
1162 return test_stream_id;
1165 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1166 * socks_request field, and send it down circ.
1168 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1171 connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
1173 char payload[CELL_PAYLOAD_SIZE];
1174 int payload_len;
1176 tor_assert(ap_conn->type == CONN_TYPE_AP);
1177 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1178 tor_assert(ap_conn->socks_request);
1180 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1181 if (ap_conn->stream_id==0) {
1182 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1183 circuit_mark_for_close(circ);
1184 return -1;
1187 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
1188 (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
1189 ap_conn->socks_request->address : "",
1190 ap_conn->socks_request->port);
1191 payload_len = strlen(payload)+1;
1193 debug(LD_APP,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1195 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
1196 payload, payload_len, ap_conn->cpath_layer) < 0)
1197 return -1; /* circuit is closed, don't continue */
1199 ap_conn->package_window = STREAMWINDOW_START;
1200 ap_conn->deliver_window = STREAMWINDOW_START;
1201 ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
1202 info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
1203 ap_conn->s, circ->n_circ_id);
1204 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
1205 return 0;
1208 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1209 * socks_request field, and send it down circ.
1211 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1214 connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
1216 int payload_len;
1217 const char *string_addr;
1219 tor_assert(ap_conn->type == CONN_TYPE_AP);
1220 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1221 tor_assert(ap_conn->socks_request);
1222 tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
1223 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
1225 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1226 if (ap_conn->stream_id==0) {
1227 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1228 circuit_mark_for_close(circ);
1229 return -1;
1232 string_addr = ap_conn->socks_request->address;
1233 payload_len = strlen(string_addr)+1;
1234 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
1236 debug(LD_APP,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1238 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
1239 string_addr, payload_len, ap_conn->cpath_layer) < 0)
1240 return -1; /* circuit is closed, don't continue */
1242 ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
1243 info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
1244 ap_conn->s, circ->n_circ_id);
1245 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
1246 return 0;
1249 /** Make an AP connection_t, do a socketpair and attach one side
1250 * to the conn, connection_add it, initialize it to circuit_wait,
1251 * and call connection_ap_handshake_attach_circuit(conn) on it.
1253 * Return the other end of the socketpair, or -1 if error.
1256 connection_ap_make_bridge(char *address, uint16_t port)
1258 int fd[2];
1259 connection_t *conn;
1260 int err;
1262 info(LD_APP,"Making AP bridge to %s:%d ...",safe_str(address),port);
1264 if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
1265 warn(LD_NET,"Couldn't construct socketpair (%s). Network down? Delaying.",
1266 tor_socket_strerror(-err));
1267 return -1;
1270 set_socket_nonblocking(fd[0]);
1271 set_socket_nonblocking(fd[1]);
1273 conn = connection_new(CONN_TYPE_AP);
1274 conn->s = fd[0];
1276 /* populate conn->socks_request */
1278 /* leave version at zero, so the socks_reply is empty */
1279 conn->socks_request->socks_version = 0;
1280 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
1281 strlcpy(conn->socks_request->address, address,
1282 sizeof(conn->socks_request->address));
1283 conn->socks_request->port = port;
1284 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
1286 conn->address = tor_strdup("(local bridge)");
1287 conn->addr = 0;
1288 conn->port = 0;
1290 if (connection_add(conn) < 0) { /* no space, forget it */
1291 connection_free(conn); /* this closes fd[0] */
1292 tor_close_socket(fd[1]);
1293 return -1;
1296 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1297 connection_start_reading(conn);
1299 /* attaching to a dirty circuit is fine */
1300 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1301 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1302 tor_close_socket(fd[1]);
1303 return -1;
1306 info(LD_APP,"... AP bridge created and connected.");
1307 return fd[1];
1310 /** Send an answer to an AP connection that has requested a DNS lookup
1311 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6) or
1312 * -1 for unreachable; the answer should be in the format specified
1313 * in the socks extensions document.
1315 void
1316 connection_ap_handshake_socks_resolved(connection_t *conn,
1317 int answer_type,
1318 size_t answer_len,
1319 const char *answer,
1320 int ttl)
1322 char buf[256];
1323 size_t replylen;
1325 if (answer_type == RESOLVED_TYPE_IPV4) {
1326 uint32_t a = ntohl(get_uint32(answer));
1327 if (a)
1328 client_dns_set_addressmap(conn->socks_request->address, a,
1329 conn->chosen_exit_name, ttl);
1332 if (conn->socks_request->socks_version == 4) {
1333 buf[0] = 0x00; /* version */
1334 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1335 buf[1] = 90; /* "Granted" */
1336 set_uint16(buf+2, 0);
1337 memcpy(buf+4, answer, 4); /* address */
1338 replylen = SOCKS4_NETWORK_LEN;
1339 } else {
1340 buf[1] = 91; /* "error" */
1341 memset(buf+2, 0, 6);
1342 replylen = SOCKS4_NETWORK_LEN;
1344 } else {
1345 /* SOCKS5 */
1346 buf[0] = 0x05; /* version */
1347 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1348 buf[1] = SOCKS5_SUCCEEDED;
1349 buf[2] = 0; /* reserved */
1350 buf[3] = 0x01; /* IPv4 address type */
1351 memcpy(buf+4, answer, 4); /* address */
1352 set_uint16(buf+8, 0); /* port == 0. */
1353 replylen = 10;
1354 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
1355 buf[1] = SOCKS5_SUCCEEDED;
1356 buf[2] = 0; /* reserved */
1357 buf[3] = 0x04; /* IPv6 address type */
1358 memcpy(buf+4, answer, 16); /* address */
1359 set_uint16(buf+20, 0); /* port == 0. */
1360 replylen = 22;
1361 } else {
1362 buf[1] = SOCKS5_HOST_UNREACHABLE;
1363 memset(buf+2, 0, 8);
1364 replylen = 10;
1367 connection_ap_handshake_socks_reply(conn, buf, replylen,
1368 (answer_type == RESOLVED_TYPE_IPV4 ||
1369 answer_type == RESOLVED_TYPE_IPV6) ?
1370 SOCKS5_SUCCEEDED : SOCKS5_HOST_UNREACHABLE);
1373 /** Send a socks reply to stream <b>conn</b>, using the appropriate
1374 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
1375 * handshaking.
1377 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
1378 * to conn and return, else reply based on <b>status</b>.
1380 * If <b>reply</b> is undefined, <b>status</b> can't be 0.
1382 void
1383 connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
1384 size_t replylen,
1385 socks5_reply_status_t status) {
1386 char buf[256];
1387 tor_assert(conn->socks_request); /* make sure it's an AP stream */
1389 control_event_stream_status(conn,
1390 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
1392 if (conn->socks_request->has_finished) {
1393 warn(LD_BUG, "Harmless bug: duplicate calls to connection_ap_handshake_socks_reply.");
1394 return;
1396 if (replylen) { /* we already have a reply in mind */
1397 connection_write_to_buf(reply, replylen, conn);
1398 conn->socks_request->has_finished = 1;
1399 return;
1401 if (conn->socks_request->socks_version == 4) {
1402 memset(buf,0,SOCKS4_NETWORK_LEN);
1403 #define SOCKS4_GRANTED 90
1404 #define SOCKS4_REJECT 91
1405 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
1406 /* leave version, destport, destip zero */
1407 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
1408 } else if (conn->socks_request->socks_version == 5) {
1409 buf[0] = 5; /* version 5 */
1410 buf[1] = (char)status;
1411 buf[2] = 0;
1412 buf[3] = 1; /* ipv4 addr */
1413 memset(buf+4,0,6); /* Set external addr/port to 0.
1414 The spec doesn't seem to say what to do here. -RD */
1415 connection_write_to_buf(buf,10,conn);
1417 /* If socks_version isn't 4 or 5, don't send anything.
1418 * This can happen in the case of AP bridges. */
1419 conn->socks_request->has_finished = 1;
1420 return;
1423 /** A relay 'begin' cell has arrived, and either we are an exit hop
1424 * for the circuit, or we are the origin and it is a rendezvous begin.
1426 * Launch a new exit connection and initialize things appropriately.
1428 * If it's a rendezvous stream, call connection_exit_connect() on
1429 * it.
1431 * For general streams, call dns_resolve() on it first, and only call
1432 * connection_exit_connect() if the dns answer is already known.
1434 * Note that we don't call connection_add() on the new stream! We wait
1435 * for connection_exit_connect() to do that.
1437 * Return -1 if we want to tear down <b>circ</b>. Else return 0.
1440 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
1442 connection_t *n_stream;
1443 relay_header_t rh;
1444 char *address=NULL;
1445 uint16_t port;
1447 assert_circuit_ok(circ);
1448 relay_header_unpack(&rh, cell->payload);
1450 /* XXX currently we don't send an end cell back if we drop the
1451 * begin because it's malformed.
1454 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
1455 warn(LD_PROTOCOL,"relay begin cell has no \\0. Dropping.");
1456 return 0;
1458 if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
1459 warn(LD_PROTOCOL,"Unable to parse addr:port in relay begin cell. Dropping.");
1460 return 0;
1462 if (port==0) {
1463 warn(LD_PROTOCOL,"Missing port in relay begin cell. Dropping.");
1464 tor_free(address);
1465 return 0;
1468 debug(LD_EXIT,"Creating new exit connection.");
1469 n_stream = connection_new(CONN_TYPE_EXIT);
1470 n_stream->purpose = EXIT_PURPOSE_CONNECT;
1472 n_stream->stream_id = rh.stream_id;
1473 n_stream->port = port;
1474 /* leave n_stream->s at -1, because it's not yet valid */
1475 n_stream->package_window = STREAMWINDOW_START;
1476 n_stream->deliver_window = STREAMWINDOW_START;
1478 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1479 debug(LD_REND,"begin is for rendezvous. configuring stream.");
1480 n_stream->address = tor_strdup("(rendezvous)");
1481 n_stream->state = EXIT_CONN_STATE_CONNECTING;
1482 strlcpy(n_stream->rend_query, circ->rend_query,
1483 sizeof(n_stream->rend_query));
1484 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
1485 assert_circuit_ok(circ);
1486 if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
1487 info(LD_REND,"Didn't find rendezvous service (port %d)",n_stream->port);
1488 connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
1489 connection_free(n_stream);
1490 circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
1491 tor_free(address);
1492 return 0;
1494 assert_circuit_ok(circ);
1495 debug(LD_REND,"Finished assigning addr/port");
1496 n_stream->cpath_layer = circ->cpath->prev; /* link it */
1498 /* add it into the linked list of n_streams on this circuit */
1499 n_stream->next_stream = circ->n_streams;
1500 n_stream->on_circuit = circ;
1501 circ->n_streams = n_stream;
1502 assert_circuit_ok(circ);
1504 connection_exit_connect(n_stream);
1505 tor_free(address);
1506 return 0;
1508 tor_strlower(address);
1509 n_stream->address = address;
1510 n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
1511 /* default to failed, change in dns_resolve if it turns out not to fail */
1513 if (we_are_hibernating()) {
1514 connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING, n_stream->cpath_layer);
1515 connection_free(n_stream);
1516 return 0;
1519 /* send it off to the gethostbyname farm */
1520 switch (dns_resolve(n_stream)) {
1521 case 1: /* resolve worked */
1523 /* add it into the linked list of n_streams on this circuit */
1524 n_stream->next_stream = circ->n_streams;
1525 n_stream->on_circuit = circ;
1526 circ->n_streams = n_stream;
1527 assert_circuit_ok(circ);
1529 connection_exit_connect(n_stream);
1530 return 0;
1531 case -1: /* resolve failed */
1532 /* n_stream got freed. don't touch it. */
1533 break;
1534 case 0: /* resolve added to pending list */
1535 /* add it into the linked list of resolving_streams on this circuit */
1536 n_stream->next_stream = circ->resolving_streams;
1537 n_stream->on_circuit = circ;
1538 circ->resolving_streams = n_stream;
1539 assert_circuit_ok(circ);
1542 return 0;
1546 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
1547 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
1550 connection_exit_begin_resolve(cell_t *cell, circuit_t *circ)
1552 connection_t *dummy_conn;
1553 relay_header_t rh;
1555 assert_circuit_ok(circ);
1556 relay_header_unpack(&rh, cell->payload);
1558 /* This 'dummy_conn' only exists to remember the stream ID
1559 * associated with the resolve request; and to make the
1560 * implementation of dns.c more uniform. (We really only need to
1561 * remember the circuit, the stream ID, and the hostname to be
1562 * resolved; but if we didn't store them in a connection like this,
1563 * the housekeeping in dns.c would get way more complicated.)
1565 dummy_conn = connection_new(CONN_TYPE_EXIT);
1566 dummy_conn->stream_id = rh.stream_id;
1567 dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
1568 rh.length);
1569 dummy_conn->port = 0;
1570 dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
1571 dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
1573 /* send it off to the gethostbyname farm */
1574 switch (dns_resolve(dummy_conn)) {
1575 case -1: /* Impossible to resolve; a resolved cell was sent. */
1576 /* Connection freed; don't touch it. */
1577 return 0;
1578 case 1: /* The result was cached; a resolved cell was sent. */
1579 if (!dummy_conn->marked_for_close)
1580 connection_free(dummy_conn);
1581 return 0;
1582 case 0: /* resolve added to pending list */
1583 dummy_conn->next_stream = circ->resolving_streams;
1584 dummy_conn->on_circuit = circ;
1585 circ->resolving_streams = dummy_conn;
1586 assert_circuit_ok(circ);
1587 break;
1589 return 0;
1592 /** Connect to conn's specified addr and port. If it worked, conn
1593 * has now been added to the connection_array.
1595 * Send back a connected cell. Include the resolved IP of the destination
1596 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
1597 * streams must not reveal what IP they connected to.)
1599 void
1600 connection_exit_connect(connection_t *conn)
1602 uint32_t addr;
1603 uint16_t port;
1605 if (!connection_edge_is_rendezvous_stream(conn) &&
1606 router_compare_to_my_exit_policy(conn)) {
1607 info(LD_EXIT,"%s:%d failed exit policy. Closing.",
1608 safe_str(conn->address), conn->port);
1609 connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
1610 circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
1611 connection_free(conn);
1612 return;
1615 addr = conn->addr;
1616 port = conn->port;
1617 if (redirect_exit_list) {
1618 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
1620 if ((addr&r->mask)==(r->addr&r->mask) &&
1621 (r->port_min <= port) && (port <= r->port_max)) {
1622 struct in_addr in;
1623 if (r->is_redirect) {
1624 char tmpbuf[INET_NTOA_BUF_LEN];
1625 addr = r->addr_dest;
1626 port = r->port_dest;
1627 in.s_addr = htonl(addr);
1628 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
1629 debug(LD_EXIT, "Redirecting connection from %s:%d to %s:%d",
1630 safe_str(conn->address), conn->port, safe_str(tmpbuf), port);
1632 break;
1637 debug(LD_EXIT,"about to try connecting");
1638 switch (connection_connect(conn, conn->address, addr, port)) {
1639 case -1:
1640 connection_edge_end_errno(conn, conn->cpath_layer);
1641 circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
1642 connection_free(conn);
1643 return;
1644 case 0:
1645 conn->state = EXIT_CONN_STATE_CONNECTING;
1647 connection_watch_events(conn, EV_WRITE | EV_READ);
1648 /* writable indicates finish;
1649 * readable/error indicates broken link in windowsland. */
1650 return;
1651 /* case 1: fall through */
1654 conn->state = EXIT_CONN_STATE_OPEN;
1655 if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
1656 warn(LD_BUG,"Bug: newly connected conn had data waiting!");
1657 // connection_start_writing(conn);
1659 connection_watch_events(conn, EV_READ);
1661 /* also, deliver a 'connected' cell back through the circuit. */
1662 if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
1663 /* don't send an address back! */
1664 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
1665 RELAY_COMMAND_CONNECTED,
1666 NULL, 0, conn->cpath_layer);
1667 } else { /* normal stream */
1668 /* This must be the original address, not the redirected address. */
1669 char connected_payload[8];
1670 set_uint32(connected_payload, htonl(conn->addr));
1671 set_uint32(connected_payload+4,
1672 htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
1673 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
1674 RELAY_COMMAND_CONNECTED,
1675 connected_payload, 8, conn->cpath_layer);
1679 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
1680 * it is a general stream.
1683 connection_edge_is_rendezvous_stream(connection_t *conn)
1685 tor_assert(conn);
1686 if (*conn->rend_query) /* XXX */
1687 return 1;
1688 return 0;
1691 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
1692 * to exit from it, or 0 if it probably will not allow it.
1693 * (We might be uncertain if conn's destination address has not yet been
1694 * resolved.)
1697 connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
1699 tor_assert(conn);
1700 tor_assert(conn->type == CONN_TYPE_AP);
1701 tor_assert(conn->socks_request);
1702 tor_assert(exit);
1704 #if 0
1705 log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
1706 exit->nickname, safe_str(conn->socks_request->address),
1707 conn->socks_request->port);
1708 #endif
1710 /* If a particular exit node has been requested for the new connection,
1711 * make sure the exit node of the existing circuit matches exactly.
1713 if (conn->chosen_exit_name) {
1714 if (router_get_by_nickname(conn->chosen_exit_name, 1) != exit) {
1715 /* doesn't match */
1716 debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
1717 conn->chosen_exit_name, exit->nickname);
1718 return 0;
1722 if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
1723 struct in_addr in;
1724 uint32_t addr = 0;
1725 addr_policy_result_t r;
1726 if (tor_inet_aton(conn->socks_request->address, &in))
1727 addr = ntohl(in.s_addr);
1728 r = router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
1729 exit->exit_policy);
1730 if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
1731 return 0;
1733 return 1;
1736 /** A helper function for socks_policy_permits_address() below.
1738 * Parse options->SocksPolicy in the same way that the exit policy
1739 * is parsed, and put the processed version in socks_policy.
1740 * Ignore port specifiers.
1742 void
1743 parse_socks_policy(void)
1745 addr_policy_t *n;
1746 if (socks_policy) {
1747 addr_policy_free(socks_policy);
1748 socks_policy = NULL;
1750 config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy, -1);
1751 /* ports aren't used. */
1752 for (n=socks_policy; n; n = n->next) {
1753 n->prt_min = 1;
1754 n->prt_max = 65535;
1758 /** Free all storage held by our SOCKS allow policy
1760 void
1761 free_socks_policy(void)
1763 addr_policy_free(socks_policy);
1764 socks_policy = NULL;
1767 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1768 * based on <b>socks_policy</b>. Else return 0.
1771 socks_policy_permits_address(uint32_t addr)
1773 int a;
1775 if (!socks_policy) /* 'no socks policy' means 'accept' */
1776 return 1;
1777 a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
1778 if (a==ADDR_POLICY_REJECTED)
1779 return 0;
1780 else if (a==ADDR_POLICY_ACCEPTED)
1781 return 1;
1782 warn(LD_BUG, "Bug: Got unexpected 'maybe' answer from socks policy");
1783 return 0;
1786 /** Make connection redirection follow the provided list of
1787 * exit_redirect_t */
1788 void
1789 set_exit_redirects(smartlist_t *lst)
1791 if (redirect_exit_list) {
1792 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
1793 smartlist_free(redirect_exit_list);
1795 redirect_exit_list = lst;
1798 /** If address is of the form "y.onion" with a well-formed handle y:
1799 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
1801 * If address is of the form "y.exit":
1802 * Put a NUL after y and return EXIT_HOSTNAME.
1804 * Otherwise:
1805 * Return NORMAL_HOSTNAME and change nothing.
1807 hostname_type_t
1808 parse_extended_hostname(char *address)
1810 char *s;
1811 char query[REND_SERVICE_ID_LEN+1];
1813 s = strrchr(address,'.');
1814 if (!s) return 0; /* no dot, thus normal */
1815 if (!strcmp(s+1,"exit")) {
1816 *s = 0; /* null-terminate it */
1817 return EXIT_HOSTNAME; /* .exit */
1819 if (strcmp(s+1,"onion"))
1820 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1822 /* so it is .onion */
1823 *s = 0; /* null-terminate it */
1824 if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
1825 goto failed;
1826 if (rend_valid_service_id(query)) {
1827 return ONION_HOSTNAME; /* success */
1829 failed:
1830 /* otherwise, return to previous state and return 0 */
1831 *s = '.';
1832 return BAD_HOSTNAME;