doxygeny goodness from tyranix
[tor.git] / src / or / connection_edge.c
blob844b6f04c3c39e6cc4992169ddf14b314ad7c763
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_edge_conn(conn),
70 RELAY_COMMAND_END,
71 NULL, 0, conn->cpath_layer);
73 return 0;
74 #else
75 if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
76 /* it still has stuff to process. don't let it die yet. */
77 return 0;
79 log_fn(LOG_INFO,"conn (fd %d) reached eof. Closing.", conn->s);
80 if (!conn->marked_for_close) {
81 /* only mark it if not already marked. it's possible to
82 * get the 'end' right around when the client hangs up on us. */
83 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
84 if (conn->socks_request) /* eof, so don't send a socks reply back */
85 conn->socks_request->has_finished = 1;
86 connection_mark_for_close(conn);
88 return 0;
89 #endif
92 /** Handle new bytes on conn->inbuf based on state:
93 * - If it's waiting for socks info, try to read another step of the
94 * socks handshake out of conn->inbuf.
95 * - If it's open, then package more relay cells from the stream.
96 * - Else, leave the bytes on inbuf alone for now.
98 * Mark and return -1 if there was an unexpected error with the conn,
99 * else return 0.
101 int connection_edge_process_inbuf(connection_t *conn, int package_partial) {
103 tor_assert(conn);
104 tor_assert(CONN_IS_EDGE(conn));
106 switch (conn->state) {
107 case AP_CONN_STATE_SOCKS_WAIT:
108 if (connection_ap_handshake_process_socks(conn) < 0) {
109 /* already marked */
110 return -1;
112 return 0;
113 case AP_CONN_STATE_OPEN:
114 case EXIT_CONN_STATE_OPEN:
115 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
116 /* (We already sent an end cell if possible) */
117 connection_mark_for_close(conn);
118 return -1;
120 return 0;
121 case EXIT_CONN_STATE_CONNECTING:
122 case AP_CONN_STATE_RENDDESC_WAIT:
123 case AP_CONN_STATE_CIRCUIT_WAIT:
124 case AP_CONN_STATE_CONNECT_WAIT:
125 case AP_CONN_STATE_RESOLVE_WAIT:
126 case AP_CONN_STATE_CONTROLLER_WAIT:
127 log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
128 conn_state_to_string(conn->type, conn->state));
129 return 0;
131 log_fn(LOG_WARN,"Bug: Got unexpected state %d. Closing.",conn->state);
132 tor_fragile_assert();
133 connection_edge_end(conn, END_STREAM_REASON_INTERNAL, conn->cpath_layer);
134 connection_mark_for_close(conn);
135 return -1;
138 /** This edge needs to be closed, because its circuit has closed.
139 * Mark it for close and return 0.
141 int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
142 tor_assert(CONN_IS_EDGE(conn));
144 if (!conn->marked_for_close) {
145 log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
146 circ_id);
147 if (conn->type == CONN_TYPE_AP) {
148 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
149 } else {
150 conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
151 connection_mark_for_close(conn);
152 conn->hold_open_until_flushed = 1;
155 conn->cpath_layer = NULL;
156 conn->on_circuit = 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 tor_fragile_assert();
178 return -1;
181 if (conn->marked_for_close) {
182 log_fn(LOG_WARN,"Bug: called on conn that's already marked for close at %s:%d.",
183 conn->marked_for_close_file, conn->marked_for_close);
184 return 0;
187 payload[0] = reason;
188 if (reason == END_STREAM_REASON_EXITPOLICY) {
189 /* this is safe even for rend circs, because they never fail
190 * because of exitpolicy */
191 set_uint32(payload+1, htonl(conn->addr));
192 payload_len += 4;
195 circ = circuit_get_by_edge_conn(conn);
196 if (circ && !circ->marked_for_close) {
197 log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
198 connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
199 payload, payload_len, cpath_layer);
200 } else {
201 log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
204 conn->has_sent_end = 1;
205 return 0;
208 /** An error has just occured on an operation on an edge connection
209 * <b>conn</b>. Extract the errno; convert it to an end reason, and send
210 * an appropriate relay end cell to <b>cpath_layer</b>.
213 connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer)
215 uint8_t reason;
216 tor_assert(conn);
217 reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->s));
218 return connection_edge_end(conn, reason, cpath_layer);
221 /** Connection <b>conn</b> has finished writing and has no bytes left on
222 * its outbuf.
224 * If it's in state 'open', stop writing, consider responding with a
225 * sendme, and return.
226 * Otherwise, stop writing and return.
228 * If <b>conn</b> is broken, mark it for close and return -1, else
229 * return 0.
231 int connection_edge_finished_flushing(connection_t *conn) {
232 tor_assert(conn);
233 tor_assert(CONN_IS_EDGE(conn));
235 switch (conn->state) {
236 case AP_CONN_STATE_OPEN:
237 case EXIT_CONN_STATE_OPEN:
238 connection_stop_writing(conn);
239 connection_edge_consider_sending_sendme(conn);
240 return 0;
241 case AP_CONN_STATE_SOCKS_WAIT:
242 case AP_CONN_STATE_RENDDESC_WAIT:
243 case AP_CONN_STATE_CIRCUIT_WAIT:
244 case AP_CONN_STATE_CONNECT_WAIT:
245 case AP_CONN_STATE_CONTROLLER_WAIT:
246 connection_stop_writing(conn);
247 return 0;
248 default:
249 log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
250 tor_fragile_assert();
251 return -1;
253 return 0;
256 /** Connected handler for exit connections: start writing pending
257 * data, deliver 'CONNECTED' relay cells as appropriate, and check
258 * any pending data that may have been received. */
259 int connection_edge_finished_connecting(connection_t *conn)
261 char connected_payload[4];
263 tor_assert(conn);
264 tor_assert(conn->type == CONN_TYPE_EXIT);
265 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
267 log_fn(LOG_INFO,"Exit connection to %s:%u established.",
268 safe_str(conn->address),conn->port);
270 conn->state = EXIT_CONN_STATE_OPEN;
271 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
272 if (connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
273 connection_start_writing(conn);
274 /* deliver a 'connected' relay cell back through the circuit. */
275 if (connection_edge_is_rendezvous_stream(conn)) {
276 if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
277 RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
278 return 0; /* circuit is closed, don't continue */
279 } else {
280 *(uint32_t*)connected_payload = htonl(conn->addr);
281 if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
282 RELAY_COMMAND_CONNECTED, connected_payload, 4, conn->cpath_layer) < 0)
283 return 0; /* circuit is closed, don't continue */
285 tor_assert(conn->package_window > 0);
286 /* in case the server has written anything */
287 return connection_edge_process_inbuf(conn, 1);
290 /** Find all general-purpose AP streams waiting for a response that sent
291 * their begin/resolve cell >=15 seconds ago. Detach from their current circuit,
292 * and mark their current circuit as unsuitable for new streams. Then call
293 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
294 * available) or launch a new one.
296 * For rendezvous streams, simply give up after 45 seconds (with no
297 * retry attempt).
299 void connection_ap_expire_beginning(void) {
300 connection_t **carray;
301 connection_t *conn;
302 circuit_t *circ;
303 int n, i;
304 time_t now = time(NULL);
305 or_options_t *options = get_options();
307 get_connection_array(&carray, &n);
309 for (i = 0; i < n; ++i) {
310 conn = carray[i];
311 if (conn->type != CONN_TYPE_AP)
312 continue;
313 if (conn->state == AP_CONN_STATE_CONTROLLER_WAIT) {
314 if (now - conn->timestamp_lastread >= 120) {
315 log_fn(LOG_NOTICE, "Closing unattached stream.");
316 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
318 continue;
321 else if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
322 conn->state != AP_CONN_STATE_CONNECT_WAIT)
323 continue;
324 if (now - conn->timestamp_lastread < 15)
325 continue;
326 circ = circuit_get_by_edge_conn(conn);
327 if (!circ) { /* it's vanished? */
328 log_fn(LOG_INFO,"Conn is waiting (address %s), but lost its circ.",
329 safe_str(conn->socks_request->address));
330 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
331 continue;
333 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
334 if (now - conn->timestamp_lastread > 45) {
335 log_fn(LOG_NOTICE,"Rend stream is %d seconds late. Giving up on address '%s'.",
336 (int)(now - conn->timestamp_lastread),
337 safe_str(conn->socks_request->address));
338 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
339 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
341 continue;
343 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
344 log_fn(LOG_NOTICE,"Stream is %d seconds late on address '%s'. Retrying.",
345 (int)(now - conn->timestamp_lastread),
346 safe_str(conn->socks_request->address));
347 circuit_log_path(LOG_NOTICE, circ);
348 /* send an end down the circuit */
349 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
350 /* un-mark it as ending, since we're going to reuse it */
351 conn->has_sent_end = 0;
352 /* kludge to make us not try this circuit again, yet to allow
353 * current streams on it to survive if they can: make it
354 * unattractive to use for new streams */
355 tor_assert(circ->timestamp_dirty);
356 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
357 /* give our stream another 15 seconds to try */
358 conn->timestamp_lastread += 15;
359 /* move it back into 'pending' state, and try to attach. */
360 if (connection_ap_detach_retriable(conn, circ)<0) {
361 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
363 } /* end for */
366 /** Tell any AP streams that are waiting for a new circuit that one is
367 * available.
369 void connection_ap_attach_pending(void)
371 connection_t **carray;
372 connection_t *conn;
373 int n, i;
375 get_connection_array(&carray, &n);
377 for (i = 0; i < n; ++i) {
378 conn = carray[i];
379 if (conn->marked_for_close ||
380 conn->type != CONN_TYPE_AP ||
381 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
382 continue;
383 if (connection_ap_handshake_attach_circuit(conn) < 0) {
384 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
389 /** The AP connection <b>conn</b> has just failed while attaching or
390 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
391 * might work. Detach the circuit, and either reattach it, launch a
392 * new circuit, tell the controller, or give up as a appropriate.
394 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
397 connection_ap_detach_retriable(connection_t *conn, circuit_t *circ)
399 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE);
400 conn->timestamp_lastread = time(NULL);
401 if (! get_options()->LeaveStreamsUnattached) {
402 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
403 circuit_detach_stream(circ,conn);
404 return connection_ap_handshake_attach_circuit(conn);
405 } else {
406 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
407 circuit_detach_stream(circ,conn);
408 return 0;
412 /** A client-side struct to remember requests to rewrite addresses
413 * to new addresses. These structs make up a tree, with addressmap
414 * below as its root.
416 * There are 5 ways to set an address mapping:
417 * - A MapAddress command from the controller [permanent]
418 * - An AddressMap directive in the torrc [permanent]
419 * - When a TrackHostExits torrc directive is triggered [temporary]
420 * - When a dns resolve succeeds [temporary]
421 * - When a dns resolve fails [temporary]
423 * When an addressmap request is made but one is already registered,
424 * the new one is replaced only if the currently registered one has
425 * no "new_address" (that is, it's in the process of dns resolve),
426 * or if the new one is permanent (expires==0 or 1).
428 * (We overload the 'expires' field, using "0" for mappings set via
429 * the configuration file, "1" for mappings set from the control
430 * interface, and other values for DNS mappings that can expire.)
432 typedef struct {
433 char *new_address;
434 time_t expires;
435 int num_resolve_failures;
436 } addressmap_entry_t;
438 typedef struct {
439 char *ipv4_address;
440 char *hostname_address;
441 } virtaddress_entry_t;
443 /** The tree of client-side address rewrite instructions. */
444 static strmap_t *addressmap=NULL;
446 * Tree mapping addresses to which virtual address, if any, we
447 * assigned them to.
449 * We maintain the following invariant: if [A,B] is in
450 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
451 * must be in addressmap. We do not require that the converse hold:
452 * if it fails, then we could end up mapping two virtual addresses to
453 * the same address, which is no disaster.
455 static strmap_t *virtaddress_reversemap=NULL;
457 /** Initialize addressmap. */
458 void addressmap_init(void) {
459 addressmap = strmap_new();
460 virtaddress_reversemap = strmap_new();
463 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
464 static void
465 addressmap_ent_free(void *_ent) {
466 addressmap_entry_t *ent = _ent;
467 tor_free(ent->new_address);
468 tor_free(ent);
471 static void
472 addressmap_virtaddress_ent_free(void *_ent) {
473 virtaddress_entry_t *ent = _ent;
474 tor_free(ent->ipv4_address);
475 tor_free(ent->hostname_address);
476 tor_free(ent);
479 static void
480 addressmap_virtaddress_remove(const char *addr, addressmap_entry_t *ent)
482 if (ent && ent->new_address && address_is_in_virtual_range(ent->new_address)) {
483 virtaddress_entry_t *ve =
484 strmap_get(virtaddress_reversemap, ent->new_address);
485 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
486 if (ve) {
487 if (!strcmp(addr, ve->ipv4_address))
488 tor_free(ve->ipv4_address);
489 if (!strcmp(addr, ve->hostname_address))
490 tor_free(ve->hostname_address);
491 if (!ve->ipv4_address && !ve->hostname_address) {
492 tor_free(ve);
493 strmap_remove(virtaddress_reversemap, ent->new_address);
499 static void
500 addressmap_ent_remove(const char *addr, addressmap_entry_t *ent)
502 addressmap_virtaddress_remove(addr, ent);
503 addressmap_ent_free(ent);
506 /** Remove all entries from the addressmap that were set via the
507 * configuration file or the command line. */
508 void
509 addressmap_clear_configured(void)
511 addressmap_get_mappings(NULL, 0, 0);
514 /** Remove all entries from the addressmap that are set to expire, ever. */
515 void
516 addressmap_clear_transient(void)
518 addressmap_get_mappings(NULL, 2, TIME_MAX);
521 /** Clean out entries from the addressmap cache that were
522 * added long enough ago that they are no longer valid.
524 void addressmap_clean(time_t now) {
525 addressmap_get_mappings(NULL, 2, now);
528 /** Free all the elements in the addressmap, and free the addressmap
529 * itself. */
530 void addressmap_free_all(void) {
531 strmap_free(addressmap, addressmap_ent_free);
532 addressmap = NULL;
533 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
536 /** Look at address, and rewrite it until it doesn't want any
537 * more rewrites; but don't get into an infinite loop.
538 * Don't write more than maxlen chars into address.
540 void addressmap_rewrite(char *address, size_t maxlen) {
541 addressmap_entry_t *ent;
542 int rewrites;
544 for (rewrites = 0; rewrites < 16; rewrites++) {
545 ent = strmap_get(addressmap, address);
547 if (!ent || !ent->new_address)
548 return; /* done, no rewrite needed */
550 log_fn(LOG_INFO, "Addressmap: rewriting '%s' to '%s'",
551 safe_str(address), safe_str(ent->new_address));
552 strlcpy(address, ent->new_address, maxlen);
554 log_fn(LOG_WARN,"Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
555 safe_str(address));
556 /* it's fine to rewrite a rewrite, but don't loop forever */
559 /** Return 1 if <b>address</b> is already registered, else return 0 */
560 int addressmap_already_mapped(const char *address) {
561 return strmap_get(addressmap, address) ? 1 : 0;
564 /** Register a request to map <b>address</b> to <b>new_address</b>,
565 * which will expire on <b>expires</b> (or 0 if never expires from
566 * config file, 1 if never expires from controller, 2 if never expires
567 * (virtual address mapping) from the controller.)
569 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
570 * free as appropriate. We will leave address alone.
572 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
573 * any mappings that exist from <b>address</b>.
575 void addressmap_register(const char *address, char *new_address, time_t expires) {
576 addressmap_entry_t *ent;
578 ent = strmap_get(addressmap, address);
579 if (!new_address || !strcasecmp(address,new_address)) {
580 /* Remove the mapping, if any. */
581 tor_free(new_address);
582 if (ent) {
583 addressmap_ent_remove(address,ent);
584 strmap_remove(addressmap, address);
586 return;
588 if (!ent) { /* make a new one and register it */
589 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
590 strmap_set(addressmap, address, ent);
591 } else if (ent->new_address) { /* we need to clean up the old mapping. */
592 if (expires > 1) {
593 log_fn(LOG_INFO,"Temporary addressmap ('%s' to '%s') not performed, since it's already mapped to '%s'",
594 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
595 tor_free(new_address);
596 return;
598 if (address_is_in_virtual_range(ent->new_address) &&
599 expires != 2) {
600 /* XXX This isn't the perfect test; we want to avoid removing
601 * mappings set from the control interface _as virtual mapping */
602 addressmap_virtaddress_remove(address, ent);
604 tor_free(ent->new_address);
605 } /* else { we have an in-progress resolve with no mapping. } */
607 ent->new_address = new_address;
608 ent->expires = expires==2 ? 1 : expires;
609 ent->num_resolve_failures = 0;
611 log_fn(LOG_INFO, "Addressmap: (re)mapped '%s' to '%s'",
612 safe_str(address), safe_str(ent->new_address));
615 /** An attempt to resolve <b>address</b> failed at some OR.
616 * Increment the number of resolve failures we have on record
617 * for it, and then return that number.
619 int client_dns_incr_failures(const char *address)
621 addressmap_entry_t *ent;
622 ent = strmap_get(addressmap,address);
623 if (!ent) {
624 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
625 ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
626 strmap_set(addressmap,address,ent);
628 ++ent->num_resolve_failures;
629 log_fn(LOG_INFO,"Address %s now has %d resolve failures.",
630 safe_str(address), ent->num_resolve_failures);
631 return ent->num_resolve_failures;
634 /** Record the fact that <b>address</b> resolved to <b>val</b>.
635 * We can now use this in subsequent streams via addressmap_rewrite()
636 * so we can more correctly choose an exit that will allow <b>address</b>.
638 * If <b>exitname</b> is defined, then append the addresses with
639 * ".exitname.exit" before registering the mapping.
641 void client_dns_set_addressmap(const char *address, uint32_t val, const char *exitname)
643 struct in_addr in;
644 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
645 char valbuf[INET_NTOA_BUF_LEN];
646 char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
648 tor_assert(address); tor_assert(val);
650 if (tor_inet_aton(address, &in))
651 return; /* If address was an IP address already, don't add a mapping. */
652 in.s_addr = htonl(val);
653 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
654 if (exitname) {
655 tor_snprintf(extendedaddress, sizeof(extendedaddress),
656 "%s.%s.exit", address, exitname);
657 tor_snprintf(extendedval, sizeof(extendedval),
658 "%s.%s.exit", valbuf, exitname);
659 } else {
660 tor_snprintf(extendedaddress, sizeof(extendedaddress),
661 "%s", address);
662 tor_snprintf(extendedval, sizeof(extendedval),
663 "%s", valbuf);
665 addressmap_register(extendedaddress, tor_strdup(extendedval),
666 time(NULL) + MAX_DNS_ENTRY_AGE);
669 /* Currently, we hand out 127.192.0.1 through 127.254.254.254.
670 * These addresses should map to localhost, so even if the
671 * application accidentally tried to connect to them directly (not
672 * via Tor), it wouldn't get too far astray.
674 * Eventually, we should probably make this configurable.
676 #define MIN_UNUSED_IPV4 0x7fc00001u
677 #define MAX_UNUSED_IPV4 0x7ffefefeu
680 * Return true iff <b>addr</b> is likely to have been returned by
681 * client_dns_get_unused_address.
683 static int
684 address_is_in_virtual_range(const char *addr)
686 struct in_addr in;
687 tor_assert(addr);
688 if (!strcasecmpend(addr, ".virtual")) {
689 return 1;
690 } else if (tor_inet_aton(addr, &in)) {
691 uint32_t a = ntohl(in.s_addr);
692 if (a >= MIN_UNUSED_IPV4 && a <= MAX_UNUSED_IPV4)
693 return 1;
695 return 0;
698 /** Return a newly allocated string holding an address of <b>type</b>
699 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
700 * and that is very unlikely to be the address of any real host.
702 static char *
703 addressmap_get_virtual_address(int type)
705 char buf[64];
706 static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
707 struct in_addr in;
709 if (type == RESOLVED_TYPE_HOSTNAME) {
710 char rand[10];
711 do {
712 crypto_rand(rand, sizeof(rand));
713 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
714 strlcat(buf, ".virtual", sizeof(buf));
715 } while (strmap_get(addressmap, buf));
716 return tor_strdup(buf);
717 } else if (type == RESOLVED_TYPE_IPV4) {
718 while (1) {
719 /* Don't hand out any .0 or .255 address. */
720 while ((next_ipv4 & 0xff) == 0 ||
721 (next_ipv4 & 0xff) == 0xff)
722 ++next_ipv4;
723 in.s_addr = htonl(next_ipv4);
724 tor_inet_ntoa(&in, buf, sizeof(buf));
725 if (!strmap_get(addressmap, buf))
726 break;
728 ++next_ipv4;
729 if (next_ipv4 > MAX_UNUSED_IPV4)
730 next_ipv4 = MIN_UNUSED_IPV4;
732 return tor_strdup(buf);
733 } else {
734 log_fn(LOG_WARN, "Called with unsupported address type (%d)",
735 type);
736 return NULL;
740 /** A controller has requested that we map some address of type
741 * <b>type</b> to the address <b>new_address</b>. Choose an address
742 * that is unlikely to be used, and map it, and return it in a newly
743 * allocated string. If another address of the same type is already
744 * mapped to <b>new_address</b>, try to return a copy of that address.
746 * The string in <b>new_address</b> may be freed, or inserted into a map
747 * as appropriate.
749 const char *
750 addressmap_register_virtual_address(int type, char *new_address)
752 char **addrp;
753 virtaddress_entry_t *vent;
755 tor_assert(new_address);
756 tor_assert(addressmap);
757 tor_assert(virtaddress_reversemap);
759 vent = strmap_get(virtaddress_reversemap, new_address);
760 if (!vent) {
761 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
762 strmap_set(virtaddress_reversemap, new_address, vent);
765 addrp = (type == RESOLVED_TYPE_IPV4) ?
766 &vent->ipv4_address : &vent->hostname_address;
767 if (*addrp) {
768 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
769 if (ent && ent->new_address && !strcasecmp(new_address, ent->new_address)) {
770 tor_free(new_address);
771 return tor_strdup(*addrp);
772 } else
773 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.",
774 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
775 ent?safe_str(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.",
794 safe_str(*addrp),safe_str(new_address));
796 #endif
798 return *addrp;
801 /** Return 1 if <b>address</b> has funny characters in it like
802 * colons. Return 0 if it's fine.
804 static int
805 address_is_invalid_destination(const char *address) {
806 /* FFFF should flesh this out */
807 if (strchr(address,':'))
808 return 1;
809 return 0;
812 /** Iterate over all address mapings which have expiry times between
813 * min_expires and max_expires, inclusive. If sl is provided, add an
814 * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
815 * remove the mappings.
817 void
818 addressmap_get_mappings(smartlist_t *sl, time_t min_expires, time_t max_expires)
820 strmap_iter_t *iter;
821 const char *key;
822 void *_val;
823 addressmap_entry_t *val;
825 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
826 strmap_iter_get(iter, &key, &_val);
827 val = _val;
828 if (val->expires >= min_expires && val->expires <= max_expires) {
829 if (!sl) {
830 addressmap_ent_remove(key, val);
831 iter = strmap_iter_next_rmv(addressmap,iter);
832 continue;
833 } else if (val->new_address) {
834 size_t len = strlen(key)+strlen(val->new_address)+2;
835 char *line = tor_malloc(len);
836 tor_snprintf(line, len, "%s %s", key, val->new_address);
837 smartlist_add(sl, line);
840 iter = strmap_iter_next(addressmap,iter);
844 /** connection_edge_process_inbuf() found a conn in state
845 * socks_wait. See if conn->inbuf has the right bytes to proceed with
846 * the socks handshake.
848 * If the handshake is complete, and it's for a general circuit, then
849 * try to attach it to a circuit (or launch one as needed). If it's for
850 * a rendezvous circuit, then fetch a rendezvous descriptor first (or
851 * attach/launch a circuit if the rendezvous descriptor is already here
852 * and fresh enough).
854 * Return -1 if an unexpected error with conn (and it should be marked
855 * for close), else return 0.
857 static int connection_ap_handshake_process_socks(connection_t *conn) {
858 socks_request_t *socks;
859 int sockshere;
860 hostname_type_t addresstype;
862 tor_assert(conn);
863 tor_assert(conn->type == CONN_TYPE_AP);
864 tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
865 tor_assert(conn->socks_request);
866 socks = conn->socks_request;
868 log_fn(LOG_DEBUG,"entered.");
870 sockshere = fetch_from_buf_socks(conn->inbuf, socks);
871 if (sockshere == 0) {
872 if (socks->replylen) {
873 connection_write_to_buf(socks->reply, socks->replylen, conn);
874 socks->replylen = 0; /* zero it out so we can do another round of negotiation */
875 } else {
876 log_fn(LOG_DEBUG,"socks handshake not all here yet.");
878 return 0;
879 } else if (sockshere == -1) {
880 if (socks->replylen) { /* we should send reply back */
881 log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
882 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
883 SOCKS5_GENERAL_ERROR);
884 } else {
885 log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
886 connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
888 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
889 return -1;
890 } /* else socks handshake is done, continue processing */
892 tor_strlower(socks->address); /* normalize it */
894 /* For address map controls, remap the address */
895 addressmap_rewrite(socks->address, sizeof(socks->address));
897 if (address_is_in_virtual_range(socks->address)) {
898 /* This address was probably handed out by client_dns_get_unmapped_address,
899 * but the mapping was discarded for some reason. We *don't* want to send
900 * the address through tor; that's likely to fail, and may leak
901 * information.
903 log_fn(LOG_WARN,"Missing mapping for virtual address '%s'. Refusing.",
904 socks->address); /* don't safe_str() this yet. */
905 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
906 return -1;
909 /* Parse the address provided by SOCKS. Modify it in-place if it
910 * specifies a hidden-service (.onion) or particular exit node (.exit).
912 addresstype = parse_extended_hostname(socks->address);
914 if (addresstype == EXIT_HOSTNAME) {
915 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
916 * node, and conn->address to hold only the address portion.*/
917 char *s = strrchr(socks->address,'.');
918 if (s) {
919 if (s[1] != '\0') {
920 conn->chosen_exit_name = tor_strdup(s+1);
921 *s = 0;
922 } else {
923 log_fn(LOG_WARN,"Malformed exit address '%s.exit'. Refusing.",
924 safe_str(socks->address));
925 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
926 return -1;
928 } else {
929 struct in_addr in;
930 routerinfo_t *r = router_get_by_nickname(socks->address);
931 if (r) {
932 conn->chosen_exit_name = tor_strdup(socks->address);
933 /* XXXX Should this use server->address instead? */
934 in.s_addr = htonl(r->addr);
935 strlcpy(socks->address, inet_ntoa(in), sizeof(socks->address));
936 } else {
937 log_fn(LOG_WARN,
938 "Unrecognized server in exit address '%s.exit'. Refusing.",
939 safe_str(socks->address));
940 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
941 return -1;
946 if (addresstype != ONION_HOSTNAME) {
947 /* not a hidden-service request (i.e. normal or .exit) */
949 if (address_is_invalid_destination(socks->address)) {
950 log_fn(LOG_WARN,"Destination '%s' seems to be an invalid hostname. Failing.",
951 safe_str(socks->address));
952 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
953 return -1;
956 if (socks->command == SOCKS_COMMAND_RESOLVE) {
957 uint32_t answer;
958 struct in_addr in;
959 /* Reply to resolves immediately if we can. */
960 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
961 log_fn(LOG_WARN,"Address to be resolved is too large. Failing.");
962 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
963 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
964 return -1;
966 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
967 answer = in.s_addr;
968 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
969 (char*)&answer);
970 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
971 return 0;
973 rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
974 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE);
975 } else { /* socks->command == SOCKS_COMMAND_CONNECT */
976 if (socks->port == 0) {
977 log_fn(LOG_NOTICE,"Application asked to connect to port 0. Refusing.");
978 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
979 return -1;
981 rep_hist_note_used_port(socks->port, time(NULL)); /* help predict this next time */
982 control_event_stream_status(conn, STREAM_EVENT_NEW);
984 if (! get_options()->LeaveStreamsUnattached) {
985 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
986 if (connection_ap_handshake_attach_circuit(conn) < 0) {
987 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
988 return -1;
990 return 0;
991 } else {
992 conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
993 return 0;
995 } else {
996 /* it's a hidden-service request */
997 rend_cache_entry_t *entry;
998 int r;
1000 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1001 /* if it's a resolve request, fail it right now, rather than
1002 * building all the circuits and then realizing it won't work. */
1003 log_fn(LOG_WARN,"Resolve requests to hidden services not allowed. Failing.");
1004 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
1005 connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
1006 return -1;
1009 strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
1010 log_fn(LOG_INFO,"Got a hidden service request for ID '%s'",
1011 safe_str(conn->rend_query));
1012 /* see if we already have it cached */
1013 r = rend_cache_lookup_entry(conn->rend_query, &entry);
1014 if (r<0) {
1015 log_fn(LOG_WARN,"Invalid service descriptor %s",
1016 safe_str(conn->rend_query));
1017 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1018 return -1;
1020 if (r==0) {
1021 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1022 log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.",
1023 safe_str(conn->rend_query));
1024 rend_client_refetch_renddesc(conn->rend_query);
1025 return 0;
1027 if (r>0) {
1028 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
1029 if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
1030 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1031 log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
1032 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1033 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1034 return -1;
1036 return 0;
1037 } else {
1038 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1039 log_fn(LOG_INFO, "Stale descriptor %s. Refetching.",
1040 safe_str(conn->rend_query));
1041 rend_client_refetch_renddesc(conn->rend_query);
1042 return 0;
1046 return 0; /* unreached but keeps the compiler happy */
1049 /** Iterate over the two bytes of stream_id until we get one that is not
1050 * already in use; return it. Return 0 if can't get a unique stream_id.
1052 static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
1053 connection_t *tmpconn;
1054 uint16_t test_stream_id;
1055 uint32_t attempts=0;
1057 again:
1058 test_stream_id = circ->next_stream_id++;
1059 if (++attempts > 1<<16) {
1060 /* Make sure we don't loop forever if all stream_id's are used. */
1061 log_fn(LOG_WARN,"No unused stream IDs. Failing.");
1062 return 0;
1064 if (test_stream_id == 0)
1065 goto again;
1066 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
1067 if (tmpconn->stream_id == test_stream_id)
1068 goto again;
1069 return test_stream_id;
1072 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1073 * socks_request field, and send it down circ.
1075 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1077 int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
1079 char payload[CELL_PAYLOAD_SIZE];
1080 int payload_len;
1082 tor_assert(ap_conn->type == CONN_TYPE_AP);
1083 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1084 tor_assert(ap_conn->socks_request);
1086 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1087 if (ap_conn->stream_id==0) {
1088 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1089 circuit_mark_for_close(circ);
1090 return -1;
1093 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
1094 (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
1095 ap_conn->socks_request->address : "",
1096 ap_conn->socks_request->port);
1097 payload_len = strlen(payload)+1;
1099 log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1101 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
1102 payload, payload_len, ap_conn->cpath_layer) < 0)
1103 return -1; /* circuit is closed, don't continue */
1105 ap_conn->package_window = STREAMWINDOW_START;
1106 ap_conn->deliver_window = STREAMWINDOW_START;
1107 ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
1108 log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",
1109 ap_conn->s, circ->n_circ_id);
1110 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
1111 return 0;
1114 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1115 * socks_request field, and send it down circ.
1117 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1119 int connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
1121 int payload_len;
1122 const char *string_addr;
1124 tor_assert(ap_conn->type == CONN_TYPE_AP);
1125 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1126 tor_assert(ap_conn->socks_request);
1127 tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
1128 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
1130 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1131 if (ap_conn->stream_id==0) {
1132 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1133 circuit_mark_for_close(circ);
1134 return -1;
1137 string_addr = ap_conn->socks_request->address;
1138 payload_len = strlen(string_addr)+1;
1139 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
1141 log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
1143 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
1144 string_addr, payload_len, ap_conn->cpath_layer) < 0)
1145 return -1; /* circuit is closed, don't continue */
1147 ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
1148 log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",
1149 ap_conn->s, circ->n_circ_id);
1150 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
1151 return 0;
1154 /** Make an AP connection_t, do a socketpair and attach one side
1155 * to the conn, connection_add it, initialize it to circuit_wait,
1156 * and call connection_ap_handshake_attach_circuit(conn) on it.
1158 * Return the other end of the socketpair, or -1 if error.
1160 int connection_ap_make_bridge(char *address, uint16_t port) {
1161 int fd[2];
1162 connection_t *conn;
1164 log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",safe_str(address),port);
1166 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
1167 log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
1168 tor_socket_strerror(tor_socket_errno(-1)));
1169 return -1;
1172 set_socket_nonblocking(fd[0]);
1173 set_socket_nonblocking(fd[1]);
1175 conn = connection_new(CONN_TYPE_AP);
1176 conn->s = fd[0];
1178 /* populate conn->socks_request */
1180 /* leave version at zero, so the socks_reply is empty */
1181 conn->socks_request->socks_version = 0;
1182 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
1183 strlcpy(conn->socks_request->address, address,
1184 sizeof(conn->socks_request->address));
1185 conn->socks_request->port = port;
1186 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
1188 conn->address = tor_strdup("(local bridge)");
1189 conn->addr = 0;
1190 conn->port = 0;
1192 if (connection_add(conn) < 0) { /* no space, forget it */
1193 connection_free(conn); /* this closes fd[0] */
1194 tor_close_socket(fd[1]);
1195 return -1;
1198 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1199 connection_start_reading(conn);
1201 /* attaching to a dirty circuit is fine */
1202 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1203 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1204 tor_close_socket(fd[1]);
1205 return -1;
1208 log_fn(LOG_INFO,"... AP bridge created and connected.");
1209 return fd[1];
1212 /** Send an answer to an AP connection that has requested a DNS lookup
1213 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6) or
1214 * -1 for unreachable; the answer should be in the format specified
1215 * in the socks extensions document.
1217 void connection_ap_handshake_socks_resolved(connection_t *conn,
1218 int answer_type,
1219 size_t answer_len,
1220 const char *answer)
1222 char buf[256];
1223 size_t replylen;
1225 if (answer_type == RESOLVED_TYPE_IPV4) {
1226 uint32_t a = get_uint32(answer);
1227 if (a)
1228 client_dns_set_addressmap(conn->socks_request->address, ntohl(a),
1229 conn->chosen_exit_name);
1232 if (conn->socks_request->socks_version == 4) {
1233 buf[0] = 0x00; /* version */
1234 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1235 buf[1] = 90; /* "Granted" */
1236 set_uint16(buf+2, 0);
1237 memcpy(buf+4, answer, 4); /* address */
1238 replylen = SOCKS4_NETWORK_LEN;
1239 } else {
1240 buf[1] = 91; /* "error" */
1241 memset(buf+2, 0, 6);
1242 replylen = SOCKS4_NETWORK_LEN;
1244 } else {
1245 /* SOCKS5 */
1246 buf[0] = 0x05; /* version */
1247 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
1248 buf[1] = SOCKS5_SUCCEEDED;
1249 buf[2] = 0; /* reserved */
1250 buf[3] = 0x01; /* IPv4 address type */
1251 memcpy(buf+4, answer, 4); /* address */
1252 set_uint16(buf+8, 0); /* port == 0. */
1253 replylen = 10;
1254 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
1255 buf[1] = SOCKS5_SUCCEEDED;
1256 buf[2] = 0; /* reserved */
1257 buf[3] = 0x04; /* IPv6 address type */
1258 memcpy(buf+4, answer, 16); /* address */
1259 set_uint16(buf+20, 0); /* port == 0. */
1260 replylen = 22;
1261 } else {
1262 buf[1] = SOCKS5_HOST_UNREACHABLE;
1263 memset(buf+2, 0, 8);
1264 replylen = 10;
1267 connection_ap_handshake_socks_reply(conn, buf, replylen,
1268 (answer_type == RESOLVED_TYPE_IPV4 ||
1269 answer_type == RESOLVED_TYPE_IPV6) ?
1270 SOCKS5_SUCCEEDED : SOCKS5_HOST_UNREACHABLE);
1273 /** Send a socks reply to stream <b>conn</b>, using the appropriate
1274 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
1275 * handshaking.
1277 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
1278 * to conn and return, else reply based on <b>status</b>.
1280 * If <b>reply</b> is undefined, <b>status</b> can't be 0.
1282 void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
1283 size_t replylen,
1284 socks5_reply_status_t status) {
1285 char buf[256];
1286 tor_assert(conn->socks_request); /* make sure it's an AP stream */
1288 control_event_stream_status(conn,
1289 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
1291 if (conn->socks_request->has_finished) {
1292 log_fn(LOG_WARN, "Harmless bug: duplicate calls to connection_ap_handshake_socks_reply.");
1293 return;
1295 if (replylen) { /* we already have a reply in mind */
1296 connection_write_to_buf(reply, replylen, conn);
1297 conn->socks_request->has_finished = 1;
1298 return;
1300 if (conn->socks_request->socks_version == 4) {
1301 memset(buf,0,SOCKS4_NETWORK_LEN);
1302 #define SOCKS4_GRANTED 90
1303 #define SOCKS4_REJECT 91
1304 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
1305 /* leave version, destport, destip zero */
1306 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
1307 } else if (conn->socks_request->socks_version == 5) {
1308 buf[0] = 5; /* version 5 */
1309 buf[1] = (char)status;
1310 buf[2] = 0;
1311 buf[3] = 1; /* ipv4 addr */
1312 memset(buf+4,0,6); /* Set external addr/port to 0.
1313 The spec doesn't seem to say what to do here. -RD */
1314 connection_write_to_buf(buf,10,conn);
1316 /* If socks_version isn't 4 or 5, don't send anything.
1317 * This can happen in the case of AP bridges. */
1318 conn->socks_request->has_finished = 1;
1319 return;
1322 /** A relay 'begin' cell has arrived, and either we are an exit hop
1323 * for the circuit, or we are the origin and it is a rendezvous begin.
1325 * Launch a new exit connection and initialize things appropriately.
1327 * If it's a rendezvous stream, call connection_exit_connect() on
1328 * it.
1330 * For general streams, call dns_resolve() on it first, and only call
1331 * connection_exit_connect() if the dns answer is already known.
1333 * Note that we don't call connection_add() on the new stream! We wait
1334 * for connection_exit_connect() to do that.
1336 * Return -1 if we want to tear down <b>circ</b>. Else return 0.
1338 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
1339 connection_t *n_stream;
1340 relay_header_t rh;
1341 char *address=NULL;
1342 uint16_t port;
1344 assert_circuit_ok(circ);
1345 relay_header_unpack(&rh, cell->payload);
1347 /* XXX currently we don't send an end cell back if we drop the
1348 * begin because it's malformed.
1351 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
1352 log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
1353 return 0;
1355 if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
1356 log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
1357 return 0;
1359 if (port==0) {
1360 log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
1361 tor_free(address);
1362 return 0;
1365 log_fn(LOG_DEBUG,"Creating new exit connection.");
1366 n_stream = connection_new(CONN_TYPE_EXIT);
1367 n_stream->purpose = EXIT_PURPOSE_CONNECT;
1369 n_stream->stream_id = rh.stream_id;
1370 n_stream->port = port;
1371 /* leave n_stream->s at -1, because it's not yet valid */
1372 n_stream->package_window = STREAMWINDOW_START;
1373 n_stream->deliver_window = STREAMWINDOW_START;
1375 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1376 log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
1377 n_stream->address = tor_strdup("(rendezvous)");
1378 n_stream->state = EXIT_CONN_STATE_CONNECTING;
1379 strlcpy(n_stream->rend_query, circ->rend_query,
1380 sizeof(n_stream->rend_query));
1381 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
1382 assert_circuit_ok(circ);
1383 if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
1384 log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
1385 connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
1386 connection_free(n_stream);
1387 circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
1388 tor_free(address);
1389 return 0;
1391 assert_circuit_ok(circ);
1392 log_fn(LOG_DEBUG,"Finished assigning addr/port");
1393 n_stream->cpath_layer = circ->cpath->prev; /* link it */
1395 /* add it into the linked list of n_streams on this circuit */
1396 n_stream->next_stream = circ->n_streams;
1397 n_stream->on_circuit = circ;
1398 circ->n_streams = n_stream;
1399 assert_circuit_ok(circ);
1401 connection_exit_connect(n_stream);
1402 tor_free(address);
1403 return 0;
1405 tor_strlower(address);
1406 n_stream->address = address;
1407 n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
1408 /* default to failed, change in dns_resolve if it turns out not to fail */
1410 if (we_are_hibernating()) {
1411 connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING, n_stream->cpath_layer);
1412 connection_free(n_stream);
1413 return 0;
1416 /* send it off to the gethostbyname farm */
1417 switch (dns_resolve(n_stream)) {
1418 case 1: /* resolve worked */
1420 /* add it into the linked list of n_streams on this circuit */
1421 n_stream->next_stream = circ->n_streams;
1422 n_stream->on_circuit = circ;
1423 circ->n_streams = n_stream;
1424 assert_circuit_ok(circ);
1426 connection_exit_connect(n_stream);
1427 return 0;
1428 case -1: /* resolve failed */
1429 /* n_stream got freed. don't touch it. */
1430 break;
1431 case 0: /* resolve added to pending list */
1432 /* add it into the linked list of resolving_streams on this circuit */
1433 n_stream->next_stream = circ->resolving_streams;
1434 n_stream->on_circuit = circ;
1435 circ->resolving_streams = n_stream;
1436 assert_circuit_ok(circ);
1439 return 0;
1443 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
1444 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
1446 int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ) {
1447 connection_t *dummy_conn;
1448 relay_header_t rh;
1450 assert_circuit_ok(circ);
1451 relay_header_unpack(&rh, cell->payload);
1453 /* This 'dummy_conn' only exists to remember the stream ID
1454 * associated with the resolve request; and to make the
1455 * implementation of dns.c more uniform. (We really only need to
1456 * remember the circuit, the stream ID, and the hostname to be
1457 * resolved; but if we didn't store them in a connection like this,
1458 * the housekeeping in dns.c would get way more complicated.)
1460 dummy_conn = connection_new(CONN_TYPE_EXIT);
1461 dummy_conn->stream_id = rh.stream_id;
1462 dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
1463 rh.length);
1464 dummy_conn->port = 0;
1465 dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
1466 dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
1468 /* send it off to the gethostbyname farm */
1469 switch (dns_resolve(dummy_conn)) {
1470 case -1: /* Impossible to resolve; a resolved cell was sent. */
1471 /* Connection freed; don't touch it. */
1472 return 0;
1473 case 1: /* The result was cached; a resolved cell was sent. */
1474 if (!dummy_conn->marked_for_close)
1475 connection_free(dummy_conn);
1476 return 0;
1477 case 0: /* resolve added to pending list */
1478 dummy_conn->next_stream = circ->resolving_streams;
1479 dummy_conn->on_circuit = circ;
1480 circ->resolving_streams = dummy_conn;
1481 assert_circuit_ok(circ);
1482 break;
1484 return 0;
1487 /** Connect to conn's specified addr and port. If it worked, conn
1488 * has now been added to the connection_array.
1490 * Send back a connected cell. Include the resolved IP of the destination
1491 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
1492 * streams must not reveal what IP they connected to.)
1494 void
1495 connection_exit_connect(connection_t *conn) {
1496 char connected_payload[4];
1497 uint32_t addr;
1498 uint16_t port;
1500 if (!connection_edge_is_rendezvous_stream(conn) &&
1501 router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
1502 log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.",
1503 safe_str(conn->address), conn->port);
1504 connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
1505 circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
1506 connection_free(conn);
1507 return;
1510 addr = conn->addr;
1511 port = conn->port;
1512 if (redirect_exit_list) {
1513 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
1515 if ((addr&r->mask)==(r->addr&r->mask) &&
1516 (r->port_min <= port) && (port <= r->port_max)) {
1517 struct in_addr in;
1518 if (r->is_redirect) {
1519 char tmpbuf[INET_NTOA_BUF_LEN];
1520 addr = r->addr_dest;
1521 port = r->port_dest;
1522 in.s_addr = htonl(addr);
1523 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
1524 log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
1525 safe_str(conn->address), conn->port, safe_str(tmpbuf), port);
1527 break;
1532 log_fn(LOG_DEBUG,"about to try connecting");
1533 switch (connection_connect(conn, conn->address, addr, port)) {
1534 case -1:
1535 connection_edge_end_errno(conn, conn->cpath_layer);
1536 circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
1537 connection_free(conn);
1538 return;
1539 case 0:
1540 conn->state = EXIT_CONN_STATE_CONNECTING;
1542 connection_watch_events(conn, EV_WRITE | EV_READ);
1543 /* writable indicates finish;
1544 * readable/error indicates broken link in windowsland. */
1545 return;
1546 /* case 1: fall through */
1549 conn->state = EXIT_CONN_STATE_OPEN;
1550 if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
1551 log_fn(LOG_WARN,"Bug: newly connected conn had data waiting!");
1552 // connection_start_writing(conn);
1554 connection_watch_events(conn, EV_READ);
1556 /* also, deliver a 'connected' cell back through the circuit. */
1557 if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
1558 /* don't send an address back! */
1559 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
1560 RELAY_COMMAND_CONNECTED,
1561 NULL, 0, conn->cpath_layer);
1562 } else { /* normal stream */
1563 /* This must be the original address, not the redirected address. */
1564 *(uint32_t*)connected_payload = htonl(conn->addr);
1565 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
1566 RELAY_COMMAND_CONNECTED,
1567 connected_payload, 4, conn->cpath_layer);
1571 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
1572 * it is a general stream.
1574 int connection_edge_is_rendezvous_stream(connection_t *conn) {
1575 tor_assert(conn);
1576 if (*conn->rend_query) /* XXX */
1577 return 1;
1578 return 0;
1581 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
1582 * to exit from it, or 0 if it probably will not allow it.
1583 * (We might be uncertain if conn's destination address has not yet been
1584 * resolved.)
1586 int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
1588 tor_assert(conn);
1589 tor_assert(conn->type == CONN_TYPE_AP);
1590 tor_assert(conn->socks_request);
1591 tor_assert(exit);
1593 log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
1594 exit->nickname, safe_str(conn->socks_request->address),
1595 conn->socks_request->port);
1597 /* If a particular exit node has been requested for the new connection,
1598 * make sure the exit node of the existing circuit matches exactly.
1600 if (conn->chosen_exit_name) {
1601 if (router_get_by_nickname(conn->chosen_exit_name) != exit) {
1602 /* doesn't match */
1603 log_fn(LOG_DEBUG,"Requested node '%s', considering node '%s'. No.",
1604 conn->chosen_exit_name, exit->nickname);
1605 return 0;
1609 if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
1610 struct in_addr in;
1611 uint32_t addr = 0;
1612 addr_policy_result_t r;
1613 if (tor_inet_aton(conn->socks_request->address, &in))
1614 addr = ntohl(in.s_addr);
1615 r = router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
1616 exit->exit_policy);
1617 if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
1618 return 0;
1620 return 1;
1623 /** A helper function for socks_policy_permits_address() below.
1625 * Parse options->SocksPolicy in the same way that the exit policy
1626 * is parsed, and put the processed version in &socks_policy.
1627 * Ignore port specifiers.
1629 void
1630 parse_socks_policy(void)
1632 addr_policy_t *n;
1633 if (socks_policy) {
1634 addr_policy_free(socks_policy);
1635 socks_policy = NULL;
1637 config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy);
1638 /* ports aren't used. */
1639 for (n=socks_policy; n; n = n->next) {
1640 n->prt_min = 1;
1641 n->prt_max = 65535;
1645 void
1646 free_socks_policy(void)
1648 addr_policy_free(socks_policy);
1649 socks_policy = NULL;
1652 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1653 * based on <b>socks_policy</b>. Else return 0.
1655 int socks_policy_permits_address(uint32_t addr)
1657 int a;
1659 if (!socks_policy) /* 'no socks policy' means 'accept' */
1660 return 1;
1661 a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
1662 if (a==ADDR_POLICY_REJECTED)
1663 return 0;
1664 else if (a==ADDR_POLICY_ACCEPTED)
1665 return 1;
1666 log_fn(LOG_WARN, "Bug: Got unexpected 'maybe' answer from socks policy");
1667 return 0;
1670 /** Make connection redirection follow the provided list of
1671 * exit_redirect_t */
1672 void
1673 set_exit_redirects(smartlist_t *lst)
1675 if (redirect_exit_list) {
1676 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
1677 smartlist_free(redirect_exit_list);
1679 redirect_exit_list = lst;
1682 /** If address is of the form "y.onion" with a well-formed handle y:
1683 * Put a \code{'\0'} after y, lower-case it, and return ONION_HOSTNAME.
1685 * If address is of the form "y.exit":
1686 * Put a \code{'\0'} after y and return EXIT_HOSTNAME.
1688 * Otherwise:
1689 * Return NORMAL_HOSTNAME and change nothing.
1691 hostname_type_t
1692 parse_extended_hostname(char *address) {
1693 char *s;
1694 char query[REND_SERVICE_ID_LEN+1];
1696 s = strrchr(address,'.');
1697 if (!s) return 0; /* no dot, thus normal */
1698 if (!strcmp(s+1,"exit")) {
1699 *s = 0; /* null-terminate it */
1700 return EXIT_HOSTNAME; /* .exit */
1702 if (strcmp(s+1,"onion"))
1703 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1705 /* so it is .onion */
1706 *s = 0; /* null-terminate it */
1707 if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
1708 goto failed;
1709 if (rend_valid_service_id(query)) {
1710 return ONION_HOSTNAME; /* success */
1712 failed:
1713 /* otherwise, return to previous state and return 0 */
1714 *s = '.';
1715 return NORMAL_HOSTNAME;