Back to index

tor  0.2.3.18-rc
connection_edge.c
Go to the documentation of this file.
00001 /* Copyright (c) 2001 Matej Pfajfar.
00002  * Copyright (c) 2001-2004, Roger Dingledine.
00003  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00004  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00005 /* See LICENSE for licensing information */
00006 
00012 #include "or.h"
00013 #include "buffers.h"
00014 #include "circuitlist.h"
00015 #include "circuituse.h"
00016 #include "config.h"
00017 #include "connection.h"
00018 #include "connection_edge.h"
00019 #include "connection_or.h"
00020 #include "control.h"
00021 #include "dns.h"
00022 #include "dnsserv.h"
00023 #include "dirserv.h"
00024 #include "hibernate.h"
00025 #include "main.h"
00026 #include "nodelist.h"
00027 #include "policies.h"
00028 #include "reasons.h"
00029 #include "relay.h"
00030 #include "rendclient.h"
00031 #include "rendcommon.h"
00032 #include "rendservice.h"
00033 #include "rephist.h"
00034 #include "router.h"
00035 #include "routerlist.h"
00036 
00037 #ifdef HAVE_LINUX_TYPES_H
00038 #include <linux/types.h>
00039 #endif
00040 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
00041 #include <linux/netfilter_ipv4.h>
00042 #define TRANS_NETFILTER
00043 #endif
00044 
00045 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
00046 #include <net/if.h>
00047 #include <net/pfvar.h>
00048 #define TRANS_PF
00049 #endif
00050 
00051 #define SOCKS4_GRANTED          90
00052 #define SOCKS4_REJECT           91
00053 
00054 static int connection_ap_handshake_process_socks(entry_connection_t *conn);
00055 static int connection_ap_process_natd(entry_connection_t *conn);
00056 static int connection_exit_connect_dir(edge_connection_t *exitconn);
00057 static int address_is_in_virtual_range(const char *addr);
00058 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
00059 static void clear_trackexithost_mappings(const char *exitname);
00060 static int connection_ap_supports_optimistic_data(const entry_connection_t *);
00061 
00066 void
00067 _connection_mark_unattached_ap(entry_connection_t *conn, int endreason,
00068                                int line, const char *file)
00069 {
00070   connection_t *base_conn = ENTRY_TO_CONN(conn);
00071   edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
00072   tor_assert(base_conn->type == CONN_TYPE_AP);
00073   ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
00074 
00075   /* If this is a rendezvous stream and it is failing without ever
00076    * being attached to a circuit, assume that an attempt to connect to
00077    * the destination hidden service has just ended.
00078    *
00079    * XXXX This condition doesn't limit to only streams failing
00080    * without ever being attached.  That sloppiness should be harmless,
00081    * but we should fix it someday anyway. */
00082   if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
00083       connection_edge_is_rendezvous_stream(edge_conn)) {
00084     rend_client_note_connection_attempt_ended(
00085                                     edge_conn->rend_data->onion_address);
00086   }
00087 
00088   if (base_conn->marked_for_close) {
00089     /* This call will warn as appropriate. */
00090     _connection_mark_for_close(base_conn, line, file);
00091     return;
00092   }
00093 
00094   if (!conn->socks_request->has_finished) {
00095     if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
00096       log_warn(LD_BUG,
00097                "stream (marked at %s:%d) sending two socks replies?",
00098                file, line);
00099 
00100     if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
00101       connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
00102     else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
00103       connection_ap_handshake_socks_resolved(conn,
00104                                              RESOLVED_TYPE_ERROR_TRANSIENT,
00105                                              0, NULL, -1, -1);
00106     else /* unknown or no handshake at all. send no response. */
00107       conn->socks_request->has_finished = 1;
00108   }
00109 
00110   _connection_mark_and_flush(base_conn, line, file);
00111 
00112   ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
00113 }
00114 
00117 int
00118 connection_edge_reached_eof(edge_connection_t *conn)
00119 {
00120   if (connection_get_inbuf_len(TO_CONN(conn)) &&
00121       connection_state_is_open(TO_CONN(conn))) {
00122     /* it still has stuff to process. don't let it die yet. */
00123     return 0;
00124   }
00125   log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
00126   if (!conn->_base.marked_for_close) {
00127     /* only mark it if not already marked. it's possible to
00128      * get the 'end' right around when the client hangs up on us. */
00129     connection_edge_end(conn, END_STREAM_REASON_DONE);
00130     if (conn->_base.type == CONN_TYPE_AP) {
00131       /* eof, so don't send a socks reply back */
00132       if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
00133         EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
00134     }
00135     connection_mark_for_close(TO_CONN(conn));
00136   }
00137   return 0;
00138 }
00139 
00150 int
00151 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
00152 {
00153   tor_assert(conn);
00154 
00155   switch (conn->_base.state) {
00156     case AP_CONN_STATE_SOCKS_WAIT:
00157       if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
00158         /* already marked */
00159         return -1;
00160       }
00161       return 0;
00162     case AP_CONN_STATE_NATD_WAIT:
00163       if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
00164         /* already marked */
00165         return -1;
00166       }
00167       return 0;
00168     case AP_CONN_STATE_OPEN:
00169     case EXIT_CONN_STATE_OPEN:
00170       if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
00171         /* (We already sent an end cell if possible) */
00172         connection_mark_for_close(TO_CONN(conn));
00173         return -1;
00174       }
00175       return 0;
00176     case AP_CONN_STATE_CONNECT_WAIT:
00177       if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
00178         log_info(LD_EDGE,
00179                  "data from edge while in '%s' state. Sending it anyway. "
00180                  "package_partial=%d, buflen=%ld",
00181                  conn_state_to_string(conn->_base.type, conn->_base.state),
00182                  package_partial,
00183                  (long)connection_get_inbuf_len(TO_CONN(conn)));
00184         if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
00185           /* (We already sent an end cell if possible) */
00186           connection_mark_for_close(TO_CONN(conn));
00187           return -1;
00188         }
00189         return 0;
00190       }
00191       /* Fall through if the connection is on a circuit without optimistic
00192        * data support. */
00193     case EXIT_CONN_STATE_CONNECTING:
00194     case AP_CONN_STATE_RENDDESC_WAIT:
00195     case AP_CONN_STATE_CIRCUIT_WAIT:
00196     case AP_CONN_STATE_RESOLVE_WAIT:
00197     case AP_CONN_STATE_CONTROLLER_WAIT:
00198       log_info(LD_EDGE,
00199                "data from edge while in '%s' state. Leaving it on buffer.",
00200                conn_state_to_string(conn->_base.type, conn->_base.state));
00201       return 0;
00202   }
00203   log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
00204   tor_fragile_assert();
00205   connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
00206   connection_mark_for_close(TO_CONN(conn));
00207   return -1;
00208 }
00209 
00213 int
00214 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
00215 {
00216   if (!conn->_base.marked_for_close) {
00217     log_info(LD_EDGE,
00218              "CircID %d: At an edge. Marking connection for close.", circ_id);
00219     if (conn->_base.type == CONN_TYPE_AP) {
00220       entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
00221       connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
00222       control_event_stream_bandwidth(conn);
00223       control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
00224                                   END_STREAM_REASON_DESTROY);
00225       conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
00226     } else {
00227       /* closing the circuit, nothing to send an END to */
00228       conn->edge_has_sent_end = 1;
00229       conn->end_reason = END_STREAM_REASON_DESTROY;
00230       conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
00231       connection_mark_and_flush(TO_CONN(conn));
00232     }
00233   }
00234   conn->cpath_layer = NULL;
00235   conn->on_circuit = NULL;
00236   return 0;
00237 }
00238 
00243 static int
00244 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
00245                               uint8_t reason, crypt_path_t *cpath_layer)
00246 {
00247   char payload[1];
00248 
00249   if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
00250     /* Never send the server an informative reason code; it doesn't need to
00251      * know why the client stream is failing. */
00252     reason = END_STREAM_REASON_MISC;
00253   }
00254 
00255   payload[0] = (char) reason;
00256 
00257   return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
00258                                       payload, 1, cpath_layer);
00259 }
00260 
00268 int
00269 connection_edge_end(edge_connection_t *conn, uint8_t reason)
00270 {
00271   char payload[RELAY_PAYLOAD_SIZE];
00272   size_t payload_len=1;
00273   circuit_t *circ;
00274   uint8_t control_reason = reason;
00275 
00276   if (conn->edge_has_sent_end) {
00277     log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
00278              "on an already ended stream?", reason);
00279     tor_fragile_assert();
00280     return -1;
00281   }
00282 
00283   if (conn->_base.marked_for_close) {
00284     log_warn(LD_BUG,
00285              "called on conn that's already marked for close at %s:%d.",
00286              conn->_base.marked_for_close_file, conn->_base.marked_for_close);
00287     return 0;
00288   }
00289 
00290   circ = circuit_get_by_edge_conn(conn);
00291   if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
00292     /* If this is a client circuit, don't send the server an informative
00293      * reason code; it doesn't need to know why the client stream is
00294      * failing. */
00295     reason = END_STREAM_REASON_MISC;
00296   }
00297 
00298   payload[0] = (char)reason;
00299   if (reason == END_STREAM_REASON_EXITPOLICY &&
00300       !connection_edge_is_rendezvous_stream(conn)) {
00301     int addrlen;
00302     if (tor_addr_family(&conn->_base.addr) == AF_INET) {
00303       set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
00304       addrlen = 4;
00305     } else {
00306       memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
00307       addrlen = 16;
00308     }
00309     set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
00310     payload_len += 4+addrlen;
00311   }
00312 
00313   if (circ && !circ->marked_for_close) {
00314     log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
00315     connection_edge_send_command(conn, RELAY_COMMAND_END,
00316                                  payload, payload_len);
00317   } else {
00318     log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
00319               conn->_base.s);
00320   }
00321 
00322   conn->edge_has_sent_end = 1;
00323   conn->end_reason = control_reason;
00324   return 0;
00325 }
00326 
00331 int
00332 connection_edge_end_errno(edge_connection_t *conn)
00333 {
00334   uint8_t reason;
00335   tor_assert(conn);
00336   reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
00337   return connection_edge_end(conn, reason);
00338 }
00339 
00345 int
00346 connection_edge_flushed_some(edge_connection_t *conn)
00347 {
00348   switch (conn->_base.state) {
00349     case AP_CONN_STATE_OPEN:
00350     case EXIT_CONN_STATE_OPEN:
00351       connection_edge_consider_sending_sendme(conn);
00352       break;
00353   }
00354   return 0;
00355 }
00356 
00367 int
00368 connection_edge_finished_flushing(edge_connection_t *conn)
00369 {
00370   tor_assert(conn);
00371 
00372   switch (conn->_base.state) {
00373     case AP_CONN_STATE_OPEN:
00374     case EXIT_CONN_STATE_OPEN:
00375       connection_edge_consider_sending_sendme(conn);
00376       return 0;
00377     case AP_CONN_STATE_SOCKS_WAIT:
00378     case AP_CONN_STATE_NATD_WAIT:
00379     case AP_CONN_STATE_RENDDESC_WAIT:
00380     case AP_CONN_STATE_CIRCUIT_WAIT:
00381     case AP_CONN_STATE_CONNECT_WAIT:
00382     case AP_CONN_STATE_CONTROLLER_WAIT:
00383     case AP_CONN_STATE_RESOLVE_WAIT:
00384       return 0;
00385     default:
00386       log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
00387       tor_fragile_assert();
00388       return -1;
00389   }
00390   return 0;
00391 }
00392 
00396 int
00397 connection_edge_finished_connecting(edge_connection_t *edge_conn)
00398 {
00399   connection_t *conn;
00400 
00401   tor_assert(edge_conn);
00402   tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
00403   conn = TO_CONN(edge_conn);
00404   tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
00405 
00406   log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
00407            escaped_safe_str(conn->address), conn->port,
00408            safe_str(fmt_addr(&conn->addr)));
00409 
00410   rep_hist_note_exit_stream_opened(conn->port);
00411 
00412   conn->state = EXIT_CONN_STATE_OPEN;
00413   IF_HAS_NO_BUFFEREVENT(conn)
00414     connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
00415   if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
00416                                         * cells */
00417     connection_start_writing(conn);
00418   /* deliver a 'connected' relay cell back through the circuit. */
00419   if (connection_edge_is_rendezvous_stream(edge_conn)) {
00420     if (connection_edge_send_command(edge_conn,
00421                                      RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
00422       return 0; /* circuit is closed, don't continue */
00423   } else {
00424     char connected_payload[20];
00425     int connected_payload_len;
00426     if (tor_addr_family(&conn->addr) == AF_INET) {
00427       set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
00428       set_uint32(connected_payload+4,
00429                  htonl(dns_clip_ttl(edge_conn->address_ttl)));
00430       connected_payload_len = 8;
00431     } else {
00432       memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
00433       set_uint32(connected_payload+16,
00434                  htonl(dns_clip_ttl(edge_conn->address_ttl)));
00435       connected_payload_len = 20;
00436     }
00437     if (connection_edge_send_command(edge_conn,
00438                                  RELAY_COMMAND_CONNECTED,
00439                                  connected_payload, connected_payload_len) < 0)
00440       return 0; /* circuit is closed, don't continue */
00441   }
00442   tor_assert(edge_conn->package_window > 0);
00443   /* in case the server has written anything */
00444   return connection_edge_process_inbuf(edge_conn, 1);
00445 }
00446 
00448 static void
00449 connection_edge_about_to_close(edge_connection_t *edge_conn)
00450 {
00451   if (!edge_conn->edge_has_sent_end) {
00452     connection_t *conn = TO_CONN(edge_conn);
00453     log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
00454              "hasn't sent end yet?",
00455              conn->marked_for_close_file, conn->marked_for_close);
00456     tor_fragile_assert();
00457   }
00458 }
00459 
00462 void
00463 connection_ap_about_to_close(entry_connection_t *entry_conn)
00464 {
00465   circuit_t *circ;
00466   edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
00467   connection_t *conn = ENTRY_TO_CONN(entry_conn);
00468 
00469   if (entry_conn->socks_request->has_finished == 0) {
00470     /* since conn gets removed right after this function finishes,
00471      * there's no point trying to send back a reply at this point. */
00472     log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
00473              " back a socks reply.",
00474              conn->marked_for_close_file, conn->marked_for_close);
00475   }
00476   if (!edge_conn->end_reason) {
00477     log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
00478              " set end_reason.",
00479              conn->marked_for_close_file, conn->marked_for_close);
00480   }
00481   if (entry_conn->dns_server_request) {
00482     log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
00483              " replied to DNS request.",
00484              conn->marked_for_close_file, conn->marked_for_close);
00485     dnsserv_reject_request(entry_conn);
00486   }
00487   control_event_stream_bandwidth(edge_conn);
00488   control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
00489                               edge_conn->end_reason);
00490   circ = circuit_get_by_edge_conn(edge_conn);
00491   if (circ)
00492     circuit_detach_stream(circ, edge_conn);
00493 }
00494 
00497 void
00498 connection_exit_about_to_close(edge_connection_t *edge_conn)
00499 {
00500   circuit_t *circ;
00501   connection_t *conn = TO_CONN(edge_conn);
00502 
00503   connection_edge_about_to_close(edge_conn);
00504 
00505   circ = circuit_get_by_edge_conn(edge_conn);
00506   if (circ)
00507     circuit_detach_stream(circ, edge_conn);
00508   if (conn->state == EXIT_CONN_STATE_RESOLVING) {
00509     connection_dns_remove(edge_conn);
00510   }
00511 }
00512 
00518 static int
00519 compute_retry_timeout(entry_connection_t *conn)
00520 {
00521   int timeout = get_options()->CircuitStreamTimeout;
00522   if (timeout) /* if our config options override the default, use them */
00523     return timeout;
00524   if (conn->num_socks_retries < 2) /* try 0 and try 1 */
00525     return 10;
00526   return 15;
00527 }
00528 
00538 void
00539 connection_ap_expire_beginning(void)
00540 {
00541   edge_connection_t *conn;
00542   entry_connection_t *entry_conn;
00543   circuit_t *circ;
00544   time_t now = time(NULL);
00545   const or_options_t *options = get_options();
00546   int severity;
00547   int cutoff;
00548   int seconds_idle, seconds_since_born;
00549   smartlist_t *conns = get_connection_array();
00550 
00551   SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
00552     if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
00553       continue;
00554     entry_conn = TO_ENTRY_CONN(base_conn);
00555     conn = ENTRY_TO_EDGE_CONN(entry_conn);
00556     /* if it's an internal linked connection, don't yell its status. */
00557     severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
00558       ? LOG_INFO : LOG_NOTICE;
00559     seconds_idle = (int)( now - base_conn->timestamp_lastread );
00560     seconds_since_born = (int)( now - base_conn->timestamp_created );
00561 
00562     if (base_conn->state == AP_CONN_STATE_OPEN)
00563       continue;
00564 
00565     /* We already consider SocksTimeout in
00566      * connection_ap_handshake_attach_circuit(), but we need to consider
00567      * it here too because controllers that put streams in controller_wait
00568      * state never ask Tor to attach the circuit. */
00569     if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
00570       if (seconds_since_born >= options->SocksTimeout) {
00571         log_fn(severity, LD_APP,
00572             "Tried for %d seconds to get a connection to %s:%d. "
00573             "Giving up. (%s)",
00574             seconds_since_born,
00575             safe_str_client(entry_conn->socks_request->address),
00576             entry_conn->socks_request->port,
00577             conn_state_to_string(CONN_TYPE_AP, base_conn->state));
00578         connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
00579       }
00580       continue;
00581     }
00582 
00583     /* We're in state connect_wait or resolve_wait now -- waiting for a
00584      * reply to our relay cell. See if we want to retry/give up. */
00585 
00586     cutoff = compute_retry_timeout(entry_conn);
00587     if (seconds_idle < cutoff)
00588       continue;
00589     circ = circuit_get_by_edge_conn(conn);
00590     if (!circ) { /* it's vanished? */
00591       log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
00592                safe_str_client(entry_conn->socks_request->address));
00593       connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
00594       continue;
00595     }
00596     if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
00597       if (seconds_idle >= options->SocksTimeout) {
00598         log_fn(severity, LD_REND,
00599                "Rend stream is %d seconds late. Giving up on address"
00600                " '%s.onion'.",
00601                seconds_idle,
00602                safe_str_client(entry_conn->socks_request->address));
00603         connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
00604         connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
00605       }
00606       continue;
00607     }
00608     tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
00609     log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
00610            "We tried for %d seconds to connect to '%s' using exit %s."
00611            " Retrying on a new circuit.",
00612            seconds_idle,
00613            safe_str_client(entry_conn->socks_request->address),
00614            conn->cpath_layer ?
00615              extend_info_describe(conn->cpath_layer->extend_info):
00616              "*unnamed*");
00617     /* send an end down the circuit */
00618     connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
00619     /* un-mark it as ending, since we're going to reuse it */
00620     conn->edge_has_sent_end = 0;
00621     conn->end_reason = 0;
00622     /* kludge to make us not try this circuit again, yet to allow
00623      * current streams on it to survive if they can: make it
00624      * unattractive to use for new streams */
00625     /* XXXX024 this is a kludgy way to do this. */
00626     tor_assert(circ->timestamp_dirty);
00627     circ->timestamp_dirty -= options->MaxCircuitDirtiness;
00628     /* give our stream another 'cutoff' seconds to try */
00629     conn->_base.timestamp_lastread += cutoff;
00630     if (entry_conn->num_socks_retries < 250) /* avoid overflow */
00631       entry_conn->num_socks_retries++;
00632     /* move it back into 'pending' state, and try to attach. */
00633     if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
00634                                        END_STREAM_REASON_TIMEOUT)<0) {
00635       if (!base_conn->marked_for_close)
00636         connection_mark_unattached_ap(entry_conn,
00637                                       END_STREAM_REASON_CANT_ATTACH);
00638     }
00639   } SMARTLIST_FOREACH_END(base_conn);
00640 }
00641 
00645 void
00646 connection_ap_attach_pending(void)
00647 {
00648   entry_connection_t *entry_conn;
00649   smartlist_t *conns = get_connection_array();
00650   SMARTLIST_FOREACH(conns, connection_t *, conn,
00651   {
00652     if (conn->marked_for_close ||
00653         conn->type != CONN_TYPE_AP ||
00654         conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
00655       continue;
00656     entry_conn = TO_ENTRY_CONN(conn);
00657     if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
00658       if (!conn->marked_for_close)
00659         connection_mark_unattached_ap(entry_conn,
00660                                       END_STREAM_REASON_CANT_ATTACH);
00661     }
00662   });
00663 }
00664 
00667 /* XXX024 We should get rid of this function, and instead attach
00668  * one-hop streams to circ->p_streams so they get marked in
00669  * circuit_mark_for_close like normal p_streams. */
00670 void
00671 connection_ap_fail_onehop(const char *failed_digest,
00672                           cpath_build_state_t *build_state)
00673 {
00674   entry_connection_t *entry_conn;
00675   char digest[DIGEST_LEN];
00676   smartlist_t *conns = get_connection_array();
00677   SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
00678     if (conn->marked_for_close ||
00679         conn->type != CONN_TYPE_AP ||
00680         conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
00681       continue;
00682     entry_conn = TO_ENTRY_CONN(conn);
00683     if (!entry_conn->want_onehop)
00684       continue;
00685     if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
00686         tor_memneq(digest, failed_digest, DIGEST_LEN))
00687       continue;
00688     if (tor_digest_is_zero(digest)) {
00689       /* we don't know the digest; have to compare addr:port */
00690       tor_addr_t addr;
00691       if (!build_state || !build_state->chosen_exit ||
00692           !entry_conn->socks_request || !entry_conn->socks_request->address)
00693         continue;
00694       if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
00695           !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
00696           build_state->chosen_exit->port != entry_conn->socks_request->port)
00697         continue;
00698     }
00699     log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
00700                      "just failed.", entry_conn->chosen_exit_name,
00701                      entry_conn->socks_request->address);
00702     connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
00703   } SMARTLIST_FOREACH_END(conn);
00704 }
00705 
00710 void
00711 circuit_discard_optional_exit_enclaves(extend_info_t *info)
00712 {
00713   entry_connection_t *entry_conn;
00714   const node_t *r1, *r2;
00715 
00716   smartlist_t *conns = get_connection_array();
00717   SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
00718     if (conn->marked_for_close ||
00719         conn->type != CONN_TYPE_AP ||
00720         conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
00721       continue;
00722     entry_conn = TO_ENTRY_CONN(conn);
00723     if (!entry_conn->chosen_exit_optional &&
00724         !entry_conn->chosen_exit_retries)
00725       continue;
00726     r1 = node_get_by_nickname(entry_conn->chosen_exit_name, 0);
00727     r2 = node_get_by_id(info->identity_digest);
00728     if (!r1 || !r2 || r1 != r2)
00729       continue;
00730     tor_assert(entry_conn->socks_request);
00731     if (entry_conn->chosen_exit_optional) {
00732       log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
00733                safe_str_client(entry_conn->chosen_exit_name),
00734                escaped_safe_str_client(entry_conn->socks_request->address));
00735       entry_conn->chosen_exit_optional = 0;
00736       tor_free(entry_conn->chosen_exit_name); /* clears it */
00737       /* if this port is dangerous, warn or reject it now that we don't
00738        * think it'll be using an enclave. */
00739       consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
00740     }
00741     if (entry_conn->chosen_exit_retries) {
00742       if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
00743         clear_trackexithost_mappings(entry_conn->chosen_exit_name);
00744         tor_free(entry_conn->chosen_exit_name); /* clears it */
00745         /* if this port is dangerous, warn or reject it now that we don't
00746          * think it'll be using an enclave. */
00747         consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
00748       }
00749     }
00750   } SMARTLIST_FOREACH_END(conn);
00751 }
00752 
00760 int
00761 connection_ap_detach_retriable(entry_connection_t *conn,
00762                                origin_circuit_t *circ,
00763                                int reason)
00764 {
00765   control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
00766   ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL);
00767 
00768   if (conn->pending_optimistic_data) {
00769     generic_buffer_set_to_copy(&conn->sending_optimistic_data,
00770                                conn->pending_optimistic_data);
00771   }
00772 
00773   if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
00774     /* If we're attaching streams ourself, or if this connection is
00775      * a tunneled directory connection, then just attach it. */
00776     ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
00777     circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
00778     return connection_ap_handshake_attach_circuit(conn);
00779   } else {
00780     ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
00781     circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
00782     return 0;
00783   }
00784 }
00785 
00812 typedef struct {
00813   char *new_address;
00814   time_t expires;
00815   addressmap_entry_source_t source:3;
00816   unsigned src_wildcard:1;
00817   unsigned dst_wildcard:1;
00818   short num_resolve_failures;
00819 } addressmap_entry_t;
00820 
00822 typedef struct {
00823   char *ipv4_address;
00824   char *hostname_address;
00825 } virtaddress_entry_t;
00826 
00828 static strmap_t *addressmap=NULL;
00839 static strmap_t *virtaddress_reversemap=NULL;
00840 
00842 void
00843 addressmap_init(void)
00844 {
00845   addressmap = strmap_new();
00846   virtaddress_reversemap = strmap_new();
00847 }
00848 
00850 static void
00851 addressmap_ent_free(void *_ent)
00852 {
00853   addressmap_entry_t *ent;
00854   if (!_ent)
00855     return;
00856 
00857   ent = _ent;
00858   tor_free(ent->new_address);
00859   tor_free(ent);
00860 }
00861 
00863 static void
00864 addressmap_virtaddress_ent_free(void *_ent)
00865 {
00866   virtaddress_entry_t *ent;
00867   if (!_ent)
00868     return;
00869 
00870   ent = _ent;
00871   tor_free(ent->ipv4_address);
00872   tor_free(ent->hostname_address);
00873   tor_free(ent);
00874 }
00875 
00877 static void
00878 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
00879 {
00880   if (ent && ent->new_address &&
00881       address_is_in_virtual_range(ent->new_address)) {
00882     virtaddress_entry_t *ve =
00883       strmap_get(virtaddress_reversemap, ent->new_address);
00884     /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
00885     if (ve) {
00886       if (!strcmp(address, ve->ipv4_address))
00887         tor_free(ve->ipv4_address);
00888       if (!strcmp(address, ve->hostname_address))
00889         tor_free(ve->hostname_address);
00890       if (!ve->ipv4_address && !ve->hostname_address) {
00891         tor_free(ve);
00892         strmap_remove(virtaddress_reversemap, ent->new_address);
00893       }
00894     }
00895   }
00896 }
00897 
00900 static void
00901 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
00902 {
00903   addressmap_virtaddress_remove(address, ent);
00904   addressmap_ent_free(ent);
00905 }
00906 
00909 static void
00910 clear_trackexithost_mappings(const char *exitname)
00911 {
00912   char *suffix = NULL;
00913   if (!addressmap || !exitname)
00914     return;
00915   tor_asprintf(&suffix, ".%s.exit", exitname);
00916   tor_strlower(suffix);
00917 
00918   STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
00919     if (ent->source == ADDRMAPSRC_TRACKEXIT &&
00920         !strcmpend(ent->new_address, suffix)) {
00921       addressmap_ent_remove(address, ent);
00922       MAP_DEL_CURRENT(address);
00923     }
00924   } STRMAP_FOREACH_END;
00925 
00926   tor_free(suffix);
00927 }
00928 
00932 void
00933 addressmap_clear_excluded_trackexithosts(const or_options_t *options)
00934 {
00935   const routerset_t *allow_nodes = options->ExitNodes;
00936   const routerset_t *exclude_nodes = options->_ExcludeExitNodesUnion;
00937 
00938   if (!addressmap)
00939     return;
00940   if (routerset_is_empty(allow_nodes))
00941     allow_nodes = NULL;
00942   if (allow_nodes == NULL && routerset_is_empty(exclude_nodes))
00943     return;
00944 
00945   STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
00946     size_t len;
00947     const char *target = ent->new_address, *dot;
00948     char *nodename;
00949     const node_t *node;
00950 
00951     if (!target) {
00952       /* DNS resolving in progress */
00953       continue;
00954     } else if (strcmpend(target, ".exit")) {
00955       /* Not a .exit mapping */
00956       continue;
00957     } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
00958       /* Not a trackexit mapping. */
00959       continue;
00960     }
00961     len = strlen(target);
00962     if (len < 6)
00963       continue; /* malformed. */
00964     dot = target + len - 6; /* dot now points to just before .exit */
00965     while (dot > target && *dot != '.')
00966       dot--;
00967     if (*dot == '.') dot++;
00968     nodename = tor_strndup(dot, len-5-(dot-target));;
00969     node = node_get_by_nickname(nodename, 0);
00970     tor_free(nodename);
00971     if (!node ||
00972         (allow_nodes && !routerset_contains_node(allow_nodes, node)) ||
00973         routerset_contains_node(exclude_nodes, node) ||
00974         !hostname_in_track_host_exits(options, address)) {
00975       /* We don't know this one, or we want to be rid of it. */
00976       addressmap_ent_remove(address, ent);
00977       MAP_DEL_CURRENT(address);
00978     }
00979   } STRMAP_FOREACH_END;
00980 }
00981 
00986 void
00987 addressmap_clear_invalid_automaps(const or_options_t *options)
00988 {
00989   int clear_all = !options->AutomapHostsOnResolve;
00990   const smartlist_t *suffixes = options->AutomapHostsSuffixes;
00991 
00992   if (!addressmap)
00993     return;
00994 
00995   if (!suffixes)
00996     clear_all = 1; /* This should be impossible, but let's be sure. */
00997 
00998   STRMAP_FOREACH_MODIFY(addressmap, src_address, addressmap_entry_t *, ent) {
00999     int remove = clear_all;
01000     if (ent->source != ADDRMAPSRC_AUTOMAP)
01001       continue; /* not an automap mapping. */
01002 
01003     if (!remove) {
01004       int suffix_found = 0;
01005       SMARTLIST_FOREACH(suffixes, const char *, suffix, {
01006           if (!strcasecmpend(src_address, suffix)) {
01007             suffix_found = 1;
01008             break;
01009           }
01010       });
01011       if (!suffix_found)
01012         remove = 1;
01013     }
01014 
01015     if (!remove && ! address_is_in_virtual_range(ent->new_address))
01016       remove = 1;
01017 
01018     if (remove) {
01019       addressmap_ent_remove(src_address, ent);
01020       MAP_DEL_CURRENT(src_address);
01021     }
01022   } STRMAP_FOREACH_END;
01023 }
01024 
01027 void
01028 addressmap_clear_configured(void)
01029 {
01030   addressmap_get_mappings(NULL, 0, 0, 0);
01031 }
01032 
01034 void
01035 addressmap_clear_transient(void)
01036 {
01037   addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
01038 }
01039 
01043 void
01044 addressmap_clean(time_t now)
01045 {
01046   addressmap_get_mappings(NULL, 2, now, 0);
01047 }
01048 
01051 void
01052 addressmap_free_all(void)
01053 {
01054   strmap_free(addressmap, addressmap_ent_free);
01055   addressmap = NULL;
01056 
01057   strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
01058   virtaddress_reversemap = NULL;
01059 }
01060 
01072 static addressmap_entry_t *
01073 addressmap_match_superdomains(char *address)
01074 {
01075   addressmap_entry_t *val;
01076   char *cp;
01077 
01078   cp = address;
01079   while ((cp = strchr(cp, '.'))) {
01080     /* cp now points to a suffix of address that begins with a . */
01081     val = strmap_get_lc(addressmap, cp+1);
01082     if (val && val->src_wildcard) {
01083       if (val->dst_wildcard)
01084         *cp = '\0';
01085       return val;
01086     }
01087     ++cp;
01088   }
01089   return NULL;
01090 }
01091 
01106 int
01107 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out,
01108                    addressmap_entry_source_t *exit_source_out)
01109 {
01110   addressmap_entry_t *ent;
01111   int rewrites;
01112   time_t expires = TIME_MAX;
01113   addressmap_entry_source_t exit_source = ADDRMAPSRC_NONE;
01114   char *addr_orig = tor_strdup(address);
01115   char *log_addr_orig = NULL;
01116 
01117   for (rewrites = 0; rewrites < 16; rewrites++) {
01118     int exact_match = 0;
01119     log_addr_orig = tor_strdup(escaped_safe_str_client(address));
01120 
01121     ent = strmap_get(addressmap, address);
01122 
01123     if (!ent || !ent->new_address) {
01124       ent = addressmap_match_superdomains(address);
01125     } else {
01126       if (ent->src_wildcard && !ent->dst_wildcard &&
01127           !strcasecmp(address, ent->new_address)) {
01128         /* This is a rule like *.example.com example.com, and we just got
01129          * "example.com" */
01130         goto done;
01131       }
01132 
01133       exact_match = 1;
01134     }
01135 
01136     if (!ent || !ent->new_address) {
01137       goto done;
01138     }
01139 
01140     if (ent->dst_wildcard && !exact_match) {
01141       strlcat(address, ".", maxlen);
01142       strlcat(address, ent->new_address, maxlen);
01143     } else {
01144       strlcpy(address, ent->new_address, maxlen);
01145     }
01146 
01147     if (!strcmpend(address, ".exit") &&
01148         strcmpend(addr_orig, ".exit") &&
01149         exit_source == ADDRMAPSRC_NONE) {
01150       exit_source = ent->source;
01151     }
01152 
01153     log_info(LD_APP, "Addressmap: rewriting %s to %s",
01154              log_addr_orig, escaped_safe_str_client(address));
01155     if (ent->expires > 1 && ent->expires < expires)
01156       expires = ent->expires;
01157 
01158     tor_free(log_addr_orig);
01159   }
01160   log_warn(LD_CONFIG,
01161            "Loop detected: we've rewritten %s 16 times! Using it as-is.",
01162            escaped_safe_str_client(address));
01163   /* it's fine to rewrite a rewrite, but don't loop forever */
01164 
01165  done:
01166   tor_free(addr_orig);
01167   tor_free(log_addr_orig);
01168   if (exit_source_out)
01169     *exit_source_out = exit_source;
01170   if (expires_out)
01171     *expires_out = TIME_MAX;
01172   return (rewrites > 0);
01173 }
01174 
01180 static int
01181 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
01182 {
01183   char *s, *cp;
01184   addressmap_entry_t *ent;
01185   int r = 0;
01186   tor_asprintf(&s, "REVERSE[%s]", address);
01187   ent = strmap_get(addressmap, s);
01188   if (ent) {
01189     cp = tor_strdup(escaped_safe_str_client(ent->new_address));
01190     log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
01191              escaped_safe_str_client(s), cp);
01192     tor_free(cp);
01193     strlcpy(address, ent->new_address, maxlen);
01194     r = 1;
01195   }
01196 
01197   if (expires_out)
01198     *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
01199 
01200   tor_free(s);
01201   return r;
01202 }
01203 
01208 int
01209 addressmap_have_mapping(const char *address, int update_expiry)
01210 {
01211   addressmap_entry_t *ent;
01212   if (!(ent=strmap_get_lc(addressmap, address)))
01213     return 0;
01214   if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
01215     ent->expires=time(NULL) + update_expiry;
01216   return 1;
01217 }
01218 
01241 void
01242 addressmap_register(const char *address, char *new_address, time_t expires,
01243                     addressmap_entry_source_t source,
01244                     const int wildcard_addr,
01245                     const int wildcard_new_addr)
01246 {
01247   addressmap_entry_t *ent;
01248 
01249   if (wildcard_new_addr)
01250     tor_assert(wildcard_addr);
01251 
01252   ent = strmap_get(addressmap, address);
01253   if (!new_address || (!strcasecmp(address,new_address) &&
01254                        wildcard_addr == wildcard_new_addr)) {
01255     /* Remove the mapping, if any. */
01256     tor_free(new_address);
01257     if (ent) {
01258       addressmap_ent_remove(address,ent);
01259       strmap_remove(addressmap, address);
01260     }
01261     return;
01262   }
01263   if (!ent) { /* make a new one and register it */
01264     ent = tor_malloc_zero(sizeof(addressmap_entry_t));
01265     strmap_set(addressmap, address, ent);
01266   } else if (ent->new_address) { /* we need to clean up the old mapping. */
01267     if (expires > 1) {
01268       log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
01269                "since it's already mapped to '%s'",
01270       safe_str_client(address),
01271       safe_str_client(new_address),
01272       safe_str_client(ent->new_address));
01273       tor_free(new_address);
01274       return;
01275     }
01276     if (address_is_in_virtual_range(ent->new_address) &&
01277         expires != 2) {
01278       /* XXX This isn't the perfect test; we want to avoid removing
01279        * mappings set from the control interface _as virtual mapping */
01280       addressmap_virtaddress_remove(address, ent);
01281     }
01282     tor_free(ent->new_address);
01283   } /* else { we have an in-progress resolve with no mapping. } */
01284 
01285   ent->new_address = new_address;
01286   ent->expires = expires==2 ? 1 : expires;
01287   ent->num_resolve_failures = 0;
01288   ent->source = source;
01289   ent->src_wildcard = wildcard_addr ? 1 : 0;
01290   ent->dst_wildcard = wildcard_new_addr ? 1 : 0;
01291 
01292   log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
01293            safe_str_client(address),
01294            safe_str_client(ent->new_address));
01295   control_event_address_mapped(address, ent->new_address, expires, NULL);
01296 }
01297 
01302 int
01303 client_dns_incr_failures(const char *address)
01304 {
01305   addressmap_entry_t *ent = strmap_get(addressmap, address);
01306   if (!ent) {
01307     ent = tor_malloc_zero(sizeof(addressmap_entry_t));
01308     ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
01309     strmap_set(addressmap,address,ent);
01310   }
01311   if (ent->num_resolve_failures < SHORT_MAX)
01312     ++ent->num_resolve_failures; /* don't overflow */
01313   log_info(LD_APP, "Address %s now has %d resolve failures.",
01314            safe_str_client(address),
01315            ent->num_resolve_failures);
01316   return ent->num_resolve_failures;
01317 }
01318 
01324 void
01325 client_dns_clear_failures(const char *address)
01326 {
01327   addressmap_entry_t *ent = strmap_get(addressmap, address);
01328   if (ent)
01329     ent->num_resolve_failures = 0;
01330 }
01331 
01342 static void
01343 client_dns_set_addressmap_impl(const char *address, const char *name,
01344                                const char *exitname,
01345                                int ttl)
01346 {
01347   /* <address>.<hex or nickname>.exit\0  or just  <address>\0 */
01348   char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
01349   /* 123.123.123.123.<hex or nickname>.exit\0  or just  123.123.123.123\0 */
01350   char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
01351 
01352   tor_assert(address);
01353   tor_assert(name);
01354 
01355   if (ttl<0)
01356     ttl = DEFAULT_DNS_TTL;
01357   else
01358     ttl = dns_clip_ttl(ttl);
01359 
01360   if (exitname) {
01361     /* XXXX fails to ever get attempts to get an exit address of
01362      * google.com.digest[=~]nickname.exit; we need a syntax for this that
01363      * won't make strict RFC952-compliant applications (like us) barf. */
01364     tor_snprintf(extendedaddress, sizeof(extendedaddress),
01365                  "%s.%s.exit", address, exitname);
01366     tor_snprintf(extendedval, sizeof(extendedval),
01367                  "%s.%s.exit", name, exitname);
01368   } else {
01369     tor_snprintf(extendedaddress, sizeof(extendedaddress),
01370                  "%s", address);
01371     tor_snprintf(extendedval, sizeof(extendedval),
01372                  "%s", name);
01373   }
01374   addressmap_register(extendedaddress, tor_strdup(extendedval),
01375                       time(NULL) + ttl, ADDRMAPSRC_DNS, 0, 0);
01376 }
01377 
01388 void
01389 client_dns_set_addressmap(const char *address, uint32_t val,
01390                           const char *exitname,
01391                           int ttl)
01392 {
01393   struct in_addr in;
01394   char valbuf[INET_NTOA_BUF_LEN];
01395 
01396   tor_assert(address);
01397 
01398   if (tor_inet_aton(address, &in))
01399     return; /* If address was an IP address already, don't add a mapping. */
01400   in.s_addr = htonl(val);
01401   tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
01402 
01403   client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
01404 }
01405 
01415 static void
01416 client_dns_set_reverse_addressmap(const char *address, const char *v,
01417                                   const char *exitname,
01418                                   int ttl)
01419 {
01420   char *s = NULL;
01421   tor_asprintf(&s, "REVERSE[%s]", address);
01422   client_dns_set_addressmap_impl(s, v, exitname, ttl);
01423   tor_free(s);
01424 }
01425 
01426 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
01427  * These addresses should map to localhost, so even if the
01428  * application accidentally tried to connect to them directly (not
01429  * via Tor), it wouldn't get too far astray.
01430  *
01431  * These options are configured by parse_virtual_addr_network().
01432  */
01435 static uint32_t virtual_addr_network = 0x7fc00000u;
01437 static maskbits_t virtual_addr_netmask_bits = 10;
01439 static uint32_t next_virtual_addr    = 0x7fc00000u;
01440 
01446 int
01447 parse_virtual_addr_network(const char *val, int validate_only,
01448                            char **msg)
01449 {
01450   uint32_t addr;
01451   uint16_t port_min, port_max;
01452   maskbits_t bits;
01453 
01454   if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
01455     if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
01456     return -1;
01457   }
01458 
01459   if (port_min != 1 || port_max != 65535) {
01460     if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
01461     return -1;
01462   }
01463 
01464   if (bits > 16) {
01465     if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
01466                                "network or larger");
01467     return -1;
01468   }
01469 
01470   if (validate_only)
01471     return 0;
01472 
01473   virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
01474   virtual_addr_netmask_bits = bits;
01475 
01476   if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
01477     next_virtual_addr = addr;
01478 
01479   return 0;
01480 }
01481 
01486 static int
01487 address_is_in_virtual_range(const char *address)
01488 {
01489   struct in_addr in;
01490   tor_assert(address);
01491   if (!strcasecmpend(address, ".virtual")) {
01492     return 1;
01493   } else if (tor_inet_aton(address, &in)) {
01494     uint32_t addr = ntohl(in.s_addr);
01495     if (!addr_mask_cmp_bits(addr, virtual_addr_network,
01496                             virtual_addr_netmask_bits))
01497       return 1;
01498   }
01499   return 0;
01500 }
01501 
01505 static INLINE void
01506 increment_virtual_addr(void)
01507 {
01508   ++next_virtual_addr;
01509   if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
01510                          virtual_addr_netmask_bits))
01511     next_virtual_addr = virtual_addr_network;
01512 }
01513 
01520 static char *
01521 addressmap_get_virtual_address(int type)
01522 {
01523   char buf[64];
01524   tor_assert(addressmap);
01525 
01526   if (type == RESOLVED_TYPE_HOSTNAME) {
01527     char rand[10];
01528     do {
01529       crypto_rand(rand, sizeof(rand));
01530       base32_encode(buf,sizeof(buf),rand,sizeof(rand));
01531       strlcat(buf, ".virtual", sizeof(buf));
01532     } while (strmap_get(addressmap, buf));
01533     return tor_strdup(buf);
01534   } else if (type == RESOLVED_TYPE_IPV4) {
01535     // This is an imperfect estimate of how many addresses are available, but
01536     // that's ok.
01537     struct in_addr in;
01538     uint32_t available = 1u << (32-virtual_addr_netmask_bits);
01539     while (available) {
01540       /* Don't hand out any .0 or .255 address. */
01541       while ((next_virtual_addr & 0xff) == 0 ||
01542              (next_virtual_addr & 0xff) == 0xff) {
01543         increment_virtual_addr();
01544         if (! --available) {
01545           log_warn(LD_CONFIG, "Ran out of virtual addresses!");
01546           return NULL;
01547         }
01548       }
01549       in.s_addr = htonl(next_virtual_addr);
01550       tor_inet_ntoa(&in, buf, sizeof(buf));
01551       if (!strmap_get(addressmap, buf)) {
01552         increment_virtual_addr();
01553         break;
01554       }
01555 
01556       increment_virtual_addr();
01557       --available;
01558       // log_info(LD_CONFIG, "%d addrs available", (int)available);
01559       if (! available) {
01560         log_warn(LD_CONFIG, "Ran out of virtual addresses!");
01561         return NULL;
01562       }
01563     }
01564     return tor_strdup(buf);
01565   } else {
01566     log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
01567     return NULL;
01568   }
01569 }
01570 
01580 const char *
01581 addressmap_register_virtual_address(int type, char *new_address)
01582 {
01583   char **addrp;
01584   virtaddress_entry_t *vent;
01585   int vent_needs_to_be_added = 0;
01586 
01587   tor_assert(new_address);
01588   tor_assert(addressmap);
01589   tor_assert(virtaddress_reversemap);
01590 
01591   vent = strmap_get(virtaddress_reversemap, new_address);
01592   if (!vent) {
01593     vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
01594     vent_needs_to_be_added = 1;
01595   }
01596 
01597   addrp = (type == RESOLVED_TYPE_IPV4) ?
01598     &vent->ipv4_address : &vent->hostname_address;
01599   if (*addrp) {
01600     addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
01601     if (ent && ent->new_address &&
01602         !strcasecmp(new_address, ent->new_address)) {
01603       tor_free(new_address);
01604       tor_assert(!vent_needs_to_be_added);
01605       return tor_strdup(*addrp);
01606     } else
01607       log_warn(LD_BUG,
01608                "Internal confusion: I thought that '%s' was mapped to by "
01609                "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
01610                safe_str_client(new_address),
01611                safe_str_client(*addrp),
01612                safe_str_client(*addrp),
01613                ent?safe_str_client(ent->new_address):"(nothing)");
01614   }
01615 
01616   tor_free(*addrp);
01617   *addrp = addressmap_get_virtual_address(type);
01618   if (!*addrp) {
01619     tor_free(vent);
01620     tor_free(new_address);
01621     return NULL;
01622   }
01623   log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
01624   if (vent_needs_to_be_added)
01625     strmap_set(virtaddress_reversemap, new_address, vent);
01626   addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP, 0, 0);
01627 
01628 #if 0
01629   {
01630     /* Try to catch possible bugs */
01631     addressmap_entry_t *ent;
01632     ent = strmap_get(addressmap, *addrp);
01633     tor_assert(ent);
01634     tor_assert(!strcasecmp(ent->new_address,new_address));
01635     vent = strmap_get(virtaddress_reversemap, new_address);
01636     tor_assert(vent);
01637     tor_assert(!strcasecmp(*addrp,
01638                            (type == RESOLVED_TYPE_IPV4) ?
01639                            vent->ipv4_address : vent->hostname_address));
01640     log_info(LD_APP, "Map from %s to %s okay.",
01641              safe_str_client(*addrp),
01642              safe_str_client(new_address));
01643   }
01644 #endif
01645 
01646   return *addrp;
01647 }
01648 
01654 int
01655 address_is_invalid_destination(const char *address, int client)
01656 {
01657   if (client) {
01658     if (get_options()->AllowNonRFC953Hostnames)
01659       return 0;
01660   } else {
01661     if (get_options()->ServerDNSAllowNonRFC953Hostnames)
01662       return 0;
01663   }
01664 
01665   while (*address) {
01666     if (TOR_ISALNUM(*address) ||
01667         *address == '-' ||
01668         *address == '.' ||
01669         *address == '_') /* Underscore is not allowed, but Windows does it
01670                           * sometimes, just to thumb its nose at the IETF. */
01671       ++address;
01672     else
01673       return 1;
01674   }
01675   return 0;
01676 }
01677 
01684 void
01685 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
01686                         time_t max_expires, int want_expiry)
01687 {
01688    strmap_iter_t *iter;
01689    const char *key;
01690    void *_val;
01691    addressmap_entry_t *val;
01692 
01693    if (!addressmap)
01694      addressmap_init();
01695 
01696    for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
01697      strmap_iter_get(iter, &key, &_val);
01698      val = _val;
01699      if (val->expires >= min_expires && val->expires <= max_expires) {
01700        if (!sl) {
01701          iter = strmap_iter_next_rmv(addressmap,iter);
01702          addressmap_ent_remove(key, val);
01703          continue;
01704        } else if (val->new_address) {
01705          const char *src_wc = val->src_wildcard ? "*." : "";
01706          const char *dst_wc = val->dst_wildcard ? "*." : "";
01707          if (want_expiry) {
01708            if (val->expires < 3 || val->expires == TIME_MAX)
01709              smartlist_add_asprintf(sl, "%s%s %s%s NEVER",
01710                                     src_wc, key, dst_wc, val->new_address);
01711            else {
01712              char time[ISO_TIME_LEN+1];
01713              format_iso_time(time, val->expires);
01714              smartlist_add_asprintf(sl, "%s%s %s%s \"%s\"",
01715                                     src_wc, key, dst_wc, val->new_address,
01716                                     time);
01717            }
01718          } else {
01719            smartlist_add_asprintf(sl, "%s%s %s%s",
01720                                   src_wc, key, dst_wc, val->new_address);
01721          }
01722        }
01723      }
01724      iter = strmap_iter_next(addressmap,iter);
01725    }
01726 }
01727 
01730 static int
01731 consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
01732 {
01733   const or_options_t *options = get_options();
01734   int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
01735 
01736   if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
01737     log_warn(LD_APP, "Application request to port %d: this port is "
01738              "commonly used for unencrypted protocols. Please make sure "
01739              "you don't send anything you would mind the rest of the "
01740              "Internet reading!%s", port, reject ? " Closing." : "");
01741     control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
01742                                 port, reject ? "REJECT" : "WARN");
01743   }
01744 
01745   if (reject) {
01746     log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
01747     connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
01748     return -1;
01749   }
01750 
01751   return 0;
01752 }
01753 
01757 #define TRACKHOSTEXITS_RETRIES 5
01758 
01765 int
01766 connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn,
01767                                             origin_circuit_t *circ,
01768                                             crypt_path_t *cpath)
01769 {
01770   const or_options_t *options = get_options();
01771 
01772   if (options->LeaveStreamsUnattached) {
01773     ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
01774     return 0;
01775   }
01776   return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
01777 }
01778 
01794 int
01795 connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
01796                                            origin_circuit_t *circ,
01797                                            crypt_path_t *cpath)
01798 {
01799   socks_request_t *socks = conn->socks_request;
01800   hostname_type_t addresstype;
01801   const or_options_t *options = get_options();
01802   struct in_addr addr_tmp;
01803   /* We set this to true if this is an address we should automatically
01804    * remap to a local address in VirtualAddrNetwork */
01805   int automap = 0;
01806   char orig_address[MAX_SOCKS_ADDR_LEN];
01807   time_t map_expires = TIME_MAX;
01808   time_t now = time(NULL);
01809   connection_t *base_conn = ENTRY_TO_CONN(conn);
01810   addressmap_entry_source_t exit_source = ADDRMAPSRC_NONE;
01811 
01812   tor_strlower(socks->address); /* normalize it */
01813   strlcpy(orig_address, socks->address, sizeof(orig_address));
01814   log_debug(LD_APP,"Client asked for %s:%d",
01815             safe_str_client(socks->address),
01816             socks->port);
01817 
01818   if (!strcmpend(socks->address, ".exit") && !options->AllowDotExit) {
01819     log_warn(LD_APP, "The  \".exit\" notation is disabled in Tor due to "
01820              "security risks. Set AllowDotExit in your torrc to enable "
01821              "it (at your own risk).");
01822     control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
01823                                 escaped(socks->address));
01824     connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
01825     return -1;
01826   }
01827 
01828   if (! conn->original_dest_address)
01829     conn->original_dest_address = tor_strdup(conn->socks_request->address);
01830 
01831   if (socks->command == SOCKS_COMMAND_RESOLVE &&
01832       !tor_inet_aton(socks->address, &addr_tmp) &&
01833       options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
01834     SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
01835                       if (!strcasecmpend(socks->address, cp)) {
01836                         automap = 1;
01837                         break;
01838                       });
01839     if (automap) {
01840       const char *new_addr;
01841       new_addr = addressmap_register_virtual_address(
01842                               RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
01843       if (! new_addr) {
01844         log_warn(LD_APP, "Unable to automap address %s",
01845                  escaped_safe_str(socks->address));
01846         connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
01847         return -1;
01848       }
01849       log_info(LD_APP, "Automapping %s to %s",
01850                escaped_safe_str_client(socks->address),
01851                safe_str_client(new_addr));
01852       strlcpy(socks->address, new_addr, sizeof(socks->address));
01853     }
01854   }
01855 
01856   if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
01857     if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
01858                                    &map_expires)) {
01859       char *result = tor_strdup(socks->address);
01860       /* remember _what_ is supposed to have been resolved. */
01861       tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
01862                   orig_address);
01863       connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
01864                                              strlen(result), (uint8_t*)result,
01865                                              -1,
01866                                              map_expires);
01867       connection_mark_unattached_ap(conn,
01868                                 END_STREAM_REASON_DONE |
01869                                 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
01870       return 0;
01871     }
01872     if (options->ClientDNSRejectInternalAddresses) {
01873       /* Don't let people try to do a reverse lookup on 10.0.0.1. */
01874       tor_addr_t addr;
01875       int ok;
01876       ok = tor_addr_parse_PTR_name(
01877                                &addr, socks->address, AF_UNSPEC, 1);
01878       if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
01879         connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
01880                                                0, NULL, -1, TIME_MAX);
01881         connection_mark_unattached_ap(conn,
01882                                  END_STREAM_REASON_SOCKSPROTOCOL |
01883                                  END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
01884         return -1;
01885       }
01886     }
01887   } else if (!automap) {
01888     /* For address map controls, remap the address. */
01889     if (addressmap_rewrite(socks->address, sizeof(socks->address),
01890                            &map_expires, &exit_source)) {
01891       control_event_stream_status(conn, STREAM_EVENT_REMAP,
01892                                   REMAP_STREAM_SOURCE_CACHE);
01893     }
01894   }
01895 
01896   if (!automap && address_is_in_virtual_range(socks->address)) {
01897     /* This address was probably handed out by client_dns_get_unmapped_address,
01898      * but the mapping was discarded for some reason.  We *don't* want to send
01899      * the address through Tor; that's likely to fail, and may leak
01900      * information.
01901      */
01902     log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
01903              safe_str_client(socks->address));
01904     connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
01905     return -1;
01906   }
01907 
01908   /* Parse the address provided by SOCKS.  Modify it in-place if it
01909    * specifies a hidden-service (.onion) or particular exit node (.exit).
01910    */
01911   addresstype = parse_extended_hostname(socks->address);
01912 
01913   if (addresstype == BAD_HOSTNAME) {
01914     control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
01915                                 escaped(socks->address));
01916     connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
01917     return -1;
01918   }
01919 
01920   if (addresstype == EXIT_HOSTNAME) {
01921     /* foo.exit -- modify conn->chosen_exit_node to specify the exit
01922      * node, and conn->address to hold only the address portion. */
01923     char *s = strrchr(socks->address,'.');
01924 
01925     /* If StrictNodes is not set, then .exit overrides ExcludeNodes. */
01926     routerset_t *excludeset = options->StrictNodes ?
01927       options->_ExcludeExitNodesUnion : options->ExcludeExitNodes;
01928     const node_t *node;
01929 
01930     if (exit_source == ADDRMAPSRC_AUTOMAP && !options->AllowDotExit) {
01931       /* Whoops; this one is stale.  It must have gotten added earlier,
01932        * when AllowDotExit was on. */
01933       log_warn(LD_APP,"Stale automapped address for '%s.exit', with "
01934                "AllowDotExit disabled. Refusing.",
01935                safe_str_client(socks->address));
01936       control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
01937                                   escaped(socks->address));
01938       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
01939       return -1;
01940     }
01941 
01942     if (exit_source == ADDRMAPSRC_DNS ||
01943         (exit_source == ADDRMAPSRC_NONE && !options->AllowDotExit)) {
01944       /* It shouldn't be possible to get a .exit address from any of these
01945        * sources. */
01946       log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
01947                ".exit part. Refusing.",
01948                safe_str_client(socks->address));
01949       control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
01950                                   escaped(socks->address));
01951       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
01952       return -1;
01953     }
01954 
01955     tor_assert(!automap);
01956     if (s) {
01957       /* The address was of the form "(stuff).(name).exit */
01958       if (s[1] != '\0') {
01959         conn->chosen_exit_name = tor_strdup(s+1);
01960         node = node_get_by_nickname(conn->chosen_exit_name, 1);
01961 
01962         if (exit_source == ADDRMAPSRC_TRACKEXIT) {
01963           /* We 5 tries before it expires the addressmap */
01964           conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
01965         }
01966         *s = 0;
01967       } else {
01968         /* Oops, the address was (stuff)..exit.  That's not okay. */
01969         log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
01970                  safe_str_client(socks->address));
01971         control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
01972                                     escaped(socks->address));
01973         connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
01974         return -1;
01975       }
01976     } else {
01977       /* It looks like they just asked for "foo.exit". */
01978 
01979       conn->chosen_exit_name = tor_strdup(socks->address);
01980       node = node_get_by_nickname(conn->chosen_exit_name, 1);
01981       if (node) {
01982         *socks->address = 0;
01983         node_get_address_string(node, socks->address, sizeof(socks->address));
01984       }
01985     }
01986     /* Now make sure that the chosen exit exists... */
01987     if (!node) {
01988       log_warn(LD_APP,
01989                "Unrecognized relay in exit address '%s.exit'. Refusing.",
01990                safe_str_client(socks->address));
01991       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
01992       return -1;
01993     }
01994     /* ...and make sure that it isn't excluded. */
01995     if (routerset_contains_node(excludeset, node)) {
01996       log_warn(LD_APP,
01997                "Excluded relay in exit address '%s.exit'. Refusing.",
01998                safe_str_client(socks->address));
01999       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
02000       return -1;
02001     }
02002     /* XXXX024-1090 Should we also allow foo.bar.exit if ExitNodes is set and
02003        Bar is not listed in it?  I say yes, but our revised manpage branch
02004        implies no. */
02005   }
02006 
02007   if (addresstype != ONION_HOSTNAME) {
02008     /* not a hidden-service request (i.e. normal or .exit) */
02009     if (address_is_invalid_destination(socks->address, 1)) {
02010       control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
02011                                   escaped(socks->address));
02012       log_warn(LD_APP,
02013                "Destination '%s' seems to be an invalid hostname. Failing.",
02014                safe_str_client(socks->address));
02015       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
02016       return -1;
02017     }
02018 
02019     if (options->Tor2webMode) {
02020       log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname %s "
02021                "because tor2web mode is enabled.",
02022                safe_str_client(socks->address));
02023       connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
02024       return -1;
02025     }
02026 
02027     if (socks->command == SOCKS_COMMAND_RESOLVE) {
02028       uint32_t answer;
02029       struct in_addr in;
02030       /* Reply to resolves immediately if we can. */
02031       if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
02032         /* leave it in network order */
02033         answer = in.s_addr;
02034         /* remember _what_ is supposed to have been resolved. */
02035         strlcpy(socks->address, orig_address, sizeof(socks->address));
02036         connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
02037                                                (uint8_t*)&answer,
02038                                                -1,map_expires);
02039         connection_mark_unattached_ap(conn,
02040                                 END_STREAM_REASON_DONE |
02041                                 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
02042         return 0;
02043       }
02044       tor_assert(!automap);
02045       rep_hist_note_used_resolve(now); /* help predict this next time */
02046     } else if (socks->command == SOCKS_COMMAND_CONNECT) {
02047       tor_assert(!automap);
02048       if (socks->port == 0) {
02049         log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
02050         connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
02051         return -1;
02052       }
02053       if (options->ClientRejectInternalAddresses &&
02054           !conn->use_begindir && !conn->chosen_exit_name && !circ) {
02055         tor_addr_t addr;
02056         if (tor_addr_hostname_is_local(socks->address) ||
02057             (tor_addr_parse(&addr, socks->address) >= 0 &&
02058              tor_addr_is_internal(&addr, 0))) {
02059           /* If this is an explicit private address with no chosen exit node,
02060            * then we really don't want to try to connect to it.  That's
02061            * probably an error. */
02062           if (conn->is_transparent_ap) {
02063 #define WARN_INTRVL_LOOP 300
02064             static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
02065             char *m;
02066             if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
02067               log_warn(LD_NET,
02068                        "Rejecting request for anonymous connection to private "
02069                        "address %s on a TransPort or NATDPort.  Possible loop "
02070                        "in your NAT rules?%s", safe_str_client(socks->address),
02071                        m);
02072               tor_free(m);
02073             }
02074           } else {
02075 #define WARN_INTRVL_PRIV 300
02076             static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
02077             char *m;
02078             if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
02079               log_warn(LD_NET,
02080                        "Rejecting SOCKS request for anonymous connection to "
02081                        "private address %s.%s",
02082                        safe_str_client(socks->address),m);
02083               tor_free(m);
02084             }
02085           }
02086           connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
02087           return -1;
02088         }
02089       }
02090 
02091       if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
02092         /* see if we can find a suitable enclave exit */
02093         const node_t *r =
02094           router_find_exact_exit_enclave(socks->address, socks->port);
02095         if (r) {
02096           log_info(LD_APP,
02097                    "Redirecting address %s to exit at enclave router %s",
02098                    safe_str_client(socks->address), node_describe(r));
02099           /* use the hex digest, not nickname, in case there are two
02100              routers with this nickname */
02101           conn->chosen_exit_name =
02102             tor_strdup(hex_str(r->identity, DIGEST_LEN));
02103           conn->chosen_exit_optional = 1;
02104         }
02105       }
02106 
02107       /* warn or reject if it's using a dangerous port */
02108       if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
02109         if (consider_plaintext_ports(conn, socks->port) < 0)
02110           return -1;
02111 
02112       if (!conn->use_begindir) {
02113         /* help predict this next time */
02114         rep_hist_note_used_port(now, socks->port);
02115       }
02116     } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
02117       rep_hist_note_used_resolve(now); /* help predict this next time */
02118       /* no extra processing needed */
02119     } else {
02120       tor_fragile_assert();
02121     }
02122     base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
02123     if ((circ && connection_ap_handshake_attach_chosen_circuit(
02124                    conn, circ, cpath) < 0) ||
02125         (!circ &&
02126          connection_ap_handshake_attach_circuit(conn) < 0)) {
02127       if (!base_conn->marked_for_close)
02128         connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
02129       return -1;
02130     }
02131     return 0;
02132   } else {
02133     /* it's a hidden-service request */
02134     rend_cache_entry_t *entry;
02135     int r;
02136     rend_service_authorization_t *client_auth;
02137     rend_data_t *rend_data;
02138     tor_assert(!automap);
02139     if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
02140       /* if it's a resolve request, fail it right now, rather than
02141        * building all the circuits and then realizing it won't work. */
02142       log_warn(LD_APP,
02143                "Resolve requests to hidden services not allowed. Failing.");
02144       connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
02145                                              0,NULL,-1,TIME_MAX);
02146       connection_mark_unattached_ap(conn,
02147                                 END_STREAM_REASON_SOCKSPROTOCOL |
02148                                 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
02149       return -1;
02150     }
02151 
02152     if (circ) {
02153       log_warn(LD_CONTROL, "Attachstream to a circuit is not "
02154                "supported for .onion addresses currently. Failing.");
02155       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
02156       return -1;
02157     }
02158 
02159     ENTRY_TO_EDGE_CONN(conn)->rend_data = rend_data =
02160       tor_malloc_zero(sizeof(rend_data_t));
02161     strlcpy(rend_data->onion_address, socks->address,
02162             sizeof(rend_data->onion_address));
02163     log_info(LD_REND,"Got a hidden service request for ID '%s'",
02164              safe_str_client(rend_data->onion_address));
02165     /* see if we already have it cached */
02166     r = rend_cache_lookup_entry(rend_data->onion_address, -1, &entry);
02167     if (r<0) {
02168       log_warn(LD_BUG,"Invalid service name '%s'",
02169                safe_str_client(rend_data->onion_address));
02170       connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
02171       return -1;
02172     }
02173 
02174     /* Help predict this next time. We're not sure if it will need
02175      * a stable circuit yet, but we know we'll need *something*. */
02176     rep_hist_note_used_internal(now, 0, 1);
02177 
02178     /* Look up if we have client authorization for it. */
02179     client_auth = rend_client_lookup_service_authorization(
02180                                           rend_data->onion_address);
02181     if (client_auth) {
02182       log_info(LD_REND, "Using previously configured client authorization "
02183                         "for hidden service request.");
02184       memcpy(rend_data->descriptor_cookie,
02185              client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
02186       rend_data->auth_type = client_auth->auth_type;
02187     }
02188     if (r==0) {
02189       base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
02190       log_info(LD_REND, "Unknown descriptor %s. Fetching.",
02191                safe_str_client(rend_data->onion_address));
02192       rend_client_refetch_v2_renddesc(rend_data);
02193     } else { /* r > 0 */
02194       base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
02195       log_info(LD_REND, "Descriptor is here. Great.");
02196       if (connection_ap_handshake_attach_circuit(conn) < 0) {
02197         if (!base_conn->marked_for_close)
02198           connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
02199         return -1;
02200       }
02201     }
02202     return 0;
02203   }
02204   return 0; /* unreached but keeps the compiler happy */
02205 }
02206 
02207 #ifdef TRANS_PF
02208 static int pf_socket = -1;
02209 int
02210 get_pf_socket(void)
02211 {
02212   int pf;
02213   /*  This should be opened before dropping privileges. */
02214   if (pf_socket >= 0)
02215     return pf_socket;
02216 
02217 #ifdef OPENBSD
02218   /* only works on OpenBSD */
02219   pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
02220 #else
02221   /* works on NetBSD and FreeBSD */
02222   pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
02223 #endif
02224 
02225   if (pf < 0) {
02226     log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
02227     return -1;
02228   }
02229 
02230   pf_socket = pf;
02231   return pf_socket;
02232 }
02233 #endif
02234 
02242 static int
02243 connection_ap_get_original_destination(entry_connection_t *conn,
02244                                        socks_request_t *req)
02245 {
02246 #ifdef TRANS_NETFILTER
02247   /* Linux 2.4+ */
02248   struct sockaddr_storage orig_dst;
02249   socklen_t orig_dst_len = sizeof(orig_dst);
02250   tor_addr_t addr;
02251 
02252   if (getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
02253                  (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
02254     int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
02255     log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
02256     return -1;
02257   }
02258 
02259   tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
02260   tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
02261 
02262   return 0;
02263 #elif defined(TRANS_PF)
02264   struct sockaddr_storage proxy_addr;
02265   socklen_t proxy_addr_len = sizeof(proxy_addr);
02266   struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
02267   struct pfioc_natlook pnl;
02268   tor_addr_t addr;
02269   int pf = -1;
02270 
02271   if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
02272                   &proxy_addr_len) < 0) {
02273     int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
02274     log_warn(LD_NET, "getsockname() to determine transocks destination "
02275              "failed: %s", tor_socket_strerror(e));
02276     return -1;
02277   }
02278 
02279   memset(&pnl, 0, sizeof(pnl));
02280   pnl.proto           = IPPROTO_TCP;
02281   pnl.direction       = PF_OUT;
02282   if (proxy_sa->sa_family == AF_INET) {
02283     struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
02284     pnl.af              = AF_INET;
02285     pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
02286     pnl.sport           = htons(ENTRY_TO_CONN(conn)->port);
02287     pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
02288     pnl.dport           = sin->sin_port;
02289   } else if (proxy_sa->sa_family == AF_INET6) {
02290     struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
02291     pnl.af = AF_INET6;
02292     memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
02293            sizeof(struct in6_addr));
02294     pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
02295     memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
02296     pnl.dport = sin6->sin6_port;
02297   } else {
02298     log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
02299              (int)proxy_sa->sa_family);
02300     return -1;
02301   }
02302 
02303   pf = get_pf_socket();
02304   if (pf<0)
02305     return -1;
02306 
02307   if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
02308     log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
02309     return -1;
02310   }
02311 
02312   if (pnl.af == AF_INET) {
02313     tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
02314   } else if (pnl.af == AF_INET6) {
02315     tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
02316   } else {
02317     tor_fragile_assert();
02318     return -1;
02319   }
02320 
02321   tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
02322   req->port = ntohs(pnl.rdport);
02323 
02324   return 0;
02325 #else
02326   (void)conn;
02327   (void)req;
02328   log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
02329            "transparent proxy method was configured.");
02330   return -1;
02331 #endif
02332 }
02333 
02344 static int
02345 connection_ap_handshake_process_socks(entry_connection_t *conn)
02346 {
02347   socks_request_t *socks;
02348   int sockshere;
02349   const or_options_t *options = get_options();
02350   int had_reply = 0;
02351   connection_t *base_conn = ENTRY_TO_CONN(conn);
02352 
02353   tor_assert(conn);
02354   tor_assert(base_conn->type == CONN_TYPE_AP);
02355   tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
02356   tor_assert(conn->socks_request);
02357   socks = conn->socks_request;
02358 
02359   log_debug(LD_APP,"entered.");
02360 
02361   IF_HAS_BUFFEREVENT(base_conn, {
02362     struct evbuffer *input = bufferevent_get_input(base_conn->bufev);
02363     sockshere = fetch_from_evbuffer_socks(input, socks,
02364                                      options->TestSocks, options->SafeSocks);
02365   }) ELSE_IF_NO_BUFFEREVENT {
02366     sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
02367                                      options->TestSocks, options->SafeSocks);
02368   };
02369 
02370   if (socks->replylen) {
02371     had_reply = 1;
02372     connection_write_to_buf((const char*)socks->reply, socks->replylen,
02373                             base_conn);
02374     socks->replylen = 0;
02375     if (sockshere == -1) {
02376       /* An invalid request just got a reply, no additional
02377        * one is necessary. */
02378       socks->has_finished = 1;
02379     }
02380   }
02381 
02382   if (sockshere == 0) {
02383     log_debug(LD_APP,"socks handshake not all here yet.");
02384     return 0;
02385   } else if (sockshere == -1) {
02386     if (!had_reply) {
02387       log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
02388       connection_ap_handshake_socks_reply(conn, NULL, 0,
02389                                           END_STREAM_REASON_SOCKSPROTOCOL);
02390     }
02391     connection_mark_unattached_ap(conn,
02392                               END_STREAM_REASON_SOCKSPROTOCOL |
02393                               END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
02394     return -1;
02395   } /* else socks handshake is done, continue processing */
02396 
02397   if (SOCKS_COMMAND_IS_CONNECT(socks->command))
02398     control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
02399   else
02400     control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
02401 
02402   return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
02403 }
02404 
02412 int
02413 connection_ap_process_transparent(entry_connection_t *conn)
02414 {
02415   socks_request_t *socks;
02416 
02417   tor_assert(conn);
02418   tor_assert(conn->socks_request);
02419   socks = conn->socks_request;
02420 
02421   /* pretend that a socks handshake completed so we don't try to
02422    * send a socks reply down a transparent conn */
02423   socks->command = SOCKS_COMMAND_CONNECT;
02424   socks->has_finished = 1;
02425 
02426   log_debug(LD_APP,"entered.");
02427 
02428   if (connection_ap_get_original_destination(conn, socks) < 0) {
02429     log_warn(LD_APP,"Fetching original destination failed. Closing.");
02430     connection_mark_unattached_ap(conn,
02431                                END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
02432     return -1;
02433   }
02434   /* we have the original destination */
02435 
02436   control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
02437 
02438   return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
02439 }
02440 
02452 static int
02453 connection_ap_process_natd(entry_connection_t *conn)
02454 {
02455   char tmp_buf[36], *tbuf, *daddr;
02456   size_t tlen = 30;
02457   int err, port_ok;
02458   socks_request_t *socks;
02459 
02460   tor_assert(conn);
02461   tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
02462   tor_assert(conn->socks_request);
02463   socks = conn->socks_request;
02464 
02465   log_debug(LD_APP,"entered.");
02466 
02467   /* look for LF-terminated "[DEST ip_addr port]"
02468    * where ip_addr is a dotted-quad and port is in string form */
02469   err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
02470   if (err == 0)
02471     return 0;
02472   if (err < 0) {
02473     log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
02474     connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
02475     return -1;
02476   }
02477 
02478   if (strcmpstart(tmp_buf, "[DEST ")) {
02479     log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
02480              "said: %s",
02481              escaped(tmp_buf));
02482     connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
02483     return -1;
02484   }
02485 
02486   daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
02487   if (!(tbuf = strchr(tbuf, ' '))) {
02488     log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
02489              "said: %s",
02490              escaped(tmp_buf));
02491     connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
02492     return -1;
02493   }
02494   *tbuf++ = '\0';
02495 
02496   /* pretend that a socks handshake completed so we don't try to
02497    * send a socks reply down a natd conn */
02498   strlcpy(socks->address, daddr, sizeof(socks->address));
02499   socks->port = (uint16_t)
02500     tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
02501   if (!port_ok) {
02502     log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
02503              "of range.", escaped(tbuf));
02504     connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
02505     return -1;
02506   }
02507 
02508   socks->command = SOCKS_COMMAND_CONNECT;
02509   socks->has_finished = 1;
02510 
02511   control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
02512 
02513   ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
02514 
02515   return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
02516 }
02517 
02521 static streamid_t
02522 get_unique_stream_id_by_circ(origin_circuit_t *circ)
02523 {
02524   edge_connection_t *tmpconn;
02525   streamid_t test_stream_id;
02526   uint32_t attempts=0;
02527 
02528  again:
02529   test_stream_id = circ->next_stream_id++;
02530   if (++attempts > 1<<16) {
02531     /* Make sure we don't loop forever if all stream_id's are used. */
02532     log_warn(LD_APP,"No unused stream IDs. Failing.");
02533     return 0;
02534   }
02535   if (test_stream_id == 0)
02536     goto again;
02537   for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
02538     if (tmpconn->stream_id == test_stream_id)
02539       goto again;
02540   return test_stream_id;
02541 }
02542 
02545 static int
02546 connection_ap_supports_optimistic_data(const entry_connection_t *conn)
02547 {
02548   const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
02549   /* We can only send optimistic data if we're connected to an open
02550      general circuit. */
02551   if (edge_conn->on_circuit == NULL ||
02552       edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
02553       edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
02554     return 0;
02555 
02556   return conn->may_use_optimistic_data;
02557 }
02558 
02564 int
02565 connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
02566 {
02567   char payload[CELL_PAYLOAD_SIZE];
02568   int payload_len;
02569   int begin_type;
02570   origin_circuit_t *circ;
02571   edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
02572   connection_t *base_conn = TO_CONN(edge_conn);
02573   tor_assert(edge_conn->on_circuit);
02574   circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
02575 
02576   tor_assert(base_conn->type == CONN_TYPE_AP);
02577   tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
02578   tor_assert(ap_conn->socks_request);
02579   tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
02580 
02581   edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
02582   if (edge_conn->stream_id==0) {
02583     /* XXXX024 Instead of closing this stream, we should make it get
02584      * retried on another circuit. */
02585     connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
02586 
02587     /* Mark this circuit "unusable for new streams". */
02588     /* XXXX024 this is a kludgy way to do this. */
02589     tor_assert(circ->_base.timestamp_dirty);
02590     circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
02591     return -1;
02592   }
02593 
02594   tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
02595                (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
02596                  ap_conn->socks_request->address : "",
02597                ap_conn->socks_request->port);
02598   payload_len = (int)strlen(payload)+1;
02599 
02600   log_info(LD_APP,
02601            "Sending relay cell %d to begin stream %d.",
02602            (int)ap_conn->use_begindir,
02603            edge_conn->stream_id);
02604 
02605   begin_type = ap_conn->use_begindir ?
02606                  RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
02607   if (begin_type == RELAY_COMMAND_BEGIN) {
02608 #ifndef NON_ANONYMOUS_MODE_ENABLED
02609     tor_assert(circ->build_state->onehop_tunnel == 0);
02610 #endif
02611   }
02612 
02613   if (connection_edge_send_command(edge_conn, begin_type,
02614                   begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
02615                   begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
02616     return -1; /* circuit is closed, don't continue */
02617 
02618   edge_conn->package_window = STREAMWINDOW_START;
02619   edge_conn->deliver_window = STREAMWINDOW_START;
02620   base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
02621   log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
02622            base_conn->s, circ->_base.n_circ_id);
02623   control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
02624 
02625   /* If there's queued-up data, send it now */
02626   if ((connection_get_inbuf_len(base_conn) ||
02627        ap_conn->sending_optimistic_data) &&
02628       connection_ap_supports_optimistic_data(ap_conn)) {
02629     log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
02630              (long)connection_get_inbuf_len(base_conn),
02631              ap_conn->sending_optimistic_data ?
02632              (long)generic_buffer_len(ap_conn->sending_optimistic_data) : 0);
02633     if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
02634       connection_mark_for_close(base_conn);
02635     }
02636   }
02637 
02638   return 0;
02639 }
02640 
02646 int
02647 connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
02648 {
02649   int payload_len, command;
02650   const char *string_addr;
02651   char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
02652   origin_circuit_t *circ;
02653   edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
02654   connection_t *base_conn = TO_CONN(edge_conn);
02655   tor_assert(edge_conn->on_circuit);
02656   circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
02657 
02658   tor_assert(base_conn->type == CONN_TYPE_AP);
02659   tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
02660   tor_assert(ap_conn->socks_request);
02661   tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
02662 
02663   command = ap_conn->socks_request->command;
02664   tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
02665 
02666   edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
02667   if (edge_conn->stream_id==0) {
02668     /* XXXX024 Instead of closing this stream, we should make it get
02669      * retried on another circuit. */
02670     connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
02671 
02672     /* Mark this circuit "unusable for new streams". */
02673     /* XXXX024 this is a kludgy way to do this. */
02674     tor_assert(circ->_base.timestamp_dirty);
02675     circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
02676     return -1;
02677   }
02678 
02679   if (command == SOCKS_COMMAND_RESOLVE) {
02680     string_addr = ap_conn->socks_request->address;
02681     payload_len = (int)strlen(string_addr)+1;
02682   } else {
02683     /* command == SOCKS_COMMAND_RESOLVE_PTR */
02684     const char *a = ap_conn->socks_request->address;
02685     tor_addr_t addr;
02686     int r;
02687 
02688     /* We're doing a reverse lookup.  The input could be an IP address, or
02689      * could be an .in-addr.arpa or .ip6.arpa address */
02690     r = tor_addr_parse_PTR_name(&addr, a, AF_INET, 1);
02691     if (r <= 0) {
02692       log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
02693                safe_str_client(a));
02694       connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
02695       return -1;
02696     }
02697 
02698     r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
02699     if (r < 0) {
02700       log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
02701                safe_str_client(a));
02702       connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
02703       return -1;
02704     }
02705 
02706     string_addr = inaddr_buf;
02707     payload_len = (int)strlen(inaddr_buf)+1;
02708     tor_assert(payload_len <= (int)sizeof(inaddr_buf));
02709   }
02710 
02711   log_debug(LD_APP,
02712             "Sending relay cell to begin stream %d.", edge_conn->stream_id);
02713 
02714   if (connection_edge_send_command(edge_conn,
02715                            RELAY_COMMAND_RESOLVE,
02716                            string_addr, payload_len) < 0)
02717     return -1; /* circuit is closed, don't continue */
02718 
02719   tor_free(base_conn->address); /* Maybe already set by dnsserv. */
02720   base_conn->address = tor_strdup("(Tor_internal)");
02721   base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
02722   log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
02723            base_conn->s, circ->_base.n_circ_id);
02724   control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
02725   control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
02726   return 0;
02727 }
02728 
02736 entry_connection_t *
02737 connection_ap_make_link(connection_t *partner,
02738                         char *address, uint16_t port,
02739                         const char *digest,
02740                         int session_group, int isolation_flags,
02741                         int use_begindir, int want_onehop)
02742 {
02743   entry_connection_t *conn;
02744   connection_t *base_conn;
02745 
02746   log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
02747            want_onehop ? "direct" : "anonymized",
02748            safe_str_client(address), port);
02749 
02750   conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
02751   base_conn = ENTRY_TO_CONN(conn);
02752   base_conn->linked = 1; /* so that we can add it safely below. */
02753 
02754   /* populate conn->socks_request */
02755 
02756   /* leave version at zero, so the socks_reply is empty */
02757   conn->socks_request->socks_version = 0;
02758   conn->socks_request->has_finished = 0; /* waiting for 'connected' */
02759   strlcpy(conn->socks_request->address, address,
02760           sizeof(conn->socks_request->address));
02761   conn->socks_request->port = port;
02762   conn->socks_request->command = SOCKS_COMMAND_CONNECT;
02763   conn->want_onehop = want_onehop;
02764   conn->use_begindir = use_begindir;
02765   if (use_begindir) {
02766     conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
02767     conn->chosen_exit_name[0] = '$';
02768     tor_assert(digest);
02769     base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
02770                   digest, DIGEST_LEN);
02771   }
02772 
02773   /* Populate isolation fields. */
02774   conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
02775   conn->original_dest_address = tor_strdup(address);
02776   conn->session_group = session_group;
02777   conn->isolation_flags = isolation_flags;
02778 
02779   base_conn->address = tor_strdup("(Tor_internal)");
02780   tor_addr_make_unspec(&base_conn->addr);
02781   base_conn->port = 0;
02782 
02783   connection_link_connections(partner, base_conn);
02784 
02785   if (connection_add(base_conn) < 0) { /* no space, forget it */
02786     connection_free(base_conn);
02787     return NULL;
02788   }
02789 
02790   base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
02791 
02792   control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
02793 
02794   /* attaching to a dirty circuit is fine */
02795   if (connection_ap_handshake_attach_circuit(conn) < 0) {
02796     if (!base_conn->marked_for_close)
02797       connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
02798     return NULL;
02799   }
02800 
02801   log_info(LD_APP,"... application connection created and linked.");
02802   return conn;
02803 }
02804 
02808 static void
02809 tell_controller_about_resolved_result(entry_connection_t *conn,
02810                                       int answer_type,
02811                                       size_t answer_len,
02812                                       const char *answer,
02813                                       int ttl,
02814                                       time_t expires)
02815 {
02816 
02817   if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
02818                    answer_type == RESOLVED_TYPE_HOSTNAME)) {
02819     return; /* we already told the controller. */
02820   } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
02821     char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
02822     control_event_address_mapped(conn->socks_request->address,
02823                                  cp, expires, NULL);
02824     tor_free(cp);
02825   } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
02826     char *cp = tor_strndup(answer, answer_len);
02827     control_event_address_mapped(conn->socks_request->address,
02828                                  cp, expires, NULL);
02829     tor_free(cp);
02830   } else {
02831     control_event_address_mapped(conn->socks_request->address,
02832                                  "<error>",
02833                                  time(NULL)+ttl,
02834                                  "error=yes");
02835   }
02836 }
02837 
02845 /* XXXX the use of the ttl and expires fields is nutty.  Let's make this
02846  * interface and those that use it less ugly. */
02847 void
02848 connection_ap_handshake_socks_resolved(entry_connection_t *conn,
02849                                        int answer_type,
02850                                        size_t answer_len,
02851                                        const uint8_t *answer,
02852                                        int ttl,
02853                                        time_t expires)
02854 {
02855   char buf[384];
02856   size_t replylen;
02857 
02858   if (ttl >= 0) {
02859     if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
02860       uint32_t a = ntohl(get_uint32(answer));
02861       if (a)
02862         client_dns_set_addressmap(conn->socks_request->address, a,
02863                                   conn->chosen_exit_name, ttl);
02864     } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
02865       char *cp = tor_strndup((char*)answer, answer_len);
02866       client_dns_set_reverse_addressmap(conn->socks_request->address,
02867                                         cp,
02868                                         conn->chosen_exit_name, ttl);
02869       tor_free(cp);
02870     }
02871   }
02872 
02873   if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
02874     if (conn->dns_server_request) {
02875       /* We had a request on our DNS port: answer it. */
02876       dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
02877       conn->socks_request->has_finished = 1;
02878       return;
02879     } else {
02880       /* This must be a request from the controller. We already sent
02881        * a mapaddress if there's a ttl. */
02882       tell_controller_about_resolved_result(conn, answer_type, answer_len,
02883                                             (char*)answer, ttl, expires);
02884       conn->socks_request->has_finished = 1;
02885       return;
02886     }
02887     /* We shouldn't need to free conn here; it gets marked by the caller. */
02888   }
02889 
02890   if (conn->socks_request->socks_version == 4) {
02891     buf[0] = 0x00; /* version */
02892     if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
02893       buf[1] = SOCKS4_GRANTED;
02894       set_uint16(buf+2, 0);
02895       memcpy(buf+4, answer, 4); /* address */
02896       replylen = SOCKS4_NETWORK_LEN;
02897     } else { /* "error" */
02898       buf[1] = SOCKS4_REJECT;
02899       memset(buf+2, 0, 6);
02900       replylen = SOCKS4_NETWORK_LEN;
02901     }
02902   } else if (conn->socks_request->socks_version == 5) {
02903     /* SOCKS5 */
02904     buf[0] = 0x05; /* version */
02905     if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
02906       buf[1] = SOCKS5_SUCCEEDED;
02907       buf[2] = 0; /* reserved */
02908       buf[3] = 0x01; /* IPv4 address type */
02909       memcpy(buf+4, answer, 4); /* address */
02910       set_uint16(buf+8, 0); /* port == 0. */
02911       replylen = 10;
02912     } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
02913       buf[1] = SOCKS5_SUCCEEDED;
02914       buf[2] = 0; /* reserved */
02915       buf[3] = 0x04; /* IPv6 address type */
02916       memcpy(buf+4, answer, 16); /* address */
02917       set_uint16(buf+20, 0); /* port == 0. */
02918       replylen = 22;
02919     } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
02920       buf[1] = SOCKS5_SUCCEEDED;
02921       buf[2] = 0; /* reserved */
02922       buf[3] = 0x03; /* Domainname address type */
02923       buf[4] = (char)answer_len;
02924       memcpy(buf+5, answer, answer_len); /* address */
02925       set_uint16(buf+5+answer_len, 0); /* port == 0. */
02926       replylen = 5+answer_len+2;
02927     } else {
02928       buf[1] = SOCKS5_HOST_UNREACHABLE;
02929       memset(buf+2, 0, 8);
02930       replylen = 10;
02931     }
02932   } else {
02933     /* no socks version info; don't send anything back */
02934     return;
02935   }
02936   connection_ap_handshake_socks_reply(conn, buf, replylen,
02937           (answer_type == RESOLVED_TYPE_IPV4 ||
02938            answer_type == RESOLVED_TYPE_IPV6 ||
02939            answer_type == RESOLVED_TYPE_HOSTNAME) ?
02940                                       0 : END_STREAM_REASON_RESOLVEFAILED);
02941 }
02942 
02952 void
02953 connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
02954                                     size_t replylen, int endreason)
02955 {
02956   char buf[256];
02957   socks5_reply_status_t status =
02958     stream_end_reason_to_socks5_response(endreason);
02959 
02960   tor_assert(conn->socks_request); /* make sure it's an AP stream */
02961 
02962   control_event_stream_status(conn,
02963      status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
02964                               endreason);
02965 
02966   if (conn->socks_request->has_finished) {
02967     log_warn(LD_BUG, "(Harmless.) duplicate calls to "
02968              "connection_ap_handshake_socks_reply.");
02969     return;
02970   }
02971   if (replylen) { /* we already have a reply in mind */
02972     connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
02973     conn->socks_request->has_finished = 1;
02974     return;
02975   }
02976   if (conn->socks_request->socks_version == 4) {
02977     memset(buf,0,SOCKS4_NETWORK_LEN);
02978     buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
02979     /* leave version, destport, destip zero */
02980     connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
02981   } else if (conn->socks_request->socks_version == 5) {
02982     buf[0] = 5; /* version 5 */
02983     buf[1] = (char)status;
02984     buf[2] = 0;
02985     buf[3] = 1; /* ipv4 addr */
02986     memset(buf+4,0,6); /* Set external addr/port to 0.
02987                           The spec doesn't seem to say what to do here. -RD */
02988     connection_write_to_buf(buf,10,ENTRY_TO_CONN(conn));
02989   }
02990   /* If socks_version isn't 4 or 5, don't send anything.
02991    * This can happen in the case of AP bridges. */
02992   conn->socks_request->has_finished = 1;
02993   return;
02994 }
02995 
03014 int
03015 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
03016 {
03017   edge_connection_t *n_stream;
03018   relay_header_t rh;
03019   char *address=NULL;
03020   uint16_t port;
03021   or_circuit_t *or_circ = NULL;
03022   const or_options_t *options = get_options();
03023 
03024   assert_circuit_ok(circ);
03025   if (!CIRCUIT_IS_ORIGIN(circ))
03026     or_circ = TO_OR_CIRCUIT(circ);
03027 
03028   relay_header_unpack(&rh, cell->payload);
03029   if (rh.length > RELAY_PAYLOAD_SIZE)
03030     return -1;
03031 
03032   /* Note: we have to use relay_send_command_from_edge here, not
03033    * connection_edge_end or connection_edge_send_command, since those require
03034    * that we have a stream connected to a circuit, and we don't connect to a
03035    * circuit until we have a pending/successful resolve. */
03036 
03037   if (!server_mode(options) &&
03038       circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
03039     log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
03040            "Relay begin cell at non-server. Closing.");
03041     relay_send_end_cell_from_edge(rh.stream_id, circ,
03042                                   END_STREAM_REASON_EXITPOLICY, NULL);
03043     return 0;
03044   }
03045 
03046   if (rh.command == RELAY_COMMAND_BEGIN) {
03047     if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
03048       log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
03049              "Relay begin cell has no \\0. Closing.");
03050       relay_send_end_cell_from_edge(rh.stream_id, circ,
03051                                     END_STREAM_REASON_TORPROTOCOL, NULL);
03052       return 0;
03053     }
03054     if (tor_addr_port_split(LOG_PROTOCOL_WARN,
03055                             (char*)(cell->payload+RELAY_HEADER_SIZE),
03056                             &address,&port)<0) {
03057       log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
03058              "Unable to parse addr:port in relay begin cell. Closing.");
03059       relay_send_end_cell_from_edge(rh.stream_id, circ,
03060                                     END_STREAM_REASON_TORPROTOCOL, NULL);
03061       return 0;
03062     }
03063     if (port==0) {
03064       log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
03065              "Missing port in relay begin cell. Closing.");
03066       relay_send_end_cell_from_edge(rh.stream_id, circ,
03067                                     END_STREAM_REASON_TORPROTOCOL, NULL);
03068       tor_free(address);
03069       return 0;
03070     }
03071     if (or_circ && or_circ->p_conn && !options->AllowSingleHopExits &&
03072         (or_circ->is_first_hop ||
03073          (!connection_or_digest_is_known_relay(
03074                                        or_circ->p_conn->identity_digest) &&
03075           should_refuse_unknown_exits(options)))) {
03076       /* Don't let clients use us as a single-hop proxy, unless the user
03077        * has explicitly allowed that in the config. It attracts attackers
03078        * and users who'd be better off with, well, single-hop proxies.
03079        */
03080       log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
03081              "Attempt by %s to open a stream %s. Closing.",
03082              safe_str(or_circ->p_conn->_base.address),
03083              or_circ->is_first_hop ? "on first hop of circuit" :
03084                                      "from unknown relay");
03085       relay_send_end_cell_from_edge(rh.stream_id, circ,
03086                                     or_circ->is_first_hop ?
03087                                       END_STREAM_REASON_TORPROTOCOL :
03088                                       END_STREAM_REASON_MISC,
03089                                     NULL);
03090       tor_free(address);
03091       return 0;
03092     }
03093   } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
03094     if (!directory_permits_begindir_requests(options) ||
03095         circ->purpose != CIRCUIT_PURPOSE_OR) {
03096       relay_send_end_cell_from_edge(rh.stream_id, circ,
03097                                     END_STREAM_REASON_NOTDIRECTORY, NULL);
03098       return 0;
03099     }
03100     /* Make sure to get the 'real' address of the previous hop: the
03101      * caller might want to know whether his IP address has changed, and
03102      * we might already have corrected _base.addr[ess] for the relay's
03103      * canonical IP address. */
03104     if (or_circ && or_circ->p_conn)
03105       address = tor_dup_addr(&or_circ->p_conn->real_addr);
03106     else
03107       address = tor_strdup("127.0.0.1");
03108     port = 1; /* XXXX This value is never actually used anywhere, and there
03109                * isn't "really" a connection here.  But we
03110                * need to set it to something nonzero. */
03111   } else {
03112     log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
03113     relay_send_end_cell_from_edge(rh.stream_id, circ,
03114                                   END_STREAM_REASON_INTERNAL, NULL);
03115     return 0;
03116   }
03117 
03118   log_debug(LD_EXIT,"Creating new exit connection.");
03119   n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
03120 
03121   /* Remember the tunneled request ID in the new edge connection, so that
03122    * we can measure download times. */
03123   TO_CONN(n_stream)->dirreq_id = circ->dirreq_id;
03124 
03125   n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
03126 
03127   n_stream->stream_id = rh.stream_id;
03128   n_stream->_base.port = port;
03129   /* leave n_stream->s at -1, because it's not yet valid */
03130   n_stream->package_window = STREAMWINDOW_START;
03131   n_stream->deliver_window = STREAMWINDOW_START;
03132 
03133   if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
03134     origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
03135     log_info(LD_REND,"begin is for rendezvous. configuring stream.");
03136     n_stream->_base.address = tor_strdup("(rendezvous)");
03137     n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
03138     n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
03139     tor_assert(connection_edge_is_rendezvous_stream(n_stream));
03140     assert_circuit_ok(circ);
03141     if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
03142       log_info(LD_REND,"Didn't find rendezvous service (port %d)",
03143                n_stream->_base.port);
03144       relay_send_end_cell_from_edge(rh.stream_id, circ,
03145                                     END_STREAM_REASON_EXITPOLICY,
03146                                     origin_circ->cpath->prev);
03147       connection_free(TO_CONN(n_stream));
03148       tor_free(address);
03149       return 0;
03150     }
03151     assert_circuit_ok(circ);
03152     log_debug(LD_REND,"Finished assigning addr/port");
03153     n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
03154 
03155     /* add it into the linked list of p_streams on this circuit */
03156     n_stream->next_stream = origin_circ->p_streams;
03157     n_stream->on_circuit = circ;
03158     origin_circ->p_streams = n_stream;
03159     assert_circuit_ok(circ);
03160 
03161     connection_exit_connect(n_stream);
03162     tor_free(address);
03163     return 0;
03164   }
03165   tor_strlower(address);
03166   n_stream->_base.address = address;
03167   n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
03168   /* default to failed, change in dns_resolve if it turns out not to fail */
03169 
03170   if (we_are_hibernating()) {
03171     relay_send_end_cell_from_edge(rh.stream_id, circ,
03172                                   END_STREAM_REASON_HIBERNATING, NULL);
03173     connection_free(TO_CONN(n_stream));
03174     return 0;
03175   }
03176 
03177   n_stream->on_circuit = circ;
03178 
03179   if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
03180     tor_assert(or_circ);
03181     if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
03182       tor_addr_copy(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
03183     return connection_exit_connect_dir(n_stream);
03184   }
03185 
03186   log_debug(LD_EXIT,"about to start the dns_resolve().");
03187 
03188   /* send it off to the gethostbyname farm */
03189   switch (dns_resolve(n_stream)) {
03190     case 1: /* resolve worked; now n_stream is attached to circ. */
03191       assert_circuit_ok(circ);
03192       log_debug(LD_EXIT,"about to call connection_exit_connect().");
03193       connection_exit_connect(n_stream);
03194       return 0;
03195     case -1: /* resolve failed */
03196       relay_send_end_cell_from_edge(rh.stream_id, circ,
03197                                     END_STREAM_REASON_RESOLVEFAILED, NULL);
03198       /* n_stream got freed. don't touch it. */
03199       break;
03200     case 0: /* resolve added to pending list */
03201       assert_circuit_ok(circ);
03202       break;
03203   }
03204   return 0;
03205 }
03206 
03212 int
03213 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
03214 {
03215   edge_connection_t *dummy_conn;
03216   relay_header_t rh;
03217 
03218   assert_circuit_ok(TO_CIRCUIT(circ));
03219   relay_header_unpack(&rh, cell->payload);
03220   if (rh.length > RELAY_PAYLOAD_SIZE)
03221     return -1;
03222 
03223   /* This 'dummy_conn' only exists to remember the stream ID
03224    * associated with the resolve request; and to make the
03225    * implementation of dns.c more uniform.  (We really only need to
03226    * remember the circuit, the stream ID, and the hostname to be
03227    * resolved; but if we didn't store them in a connection like this,
03228    * the housekeeping in dns.c would get way more complicated.)
03229    */
03230   dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
03231   dummy_conn->stream_id = rh.stream_id;
03232   dummy_conn->_base.address = tor_strndup(
03233                                        (char*)cell->payload+RELAY_HEADER_SIZE,
03234                                        rh.length);
03235   dummy_conn->_base.port = 0;
03236   dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
03237   dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
03238 
03239   dummy_conn->on_circuit = TO_CIRCUIT(circ);
03240 
03241   /* send it off to the gethostbyname farm */
03242   switch (dns_resolve(dummy_conn)) {
03243     case -1: /* Impossible to resolve; a resolved cell was sent. */
03244       /* Connection freed; don't touch it. */
03245       return 0;
03246     case 1: /* The result was cached; a resolved cell was sent. */
03247       if (!dummy_conn->_base.marked_for_close)
03248         connection_free(TO_CONN(dummy_conn));
03249       return 0;
03250     case 0: /* resolve added to pending list */
03251       assert_circuit_ok(TO_CIRCUIT(circ));
03252       break;
03253   }
03254   return 0;
03255 }
03256 
03264 void
03265 connection_exit_connect(edge_connection_t *edge_conn)
03266 {
03267   const tor_addr_t *addr;
03268   uint16_t port;
03269   connection_t *conn = TO_CONN(edge_conn);
03270   int socket_error = 0;
03271 
03272   if (!connection_edge_is_rendezvous_stream(edge_conn) &&
03273       router_compare_to_my_exit_policy(edge_conn)) {
03274     log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
03275              escaped_safe_str_client(conn->address), conn->port);
03276     connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
03277     circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
03278     connection_free(conn);
03279     return;
03280   }
03281 
03282   addr = &conn->addr;
03283   port = conn->port;
03284 
03285   log_debug(LD_EXIT,"about to try connecting");
03286   switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
03287     case -1: {
03288       int reason = errno_to_stream_end_reason(socket_error);
03289       connection_edge_end(edge_conn, reason);
03290       circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
03291       connection_free(conn);
03292       return;
03293     }
03294     case 0:
03295       conn->state = EXIT_CONN_STATE_CONNECTING;
03296 
03297       connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
03298       /* writable indicates finish;
03299        * readable/error indicates broken link in windows-land. */
03300       return;
03301     /* case 1: fall through */
03302   }
03303 
03304   conn->state = EXIT_CONN_STATE_OPEN;
03305   if (connection_get_outbuf_len(conn)) {
03306     /* in case there are any queued data cells */
03307     log_warn(LD_BUG,"newly connected conn had data waiting!");
03308 //    connection_start_writing(conn);
03309   }
03310   IF_HAS_NO_BUFFEREVENT(conn)
03311     connection_watch_events(conn, READ_EVENT);
03312 
03313   /* also, deliver a 'connected' cell back through the circuit. */
03314   if (connection_edge_is_rendezvous_stream(edge_conn)) {
03315     /* rendezvous stream */
03316     /* don't send an address back! */
03317     connection_edge_send_command(edge_conn,
03318                                  RELAY_COMMAND_CONNECTED,
03319                                  NULL, 0);
03320   } else { /* normal stream */
03321     char connected_payload[20];
03322     int connected_payload_len;
03323     if (tor_addr_family(&conn->addr) == AF_INET) {
03324       set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
03325       connected_payload_len = 4;
03326     } else {
03327       memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
03328       connected_payload_len = 16;
03329     }
03330     set_uint32(connected_payload+connected_payload_len,
03331                htonl(dns_clip_ttl(edge_conn->address_ttl)));
03332     connected_payload_len += 4;
03333     connection_edge_send_command(edge_conn,
03334                                  RELAY_COMMAND_CONNECTED,
03335                                  connected_payload, connected_payload_len);
03336   }
03337 }
03338 
03346 static int
03347 connection_exit_connect_dir(edge_connection_t *exitconn)
03348 {
03349   dir_connection_t *dirconn = NULL;
03350   or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
03351 
03352   log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
03353 
03354   exitconn->_base.state = EXIT_CONN_STATE_OPEN;
03355 
03356   dirconn = dir_connection_new(tor_addr_family(&exitconn->_base.addr));
03357 
03358   tor_addr_copy(&dirconn->_base.addr, &exitconn->_base.addr);
03359   dirconn->_base.port = 0;
03360   dirconn->_base.address = tor_strdup(exitconn->_base.address);
03361   dirconn->_base.type = CONN_TYPE_DIR;
03362   dirconn->_base.purpose = DIR_PURPOSE_SERVER;
03363   dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
03364 
03365   /* Note that the new dir conn belongs to the same tunneled request as
03366    * the edge conn, so that we can measure download times. */
03367   TO_CONN(dirconn)->dirreq_id = TO_CONN(exitconn)->dirreq_id;
03368 
03369   connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
03370 
03371   if (connection_add(TO_CONN(exitconn))<0) {
03372     connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
03373     connection_free(TO_CONN(exitconn));
03374     connection_free(TO_CONN(dirconn));
03375     return 0;
03376   }
03377 
03378   /* link exitconn to circ, now that we know we can use it. */
03379   exitconn->next_stream = circ->n_streams;
03380   circ->n_streams = exitconn;
03381 
03382   if (connection_add(TO_CONN(dirconn))<0) {
03383     connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
03384     connection_close_immediate(TO_CONN(exitconn));
03385     connection_mark_for_close(TO_CONN(exitconn));
03386     connection_free(TO_CONN(dirconn));
03387     return 0;
03388   }
03389 
03390   connection_start_reading(TO_CONN(dirconn));
03391   connection_start_reading(TO_CONN(exitconn));
03392 
03393   if (connection_edge_send_command(exitconn,
03394                                    RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
03395     connection_mark_for_close(TO_CONN(exitconn));
03396     connection_mark_for_close(TO_CONN(dirconn));
03397     return 0;
03398   }
03399 
03400   return 0;
03401 }
03402 
03406 int
03407 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
03408 {
03409   tor_assert(conn);
03410   if (conn->rend_data)
03411     return 1;
03412   return 0;
03413 }
03414 
03420 int
03421 connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit)
03422 {
03423   const or_options_t *options = get_options();
03424 
03425   tor_assert(conn);
03426   tor_assert(conn->socks_request);
03427   tor_assert(exit);
03428 
03429   /* If a particular exit node has been requested for the new connection,
03430    * make sure the exit node of the existing circuit matches exactly.
03431    */
03432   if (conn->chosen_exit_name) {
03433     const node_t *chosen_exit =
03434       node_get_by_nickname(conn->chosen_exit_name, 1);
03435     if (!chosen_exit || tor_memneq(chosen_exit->identity,
03436                                exit->identity, DIGEST_LEN)) {
03437       /* doesn't match */
03438 //      log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
03439 //                conn->chosen_exit_name, exit->nickname);
03440       return 0;
03441     }
03442   }
03443 
03444   if (conn->use_begindir) {
03445     /* Internal directory fetches do not count as exiting. */
03446     return 1;
03447   }
03448 
03449   if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
03450     struct in_addr in;
03451     tor_addr_t addr, *addrp = NULL;
03452     addr_policy_result_t r;
03453     if (tor_inet_aton(conn->socks_request->address, &in)) {
03454       tor_addr_from_in(&addr, &in);
03455       addrp = &addr;
03456     }
03457     r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,exit);
03458     if (r == ADDR_POLICY_REJECTED)
03459       return 0; /* We know the address, and the exit policy rejects it. */
03460     if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
03461       return 0; /* We don't know the addr, but the exit policy rejects most
03462                  * addresses with this port. Since the user didn't ask for
03463                  * this node, err on the side of caution. */
03464   } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
03465     /* Don't send DNS requests to non-exit servers by default. */
03466     if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
03467       return 0;
03468   }
03469   if (routerset_contains_node(options->_ExcludeExitNodesUnion, exit)) {
03470     /* Not a suitable exit. Refuse it. */
03471     return 0;
03472   }
03473 
03474   return 1;
03475 }
03476 
03489 hostname_type_t
03490 parse_extended_hostname(char *address)
03491 {
03492     char *s;
03493     char query[REND_SERVICE_ID_LEN_BASE32+1];
03494 
03495     s = strrchr(address,'.');
03496     if (!s)
03497       return NORMAL_HOSTNAME; /* no dot, thus normal */
03498     if (!strcmp(s+1,"exit")) {
03499       *s = 0; /* NUL-terminate it */
03500       return EXIT_HOSTNAME; /* .exit */
03501     }
03502     if (strcmp(s+1,"onion"))
03503       return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
03504 
03505     /* so it is .onion */
03506     *s = 0; /* NUL-terminate it */
03507     if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
03508         REND_SERVICE_ID_LEN_BASE32+1)
03509       goto failed;
03510     if (rend_valid_service_id(query)) {
03511       return ONION_HOSTNAME; /* success */
03512     }
03513  failed:
03514     /* otherwise, return to previous state and return 0 */
03515     *s = '.';
03516     log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
03517              safe_str_client(address));
03518     return BAD_HOSTNAME;
03519 }
03520 
03524 static int
03525 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
03526 {
03527   if (a == NULL) {
03528     return (b == NULL);
03529   } else if (b == NULL) {
03530     return 0;
03531   } else if (alen != blen) {
03532     return 0;
03533   } else {
03534     return tor_memeq(a, b, alen);
03535   }
03536 }
03537 
03542 int
03543 connection_edge_compatible_with_circuit(const entry_connection_t *conn,
03544                                         const origin_circuit_t *circ)
03545 {
03546   const uint8_t iso = conn->isolation_flags;
03547   const socks_request_t *sr = conn->socks_request;
03548 
03549   /* If circ has never been used for an isolated connection, we can
03550    * totally use it for this one. */
03551   if (!circ->isolation_values_set)
03552     return 1;
03553 
03554   /* If circ has been used for connections having more than one value
03555    * for some field f, it will have the corresponding bit set in
03556    * isolation_flags_mixed.  If isolation_flags_mixed has any bits
03557    * in common with iso, then conn must be isolated from at least
03558    * one stream that has been attached to circ. */
03559   if ((iso & circ->isolation_flags_mixed) != 0) {
03560     /* For at least one field where conn is isolated, the circuit
03561      * already has mixed streams. */
03562     return 0;
03563   }
03564 
03565   if (! conn->original_dest_address) {
03566     log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
03567              "having set conn->original_dest_address");
03568     ((entry_connection_t*)conn)->original_dest_address =
03569       tor_strdup(conn->socks_request->address);
03570   }
03571 
03572   if ((iso & ISO_STREAM) &&
03573       (circ->associated_isolated_stream_global_id !=
03574        ENTRY_TO_CONN(conn)->global_identifier))
03575     return 0;
03576 
03577   if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
03578     return 0;
03579   if ((iso & ISO_DESTADDR) &&
03580       strcasecmp(conn->original_dest_address, circ->dest_address))
03581     return 0;
03582   if ((iso & ISO_SOCKSAUTH) &&
03583       (! memeq_opt(sr->username, sr->usernamelen,
03584                    circ->socks_username, circ->socks_username_len) ||
03585        ! memeq_opt(sr->password, sr->passwordlen,
03586                    circ->socks_password, circ->socks_password_len)))
03587     return 0;
03588   if ((iso & ISO_CLIENTPROTO) &&
03589       (conn->socks_request->listener_type != circ->client_proto_type ||
03590        conn->socks_request->socks_version != circ->client_proto_socksver))
03591     return 0;
03592   if ((iso & ISO_CLIENTADDR) &&
03593       !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
03594     return 0;
03595   if ((iso & ISO_SESSIONGRP) && conn->session_group != circ->session_group)
03596     return 0;
03597   if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
03598     return 0;
03599 
03600   return 1;
03601 }
03602 
03611 int
03612 connection_edge_update_circuit_isolation(const entry_connection_t *conn,
03613                                          origin_circuit_t *circ,
03614                                          int dry_run)
03615 {
03616   const socks_request_t *sr = conn->socks_request;
03617   if (! conn->original_dest_address) {
03618     log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
03619              "having set conn->original_dest_address");
03620     ((entry_connection_t*)conn)->original_dest_address =
03621       tor_strdup(conn->socks_request->address);
03622   }
03623 
03624   if (!circ->isolation_values_set) {
03625     if (dry_run)
03626       return -1;
03627     circ->associated_isolated_stream_global_id =
03628       ENTRY_TO_CONN(conn)->global_identifier;
03629     circ->dest_port = conn->socks_request->port;
03630     circ->dest_address = tor_strdup(conn->original_dest_address);
03631     circ->client_proto_type = conn->socks_request->listener_type;
03632     circ->client_proto_socksver = conn->socks_request->socks_version;
03633     tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
03634     circ->session_group = conn->session_group;
03635     circ->nym_epoch = conn->nym_epoch;
03636     circ->socks_username = sr->username ?
03637       tor_memdup(sr->username, sr->usernamelen) : NULL;
03638     circ->socks_password = sr->password ?
03639       tor_memdup(sr->password, sr->passwordlen) : NULL;
03640     circ->socks_username_len = sr->usernamelen;
03641     circ->socks_password_len = sr->passwordlen;
03642 
03643     circ->isolation_values_set = 1;
03644     return 0;
03645   } else {
03646     uint8_t mixed = 0;
03647     if (conn->socks_request->port != circ->dest_port)
03648       mixed |= ISO_DESTPORT;
03649     if (strcasecmp(conn->original_dest_address, circ->dest_address))
03650       mixed |= ISO_DESTADDR;
03651     if (!memeq_opt(sr->username, sr->usernamelen,
03652                    circ->socks_username, circ->socks_username_len) ||
03653         !memeq_opt(sr->password, sr->passwordlen,
03654                    circ->socks_password, circ->socks_password_len))
03655       mixed |= ISO_SOCKSAUTH;
03656     if ((conn->socks_request->listener_type != circ->client_proto_type ||
03657          conn->socks_request->socks_version != circ->client_proto_socksver))
03658       mixed |= ISO_CLIENTPROTO;
03659     if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
03660       mixed |= ISO_CLIENTADDR;
03661     if (conn->session_group != circ->session_group)
03662       mixed |= ISO_SESSIONGRP;
03663     if (conn->nym_epoch != circ->nym_epoch)
03664       mixed |= ISO_NYM_EPOCH;
03665 
03666     if (dry_run)
03667       return mixed;
03668 
03669     if ((mixed & conn->isolation_flags) != 0) {
03670       log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
03671                "isolation flags.");
03672     }
03673     circ->isolation_flags_mixed |= mixed;
03674     return 0;
03675   }
03676 }
03677 
03689 void
03690 circuit_clear_isolation(origin_circuit_t *circ)
03691 {
03692   if (circ->isolation_any_streams_attached) {
03693     log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
03694     return;
03695   }
03696   if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
03697     log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
03698              "circuit");
03699     return;
03700   }
03701 
03702   circ->isolation_values_set = 0;
03703   circ->isolation_flags_mixed = 0;
03704   circ->associated_isolated_stream_global_id = 0;
03705   circ->client_proto_type = 0;
03706   circ->client_proto_socksver = 0;
03707   circ->dest_port = 0;
03708   tor_addr_make_unspec(&circ->client_addr);
03709   tor_free(circ->dest_address);
03710   circ->session_group = -1;
03711   circ->nym_epoch = 0;
03712   if (circ->socks_username) {
03713     memset(circ->socks_username, 0x11, circ->socks_username_len);
03714     tor_free(circ->socks_username);
03715   }
03716   if (circ->socks_password) {
03717     memset(circ->socks_password, 0x05, circ->socks_password_len);
03718     tor_free(circ->socks_password);
03719   }
03720   circ->socks_username_len = circ->socks_password_len = 0;
03721 }
03722