Move most of *_mark_for_close out of macros.
[tor.git] / src / or / connection_edge.c
blob1e72d6f7d373c1662c3749cf375fb2dc9cd94149
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"
14 #include "tree.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);
21 static int address_is_in_virtual_range(const char *addr);
23 /** An AP stream has failed/finished. If it hasn't already sent back
24 * a socks reply, send one now (based on endreason). Also set
25 * has_sent_end to 1, and mark the conn.
27 void
28 _connection_mark_unattached_ap(connection_t *conn, int endreason,
29 int line, const char *file) {
31 tor_assert(conn->type == CONN_TYPE_AP);
32 conn->has_sent_end = 1; /* no circ yet */
34 if (conn->marked_for_close) {
35 /* This call will warn as appropriate. */
36 _connection_mark_for_close(conn, line, file);
37 return;
40 if (!conn->socks_request->has_finished) {
41 socks5_reply_status_t socksreason =
42 connection_edge_end_reason_socks5_response(endreason);
44 if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
45 log_fn(LOG_WARN,"Bug: stream (marked at %s:%d) sending two socks replies?",
46 file, line);
48 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
49 connection_ap_handshake_socks_reply(conn, NULL, 0, socksreason);
50 else
51 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
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 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_conn(conn), RELAY_COMMAND_END,
70 NULL, 0, conn->cpath_layer);
72 return 0;
73 #else
74 if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
75 /* it still has stuff to process. don't let it die yet. */
76 return 0;
78 log_fn(LOG_INFO,"conn (fd %d) reached eof (stream size %d). Closing.", conn->s, (int)conn->stream_size);
79 if (!conn->marked_for_close) {
80 /* only mark it if not already marked. it's possible to
81 * get the 'end' right around when the client hangs up on us. */
82 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
83 if (conn->socks_request) /* eof, so don't send a socks reply back */
84 conn->socks_request->has_finished = 1;
85 connection_mark_for_close(conn);
87 return 0;
88 #endif
91 /** Handle new bytes on conn->inbuf based on state:
92 * - If it's waiting for socks info, try to read another step of the
93 * socks handshake out of conn->inbuf.
94 * - If it's open, then package more relay cells from the stream.
95 * - Else, leave the bytes on inbuf alone for now.
97 * Mark and return -1 if there was an unexpected error with the conn,
98 * else return 0.
100 int connection_edge_process_inbuf(connection_t *conn, int package_partial) {
102 tor_assert(conn);
103 tor_assert(CONN_IS_EDGE(conn));
105 switch (conn->state) {
106 case AP_CONN_STATE_SOCKS_WAIT:
107 if (connection_ap_handshake_process_socks(conn) < 0) {
108 /* already marked */
109 return -1;
111 return 0;
112 case AP_CONN_STATE_OPEN:
113 case EXIT_CONN_STATE_OPEN:
114 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
115 /* (We already sent an end cell if possible) */
116 connection_mark_for_close(conn);
117 return -1;
119 return 0;
120 case EXIT_CONN_STATE_CONNECTING:
121 case AP_CONN_STATE_RENDDESC_WAIT:
122 case AP_CONN_STATE_CIRCUIT_WAIT:
123 case AP_CONN_STATE_CONNECT_WAIT:
124 case AP_CONN_STATE_RESOLVE_WAIT:
125 case AP_CONN_STATE_CONTROLLER_WAIT:
126 log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
127 conn_state_to_string[conn->type][conn->state]);
128 return 0;
130 log_fn(LOG_WARN,"Bug: Got unexpected state %d. Closing.",conn->state);
131 #ifdef TOR_FRAGILE
132 tor_assert(0);
133 #endif
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.
142 int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
143 tor_assert(CONN_IS_EDGE(conn));
145 if (conn->marked_for_close)
146 return 0; /* already marked; probably got an 'end' */
147 log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
148 circ_id);
149 if (conn->type == CONN_TYPE_AP) {
150 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
151 } else {
152 conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
153 connection_mark_for_close(conn);
154 conn->hold_open_until_flushed = 1;
156 conn->cpath_layer = NULL;
157 return 0;
160 /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
161 * with a destination of cpath_layer. (If cpath_layer is NULL, the
162 * destination is the circuit's origin.) Mark the relay end cell as
163 * closing because of <b>reason</b>.
165 * Return -1 if this function has already been called on this conn,
166 * else return 0.
169 connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
171 char payload[5];
172 size_t payload_len=1;
173 circuit_t *circ;
175 if (conn->has_sent_end) {
176 log_fn(LOG_WARN,"Harmless bug: Calling connection_edge_end (reason %d) on an already ended stream?", reason);
177 #ifdef TOR_FRAGILE
178 tor_assert(0);
179 #endif
180 return -1;
183 if (conn->marked_for_close) {
184 log_fn(LOG_WARN,"Bug: called on conn that's already marked for close at %s:%d.",
185 conn->marked_for_close_file, conn->marked_for_close);
186 return 0;
189 payload[0] = reason;
190 if (reason == END_STREAM_REASON_EXITPOLICY) {
191 /* this is safe even for rend circs, because they never fail
192 * because of exitpolicy */
193 set_uint32(payload+1, htonl(conn->addr));
194 payload_len += 4;
197 circ = circuit_get_by_conn(conn);
198 if (circ && !circ->marked_for_close) {
199 log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
200 connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
201 payload, payload_len, cpath_layer);
202 } else {
203 log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
206 conn->has_sent_end = 1;
207 return 0;
210 /** An error has just occured on an operation on an edge connection
211 * <b>conn</b>. Extract the errno; convert it to an end reason, and send
212 * an appropriate relay end cell to <b>cpath_layer</b>.
215 connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer)
217 uint8_t reason;
218 tor_assert(conn);
219 reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->s));
220 return connection_edge_end(conn, reason, cpath_layer);
223 /** Connection <b>conn</b> has finished writing and has no bytes left on
224 * its outbuf.
226 * If it's in state 'open', stop writing, consider responding with a
227 * sendme, and return.
228 * Otherwise, stop writing and return.
230 * If <b>conn</b> is broken, mark it for close and return -1, else
231 * return 0.
233 int connection_edge_finished_flushing(connection_t *conn) {
234 tor_assert(conn);
235 tor_assert(CONN_IS_EDGE(conn));
237 switch (conn->state) {
238 case AP_CONN_STATE_OPEN:
239 case EXIT_CONN_STATE_OPEN:
240 connection_stop_writing(conn);
241 connection_edge_consider_sending_sendme(conn);
242 return 0;
243 case AP_CONN_STATE_SOCKS_WAIT:
244 case AP_CONN_STATE_RENDDESC_WAIT:
245 case AP_CONN_STATE_CIRCUIT_WAIT:
246 case AP_CONN_STATE_CONNECT_WAIT:
247 case AP_CONN_STATE_CONTROLLER_WAIT:
248 connection_stop_writing(conn);
249 return 0;
250 default:
251 log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
252 #ifdef TOR_FRAGILE
253 tor_assert(0);
254 #endif
255 return -1;
257 return 0;
260 /** Connected handler for exit connections: start writing pending
261 * data, deliver 'CONNECTED' relay cells as appropriate, and check
262 * any pending data that may have been received. */
263 int connection_edge_finished_connecting(connection_t *conn)
265 unsigned char connected_payload[4];
267 tor_assert(conn);
268 tor_assert(conn->type == CONN_TYPE_EXIT);
269 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
271 log_fn(LOG_INFO,"Exit connection to %s:%u established.",
272 conn->address,conn->port);
274 conn->state = EXIT_CONN_STATE_OPEN;
275 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
276 if (connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
277 connection_start_writing(conn);
278 /* deliver a 'connected' relay cell back through the circuit. */
279 if (connection_edge_is_rendezvous_stream(conn)) {
280 if (connection_edge_send_command(conn, circuit_get_by_conn(conn),
281 RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
282 return 0; /* circuit is closed, don't continue */
283 } else {
284 *(uint32_t*)connected_payload = htonl(conn->addr);
285 if (connection_edge_send_command(conn, circuit_get_by_conn(conn),
286 RELAY_COMMAND_CONNECTED, connected_payload, 4, conn->cpath_layer) < 0)
287 return 0; /* circuit is closed, don't continue */
289 tor_assert(conn->package_window > 0);
290 /* in case the server has written anything */
291 return connection_edge_process_inbuf(conn, 1);
294 /** Find all general-purpose AP streams waiting for a response that sent
295 * their begin/resolve cell >=15 seconds ago. Detach from their current circuit,
296 * and mark their current circuit as unsuitable for new streams. Then call
297 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
298 * available) or launch a new one.
300 * For rendezvous streams, simply give up after 45 seconds (with no
301 * retry attempt).
303 void connection_ap_expire_beginning(void) {
304 connection_t **carray;
305 connection_t *conn;
306 circuit_t *circ;
307 int n, i;
308 time_t now = time(NULL);
309 or_options_t *options = get_options();
311 get_connection_array(&carray, &n);
313 for (i = 0; i < n; ++i) {
314 conn = carray[i];
315 if (conn->type != CONN_TYPE_AP)
316 continue;
317 if (conn->state == AP_CONN_STATE_CONTROLLER_WAIT) {
318 if (now - conn->timestamp_lastread >= 120) {
319 log_fn(LOG_NOTICE, "Closing unattached stream.");
320 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
322 continue;
325 else if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
326 conn->state != AP_CONN_STATE_CONNECT_WAIT)
327 continue;
328 if (now - conn->timestamp_lastread < 15)
329 continue;
330 circ = circuit_get_by_conn(conn);
331 if (!circ) { /* it's vanished? */
332 log_fn(LOG_INFO,"Conn is waiting (address %s), but lost its circ.",
333 conn->socks_request->address);
334 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
335 continue;
337 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
338 if (now - conn->timestamp_lastread > 45) {
339 log_fn(LOG_NOTICE,"Rend stream is %d seconds late. Giving up on address '%s'.",
340 (int)(now - conn->timestamp_lastread), conn->socks_request->address);
341 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
342 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
344 continue;
346 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
347 log_fn(LOG_NOTICE,"Stream is %d seconds late on address '%s'. Retrying.",
348 (int)(now - conn->timestamp_lastread), conn->socks_request->address);
349 circuit_log_path(LOG_NOTICE, circ);
350 /* send an end down the circuit */
351 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
352 /* un-mark it as ending, since we're going to reuse it */
353 conn->has_sent_end = 0;
354 /* kludge to make us not try this circuit again, yet to allow
355 * current streams on it to survive if they can: make it
356 * unattractive to use for new streams */
357 tor_assert(circ->timestamp_dirty);
358 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
359 /* give our stream another 15 seconds to try */
360 conn->timestamp_lastread += 15;
361 /* move it back into 'pending' state, and try to attach. */
362 if (connection_ap_detach_retriable(conn, circ)<0) {
363 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
365 } /* end for */
368 /** Tell any AP streams that are waiting for a new circuit that one is
369 * available.
371 void connection_ap_attach_pending(void)
373 connection_t **carray;
374 connection_t *conn;
375 int n, i;
377 get_connection_array(&carray, &n);
379 for (i = 0; i < n; ++i) {
380 conn = carray[i];
381 if (conn->marked_for_close ||
382 conn->type != CONN_TYPE_AP ||
383 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
384 continue;
385 if (connection_ap_handshake_attach_circuit(conn) < 0) {
386 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
391 /** The AP connection <b>conn</b> has just failed while attaching or
392 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
393 * might work. Detach the circuit, and either reattach it, launch a
394 * new circuit, tell the controller, or give up as a appropriate.
396 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
399 connection_ap_detach_retriable(connection_t *conn, circuit_t *circ)
401 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE);
402 conn->timestamp_lastread = time(NULL);
403 if (! get_options()->LeaveStreamsUnattached) {
404 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
405 circuit_detach_stream(circ,conn);
406 return connection_ap_handshake_attach_circuit(conn);
407 } else {
408 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
409 circuit_detach_stream(circ,conn);
410 return 0;
414 /** A client-side struct to remember requests to rewrite addresses
415 * to new addresses. These structs make up a tree, with addressmap
416 * below as its root.
418 * There are 5 ways to set an address mapping:
419 * - A MapAddress command from the controller [permanent]
420 * - An AddressMap directive in the torrc [permanent]
421 * - When a TrackHostExits torrc directive is triggered [temporary]
422 * - When a dns resolve succeeds [temporary]
423 * - When a dns resolve fails [temporary]
425 * When an addressmap request is made but one is already registered,
426 * the new one is replaced only if the currently registered one has
427 * no "new_address" (that is, it's in the process of dns resolve),
428 * or if the new one is permanent (expires==0 or 1).
430 * (We overload the 'expires' field, using "0" for mappings set via
431 * the configuration file, "1" for mappings set from the control
432 * interface, and other values for DNS mappings that can expire.)
434 typedef struct {
435 char *new_address;
436 time_t expires;
437 int num_resolve_failures;
438 } addressmap_entry_t;
440 typedef struct {
441 char *ipv4_address;
442 char *hostname_address;
443 } virtaddress_entry_t;
445 /** The tree of client-side address rewrite instructions. */
446 static strmap_t *addressmap=NULL;
448 * Tree mapping addresses to which virtual address, if any, we
449 * assigned them to.
451 * We maintain the following invariant: if [A,B] is in
452 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
453 * must be in addressmap. We do not require that the converse hold:
454 * if it fails, then we could end up mapping two virtual addresses to
455 * the same address, which is no disaster.
457 static strmap_t *virtaddress_reversemap=NULL;
459 /** Initialize addressmap. */
460 void addressmap_init(void) {
461 addressmap = strmap_new();
462 virtaddress_reversemap = strmap_new();
465 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
466 static void
467 addressmap_ent_free(void *_ent) {
468 addressmap_entry_t *ent = _ent;
469 tor_free(ent->new_address);
470 tor_free(ent);
473 static void
474 addressmap_virtaddress_ent_free(void *_ent) {
475 virtaddress_entry_t *ent = _ent;
476 tor_free(ent->ipv4_address);
477 tor_free(ent->hostname_address);
478 tor_free(ent);
481 static void
482 addressmap_virtaddress_remove(const char *addr, addressmap_entry_t *ent)
484 if (ent && ent->new_address && address_is_in_virtual_range(ent->new_address)) {
485 virtaddress_entry_t *ve =
486 strmap_get(virtaddress_reversemap, ent->new_address);
487 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
488 if (ve) {
489 if (!strcmp(addr, ve->ipv4_address))
490 tor_free(ve->ipv4_address);
491 if (!strcmp(addr, ve->hostname_address))
492 tor_free(ve->hostname_address);
493 if (!ve->ipv4_address && !ve->hostname_address) {
494 tor_free(ve);
495 strmap_remove(virtaddress_reversemap, ent->new_address);
501 static void
502 addressmap_ent_remove(const char *addr, addressmap_entry_t *ent)
504 addressmap_virtaddress_remove(addr, ent);
505 addressmap_ent_free(ent);
508 /** Remove all entries from the addressmap that were set via the
509 * configuration file or the command line. */
510 void
511 addressmap_clear_configured(void)
513 addressmap_get_mappings(NULL, 0, 0);
516 /** Remove all entries from the addressmap that are set to expire, ever. */
517 void
518 addressmap_clear_transient(void)
520 addressmap_get_mappings(NULL, 2, TIME_MAX);
523 /** Clean out entries from the addressmap cache that were
524 * added long enough ago that they are no longer valid.
526 void addressmap_clean(time_t now) {
527 addressmap_get_mappings(NULL, 2, now);
530 /** Free all the elements in the addressmap, and free the addressmap
531 * itself. */
532 void addressmap_free_all(void) {
533 strmap_free(addressmap, addressmap_ent_free);
534 addressmap = NULL;
535 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
538 /** Look at address, and rewrite it until it doesn't want any
539 * more rewrites; but don't get into an infinite loop.
540 * Don't write more than maxlen chars into address.
542 void addressmap_rewrite(char *address, size_t maxlen) {
543 addressmap_entry_t *ent;
544 int rewrites;
546 for (rewrites = 0; rewrites < 16; rewrites++) {
547 ent = strmap_get(addressmap, address);
549 if (!ent || !ent->new_address)
550 return; /* done, no rewrite needed */
552 log_fn(LOG_INFO, "Addressmap: rewriting '%s' to '%s'",
553 address, ent->new_address);
554 strlcpy(address, ent->new_address, maxlen);
556 log_fn(LOG_WARN,"Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
557 address);
558 /* it's fine to rewrite a rewrite, but don't loop forever */
561 /** Return 1 if <b>address</b> is already registered, else return 0 */
562 int addressmap_already_mapped(const char *address) {
563 return strmap_get(addressmap, address) ? 1 : 0;
566 /** Register a request to map <b>address</b> to <b>new_address</b>,
567 * which will expire on <b>expires</b> (or 0 if never expires from
568 * config file, 1 if never expires from controller, 2 if never expires
569 * (virtual address mapping) from the controller.)
571 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
572 * free as appropriate. We will leave address alone.
574 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
575 * any mappings that exist from <b>address</b>.
577 void addressmap_register(const char *address, char *new_address, time_t expires) {
578 addressmap_entry_t *ent;
580 ent = strmap_get(addressmap, address);
581 if (!new_address || !strcasecmp(address,new_address)) {
582 /* Remove the mapping, if any. */
583 tor_free(new_address);
584 if (ent) {
585 addressmap_ent_remove(address,ent);
586 strmap_remove(addressmap, address);
588 return;
590 if (!ent) { /* make a new one and register it */
591 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
592 strmap_set(addressmap, address, ent);
593 } else if (ent->new_address) { /* we need to clean up the old mapping. */
594 if (expires > 1) {
595 log_fn(LOG_INFO,"Temporary addressmap ('%s' to '%s') not performed, since it's already mapped to '%s'", address, new_address, ent->new_address);
596 tor_free(new_address);
597 return;
599 if (address_is_in_virtual_range(ent->new_address) &&
600 expires != 2) {
601 /* XXX This isn't the perfect test; we want to avoid removing
602 * mappings set from the control interface _as virtual mapping */
603 addressmap_virtaddress_remove(address, ent);
605 tor_free(ent->new_address);
606 } /* else { we have an in-progress resolve with no mapping. } */
608 ent->new_address = new_address;
609 ent->expires = expires==2 ? 1 : expires;
610 ent->num_resolve_failures = 0;
612 log_fn(LOG_INFO, "Addressmap: (re)mapped '%s' to '%s'",
613 address, ent->new_address);
616 /** An attempt to resolve <b>address</b> failed at some OR.
617 * Increment the number of resolve failures we have on record
618 * for it, and then return that number.
620 int client_dns_incr_failures(const char *address)
622 addressmap_entry_t *ent;
623 ent = strmap_get(addressmap,address);
624 if (!ent) {
625 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
626 ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
627 strmap_set(addressmap,address,ent);
629 ++ent->num_resolve_failures;
630 log_fn(LOG_INFO,"Address %s now has %d resolve failures.",
631 address, ent->num_resolve_failures);
632 return ent->num_resolve_failures;
635 /** Record the fact that <b>address</b> resolved to <b>val</b>.
636 * We can now use this in subsequent streams via addressmap_rewrite()
637 * so we can more correctly choose an exit that will allow <b>address</b>.
639 * If <b>exitname</b> is defined, then append the addresses with
640 * ".exitname.exit" before registering the mapping.
642 void client_dns_set_addressmap(const char *address, uint32_t val, const char *exitname)
644 struct in_addr in;
645 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
646 char valbuf[INET_NTOA_BUF_LEN];
647 char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
649 tor_assert(address); tor_assert(val);
651 if (tor_inet_aton(address, &in))
652 return; /* If address was an IP address already, don't add a mapping. */
653 in.s_addr = htonl(val);
654 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
655 if (exitname) {
656 tor_snprintf(extendedaddress, sizeof(extendedaddress),
657 "%s.%s.exit", address, exitname);
658 tor_snprintf(extendedval, sizeof(extendedval),
659 "%s.%s.exit", valbuf, exitname);
660 } else {
661 tor_snprintf(extendedaddress, sizeof(extendedaddress),
662 "%s", address);
663 tor_snprintf(extendedval, sizeof(extendedval),
664 "%s", valbuf);
666 addressmap_register(extendedaddress, tor_strdup(extendedval),
667 time(NULL) + MAX_DNS_ENTRY_AGE);
670 /* Currently, we hand out 127.192.0.1 through 127.254.254.254.
671 * These addresses should map to localhost, so even if the
672 * application accidentally tried to connect to them directly (not
673 * via Tor), it wouldn't get too far astray.
675 * Eventually, we should probably make this configurable.
677 #define MIN_UNUSED_IPV4 0x7fc00001u
678 #define MAX_UNUSED_IPV4 0x7ffefefeu
681 * Return true iff <b>addr</b> is likely to have been returned by
682 * client_dns_get_unused_address.
684 static int
685 address_is_in_virtual_range(const char *addr)
687 struct in_addr in;
688 tor_assert(addr);
689 if (!strcasecmpend(addr, ".virtual")) {
690 return 1;
691 } else if (tor_inet_aton(addr, &in)) {
692 uint32_t a = ntohl(in.s_addr);
693 if (a >= MIN_UNUSED_IPV4 && a <= MAX_UNUSED_IPV4)
694 return 1;
696 return 0;
699 /** Return a newly allocated string holding an address of <b>type</b>
700 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
701 * and that is very unlikely to be the address of any real host.
703 static char *
704 addressmap_get_virtual_address(int type)
706 char buf[64];
707 static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
708 struct in_addr in;
710 if (type == RESOLVED_TYPE_HOSTNAME) {
711 char rand[10];
712 do {
713 crypto_rand(rand, sizeof(rand));
714 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
715 strlcat(buf, ".virtual", sizeof(buf));
716 } while (strmap_get(addressmap, buf));
717 return tor_strdup(buf);
718 } else if (type == RESOLVED_TYPE_IPV4) {
719 while (1) {
720 /* Don't hand out any .0 or .255 address. */
721 while ((next_ipv4 & 0xff) == 0 ||
722 (next_ipv4 & 0xff) == 0xff)
723 ++next_ipv4;
724 in.s_addr = htonl(next_ipv4);
725 tor_inet_ntoa(&in, buf, sizeof(buf));
726 if (!strmap_get(addressmap, buf))
727 break;
729 ++next_ipv4;
730 if (next_ipv4 > MAX_UNUSED_IPV4)
731 next_ipv4 = MIN_UNUSED_IPV4;
733 return tor_strdup(buf);
734 } else {
735 log_fn(LOG_WARN, "Called with unsupported address type (%d)",
736 type);
737 return NULL;
741 /** A controller has requested that we map some address of type
742 * <b>type</b> to the address <b>new_address</b>. Choose an address
743 * that is unlikely to be used, and map it, and return it in a newly
744 * allocated string. If another address of the same type is already
745 * mapped to <b>new_address</b>, try to return a copy of that address.
747 * The string in <b>new_address</b> may be freed, or inserted into a map
748 * as appropriate.
750 const char *
751 addressmap_register_virtual_address(int type, char *new_address)
753 char **addrp;
754 virtaddress_entry_t *vent;
756 tor_assert(new_address);
757 tor_assert(addressmap);
758 tor_assert(virtaddress_reversemap);
760 vent = strmap_get(virtaddress_reversemap, new_address);
761 if (!vent) {
762 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
763 strmap_set(virtaddress_reversemap, new_address, vent);
766 addrp = (type == RESOLVED_TYPE_IPV4) ?
767 &vent->ipv4_address : &vent->hostname_address;
768 if (*addrp) {
769 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
770 if (ent && ent->new_address && !strcasecmp(new_address, ent->new_address)) {
771 tor_free(new_address);
772 return tor_strdup(*addrp);
773 } else
774 log_fn(LOG_WARN, "Internal confusion: I thought that '%s' was mapped to by '%s', but '%s' really maps to '%s'. This is a harmless bug.",
775 new_address, *addrp, *addrp, ent?ent->new_address:"(nothing)");
778 tor_free(*addrp);
779 *addrp = addressmap_get_virtual_address(type);
780 addressmap_register(*addrp, new_address, 2);
782 #if 0
784 addressmap_entry_t *ent;
785 ent = strmap_get(addressmap, *addrp);
786 tor_assert(ent);
787 tor_assert(!strcasecmp(ent->new_address,new_address));
788 vent = strmap_get(virtaddress_reversemap, new_address);
789 tor_assert(vent);
790 tor_assert(!strcasecmp(*addrp,
791 (type == RESOLVED_TYPE_IPV4) ?
792 vent->ipv4_address : vent->hostname_address));
793 log_fn(LOG_INFO, "Map from %s to %s okay.",*addrp,new_address);
795 #endif
797 return *addrp;
800 /** Return 1 if <b>address</b> has funny characters in it like
801 * colons. Return 0 if it's fine.
803 static int
804 address_is_invalid_destination(const char *address) {
805 /* FFFF should flesh this out */
806 if (strchr(address,':'))
807 return 1;
808 return 0;
811 /** Iterate over all address mapings which have expiry times between
812 * min_expires and max_expires, inclusive. If sl is provided, add an
813 * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
814 * remove the mappings.
816 void
817 addressmap_get_mappings(smartlist_t *sl, time_t min_expires, time_t max_expires)
819 strmap_iter_t *iter;
820 const char *key;
821 void *_val;
822 addressmap_entry_t *val;
824 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
825 strmap_iter_get(iter, &key, &_val);
826 val = _val;
827 if (val->expires >= min_expires && val->expires <= max_expires) {
828 if (!sl) {
829 addressmap_ent_remove(key, val);
830 iter = strmap_iter_next_rmv(addressmap,iter);
831 continue;
832 } else if (val->new_address) {
833 size_t len = strlen(key)+strlen(val->new_address)+2;
834 char *line = tor_malloc(len);
835 tor_snprintf(line, len, "%s %s", key, val->new_address);
836 smartlist_add(sl, line);
839 iter = strmap_iter_next(addressmap,iter);
843 /** connection_edge_process_inbuf() found a conn in state
844 * socks_wait. See if conn->inbuf has the right bytes to proceed with
845 * the socks handshake.
847 * If the handshake is complete, and it's for a general circuit, then
848 * try to attach it to a circuit (or launch one as needed). If it's for
849 * a rendezvous circuit, then fetch a rendezvous descriptor first (or
850 * attach/launch a circuit if the rendezvous descriptor is already here
851 * and fresh enough).
853 * Return -1 if an unexpected error with conn (and it should be marked
854 * for close), else return 0.
856 static int connection_ap_handshake_process_socks(connection_t *conn) {
857 socks_request_t *socks;
858 int sockshere;
859 hostname_type_t addresstype;
861 tor_assert(conn);
862 tor_assert(conn->type == CONN_TYPE_AP);
863 tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
864 tor_assert(conn->socks_request);
865 socks = conn->socks_request;
867 log_fn(LOG_DEBUG,"entered.");
869 sockshere = fetch_from_buf_socks(conn->inbuf, socks);
870 if (sockshere == 0) {
871 if (socks->replylen) {
872 connection_write_to_buf(socks->reply, socks->replylen, conn);
873 socks->replylen = 0; /* zero it out so we can do another round of negotiation */
874 } else {
875 log_fn(LOG_DEBUG,"socks handshake not all here yet.");
877 return 0;
878 } else if (sockshere == -1) {
879 if (socks->replylen) { /* we should send reply back */
880 log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
881 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
882 SOCKS5_GENERAL_ERROR);
883 } else {
884 log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
885 connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
887 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
888 return -1;
889 } /* else socks handshake is done, continue processing */
891 tor_strlower(socks->address); /* normalize it */
893 /* For address map controls, remap the address */
894 addressmap_rewrite(socks->address, sizeof(socks->address));
896 if (address_is_in_virtual_range(socks->address)) {
897 /* This address was probably handed out by client_dns_get_unmapped_address,
898 * but the mapping was discarded for some reason. We *don't* want to send
899 * the address through tor; that's likely to fail, and may leak
900 * information.
902 log_fn(LOG_WARN,"Missing mapping for virtual address '%s'. Refusing.",
903 socks->address);
904 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
905 return -1;
908 /* Parse the address provided by SOCKS. Modify it in-place if it
909 * specifies a hidden-service (.onion) or particular exit node (.exit).
911 addresstype = parse_extended_hostname(socks->address);
913 if (addresstype == EXIT_HOSTNAME) {
914 /* .exit -- modify conn to specify the exit node. */
915 char *s = strrchr(socks->address,'.');
916 if (!s || s[1] == '\0') {
917 log_fn(LOG_WARN,"Malformed exit address '%s'. Refusing.", socks->address);
918 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
919 return -1;
921 conn->chosen_exit_name = tor_strdup(s+1);
922 *s = 0;
925 if (addresstype != ONION_HOSTNAME) {
926 /* not a hidden-service request (i.e. normal or .exit) */
928 if (address_is_invalid_destination(socks->address)) {
929 log_fn(LOG_WARN,"Destination '%s' seems to be an invalid hostname. Failing.", socks->address);
930 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
931 return -1;
934 if (socks->command == SOCKS_COMMAND_RESOLVE) {
935 uint32_t answer;
936 struct in_addr in;
937 /* Reply to resolves immediately if we can. */
938 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
939 log_fn(LOG_WARN,"Address to be resolved is too large. Failing.");
940 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
941 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
942 return -1;
944 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
945 answer = in.s_addr;
946 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
947 (char*)&answer);
948 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
949 return 0;
951 rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
952 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE);
953 } else { /* socks->command == SOCKS_COMMAND_CONNECT */
954 if (socks->port == 0) {
955 log_fn(LOG_NOTICE,"Application asked to connect to port 0. Refusing.");
956 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
957 return -1;
959 rep_hist_note_used_port(socks->port, time(NULL)); /* help predict this next time */
960 control_event_stream_status(conn, STREAM_EVENT_NEW);
962 if (! get_options()->LeaveStreamsUnattached) {
963 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
964 if (connection_ap_handshake_attach_circuit(conn) < 0) {
965 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
966 return -1;
968 return 0;
969 } else {
970 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
971 return 0;
973 } else {
974 /* it's a hidden-service request */
975 rend_cache_entry_t *entry;
976 int r;
978 if (socks->command == SOCKS_COMMAND_RESOLVE) {
979 /* if it's a resolve request, fail it right now, rather than
980 * building all the circuits and then realizing it won't work. */
981 log_fn(LOG_WARN,"Resolve requests to hidden services not allowed. Failing.");
982 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
983 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
984 return -1;
987 strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
988 log_fn(LOG_INFO,"Got a hidden service request for ID '%s'", conn->rend_query);
989 /* see if we already have it cached */
990 r = rend_cache_lookup_entry(conn->rend_query, &entry);
991 if (r<0) {
992 log_fn(LOG_WARN,"Invalid service descriptor %s", conn->rend_query);
993 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
994 return -1;
996 if (r==0) {
997 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
998 log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.", conn->rend_query);
999 rend_client_refetch_renddesc(conn->rend_query);
1000 return 0;
1002 if (r>0) {
1003 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
1004 if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
1005 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1006 log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
1007 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1008 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1009 return -1;
1011 return 0;
1012 } else {
1013 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1014 log_fn(LOG_INFO, "Stale descriptor %s. Refetching.", conn->rend_query);
1015 rend_client_refetch_renddesc(conn->rend_query);
1016 return 0;
1020 return 0; /* unreached but keeps the compiler happy */
1023 /** Iterate over the two bytes of stream_id until we get one that is not
1024 * already in use; return it. Return 0 if can't get a unique stream_id.
1026 static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
1027 connection_t *tmpconn;
1028 uint16_t test_stream_id;
1029 uint32_t attempts=0;
1031 again:
1032 test_stream_id = circ->next_stream_id++;
1033 if (++attempts > 1<<16) {
1034 /* Make sure we don't loop forever if all stream_id's are used. */
1035 log_fn(LOG_WARN,"No unused stream IDs. Failing.");
1036 return 0;
1038 if (test_stream_id == 0)
1039 goto again;
1040 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
1041 if (tmpconn->stream_id == test_stream_id)
1042 goto again;
1043 return test_stream_id;
1046 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1047 * socks_request field, and send it down circ.
1049 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1051 int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
1053 char payload[CELL_PAYLOAD_SIZE];
1054 int payload_len;
1056 tor_assert(ap_conn->type == CONN_TYPE_AP);
1057 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1058 tor_assert(ap_conn->socks_request);
1060 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1061 if (ap_conn->stream_id==0) {
1062 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1063 circuit_mark_for_close(circ);
1064 return -1;
1067 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
1068 (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
1069 ap_conn->socks_request->address : "",
1070 ap_conn->socks_request->port);
1071 payload_len = strlen(payload)+1;
1073 log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1075 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
1076 payload, payload_len, ap_conn->cpath_layer) < 0)
1077 return -1; /* circuit is closed, don't continue */
1079 ap_conn->package_window = STREAMWINDOW_START;
1080 ap_conn->deliver_window = STREAMWINDOW_START;
1081 ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
1082 log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",
1083 ap_conn->s, circ->n_circ_id);
1084 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
1085 return 0;
1088 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1089 * socks_request field, and send it down circ.
1091 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1093 int connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
1095 int payload_len;
1096 const char *string_addr;
1098 tor_assert(ap_conn->type == CONN_TYPE_AP);
1099 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1100 tor_assert(ap_conn->socks_request);
1101 tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
1102 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
1104 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1105 if (ap_conn->stream_id==0) {
1106 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1107 circuit_mark_for_close(circ);
1108 return -1;
1111 string_addr = ap_conn->socks_request->address;
1112 payload_len = strlen(string_addr)+1;
1113 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
1115 log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1117 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
1118 string_addr, payload_len, ap_conn->cpath_layer) < 0)
1119 return -1; /* circuit is closed, don't continue */
1121 ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
1122 log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",
1123 ap_conn->s, circ->n_circ_id);
1124 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
1125 return 0;
1128 /** Make an AP connection_t, do a socketpair and attach one side
1129 * to the conn, connection_add it, initialize it to circuit_wait,
1130 * and call connection_ap_handshake_attach_circuit(conn) on it.
1132 * Return the other end of the socketpair, or -1 if error.
1134 int connection_ap_make_bridge(char *address, uint16_t port) {
1135 int fd[2];
1136 connection_t *conn;
1138 log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
1140 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
1141 log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
1142 tor_socket_strerror(tor_socket_errno(-1)));
1143 return -1;
1146 set_socket_nonblocking(fd[0]);
1147 set_socket_nonblocking(fd[1]);
1149 conn = connection_new(CONN_TYPE_AP);
1150 conn->s = fd[0];
1152 /* populate conn->socks_request */
1154 /* leave version at zero, so the socks_reply is empty */
1155 conn->socks_request->socks_version = 0;
1156 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
1157 strlcpy(conn->socks_request->address, address,
1158 sizeof(conn->socks_request->address));
1159 conn->socks_request->port = port;
1160 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
1162 conn->address = tor_strdup("(local bridge)");
1163 conn->addr = 0;
1164 conn->port = 0;
1166 if (connection_add(conn) < 0) { /* no space, forget it */
1167 connection_free(conn); /* this closes fd[0] */
1168 tor_close_socket(fd[1]);
1169 return -1;
1172 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1173 connection_start_reading(conn);
1175 /* attaching to a dirty circuit is fine */
1176 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1177 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1178 tor_close_socket(fd[1]);
1179 return -1;
1182 log_fn(LOG_INFO,"... AP bridge created and connected.");
1183 return fd[1];
1186 /** Send an answer to an AP connection that has requested a DNS lookup
1187 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6) or
1188 * -1 for unreachable; the answer should be in the format specified
1189 * in the socks extensions document.
1191 void connection_ap_handshake_socks_resolved(connection_t *conn,
1192 int answer_type,
1193 size_t answer_len,
1194 const char *answer)
1196 char buf[256];
1197 size_t replylen;
1199 if (answer_type == RESOLVED_TYPE_IPV4) {
1200 uint32_t a = get_uint32(answer);
1201 if (a)
1202 client_dns_set_addressmap(conn->socks_request->address, ntohl(a),
1203 conn->chosen_exit_name);
1206 if (conn->socks_request->socks_version == 4) {
1207 buf[0] = 0x00; /* version */
1208 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1209 buf[1] = 90; /* "Granted" */
1210 set_uint16(buf+2, 0);
1211 memcpy(buf+4, answer, 4); /* address */
1212 replylen = SOCKS4_NETWORK_LEN;
1213 } else {
1214 buf[1] = 91; /* "error" */
1215 memset(buf+2, 0, 6);
1216 replylen = SOCKS4_NETWORK_LEN;
1218 } else {
1219 /* SOCKS5 */
1220 buf[0] = 0x05; /* version */
1221 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1222 buf[1] = SOCKS5_SUCCEEDED;
1223 buf[2] = 0; /* reserved */
1224 buf[3] = 0x01; /* IPv4 address type */
1225 memcpy(buf+4, answer, 4); /* address */
1226 set_uint16(buf+8, 0); /* port == 0. */
1227 replylen = 10;
1228 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
1229 buf[1] = SOCKS5_SUCCEEDED;
1230 buf[2] = 0; /* reserved */
1231 buf[3] = 0x04; /* IPv6 address type */
1232 memcpy(buf+4, answer, 16); /* address */
1233 set_uint16(buf+20, 0); /* port == 0. */
1234 replylen = 22;
1235 } else {
1236 buf[1] = SOCKS5_HOST_UNREACHABLE;
1237 memset(buf+2, 0, 8);
1238 replylen = 10;
1241 connection_ap_handshake_socks_reply(conn, buf, replylen,
1242 (answer_type == RESOLVED_TYPE_IPV4 ||
1243 answer_type == RESOLVED_TYPE_IPV6) ?
1244 SOCKS5_SUCCEEDED : SOCKS5_HOST_UNREACHABLE);
1247 /** Send a socks reply to stream <b>conn</b>, using the appropriate
1248 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
1249 * handshaking.
1251 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
1252 * to conn and return, else reply based on <b>status</b>.
1254 * If <b>reply</b> is undefined, <b>status</b> can't be 0.
1256 void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
1257 size_t replylen,
1258 socks5_reply_status_t status) {
1259 char buf[256];
1260 tor_assert(conn->socks_request); /* make sure it's an AP stream */
1262 control_event_stream_status(conn,
1263 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
1265 if (conn->socks_request->has_finished) {
1266 log_fn(LOG_WARN, "Harmless bug: duplicate calls to connection_ap_handshake_socks_reply.");
1267 return;
1269 if (replylen) { /* we already have a reply in mind */
1270 connection_write_to_buf(reply, replylen, conn);
1271 conn->socks_request->has_finished = 1;
1272 return;
1274 if (conn->socks_request->socks_version == 4) {
1275 memset(buf,0,SOCKS4_NETWORK_LEN);
1276 #define SOCKS4_GRANTED 90
1277 #define SOCKS4_REJECT 91
1278 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
1279 /* leave version, destport, destip zero */
1280 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
1281 } else if (conn->socks_request->socks_version == 5) {
1282 buf[0] = 5; /* version 5 */
1283 buf[1] = (char)status;
1284 buf[2] = 0;
1285 buf[3] = 1; /* ipv4 addr */
1286 memset(buf+4,0,6); /* Set external addr/port to 0.
1287 The spec doesn't seem to say what to do here. -RD */
1288 connection_write_to_buf(buf,10,conn);
1290 /* If socks_version isn't 4 or 5, don't send anything.
1291 * This can happen in the case of AP bridges. */
1292 conn->socks_request->has_finished = 1;
1293 return;
1296 /** A relay 'begin' cell has arrived, and either we are an exit hop
1297 * for the circuit, or we are the origin and it is a rendezvous begin.
1299 * Launch a new exit connection and initialize things appropriately.
1301 * If it's a rendezvous stream, call connection_exit_connect() on
1302 * it.
1304 * For general streams, call dns_resolve() on it first, and only call
1305 * connection_exit_connect() if the dns answer is already known.
1307 * Note that we don't call connection_add() on the new stream! We wait
1308 * for connection_exit_connect() to do that.
1310 * Return -1 if we want to tear down <b>circ</b>. Else return 0.
1312 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
1313 connection_t *n_stream;
1314 relay_header_t rh;
1315 char *address=NULL;
1316 uint16_t port;
1318 assert_circuit_ok(circ);
1319 relay_header_unpack(&rh, cell->payload);
1321 /* XXX currently we don't send an end cell back if we drop the
1322 * begin because it's malformed.
1325 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
1326 log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
1327 return 0;
1329 if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
1330 log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
1331 return 0;
1333 if (port==0) {
1334 log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
1335 tor_free(address);
1336 return 0;
1339 log_fn(LOG_DEBUG,"Creating new exit connection.");
1340 n_stream = connection_new(CONN_TYPE_EXIT);
1341 n_stream->purpose = EXIT_PURPOSE_CONNECT;
1343 n_stream->stream_id = rh.stream_id;
1344 n_stream->port = port;
1345 /* leave n_stream->s at -1, because it's not yet valid */
1346 n_stream->package_window = STREAMWINDOW_START;
1347 n_stream->deliver_window = STREAMWINDOW_START;
1349 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1350 log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
1351 n_stream->address = tor_strdup("(rendezvous)");
1352 n_stream->state = EXIT_CONN_STATE_CONNECTING;
1353 strlcpy(n_stream->rend_query, circ->rend_query,
1354 sizeof(n_stream->rend_query));
1355 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
1356 assert_circuit_ok(circ);
1357 if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
1358 log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
1359 connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
1360 connection_free(n_stream);
1361 circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
1362 tor_free(address);
1363 return 0;
1365 assert_circuit_ok(circ);
1366 log_fn(LOG_DEBUG,"Finished assigning addr/port");
1367 n_stream->cpath_layer = circ->cpath->prev; /* link it */
1369 /* add it into the linked list of n_streams on this circuit */
1370 n_stream->next_stream = circ->n_streams;
1371 circ->n_streams = n_stream;
1372 assert_circuit_ok(circ);
1374 connection_exit_connect(n_stream);
1375 tor_free(address);
1376 return 0;
1378 tor_strlower(address);
1379 n_stream->address = address;
1380 n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
1381 /* default to failed, change in dns_resolve if it turns out not to fail */
1383 if (we_are_hibernating()) {
1384 connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING, n_stream->cpath_layer);
1385 connection_free(n_stream);
1386 return 0;
1389 /* send it off to the gethostbyname farm */
1390 switch (dns_resolve(n_stream)) {
1391 case 1: /* resolve worked */
1393 /* add it into the linked list of n_streams on this circuit */
1394 n_stream->next_stream = circ->n_streams;
1395 circ->n_streams = n_stream;
1396 assert_circuit_ok(circ);
1398 connection_exit_connect(n_stream);
1399 return 0;
1400 case -1: /* resolve failed */
1401 /* n_stream got freed. don't touch it. */
1402 break;
1403 case 0: /* resolve added to pending list */
1404 /* add it into the linked list of resolving_streams on this circuit */
1405 n_stream->next_stream = circ->resolving_streams;
1406 circ->resolving_streams = n_stream;
1407 assert_circuit_ok(circ);
1410 return 0;
1414 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
1415 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
1417 int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ) {
1418 connection_t *dummy_conn;
1419 relay_header_t rh;
1421 assert_circuit_ok(circ);
1422 relay_header_unpack(&rh, cell->payload);
1424 /* This 'dummy_conn' only exists to remember the stream ID
1425 * associated with the resolve request; and to make the
1426 * implementation of dns.c more uniform. (We really only need to
1427 * remember the circuit, the stream ID, and the hostname to be
1428 * resolved; but if we didn't store them in a connection like this,
1429 * the housekeeping in dns.c would get way more complicated.)
1431 dummy_conn = connection_new(CONN_TYPE_EXIT);
1432 dummy_conn->stream_id = rh.stream_id;
1433 dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
1434 rh.length);
1435 dummy_conn->port = 0;
1436 dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
1437 dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
1439 /* send it off to the gethostbyname farm */
1440 switch (dns_resolve(dummy_conn)) {
1441 case -1: /* Impossible to resolve; a resolved cell was sent. */
1442 /* Connection freed; don't touch it. */
1443 return 0;
1444 case 1: /* The result was cached; a resolved cell was sent. */
1445 if (!dummy_conn->marked_for_close)
1446 connection_free(dummy_conn);
1447 return 0;
1448 case 0: /* resolve added to pending list */
1449 dummy_conn->next_stream = circ->resolving_streams;
1450 circ->resolving_streams = dummy_conn;
1451 assert_circuit_ok(circ);
1452 break;
1454 return 0;
1457 /** Connect to conn's specified addr and port. If it worked, conn
1458 * has now been added to the connection_array.
1460 * Send back a connected cell. Include the resolved IP of the destination
1461 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
1462 * streams must not reveal what IP they connected to.)
1464 void
1465 connection_exit_connect(connection_t *conn) {
1466 unsigned char connected_payload[4];
1467 uint32_t addr;
1468 uint16_t port;
1470 if (!connection_edge_is_rendezvous_stream(conn) &&
1471 router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
1472 log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
1473 connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
1474 circuit_detach_stream(circuit_get_by_conn(conn), conn);
1475 connection_free(conn);
1476 return;
1479 addr = conn->addr;
1480 port = conn->port;
1481 if (redirect_exit_list) {
1482 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
1484 if ((addr&r->mask)==(r->addr&r->mask) &&
1485 (r->port_min <= port) && (port <= r->port_max)) {
1486 struct in_addr in;
1487 if (r->is_redirect) {
1488 char tmpbuf[INET_NTOA_BUF_LEN];
1489 addr = r->addr_dest;
1490 port = r->port_dest;
1491 in.s_addr = htonl(addr);
1492 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
1493 log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
1494 conn->address, conn->port, tmpbuf, port);
1496 break;
1501 log_fn(LOG_DEBUG,"about to try connecting");
1502 switch (connection_connect(conn, conn->address, addr, port)) {
1503 case -1:
1504 connection_edge_end_errno(conn, conn->cpath_layer);
1505 circuit_detach_stream(circuit_get_by_conn(conn), conn);
1506 connection_free(conn);
1507 return;
1508 case 0:
1509 conn->state = EXIT_CONN_STATE_CONNECTING;
1511 connection_watch_events(conn, EV_WRITE | EV_READ);
1512 /* writable indicates finish;
1513 * readable/error indicates broken link in windowsland. */
1514 return;
1515 /* case 1: fall through */
1518 conn->state = EXIT_CONN_STATE_OPEN;
1519 if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
1520 log_fn(LOG_WARN,"Bug: newly connected conn had data waiting!");
1521 // connection_start_writing(conn);
1523 connection_watch_events(conn, EV_READ);
1525 /* also, deliver a 'connected' cell back through the circuit. */
1526 if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
1527 /* don't send an address back! */
1528 connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
1529 NULL, 0, conn->cpath_layer);
1530 } else { /* normal stream */
1531 /* This must be the original address, not the redirected address. */
1532 *(uint32_t*)connected_payload = htonl(conn->addr);
1533 connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
1534 connected_payload, 4, conn->cpath_layer);
1538 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
1539 * it is a general stream.
1541 int connection_edge_is_rendezvous_stream(connection_t *conn) {
1542 tor_assert(conn);
1543 if (*conn->rend_query) /* XXX */
1544 return 1;
1545 return 0;
1548 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
1549 * to exit from it, or 0 if it probably will not allow it.
1550 * (We might be uncertain if conn's destination address has not yet been
1551 * resolved.)
1553 int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
1555 tor_assert(conn);
1556 tor_assert(conn->type == CONN_TYPE_AP);
1557 tor_assert(conn->socks_request);
1558 tor_assert(exit);
1560 log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
1561 exit->nickname, conn->socks_request->address,
1562 conn->socks_request->port);
1564 /* If a particular exit node has been requested for the new connection,
1565 * make sure the exit node of the existing circuit matches exactly.
1567 if (conn->chosen_exit_name) {
1568 if (router_get_by_nickname(conn->chosen_exit_name) != exit) {
1569 /* doesn't match */
1570 log_fn(LOG_DEBUG,"Requested node '%s', considering node '%s'. No.",
1571 conn->chosen_exit_name, exit->nickname);
1572 return 0;
1576 if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
1577 struct in_addr in;
1578 uint32_t addr = 0;
1579 addr_policy_result_t r;
1580 if (tor_inet_aton(conn->socks_request->address, &in))
1581 addr = ntohl(in.s_addr);
1582 r = router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
1583 exit->exit_policy);
1584 if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
1585 return 0;
1587 return 1;
1590 /** A helper function for socks_policy_permits_address() below.
1592 * Parse options->SocksPolicy in the same way that the exit policy
1593 * is parsed, and put the processed version in &socks_policy.
1594 * Ignore port specifiers.
1596 void
1597 parse_socks_policy(void)
1599 addr_policy_t *n;
1600 if (socks_policy) {
1601 addr_policy_free(socks_policy);
1602 socks_policy = NULL;
1604 config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy);
1605 /* ports aren't used. */
1606 for (n=socks_policy; n; n = n->next) {
1607 n->prt_min = 1;
1608 n->prt_max = 65535;
1612 void
1613 free_socks_policy(void)
1615 addr_policy_free(socks_policy);
1616 socks_policy = NULL;
1619 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1620 * based on <b>socks_policy</b>. Else return 0.
1622 int socks_policy_permits_address(uint32_t addr)
1624 int a;
1626 if (!socks_policy) /* 'no socks policy' means 'accept' */
1627 return 1;
1628 a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
1629 if (a==ADDR_POLICY_REJECTED)
1630 return 0;
1631 else if (a==ADDR_POLICY_ACCEPTED)
1632 return 1;
1633 log_fn(LOG_WARN, "Bug: Got unexpected 'maybe' answer from socks policy");
1634 return 0;
1637 /** Make connection redirection follow the provided list of
1638 * exit_redirect_t */
1639 void
1640 set_exit_redirects(smartlist_t *lst)
1642 if (redirect_exit_list) {
1643 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
1644 smartlist_free(redirect_exit_list);
1646 redirect_exit_list = lst;
1649 /** If address is of the form "y.onion" with a well-formed handle y:
1650 * Put a '\0' after y, lower-case it, and return ONION_HOSTNAME.
1652 * If address is of the form "y.exit":
1653 * Put a '\0' after y and return EXIT_HOSTNAME.
1655 * Otherwise:
1656 * Return NORMAL_HOSTNAME and change nothing.
1658 hostname_type_t
1659 parse_extended_hostname(char *address) {
1660 char *s;
1661 char query[REND_SERVICE_ID_LEN+1];
1663 s = strrchr(address,'.');
1664 if (!s) return 0; /* no dot, thus normal */
1665 if (!strcmp(s+1,"exit")) {
1666 *s = 0; /* null-terminate it */
1667 return EXIT_HOSTNAME; /* .exit */
1669 if (strcmp(s+1,"onion"))
1670 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1672 /* so it is .onion */
1673 *s = 0; /* null-terminate it */
1674 if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
1675 goto failed;
1676 if (rend_valid_service_id(query)) {
1677 return ONION_HOSTNAME; /* success */
1679 failed:
1680 /* otherwise, return to previous state and return 0 */
1681 *s = '.';
1682 return NORMAL_HOSTNAME;