Stupid cut-and-paste bug.
[tor.git] / src / or / connection_edge.c
blob29dcac32c2f6b04c1e4694c32da692badfbe4e12
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[] =
7 "$Id$";
9 /**
10 * \file connection_edge.c
11 * \brief Handle edge streams.
12 **/
14 #include "or.h"
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 /** An AP stream has failed/finished. If it hasn't already sent back
23 * a socks reply, send one now (based on endreason). Also set
24 * has_sent_end to 1, and mark the conn.
26 void
27 _connection_mark_unattached_ap(connection_t *conn, int endreason,
28 int line, const char *file)
30 tor_assert(conn->type == CONN_TYPE_AP);
31 conn->has_sent_end = 1; /* no circ yet */
33 if (conn->marked_for_close) {
34 /* This call will warn as appropriate. */
35 _connection_mark_for_close(conn, line, file);
36 return;
39 if (!conn->socks_request->has_finished) {
40 socks5_reply_status_t socksreason =
41 connection_edge_end_reason_socks5_response(endreason);
43 if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
44 warn(LD_BUG,"Bug: stream (marked at %s:%d) sending two socks replies?",
45 file, line);
47 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
48 connection_ap_handshake_socks_reply(conn, NULL, 0, socksreason);
49 else
50 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
51 0, NULL, -1);
54 _connection_mark_for_close(conn, line, file);
55 conn->hold_open_until_flushed = 1;
58 /** There was an EOF. Send an end and mark the connection for close.
60 int
61 connection_edge_reached_eof(connection_t *conn)
63 #ifdef HALF_OPEN
64 /* eof reached; we're done reading, but we might want to write more. */
65 conn->done_receiving = 1;
66 shutdown(conn->s, 0); /* XXX check return, refactor NM */
67 if (conn->done_sending) {
68 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
69 connection_mark_for_close(conn);
70 } else {
71 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
72 RELAY_COMMAND_END,
73 NULL, 0, conn->cpath_layer);
75 return 0;
76 #else
77 if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
78 /* it still has stuff to process. don't let it die yet. */
79 return 0;
81 info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->s);
82 if (!conn->marked_for_close) {
83 /* only mark it if not already marked. it's possible to
84 * get the 'end' right around when the client hangs up on us. */
85 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
86 if (conn->socks_request) /* eof, so don't send a socks reply back */
87 conn->socks_request->has_finished = 1;
88 connection_mark_for_close(conn);
90 return 0;
91 #endif
94 /** Handle new bytes on conn->inbuf based on state:
95 * - If it's waiting for socks info, try to read another step of the
96 * socks handshake out of conn->inbuf.
97 * - If it's open, then package more relay cells from the stream.
98 * - Else, leave the bytes on inbuf alone for now.
100 * Mark and return -1 if there was an unexpected error with the conn,
101 * else return 0.
104 connection_edge_process_inbuf(connection_t *conn, int package_partial)
106 tor_assert(conn);
107 tor_assert(CONN_IS_EDGE(conn));
109 switch (conn->state) {
110 case AP_CONN_STATE_SOCKS_WAIT:
111 if (connection_ap_handshake_process_socks(conn) < 0) {
112 /* already marked */
113 return -1;
115 return 0;
116 case AP_CONN_STATE_OPEN:
117 case EXIT_CONN_STATE_OPEN:
118 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
119 /* (We already sent an end cell if possible) */
120 connection_mark_for_close(conn);
121 return -1;
123 return 0;
124 case EXIT_CONN_STATE_CONNECTING:
125 case AP_CONN_STATE_RENDDESC_WAIT:
126 case AP_CONN_STATE_CIRCUIT_WAIT:
127 case AP_CONN_STATE_CONNECT_WAIT:
128 case AP_CONN_STATE_RESOLVE_WAIT:
129 case AP_CONN_STATE_CONTROLLER_WAIT:
130 info(LD_EDGE,"data from edge while in '%s' state. Leaving it on buffer.",
131 conn_state_to_string(conn->type, conn->state));
132 return 0;
134 warn(LD_BUG,"Bug: Got unexpected state %d. Closing.",conn->state);
135 tor_fragile_assert();
136 connection_edge_end(conn, END_STREAM_REASON_INTERNAL, conn->cpath_layer);
137 connection_mark_for_close(conn);
138 return -1;
141 /** This edge needs to be closed, because its circuit has closed.
142 * Mark it for close and return 0.
145 connection_edge_destroy(uint16_t circ_id, connection_t *conn)
147 tor_assert(CONN_IS_EDGE(conn));
149 if (!conn->marked_for_close) {
150 info(LD_EDGE,
151 "CircID %d: At an edge. Marking connection for close.", circ_id);
152 if (conn->type == CONN_TYPE_AP) {
153 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
154 } else {
155 conn->has_sent_end = 1; /* closing the circuit, nothing to send to */
156 connection_mark_for_close(conn);
157 conn->hold_open_until_flushed = 1;
160 conn->cpath_layer = NULL;
161 conn->on_circuit = NULL;
162 return 0;
165 /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
166 * with a destination of cpath_layer. (If cpath_layer is NULL, the
167 * destination is the circuit's origin.) Mark the relay end cell as
168 * closing because of <b>reason</b>.
170 * Return -1 if this function has already been called on this conn,
171 * else return 0.
174 connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
176 char payload[RELAY_PAYLOAD_SIZE];
177 size_t payload_len=1;
178 circuit_t *circ;
180 if (conn->has_sent_end) {
181 warn(LD_BUG,"Harmless bug: Calling connection_edge_end (reason %d) "
182 "on an already ended stream?", reason);
183 tor_fragile_assert();
184 return -1;
187 if (conn->marked_for_close) {
188 warn(LD_BUG,
189 "Bug: called on conn that's already marked for close at %s:%d.",
190 conn->marked_for_close_file, conn->marked_for_close);
191 return 0;
194 payload[0] = reason;
195 if (reason == END_STREAM_REASON_EXITPOLICY &&
196 !connection_edge_is_rendezvous_stream(conn)) {
197 set_uint32(payload+1, htonl(conn->addr));
198 /* XXXX fill with a real TTL! */
199 set_uint32(payload+5, htonl(MAX_DNS_ENTRY_AGE));
200 payload_len += 8;
203 circ = circuit_get_by_edge_conn(conn);
204 if (circ && !circ->marked_for_close) {
205 debug(LD_EDGE,"Marking conn (fd %d) and sending end.",conn->s);
206 connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
207 payload, payload_len, cpath_layer);
208 } else {
209 debug(LD_EDGE,"Marking conn (fd %d); no circ to send end.",conn->s);
212 conn->has_sent_end = 1;
213 return 0;
216 /** An error has just occured on an operation on an edge connection
217 * <b>conn</b>. Extract the errno; convert it to an end reason, and send
218 * an appropriate relay end cell to <b>cpath_layer</b>.
221 connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer)
223 uint8_t reason;
224 tor_assert(conn);
225 reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->s));
226 return connection_edge_end(conn, reason, cpath_layer);
229 /** Connection <b>conn</b> has finished writing and has no bytes left on
230 * its outbuf.
232 * If it's in state 'open', stop writing, consider responding with a
233 * sendme, and return.
234 * Otherwise, stop writing and return.
236 * If <b>conn</b> is broken, mark it for close and return -1, else
237 * return 0.
240 connection_edge_finished_flushing(connection_t *conn)
242 tor_assert(conn);
243 tor_assert(CONN_IS_EDGE(conn));
245 switch (conn->state) {
246 case AP_CONN_STATE_OPEN:
247 case EXIT_CONN_STATE_OPEN:
248 connection_stop_writing(conn);
249 connection_edge_consider_sending_sendme(conn);
250 return 0;
251 case AP_CONN_STATE_SOCKS_WAIT:
252 case AP_CONN_STATE_RENDDESC_WAIT:
253 case AP_CONN_STATE_CIRCUIT_WAIT:
254 case AP_CONN_STATE_CONNECT_WAIT:
255 case AP_CONN_STATE_CONTROLLER_WAIT:
256 connection_stop_writing(conn);
257 return 0;
258 default:
259 warn(LD_BUG,"BUG: called in unexpected state %d.", conn->state);
260 tor_fragile_assert();
261 return -1;
263 return 0;
266 /** Connected handler for exit connections: start writing pending
267 * data, deliver 'CONNECTED' relay cells as appropriate, and check
268 * any pending data that may have been received. */
270 connection_edge_finished_connecting(connection_t *conn)
272 char valbuf[INET_NTOA_BUF_LEN];
273 struct in_addr in;
275 tor_assert(conn);
276 tor_assert(conn->type == CONN_TYPE_EXIT);
277 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
279 in.s_addr = htonl(conn->addr);
280 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
281 info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
282 safe_str(conn->address),conn->port,safe_str(valbuf));
284 conn->state = EXIT_CONN_STATE_OPEN;
285 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
286 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
287 * cells */
288 connection_start_writing(conn);
289 /* deliver a 'connected' relay cell back through the circuit. */
290 if (connection_edge_is_rendezvous_stream(conn)) {
291 if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
292 RELAY_COMMAND_CONNECTED, NULL, 0,
293 conn->cpath_layer) < 0)
294 return 0; /* circuit is closed, don't continue */
295 } else {
296 char connected_payload[8];
297 set_uint32(connected_payload, htonl(conn->addr));
298 set_uint32(connected_payload+4,
299 htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
300 if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
301 RELAY_COMMAND_CONNECTED, connected_payload, 8, conn->cpath_layer) < 0)
302 return 0; /* circuit is closed, don't continue */
304 tor_assert(conn->package_window > 0);
305 /* in case the server has written anything */
306 return connection_edge_process_inbuf(conn, 1);
309 /** Find all general-purpose AP streams waiting for a response that sent their
310 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
311 * mark their current circuit as unsuitable for new streams. Then call
312 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
313 * available) or launch a new one.
315 * For rendezvous streams, simply give up after 45 seconds (with no
316 * retry attempt).
318 void
319 connection_ap_expire_beginning(void)
321 connection_t **carray;
322 connection_t *conn;
323 circuit_t *circ;
324 const char *nickname;
325 int n, i;
326 time_t now = time(NULL);
327 or_options_t *options = get_options();
329 get_connection_array(&carray, &n);
331 for (i = 0; i < n; ++i) {
332 conn = carray[i];
333 if (conn->type != CONN_TYPE_AP)
334 continue;
335 if (conn->state == AP_CONN_STATE_CONTROLLER_WAIT) {
336 if (now - conn->timestamp_lastread >= 120) {
337 notice(LD_APP, "Closing unattached stream.");
338 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
340 continue;
343 else if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
344 conn->state != AP_CONN_STATE_CONNECT_WAIT)
345 continue;
346 if (now - conn->timestamp_lastread < 15)
347 continue;
348 circ = circuit_get_by_edge_conn(conn);
349 if (!circ) { /* it's vanished? */
350 info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
351 safe_str(conn->socks_request->address));
352 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
353 continue;
355 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
356 if (now - conn->timestamp_lastread > 45) {
357 notice(LD_REND, "Rend stream is %d seconds late. Giving up on address"
358 " '%s.onion'.",
359 (int)(now - conn->timestamp_lastread),
360 safe_str(conn->socks_request->address));
361 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT,
362 conn->cpath_layer);
363 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
365 continue;
367 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
368 nickname = build_state_get_exit_nickname(circ->build_state);
369 notice(LD_APP,"We tried for %d seconds to connect to '%s' using exit '%s'."
370 " Retrying on a new circuit.",
371 (int)(now - conn->timestamp_lastread),
372 safe_str(conn->socks_request->address),
373 nickname ? nickname : "*unnamed*");
374 /* send an end down the circuit */
375 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
376 /* un-mark it as ending, since we're going to reuse it */
377 conn->has_sent_end = 0;
378 /* kludge to make us not try this circuit again, yet to allow
379 * current streams on it to survive if they can: make it
380 * unattractive to use for new streams */
381 tor_assert(circ->timestamp_dirty);
382 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
383 /* give our stream another 15 seconds to try */
384 conn->timestamp_lastread += 15;
385 /* move it back into 'pending' state, and try to attach. */
386 if (connection_ap_detach_retriable(conn, circ)<0) {
387 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
389 } /* end for */
392 /** Tell any AP streams that are waiting for a new circuit that one is
393 * available.
395 void
396 connection_ap_attach_pending(void)
398 connection_t **carray;
399 connection_t *conn;
400 int n, i;
402 get_connection_array(&carray, &n);
404 for (i = 0; i < n; ++i) {
405 conn = carray[i];
406 if (conn->marked_for_close ||
407 conn->type != CONN_TYPE_AP ||
408 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
409 continue;
410 if (connection_ap_handshake_attach_circuit(conn) < 0) {
411 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
416 /** The AP connection <b>conn</b> has just failed while attaching or
417 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
418 * might work. Detach the circuit, and either reattach it, launch a
419 * new circuit, tell the controller, or give up as a appropriate.
421 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
424 connection_ap_detach_retriable(connection_t *conn, circuit_t *circ)
426 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE);
427 conn->timestamp_lastread = time(NULL);
428 if (! get_options()->LeaveStreamsUnattached) {
429 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
430 circuit_detach_stream(circ,conn);
431 return connection_ap_handshake_attach_circuit(conn);
432 } else {
433 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
434 circuit_detach_stream(circ,conn);
435 return 0;
439 /** A client-side struct to remember requests to rewrite addresses
440 * to new addresses. These structs are stored in the hash table
441 * "addressmap" below.
443 * There are 5 ways to set an address mapping:
444 * - A MapAddress command from the controller [permanent]
445 * - An AddressMap directive in the torrc [permanent]
446 * - When a TrackHostExits torrc directive is triggered [temporary]
447 * - When a dns resolve succeeds [temporary]
448 * - When a dns resolve fails [temporary]
450 * When an addressmap request is made but one is already registered,
451 * the new one is replaced only if the currently registered one has
452 * no "new_address" (that is, it's in the process of dns resolve),
453 * or if the new one is permanent (expires==0 or 1).
455 * (We overload the 'expires' field, using "0" for mappings set via
456 * the configuration file, "1" for mappings set from the control
457 * interface, and other values for DNS mappings that can expire.)
459 typedef struct {
460 char *new_address;
461 time_t expires;
462 int num_resolve_failures;
463 } addressmap_entry_t;
465 /** Entry for mapping addresses to which virtual address we mapped them to. */
466 typedef struct {
467 char *ipv4_address;
468 char *hostname_address;
469 } virtaddress_entry_t;
471 /** A hash table to store client-side address rewrite instructions. */
472 static strmap_t *addressmap=NULL;
474 * Table mapping addresses to which virtual address, if any, we
475 * assigned them to.
477 * We maintain the following invariant: if [A,B] is in
478 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
479 * must be in addressmap. We do not require that the converse hold:
480 * if it fails, then we could end up mapping two virtual addresses to
481 * the same address, which is no disaster.
483 static strmap_t *virtaddress_reversemap=NULL;
485 /** Initialize addressmap. */
486 void
487 addressmap_init(void)
489 addressmap = strmap_new();
490 virtaddress_reversemap = strmap_new();
493 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
494 static void
495 addressmap_ent_free(void *_ent)
497 addressmap_entry_t *ent = _ent;
498 tor_free(ent->new_address);
499 tor_free(ent);
502 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
503 static void
504 addressmap_virtaddress_ent_free(void *_ent)
506 virtaddress_entry_t *ent = _ent;
507 tor_free(ent->ipv4_address);
508 tor_free(ent->hostname_address);
509 tor_free(ent);
512 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
513 static void
514 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
516 if (ent && ent->new_address &&
517 address_is_in_virtual_range(ent->new_address)) {
518 virtaddress_entry_t *ve =
519 strmap_get(virtaddress_reversemap, ent->new_address);
520 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
521 if (ve) {
522 if (!strcmp(address, ve->ipv4_address))
523 tor_free(ve->ipv4_address);
524 if (!strcmp(address, ve->hostname_address))
525 tor_free(ve->hostname_address);
526 if (!ve->ipv4_address && !ve->hostname_address) {
527 tor_free(ve);
528 strmap_remove(virtaddress_reversemap, ent->new_address);
534 /* DOCDOC */
535 static void
536 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
538 addressmap_virtaddress_remove(address, ent);
539 addressmap_ent_free(ent);
542 /** Remove all entries from the addressmap that were set via the
543 * configuration file or the command line. */
544 void
545 addressmap_clear_configured(void)
547 addressmap_get_mappings(NULL, 0, 0);
550 /** Remove all entries from the addressmap that are set to expire, ever. */
551 void
552 addressmap_clear_transient(void)
554 addressmap_get_mappings(NULL, 2, TIME_MAX);
557 /** Clean out entries from the addressmap cache that were
558 * added long enough ago that they are no longer valid.
560 void
561 addressmap_clean(time_t now)
563 addressmap_get_mappings(NULL, 2, now);
566 /** Free all the elements in the addressmap, and free the addressmap
567 * itself. */
568 void
569 addressmap_free_all(void)
571 if (addressmap) {
572 strmap_free(addressmap, addressmap_ent_free);
573 addressmap = NULL;
575 if (virtaddress_reversemap) {
576 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
577 virtaddress_reversemap = NULL;
581 /** Look at address, and rewrite it until it doesn't want any
582 * more rewrites; but don't get into an infinite loop.
583 * Don't write more than maxlen chars into address.
585 void
586 addressmap_rewrite(char *address, size_t maxlen)
588 addressmap_entry_t *ent;
589 int rewrites;
591 for (rewrites = 0; rewrites < 16; rewrites++) {
592 ent = strmap_get(addressmap, address);
594 if (!ent || !ent->new_address)
595 return; /* done, no rewrite needed */
597 info(LD_APP, "Addressmap: rewriting '%s' to '%s'",
598 safe_str(address), safe_str(ent->new_address));
599 strlcpy(address, ent->new_address, maxlen);
601 warn(LD_CONFIG,
602 "Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
603 safe_str(address));
604 /* it's fine to rewrite a rewrite, but don't loop forever */
607 /** Return 1 if <b>address</b> is already registered, else return 0 */
609 addressmap_already_mapped(const char *address)
611 return strmap_get(addressmap, address) ? 1 : 0;
614 /** Register a request to map <b>address</b> to <b>new_address</b>,
615 * which will expire on <b>expires</b> (or 0 if never expires from
616 * config file, 1 if never expires from controller, 2 if never expires
617 * (virtual address mapping) from the controller.)
619 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
620 * free as appropriate. We will leave address alone.
622 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
623 * any mappings that exist from <b>address</b>.
625 void
626 addressmap_register(const char *address, char *new_address, time_t expires)
628 addressmap_entry_t *ent;
630 ent = strmap_get(addressmap, address);
631 if (!new_address || !strcasecmp(address,new_address)) {
632 /* Remove the mapping, if any. */
633 tor_free(new_address);
634 if (ent) {
635 addressmap_ent_remove(address,ent);
636 strmap_remove(addressmap, address);
638 return;
640 if (!ent) { /* make a new one and register it */
641 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
642 strmap_set(addressmap, address, ent);
643 } else if (ent->new_address) { /* we need to clean up the old mapping. */
644 if (expires > 1) {
645 info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
646 "since it's already mapped to '%s'",
647 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
648 tor_free(new_address);
649 return;
651 if (address_is_in_virtual_range(ent->new_address) &&
652 expires != 2) {
653 /* XXX This isn't the perfect test; we want to avoid removing
654 * mappings set from the control interface _as virtual mapping */
655 addressmap_virtaddress_remove(address, ent);
657 tor_free(ent->new_address);
658 } /* else { we have an in-progress resolve with no mapping. } */
660 ent->new_address = new_address;
661 ent->expires = expires==2 ? 1 : expires;
662 ent->num_resolve_failures = 0;
664 info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
665 safe_str(address), safe_str(ent->new_address));
666 control_event_address_mapped(address, ent->new_address, expires);
669 /** An attempt to resolve <b>address</b> failed at some OR.
670 * Increment the number of resolve failures we have on record
671 * for it, and then return that number.
674 client_dns_incr_failures(const char *address)
676 addressmap_entry_t *ent = strmap_get(addressmap, address);
677 if (!ent) {
678 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
679 ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
680 strmap_set(addressmap,address,ent);
682 ++ent->num_resolve_failures;
683 info(LD_APP, "Address %s now has %d resolve failures.",
684 safe_str(address), ent->num_resolve_failures);
685 return ent->num_resolve_failures;
688 /** If <b>address</b> is in the client dns addressmap, reset
689 * the number of resolve failures we have on record for it.
690 * This is used when we fail a stream because it won't resolve:
691 * otherwise future attempts on that address will only try once.
693 void
694 client_dns_clear_failures(const char *address)
696 addressmap_entry_t *ent = strmap_get(addressmap, address);
697 if (ent)
698 ent->num_resolve_failures = 0;
701 /** Record the fact that <b>address</b> resolved to <b>val</b>.
702 * We can now use this in subsequent streams via addressmap_rewrite()
703 * so we can more correctly choose an exit that will allow <b>address</b>.
705 * If <b>exitname</b> is defined, then append the addresses with
706 * ".exitname.exit" before registering the mapping.
708 * If <b>ttl</b> is nonnegative, the mapping will be valid for
709 * <b>ttl</b>seconds.
711 void
712 client_dns_set_addressmap(const char *address, uint32_t val,
713 const char *exitname,
714 int ttl)
716 struct in_addr in;
717 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
718 char valbuf[INET_NTOA_BUF_LEN];
719 char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
721 tor_assert(address); tor_assert(val);
723 if (ttl<0 || ttl>MAX_DNS_ENTRY_AGE)
724 ttl = MAX_DNS_ENTRY_AGE;
726 if (tor_inet_aton(address, &in))
727 return; /* If address was an IP address already, don't add a mapping. */
728 in.s_addr = htonl(val);
729 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
730 if (exitname) {
731 tor_snprintf(extendedaddress, sizeof(extendedaddress),
732 "%s.%s.exit", address, exitname);
733 tor_snprintf(extendedval, sizeof(extendedval),
734 "%s.%s.exit", valbuf, exitname);
735 } else {
736 tor_snprintf(extendedaddress, sizeof(extendedaddress),
737 "%s", address);
738 tor_snprintf(extendedval, sizeof(extendedval),
739 "%s", valbuf);
741 addressmap_register(extendedaddress, tor_strdup(extendedval),
742 time(NULL) + ttl);
745 /* Currently, we hand out 127.192.0.1 through 127.254.254.254.
746 * These addresses should map to localhost, so even if the
747 * application accidentally tried to connect to them directly (not
748 * via Tor), it wouldn't get too far astray.
750 * Eventually, we should probably make this configurable.
752 #define MIN_UNUSED_IPV4 0x7fc00001u
753 #define MAX_UNUSED_IPV4 0x7ffefefeu
756 * Return true iff <b>addr</b> is likely to have been returned by
757 * client_dns_get_unused_address.
760 address_is_in_virtual_range(const char *address)
762 struct in_addr in;
763 tor_assert(address);
764 if (!strcasecmpend(address, ".virtual")) {
765 return 1;
766 } else if (tor_inet_aton(address, &in)) {
767 uint32_t addr = ntohl(in.s_addr);
768 if (addr >= MIN_UNUSED_IPV4 && addr <= MAX_UNUSED_IPV4)
769 return 1;
771 return 0;
774 /** Return a newly allocated string holding an address of <b>type</b>
775 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
776 * and that is very unlikely to be the address of any real host.
778 static char *
779 addressmap_get_virtual_address(int type)
781 char buf[64];
782 static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
783 struct in_addr in;
785 if (type == RESOLVED_TYPE_HOSTNAME) {
786 char rand[10];
787 do {
788 crypto_rand(rand, sizeof(rand));
789 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
790 strlcat(buf, ".virtual", sizeof(buf));
791 } while (strmap_get(addressmap, buf));
792 return tor_strdup(buf);
793 } else if (type == RESOLVED_TYPE_IPV4) {
794 while (1) {
795 /* Don't hand out any .0 or .255 address. */
796 while ((next_ipv4 & 0xff) == 0 ||
797 (next_ipv4 & 0xff) == 0xff)
798 ++next_ipv4;
799 in.s_addr = htonl(next_ipv4);
800 tor_inet_ntoa(&in, buf, sizeof(buf));
801 if (!strmap_get(addressmap, buf))
802 break;
804 ++next_ipv4;
805 if (next_ipv4 > MAX_UNUSED_IPV4)
806 next_ipv4 = MIN_UNUSED_IPV4;
808 return tor_strdup(buf);
809 } else {
810 warn(LD_BUG, "Called with unsupported address type (%d)", type);
811 return NULL;
815 /** A controller has requested that we map some address of type
816 * <b>type</b> to the address <b>new_address</b>. Choose an address
817 * that is unlikely to be used, and map it, and return it in a newly
818 * allocated string. If another address of the same type is already
819 * mapped to <b>new_address</b>, try to return a copy of that address.
821 * The string in <b>new_address</b> may be freed, or inserted into a map
822 * as appropriate.
824 const char *
825 addressmap_register_virtual_address(int type, char *new_address)
827 char **addrp;
828 virtaddress_entry_t *vent;
830 tor_assert(new_address);
831 tor_assert(addressmap);
832 tor_assert(virtaddress_reversemap);
834 vent = strmap_get(virtaddress_reversemap, new_address);
835 if (!vent) {
836 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
837 strmap_set(virtaddress_reversemap, new_address, vent);
840 addrp = (type == RESOLVED_TYPE_IPV4) ?
841 &vent->ipv4_address : &vent->hostname_address;
842 if (*addrp) {
843 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
844 if (ent && ent->new_address &&
845 !strcasecmp(new_address, ent->new_address)) {
846 tor_free(new_address);
847 return tor_strdup(*addrp);
848 } else
849 warn(LD_BUG, "Internal confusion: I thought that '%s' was mapped to "
850 "by '%s', but '%s' really maps to '%s'. This is a harmless bug.",
851 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
852 ent?safe_str(ent->new_address):"(nothing)");
855 tor_free(*addrp);
856 *addrp = addressmap_get_virtual_address(type);
857 addressmap_register(*addrp, new_address, 2);
859 #if 0
861 /* Try to catch possible bugs */
862 addressmap_entry_t *ent;
863 ent = strmap_get(addressmap, *addrp);
864 tor_assert(ent);
865 tor_assert(!strcasecmp(ent->new_address,new_address));
866 vent = strmap_get(virtaddress_reversemap, new_address);
867 tor_assert(vent);
868 tor_assert(!strcasecmp(*addrp,
869 (type == RESOLVED_TYPE_IPV4) ?
870 vent->ipv4_address : vent->hostname_address));
871 log_fn(LOG_INFO, "Map from %s to %s okay.",
872 safe_str(*addrp),safe_str(new_address));
874 #endif
876 return *addrp;
879 /** Return 1 if <b>address</b> has funny characters in it like
880 * colons. Return 0 if it's fine.
882 static int
883 address_is_invalid_destination(const char *address)
885 /* FFFF should flesh this out */
886 if (strchr(address,':'))
887 return 1;
888 return 0;
891 /** Iterate over all address mapings which have expiry times between
892 * min_expires and max_expires, inclusive. If sl is provided, add an
893 * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
894 * remove the mappings.
896 void
897 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
898 time_t max_expires)
900 strmap_iter_t *iter;
901 const char *key;
902 void *_val;
903 addressmap_entry_t *val;
905 if (!addressmap)
906 addressmap_init();
908 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
909 strmap_iter_get(iter, &key, &_val);
910 val = _val;
911 if (val->expires >= min_expires && val->expires <= max_expires) {
912 if (!sl) {
913 iter = strmap_iter_next_rmv(addressmap,iter);
914 addressmap_ent_remove(key, val);
915 continue;
916 } else if (val->new_address) {
917 size_t len = strlen(key)+strlen(val->new_address)+2;
918 char *line = tor_malloc(len);
919 tor_snprintf(line, len, "%s %s", key, val->new_address);
920 smartlist_add(sl, line);
923 iter = strmap_iter_next(addressmap,iter);
927 /* Connection <b>conn</b> just finished its socks handshake, or the
928 * controller asked us to take care of it.
930 * First, parse whether it's a .exit address, remap it, and so on. Then
931 * it's for a general circuit, try to attach it to a circuit (or launch
932 * one as needed), else if it's for a rendezvous circuit, fetch a
933 * rendezvous descriptor first (or attach/launch a circuit if the
934 * rendezvous descriptor is already here and fresh enough).
937 connection_ap_handshake_rewrite_and_attach(connection_t *conn)
939 socks_request_t *socks = conn->socks_request;
940 hostname_type_t addresstype;
942 tor_strlower(socks->address); /* normalize it */
943 debug(LD_APP,"Client asked for %s:%d", safe_str(socks->address),
944 socks->port);
946 /* For address map controls, remap the address */
947 addressmap_rewrite(socks->address, sizeof(socks->address));
949 if (address_is_in_virtual_range(socks->address)) {
950 /* This address was probably handed out by client_dns_get_unmapped_address,
951 * but the mapping was discarded for some reason. We *don't* want to send
952 * the address through Tor; that's likely to fail, and may leak
953 * information.
955 warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
956 socks->address); /* don't safe_str() this yet. */
957 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
958 return -1;
961 /* Parse the address provided by SOCKS. Modify it in-place if it
962 * specifies a hidden-service (.onion) or particular exit node (.exit).
964 addresstype = parse_extended_hostname(socks->address);
966 if (addresstype == BAD_HOSTNAME) {
967 warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
968 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
969 return -1;
972 if (addresstype == EXIT_HOSTNAME) {
973 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
974 * node, and conn->address to hold only the address portion.*/
975 char *s = strrchr(socks->address,'.');
976 if (s) {
977 if (s[1] != '\0') {
978 conn->chosen_exit_name = tor_strdup(s+1);
979 *s = 0;
980 } else {
981 warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
982 safe_str(socks->address));
983 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
984 return -1;
986 } else {
987 struct in_addr in;
988 routerinfo_t *r;
989 conn->chosen_exit_name = tor_strdup(socks->address);
990 r = router_get_by_nickname(conn->chosen_exit_name, 1);
991 *socks->address = 0;
992 if (r) {
993 /* XXXX Should this use server->address instead? */
994 in.s_addr = htonl(r->addr);
995 strlcpy(socks->address, inet_ntoa(in), sizeof(socks->address));
996 } else {
997 warn(LD_APP,
998 "Unrecognized server in exit address '%s.exit'. Refusing.",
999 safe_str(socks->address));
1000 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1001 return -1;
1006 if (addresstype != ONION_HOSTNAME) {
1007 /* not a hidden-service request (i.e. normal or .exit) */
1009 if (address_is_invalid_destination(socks->address)) {
1010 warn(LD_APP,"Destination '%s' seems to be an invalid hostname. Failing.",
1011 safe_str(socks->address));
1012 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1013 return -1;
1016 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1017 uint32_t answer;
1018 struct in_addr in;
1019 /* Reply to resolves immediately if we can. */
1020 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1021 warn(LD_APP,"Address to be resolved is too large. Failing.");
1022 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1023 0,NULL,-1);
1024 connection_mark_unattached_ap(conn,
1025 END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1026 return -1;
1028 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1029 answer = in.s_addr; /* leave it in network order */
1030 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1031 (char*)&answer,-1);
1032 connection_mark_unattached_ap(conn,
1033 END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1034 return 0;
1036 rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
1037 } else { /* socks->command == SOCKS_COMMAND_CONNECT */
1038 if (socks->port == 0) {
1039 notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1040 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1041 return -1;
1044 if (!conn->chosen_exit_name) {
1045 /* see if we can find a suitable enclave exit */
1046 routerinfo_t *r =
1047 router_find_exact_exit_enclave(socks->address, socks->port);
1048 if (r) {
1049 info(LD_APP,"Redirecting address %s to exit at enclave router %s",
1050 safe_str(socks->address), r->nickname);
1051 /* use the hex digest, not nickname, in case there are two
1052 routers with this nickname */
1053 conn->chosen_exit_name =
1054 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1058 /* help predict this next time */
1059 rep_hist_note_used_port(socks->port, time(NULL));
1061 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1062 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1063 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1064 return -1;
1066 return 0;
1067 } else {
1068 /* it's a hidden-service request */
1069 rend_cache_entry_t *entry;
1070 int r;
1072 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1073 /* if it's a resolve request, fail it right now, rather than
1074 * building all the circuits and then realizing it won't work. */
1075 warn(LD_APP,"Resolve requests to hidden services not allowed. Failing.");
1076 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1077 0,NULL,-1);
1078 connection_mark_unattached_ap(conn,
1079 END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1080 return -1;
1083 strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
1084 info(LD_REND,"Got a hidden service request for ID '%s'",
1085 safe_str(conn->rend_query));
1086 /* see if we already have it cached */
1087 r = rend_cache_lookup_entry(conn->rend_query, -1, &entry);
1088 if (r<0) {
1089 warn(LD_BUG,"Bug: Invalid service name '%s'",
1090 safe_str(conn->rend_query));
1091 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1092 return -1;
1094 if (r==0) {
1095 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1096 info(LD_REND, "Unknown descriptor %s. Fetching.",
1097 safe_str(conn->rend_query));
1098 rend_client_refetch_renddesc(conn->rend_query);
1099 } else { /* r > 0 */
1100 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
1101 if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
1102 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1103 info(LD_REND, "Descriptor is here and fresh enough. Great.");
1104 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1105 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1106 return -1;
1108 } else {
1109 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1110 info(LD_REND, "Stale descriptor %s. Refetching.",
1111 safe_str(conn->rend_query));
1112 rend_client_refetch_renddesc(conn->rend_query);
1115 return 0;
1117 return 0; /* unreached but keeps the compiler happy */
1120 /** connection_edge_process_inbuf() found a conn in state
1121 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1122 * the socks handshake.
1124 * If the handshake is complete, send it to
1125 * connection_ap_handshake_rewrite_and_attach().
1127 * Return -1 if an unexpected error with conn (and it should be marked
1128 * for close), else return 0.
1130 static int
1131 connection_ap_handshake_process_socks(connection_t *conn)
1133 socks_request_t *socks;
1134 int sockshere;
1135 or_options_t *options = get_options();
1137 tor_assert(conn);
1138 tor_assert(conn->type == CONN_TYPE_AP);
1139 tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
1140 tor_assert(conn->socks_request);
1141 socks = conn->socks_request;
1143 debug(LD_APP,"entered.");
1145 sockshere = fetch_from_buf_socks(conn->inbuf, socks, options->TestSocks);
1146 if (sockshere == 0) {
1147 if (socks->replylen) {
1148 connection_write_to_buf(socks->reply, socks->replylen, conn);
1149 /* zero it out so we can do another round of negotiation */
1150 socks->replylen = 0;
1151 } else {
1152 debug(LD_APP,"socks handshake not all here yet.");
1154 return 0;
1155 } else if (sockshere == -1) {
1156 if (socks->replylen) { /* we should send reply back */
1157 debug(LD_APP,"reply is already set for us. Using it.");
1158 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1159 SOCKS5_GENERAL_ERROR);
1160 } else {
1161 warn(LD_APP,"Fetching socks handshake failed. Closing.");
1162 connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
1164 connection_mark_unattached_ap(conn,
1165 END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1166 return -1;
1167 } /* else socks handshake is done, continue processing */
1169 if (socks->command == SOCKS_COMMAND_CONNECT)
1170 control_event_stream_status(conn, STREAM_EVENT_NEW);
1171 else
1172 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE);
1174 if (options->LeaveStreamsUnattached) {
1175 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
1176 return 0;
1177 } else
1178 return connection_ap_handshake_rewrite_and_attach(conn);
1181 /** Iterate over the two bytes of stream_id until we get one that is not
1182 * already in use; return it. Return 0 if can't get a unique stream_id.
1184 static uint16_t
1185 get_unique_stream_id_by_circ(circuit_t *circ)
1187 connection_t *tmpconn;
1188 uint16_t test_stream_id;
1189 uint32_t attempts=0;
1191 again:
1192 test_stream_id = circ->next_stream_id++;
1193 if (++attempts > 1<<16) {
1194 /* Make sure we don't loop forever if all stream_id's are used. */
1195 warn(LD_APP,"No unused stream IDs. Failing.");
1196 return 0;
1198 if (test_stream_id == 0)
1199 goto again;
1200 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
1201 if (tmpconn->stream_id == test_stream_id)
1202 goto again;
1203 return test_stream_id;
1206 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1207 * socks_request field, and send it down circ.
1209 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1212 connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
1214 char payload[CELL_PAYLOAD_SIZE];
1215 int payload_len;
1217 tor_assert(ap_conn->type == CONN_TYPE_AP);
1218 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1219 tor_assert(ap_conn->socks_request);
1221 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1222 if (ap_conn->stream_id==0) {
1223 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1224 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
1225 return -1;
1228 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
1229 (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
1230 ap_conn->socks_request->address : "",
1231 ap_conn->socks_request->port);
1232 payload_len = strlen(payload)+1;
1234 debug(LD_APP,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1236 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
1237 payload, payload_len,
1238 ap_conn->cpath_layer) < 0)
1239 return -1; /* circuit is closed, don't continue */
1241 ap_conn->package_window = STREAMWINDOW_START;
1242 ap_conn->deliver_window = STREAMWINDOW_START;
1243 ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
1244 info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
1245 ap_conn->s, circ->n_circ_id);
1246 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
1247 return 0;
1250 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1251 * socks_request field, and send it down circ.
1253 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1256 connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
1258 int payload_len;
1259 const char *string_addr;
1261 tor_assert(ap_conn->type == CONN_TYPE_AP);
1262 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1263 tor_assert(ap_conn->socks_request);
1264 tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
1265 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
1267 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1268 if (ap_conn->stream_id==0) {
1269 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1270 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
1271 return -1;
1274 string_addr = ap_conn->socks_request->address;
1275 payload_len = strlen(string_addr)+1;
1276 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
1278 debug(LD_APP,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1280 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
1281 string_addr, payload_len, ap_conn->cpath_layer) < 0)
1282 return -1; /* circuit is closed, don't continue */
1284 ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
1285 info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
1286 ap_conn->s, circ->n_circ_id);
1287 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
1288 return 0;
1291 /** Make an AP connection_t, do a socketpair and attach one side
1292 * to the conn, connection_add it, initialize it to circuit_wait,
1293 * and call connection_ap_handshake_attach_circuit(conn) on it.
1295 * Return the other end of the socketpair, or -1 if error.
1298 connection_ap_make_bridge(char *address, uint16_t port)
1300 int fd[2];
1301 connection_t *conn;
1302 int err;
1304 info(LD_APP,"Making AP bridge to %s:%d ...",safe_str(address),port);
1306 if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
1307 warn(LD_NET,"Couldn't construct socketpair (%s). Network down? Delaying.",
1308 tor_socket_strerror(-err));
1309 return -1;
1312 set_socket_nonblocking(fd[0]);
1313 set_socket_nonblocking(fd[1]);
1315 conn = connection_new(CONN_TYPE_AP);
1316 conn->s = fd[0];
1318 /* populate conn->socks_request */
1320 /* leave version at zero, so the socks_reply is empty */
1321 conn->socks_request->socks_version = 0;
1322 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
1323 strlcpy(conn->socks_request->address, address,
1324 sizeof(conn->socks_request->address));
1325 conn->socks_request->port = port;
1326 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
1328 conn->address = tor_strdup("(local bridge)");
1329 conn->addr = 0;
1330 conn->port = 0;
1332 if (connection_add(conn) < 0) { /* no space, forget it */
1333 connection_free(conn); /* this closes fd[0] */
1334 tor_close_socket(fd[1]);
1335 return -1;
1338 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1339 connection_start_reading(conn);
1341 /* attaching to a dirty circuit is fine */
1342 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1343 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1344 tor_close_socket(fd[1]);
1345 return -1;
1348 info(LD_APP,"... AP bridge created and connected.");
1349 return fd[1];
1352 /** Send an answer to an AP connection that has requested a DNS lookup
1353 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6) or
1354 * -1 for unreachable; the answer should be in the format specified
1355 * in the socks extensions document.
1357 void
1358 connection_ap_handshake_socks_resolved(connection_t *conn,
1359 int answer_type,
1360 size_t answer_len,
1361 const char *answer,
1362 int ttl)
1364 char buf[256];
1365 size_t replylen;
1367 if (answer_type == RESOLVED_TYPE_IPV4) {
1368 uint32_t a = ntohl(get_uint32(answer));
1369 if (a)
1370 client_dns_set_addressmap(conn->socks_request->address, a,
1371 conn->chosen_exit_name, ttl);
1374 if (conn->socks_request->socks_version == 4) {
1375 buf[0] = 0x00; /* version */
1376 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1377 buf[1] = 90; /* "Granted" */
1378 set_uint16(buf+2, 0);
1379 memcpy(buf+4, answer, 4); /* address */
1380 replylen = SOCKS4_NETWORK_LEN;
1381 } else {
1382 buf[1] = 91; /* "error" */
1383 memset(buf+2, 0, 6);
1384 replylen = SOCKS4_NETWORK_LEN;
1386 } else {
1387 /* SOCKS5 */
1388 buf[0] = 0x05; /* version */
1389 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1390 buf[1] = SOCKS5_SUCCEEDED;
1391 buf[2] = 0; /* reserved */
1392 buf[3] = 0x01; /* IPv4 address type */
1393 memcpy(buf+4, answer, 4); /* address */
1394 set_uint16(buf+8, 0); /* port == 0. */
1395 replylen = 10;
1396 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
1397 buf[1] = SOCKS5_SUCCEEDED;
1398 buf[2] = 0; /* reserved */
1399 buf[3] = 0x04; /* IPv6 address type */
1400 memcpy(buf+4, answer, 16); /* address */
1401 set_uint16(buf+20, 0); /* port == 0. */
1402 replylen = 22;
1403 } else {
1404 buf[1] = SOCKS5_HOST_UNREACHABLE;
1405 memset(buf+2, 0, 8);
1406 replylen = 10;
1409 connection_ap_handshake_socks_reply(conn, buf, replylen,
1410 (answer_type == RESOLVED_TYPE_IPV4 ||
1411 answer_type == RESOLVED_TYPE_IPV6) ?
1412 SOCKS5_SUCCEEDED : SOCKS5_HOST_UNREACHABLE);
1415 /** Send a socks reply to stream <b>conn</b>, using the appropriate
1416 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
1417 * handshaking.
1419 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
1420 * to conn and return, else reply based on <b>status</b>.
1422 * If <b>reply</b> is undefined, <b>status</b> can't be 0.
1424 void
1425 connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
1426 size_t replylen,
1427 socks5_reply_status_t status) {
1428 char buf[256];
1429 tor_assert(conn->socks_request); /* make sure it's an AP stream */
1431 control_event_stream_status(conn,
1432 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
1434 if (conn->socks_request->has_finished) {
1435 warn(LD_BUG, "Harmless bug: duplicate calls to "
1436 "connection_ap_handshake_socks_reply.");
1437 return;
1439 if (replylen) { /* we already have a reply in mind */
1440 connection_write_to_buf(reply, replylen, conn);
1441 conn->socks_request->has_finished = 1;
1442 return;
1444 if (conn->socks_request->socks_version == 4) {
1445 memset(buf,0,SOCKS4_NETWORK_LEN);
1446 #define SOCKS4_GRANTED 90
1447 #define SOCKS4_REJECT 91
1448 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
1449 /* leave version, destport, destip zero */
1450 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
1451 } else if (conn->socks_request->socks_version == 5) {
1452 buf[0] = 5; /* version 5 */
1453 buf[1] = (char)status;
1454 buf[2] = 0;
1455 buf[3] = 1; /* ipv4 addr */
1456 memset(buf+4,0,6); /* Set external addr/port to 0.
1457 The spec doesn't seem to say what to do here. -RD */
1458 connection_write_to_buf(buf,10,conn);
1460 /* If socks_version isn't 4 or 5, don't send anything.
1461 * This can happen in the case of AP bridges. */
1462 conn->socks_request->has_finished = 1;
1463 return;
1466 /** A relay 'begin' cell has arrived, and either we are an exit hop
1467 * for the circuit, or we are the origin and it is a rendezvous begin.
1469 * Launch a new exit connection and initialize things appropriately.
1471 * If it's a rendezvous stream, call connection_exit_connect() on
1472 * it.
1474 * For general streams, call dns_resolve() on it first, and only call
1475 * connection_exit_connect() if the dns answer is already known.
1477 * Note that we don't call connection_add() on the new stream! We wait
1478 * for connection_exit_connect() to do that.
1480 * Return -1 if we want to tear down <b>circ</b>. Else return 0.
1483 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
1485 connection_t *n_stream;
1486 relay_header_t rh;
1487 char *address=NULL;
1488 uint16_t port;
1490 assert_circuit_ok(circ);
1491 relay_header_unpack(&rh, cell->payload);
1493 /* XXX currently we don't send an end cell back if we drop the
1494 * begin because it's malformed.
1497 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
1498 warn(LD_PROTOCOL,"relay begin cell has no \\0. Dropping.");
1499 return 0;
1501 if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
1502 warn(LD_PROTOCOL,"Unable to parse addr:port in relay begin cell. "
1503 "Dropping.");
1504 return 0;
1506 if (port==0) {
1507 warn(LD_PROTOCOL,"Missing port in relay begin cell. Dropping.");
1508 tor_free(address);
1509 return 0;
1512 debug(LD_EXIT,"Creating new exit connection.");
1513 n_stream = connection_new(CONN_TYPE_EXIT);
1514 n_stream->purpose = EXIT_PURPOSE_CONNECT;
1516 n_stream->stream_id = rh.stream_id;
1517 n_stream->port = port;
1518 /* leave n_stream->s at -1, because it's not yet valid */
1519 n_stream->package_window = STREAMWINDOW_START;
1520 n_stream->deliver_window = STREAMWINDOW_START;
1522 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1523 debug(LD_REND,"begin is for rendezvous. configuring stream.");
1524 n_stream->address = tor_strdup("(rendezvous)");
1525 n_stream->state = EXIT_CONN_STATE_CONNECTING;
1526 strlcpy(n_stream->rend_query, circ->rend_query,
1527 sizeof(n_stream->rend_query));
1528 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
1529 assert_circuit_ok(circ);
1530 if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
1531 info(LD_REND,"Didn't find rendezvous service (port %d)",n_stream->port);
1532 connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY,
1533 n_stream->cpath_layer);
1534 connection_free(n_stream);
1535 /* knock the whole thing down, somebody screwed up */
1536 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
1537 tor_free(address);
1538 return 0;
1540 assert_circuit_ok(circ);
1541 debug(LD_REND,"Finished assigning addr/port");
1542 n_stream->cpath_layer = circ->cpath->prev; /* link it */
1544 /* add it into the linked list of n_streams on this circuit */
1545 n_stream->next_stream = circ->n_streams;
1546 n_stream->on_circuit = circ;
1547 circ->n_streams = n_stream;
1548 assert_circuit_ok(circ);
1550 connection_exit_connect(n_stream);
1551 tor_free(address);
1552 return 0;
1554 tor_strlower(address);
1555 n_stream->address = address;
1556 n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
1557 /* default to failed, change in dns_resolve if it turns out not to fail */
1559 if (we_are_hibernating()) {
1560 connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING,
1561 n_stream->cpath_layer);
1562 connection_free(n_stream);
1563 return 0;
1566 /* send it off to the gethostbyname farm */
1567 switch (dns_resolve(n_stream)) {
1568 case 1: /* resolve worked */
1570 /* add it into the linked list of n_streams on this circuit */
1571 n_stream->next_stream = circ->n_streams;
1572 n_stream->on_circuit = circ;
1573 circ->n_streams = n_stream;
1574 assert_circuit_ok(circ);
1576 connection_exit_connect(n_stream);
1577 return 0;
1578 case -1: /* resolve failed */
1579 /* n_stream got freed. don't touch it. */
1580 break;
1581 case 0: /* resolve added to pending list */
1582 /* add it into the linked list of resolving_streams on this circuit */
1583 n_stream->next_stream = circ->resolving_streams;
1584 n_stream->on_circuit = circ;
1585 circ->resolving_streams = n_stream;
1586 assert_circuit_ok(circ);
1589 return 0;
1593 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
1594 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
1597 connection_exit_begin_resolve(cell_t *cell, circuit_t *circ)
1599 connection_t *dummy_conn;
1600 relay_header_t rh;
1602 assert_circuit_ok(circ);
1603 relay_header_unpack(&rh, cell->payload);
1605 /* This 'dummy_conn' only exists to remember the stream ID
1606 * associated with the resolve request; and to make the
1607 * implementation of dns.c more uniform. (We really only need to
1608 * remember the circuit, the stream ID, and the hostname to be
1609 * resolved; but if we didn't store them in a connection like this,
1610 * the housekeeping in dns.c would get way more complicated.)
1612 dummy_conn = connection_new(CONN_TYPE_EXIT);
1613 dummy_conn->stream_id = rh.stream_id;
1614 dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
1615 rh.length);
1616 dummy_conn->port = 0;
1617 dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
1618 dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
1620 /* send it off to the gethostbyname farm */
1621 switch (dns_resolve(dummy_conn)) {
1622 case -1: /* Impossible to resolve; a resolved cell was sent. */
1623 /* Connection freed; don't touch it. */
1624 return 0;
1625 case 1: /* The result was cached; a resolved cell was sent. */
1626 if (!dummy_conn->marked_for_close)
1627 connection_free(dummy_conn);
1628 return 0;
1629 case 0: /* resolve added to pending list */
1630 dummy_conn->next_stream = circ->resolving_streams;
1631 dummy_conn->on_circuit = circ;
1632 circ->resolving_streams = dummy_conn;
1633 assert_circuit_ok(circ);
1634 break;
1636 return 0;
1639 /** Connect to conn's specified addr and port. If it worked, conn
1640 * has now been added to the connection_array.
1642 * Send back a connected cell. Include the resolved IP of the destination
1643 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
1644 * streams must not reveal what IP they connected to.)
1646 void
1647 connection_exit_connect(connection_t *conn)
1649 uint32_t addr;
1650 uint16_t port;
1652 if (!connection_edge_is_rendezvous_stream(conn) &&
1653 router_compare_to_my_exit_policy(conn)) {
1654 info(LD_EXIT,"%s:%d failed exit policy. Closing.",
1655 safe_str(conn->address), conn->port);
1656 connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
1657 circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
1658 connection_free(conn);
1659 return;
1662 addr = conn->addr;
1663 port = conn->port;
1664 if (redirect_exit_list) {
1665 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
1667 if ((addr&r->mask)==(r->addr&r->mask) &&
1668 (r->port_min <= port) && (port <= r->port_max)) {
1669 struct in_addr in;
1670 if (r->is_redirect) {
1671 char tmpbuf[INET_NTOA_BUF_LEN];
1672 addr = r->addr_dest;
1673 port = r->port_dest;
1674 in.s_addr = htonl(addr);
1675 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
1676 debug(LD_EXIT, "Redirecting connection from %s:%d to %s:%d",
1677 safe_str(conn->address), conn->port, safe_str(tmpbuf), port);
1679 break;
1684 debug(LD_EXIT,"about to try connecting");
1685 switch (connection_connect(conn, conn->address, addr, port)) {
1686 case -1:
1687 connection_edge_end_errno(conn, conn->cpath_layer);
1688 circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
1689 connection_free(conn);
1690 return;
1691 case 0:
1692 conn->state = EXIT_CONN_STATE_CONNECTING;
1694 connection_watch_events(conn, EV_WRITE | EV_READ);
1695 /* writable indicates finish;
1696 * readable/error indicates broken link in windowsland. */
1697 return;
1698 /* case 1: fall through */
1701 conn->state = EXIT_CONN_STATE_OPEN;
1702 if (connection_wants_to_flush(conn)) {
1703 /* in case there are any queued data cells */
1704 warn(LD_BUG,"Bug: newly connected conn had data waiting!");
1705 // connection_start_writing(conn);
1707 connection_watch_events(conn, EV_READ);
1709 /* also, deliver a 'connected' cell back through the circuit. */
1710 if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
1711 /* don't send an address back! */
1712 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
1713 RELAY_COMMAND_CONNECTED,
1714 NULL, 0, conn->cpath_layer);
1715 } else { /* normal stream */
1716 /* This must be the original address, not the redirected address. */
1717 char connected_payload[8];
1718 set_uint32(connected_payload, htonl(conn->addr));
1719 set_uint32(connected_payload+4,
1720 htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
1721 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
1722 RELAY_COMMAND_CONNECTED,
1723 connected_payload, 8, conn->cpath_layer);
1727 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
1728 * it is a general stream.
1731 connection_edge_is_rendezvous_stream(connection_t *conn)
1733 tor_assert(conn);
1734 if (*conn->rend_query) /* XXX */
1735 return 1;
1736 return 0;
1739 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
1740 * to exit from it, or 0 if it probably will not allow it.
1741 * (We might be uncertain if conn's destination address has not yet been
1742 * resolved.)
1745 connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
1747 tor_assert(conn);
1748 tor_assert(conn->type == CONN_TYPE_AP);
1749 tor_assert(conn->socks_request);
1750 tor_assert(exit);
1752 #if 0
1753 log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
1754 exit->nickname, safe_str(conn->socks_request->address),
1755 conn->socks_request->port);
1756 #endif
1758 /* If a particular exit node has been requested for the new connection,
1759 * make sure the exit node of the existing circuit matches exactly.
1761 if (conn->chosen_exit_name) {
1762 if (router_get_by_nickname(conn->chosen_exit_name, 1) != exit) {
1763 /* doesn't match */
1764 debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
1765 conn->chosen_exit_name, exit->nickname);
1766 return 0;
1770 if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
1771 struct in_addr in;
1772 uint32_t addr = 0;
1773 addr_policy_result_t r;
1774 if (tor_inet_aton(conn->socks_request->address, &in))
1775 addr = ntohl(in.s_addr);
1776 r = router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
1777 exit->exit_policy);
1778 if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
1779 return 0;
1781 return 1;
1784 /** A helper function for socks_policy_permits_address() below.
1786 * Parse options->SocksPolicy in the same way that the exit policy
1787 * is parsed, and put the processed version in socks_policy.
1788 * Ignore port specifiers.
1790 void
1791 parse_socks_policy(void)
1793 addr_policy_t *n;
1794 if (socks_policy) {
1795 addr_policy_free(socks_policy);
1796 socks_policy = NULL;
1798 config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy, -1);
1799 /* ports aren't used. */
1800 for (n=socks_policy; n; n = n->next) {
1801 n->prt_min = 1;
1802 n->prt_max = 65535;
1806 /** Free all storage held by our SOCKS allow policy
1808 void
1809 free_socks_policy(void)
1811 addr_policy_free(socks_policy);
1812 socks_policy = NULL;
1815 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1816 * based on <b>socks_policy</b>. Else return 0.
1819 socks_policy_permits_address(uint32_t addr)
1821 int a;
1823 if (!socks_policy) /* 'no socks policy' means 'accept' */
1824 return 1;
1825 a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
1826 if (a==ADDR_POLICY_REJECTED)
1827 return 0;
1828 else if (a==ADDR_POLICY_ACCEPTED)
1829 return 1;
1830 warn(LD_BUG, "Bug: Got unexpected 'maybe' answer from socks policy");
1831 return 0;
1834 /** Make connection redirection follow the provided list of
1835 * exit_redirect_t */
1836 void
1837 set_exit_redirects(smartlist_t *lst)
1839 if (redirect_exit_list) {
1840 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
1841 smartlist_free(redirect_exit_list);
1843 redirect_exit_list = lst;
1846 /** If address is of the form "y.onion" with a well-formed handle y:
1847 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
1849 * If address is of the form "y.exit":
1850 * Put a NUL after y and return EXIT_HOSTNAME.
1852 * Otherwise:
1853 * Return NORMAL_HOSTNAME and change nothing.
1855 hostname_type_t
1856 parse_extended_hostname(char *address)
1858 char *s;
1859 char query[REND_SERVICE_ID_LEN+1];
1861 s = strrchr(address,'.');
1862 if (!s) return 0; /* no dot, thus normal */
1863 if (!strcmp(s+1,"exit")) {
1864 *s = 0; /* null-terminate it */
1865 return EXIT_HOSTNAME; /* .exit */
1867 if (strcmp(s+1,"onion"))
1868 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1870 /* so it is .onion */
1871 *s = 0; /* null-terminate it */
1872 if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >=
1873 REND_SERVICE_ID_LEN+1)
1874 goto failed;
1875 if (rend_valid_service_id(query)) {
1876 return ONION_HOSTNAME; /* success */
1878 failed:
1879 /* otherwise, return to previous state and return 0 */
1880 *s = '.';
1881 return BAD_HOSTNAME;