Back to index

tor  0.2.3.18-rc
connection_or.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 
00013 #include "or.h"
00014 #include "buffers.h"
00015 #include "circuitbuild.h"
00016 #include "circuitlist.h"
00017 #include "command.h"
00018 #include "config.h"
00019 #include "connection.h"
00020 #include "connection_or.h"
00021 #include "control.h"
00022 #include "dirserv.h"
00023 #include "geoip.h"
00024 #include "main.h"
00025 #include "networkstatus.h"
00026 #include "nodelist.h"
00027 #include "reasons.h"
00028 #include "relay.h"
00029 #include "rephist.h"
00030 #include "router.h"
00031 #include "routerlist.h"
00032 
00033 #ifdef USE_BUFFEREVENTS
00034 #include <event2/bufferevent_ssl.h>
00035 #endif
00036 
00037 static int connection_tls_finish_handshake(or_connection_t *conn);
00038 static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
00039 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
00040 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
00041                                                    int started_here,
00042                                                    char *digest_rcvd_out);
00043 
00044 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
00045 
00046 #ifdef USE_BUFFEREVENTS
00047 static void connection_or_handle_event_cb(struct bufferevent *bufev,
00048                                           short event, void *arg);
00049 #include <event2/buffer.h>/*XXXX REMOVE */
00050 #endif
00051 
00052 /**************************************************************/
00053 
00057 static digestmap_t *orconn_identity_map = NULL;
00058 
00061 void
00062 connection_or_remove_from_identity_map(or_connection_t *conn)
00063 {
00064   or_connection_t *tmp;
00065   tor_assert(conn);
00066   if (!orconn_identity_map)
00067     return;
00068   tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
00069   if (!tmp) {
00070     if (!tor_digest_is_zero(conn->identity_digest)) {
00071       log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
00072                "trying to remove it.",
00073                conn->nickname ? conn->nickname : "NULL");
00074     }
00075     return;
00076   }
00077   if (conn == tmp) {
00078     if (conn->next_with_same_id)
00079       digestmap_set(orconn_identity_map, conn->identity_digest,
00080                     conn->next_with_same_id);
00081     else
00082       digestmap_remove(orconn_identity_map, conn->identity_digest);
00083   } else {
00084     while (tmp->next_with_same_id) {
00085       if (tmp->next_with_same_id == conn) {
00086         tmp->next_with_same_id = conn->next_with_same_id;
00087         break;
00088       }
00089       tmp = tmp->next_with_same_id;
00090     }
00091   }
00092   memset(conn->identity_digest, 0, DIGEST_LEN);
00093   conn->next_with_same_id = NULL;
00094 }
00095 
00098 void
00099 connection_or_clear_identity_map(void)
00100 {
00101   smartlist_t *conns = get_connection_array();
00102   SMARTLIST_FOREACH(conns, connection_t *, conn,
00103   {
00104     if (conn->type == CONN_TYPE_OR) {
00105       or_connection_t *or_conn = TO_OR_CONN(conn);
00106       memset(or_conn->identity_digest, 0, DIGEST_LEN);
00107       or_conn->next_with_same_id = NULL;
00108     }
00109   });
00110 
00111   digestmap_free(orconn_identity_map, NULL);
00112   orconn_identity_map = NULL;
00113 }
00114 
00117 static void
00118 connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
00119 {
00120   or_connection_t *tmp;
00121   tor_assert(conn);
00122   tor_assert(digest);
00123 
00124   if (!orconn_identity_map)
00125     orconn_identity_map = digestmap_new();
00126   if (tor_memeq(conn->identity_digest, digest, DIGEST_LEN))
00127     return;
00128 
00129   /* If the identity was set previously, remove the old mapping. */
00130   if (! tor_digest_is_zero(conn->identity_digest))
00131     connection_or_remove_from_identity_map(conn);
00132 
00133   memcpy(conn->identity_digest, digest, DIGEST_LEN);
00134 
00135   /* If we're setting the ID to zero, don't add a mapping. */
00136   if (tor_digest_is_zero(digest))
00137     return;
00138 
00139   tmp = digestmap_set(orconn_identity_map, digest, conn);
00140   conn->next_with_same_id = tmp;
00141 
00142 #if 1
00143   /* Testing code to check for bugs in representation. */
00144   for (; tmp; tmp = tmp->next_with_same_id) {
00145     tor_assert(tor_memeq(tmp->identity_digest, digest, DIGEST_LEN));
00146     tor_assert(tmp != conn);
00147   }
00148 #endif
00149 }
00150 
00151 /**************************************************************/
00152 
00157 static strmap_t *broken_connection_counts;
00158 
00160 static int disable_broken_connection_counts = 0;
00161 
00163 static void
00164 note_broken_connection(const char *state)
00165 {
00166   void *ptr;
00167   intptr_t val;
00168   if (disable_broken_connection_counts)
00169     return;
00170 
00171   if (!broken_connection_counts)
00172     broken_connection_counts = strmap_new();
00173 
00174   ptr = strmap_get(broken_connection_counts, state);
00175   val = (intptr_t)ptr;
00176   val++;
00177   ptr = (void*)val;
00178   strmap_set(broken_connection_counts, state, ptr);
00179 }
00180 
00183 void
00184 clear_broken_connection_map(int stop_recording)
00185 {
00186   if (broken_connection_counts)
00187     strmap_free(broken_connection_counts, NULL);
00188   broken_connection_counts = NULL;
00189   if (stop_recording)
00190     disable_broken_connection_counts = 1;
00191 }
00192 
00197 static void
00198 connection_or_get_state_description(or_connection_t *orconn,
00199                                     char *buf, size_t buflen)
00200 {
00201   connection_t *conn = TO_CONN(orconn);
00202   const char *conn_state;
00203   char tls_state[256];
00204 
00205   tor_assert(conn->type == CONN_TYPE_OR);
00206 
00207   conn_state = conn_state_to_string(conn->type, conn->state);
00208   tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
00209 
00210   tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
00211 }
00212 
00215 static void
00216 connection_or_note_state_when_broken(or_connection_t *orconn)
00217 {
00218   char buf[256];
00219   if (disable_broken_connection_counts)
00220     return;
00221   connection_or_get_state_description(orconn, buf, sizeof(buf));
00222   log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
00223   note_broken_connection(buf);
00224 }
00225 
00227 typedef struct broken_state_count_t {
00228   intptr_t count;
00229   const char *state;
00230 } broken_state_count_t;
00231 
00233 static int
00234 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
00235 {
00236   const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
00237   if (b->count < a->count)
00238     return -1;
00239   else if (b->count == a->count)
00240     return 0;
00241   else
00242     return 1;
00243 }
00244 
00247 #define MAX_REASONS_TO_REPORT 10
00248 
00251 void
00252 connection_or_report_broken_states(int severity, int domain)
00253 {
00254   int total = 0;
00255   smartlist_t *items;
00256 
00257   if (!broken_connection_counts || disable_broken_connection_counts)
00258     return;
00259 
00260   items = smartlist_new();
00261   STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
00262     broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
00263     c->count = (intptr_t)countptr;
00264     total += (int)c->count;
00265     c->state = state;
00266     smartlist_add(items, c);
00267   } STRMAP_FOREACH_END;
00268 
00269   smartlist_sort(items, broken_state_count_compare);
00270 
00271   log(severity, domain, "%d connections have failed%s", total,
00272       smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
00273 
00274   SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
00275     if (c_sl_idx > MAX_REASONS_TO_REPORT)
00276       break;
00277     log(severity, domain,
00278         " %d connections died in state %s", (int)c->count, c->state);
00279   } SMARTLIST_FOREACH_END(c);
00280 
00281   SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
00282   smartlist_free(items);
00283 }
00284 
00285 /**************************************************************/
00286 
00294 void
00295 cell_pack(packed_cell_t *dst, const cell_t *src)
00296 {
00297   char *dest = dst->body;
00298   set_uint16(dest, htons(src->circ_id));
00299   *(uint8_t*)(dest+2) = src->command;
00300   memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
00301 }
00302 
00306 static void
00307 cell_unpack(cell_t *dest, const char *src)
00308 {
00309   dest->circ_id = ntohs(get_uint16(src));
00310   dest->command = *(uint8_t*)(src+2);
00311   memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
00312 }
00313 
00316 void
00317 var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
00318 {
00319   set_uint16(hdr_out, htons(cell->circ_id));
00320   set_uint8(hdr_out+2, cell->command);
00321   set_uint16(hdr_out+3, htons(cell->payload_len));
00322 }
00323 
00326 var_cell_t *
00327 var_cell_new(uint16_t payload_len)
00328 {
00329   size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
00330   var_cell_t *cell = tor_malloc(size);
00331   cell->payload_len = payload_len;
00332   cell->command = 0;
00333   cell->circ_id = 0;
00334   return cell;
00335 }
00336 
00338 void
00339 var_cell_free(var_cell_t *cell)
00340 {
00341   tor_free(cell);
00342 }
00343 
00345 int
00346 connection_or_reached_eof(or_connection_t *conn)
00347 {
00348   log_info(LD_OR,"OR connection reached EOF. Closing.");
00349   connection_mark_for_close(TO_CONN(conn));
00350   return 0;
00351 }
00352 
00358 int
00359 connection_or_process_inbuf(or_connection_t *conn)
00360 {
00364 #define MAX_OR_INBUF_WHEN_NONOPEN 0
00365 
00366   int ret = 0;
00367   tor_assert(conn);
00368 
00369   switch (conn->_base.state) {
00370     case OR_CONN_STATE_PROXY_HANDSHAKING:
00371       ret = connection_read_proxy_handshake(TO_CONN(conn));
00372 
00373       /* start TLS after handshake completion, or deal with error */
00374       if (ret == 1) {
00375         tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
00376         if (connection_tls_start_handshake(conn, 0) < 0)
00377           ret = -1;
00378       }
00379       if (ret < 0) {
00380         connection_mark_for_close(TO_CONN(conn));
00381       }
00382 
00383       return ret;
00384     case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
00385 #ifdef USE_BUFFEREVENTS
00386       if (tor_tls_server_got_renegotiate(conn->tls))
00387         connection_or_tls_renegotiated_cb(conn->tls, conn);
00388       if (conn->_base.marked_for_close)
00389         return 0;
00390       /* fall through. */
00391 #endif
00392     case OR_CONN_STATE_OPEN:
00393     case OR_CONN_STATE_OR_HANDSHAKING_V2:
00394     case OR_CONN_STATE_OR_HANDSHAKING_V3:
00395       return connection_or_process_cells_from_inbuf(conn);
00396     default:
00397       break; /* don't do anything */
00398   }
00399 
00400   /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
00401    * check would otherwise just let data accumulate.  It serves no purpose
00402    * in 0.2.3.
00403    *
00404    * XXX024 Remove this check once we verify that the above paragraph is
00405    * 100% true. */
00406   if (buf_datalen(conn->_base.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
00407     log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
00408            "on nonopen OR connection %s %s:%u in state %s; closing.",
00409            (int)buf_datalen(conn->_base.inbuf),
00410            connection_or_nonopen_was_started_here(conn) ? "to" : "from",
00411            conn->_base.address, conn->_base.port,
00412            conn_state_to_string(conn->_base.type, conn->_base.state));
00413     connection_mark_for_close(TO_CONN(conn));
00414     ret = -1;
00415   }
00416 
00417   return ret;
00418 }
00419 
00422 #define OR_CONN_HIGHWATER (32*1024)
00423 
00426 #define OR_CONN_LOWWATER (16*1024)
00427 
00430 int
00431 connection_or_flushed_some(or_connection_t *conn)
00432 {
00433   size_t datalen = connection_get_outbuf_len(TO_CONN(conn));
00434   /* If we're under the low water mark, add cells until we're just over the
00435    * high water mark. */
00436   if (datalen < OR_CONN_LOWWATER) {
00437     ssize_t n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, CELL_NETWORK_SIZE);
00438     time_t now = approx_time();
00439     while (conn->active_circuits && n > 0) {
00440       int flushed;
00441       flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
00442       n -= flushed;
00443     }
00444   }
00445   return 0;
00446 }
00447 
00456 int
00457 connection_or_finished_flushing(or_connection_t *conn)
00458 {
00459   tor_assert(conn);
00460   assert_connection_ok(TO_CONN(conn),0);
00461 
00462   switch (conn->_base.state) {
00463     case OR_CONN_STATE_PROXY_HANDSHAKING:
00464     case OR_CONN_STATE_OPEN:
00465     case OR_CONN_STATE_OR_HANDSHAKING_V2:
00466     case OR_CONN_STATE_OR_HANDSHAKING_V3:
00467       break;
00468     default:
00469       log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
00470       tor_fragile_assert();
00471       return -1;
00472   }
00473   return 0;
00474 }
00475 
00478 int
00479 connection_or_finished_connecting(or_connection_t *or_conn)
00480 {
00481   const int proxy_type = or_conn->proxy_type;
00482   connection_t *conn;
00483   tor_assert(or_conn);
00484   conn = TO_CONN(or_conn);
00485   tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
00486 
00487   log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
00488             conn->address,conn->port);
00489   control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
00490 
00491   if (proxy_type != PROXY_NONE) {
00492     /* start proxy handshake */
00493     if (connection_proxy_connect(conn, proxy_type) < 0) {
00494       connection_mark_for_close(conn);
00495       return -1;
00496     }
00497 
00498     connection_start_reading(conn);
00499     conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
00500     return 0;
00501   }
00502 
00503   if (connection_tls_start_handshake(or_conn, 0) < 0) {
00504     /* TLS handshaking error of some kind. */
00505     connection_mark_for_close(conn);
00506     return -1;
00507   }
00508   return 0;
00509 }
00510 
00513 void
00514 connection_or_about_to_close(or_connection_t *or_conn)
00515 {
00516   time_t now = time(NULL);
00517   connection_t *conn = TO_CONN(or_conn);
00518 
00519   /* Remember why we're closing this connection. */
00520   if (conn->state != OR_CONN_STATE_OPEN) {
00521     /* Inform any pending (not attached) circs that they should
00522      * give up. */
00523     circuit_n_conn_done(TO_OR_CONN(conn), 0);
00524     /* now mark things down as needed */
00525     if (connection_or_nonopen_was_started_here(or_conn)) {
00526       const or_options_t *options = get_options();
00527       connection_or_note_state_when_broken(or_conn);
00528       rep_hist_note_connect_failed(or_conn->identity_digest, now);
00529       entry_guard_register_connect_status(or_conn->identity_digest,0,
00530                                           !options->HTTPSProxy, now);
00531       if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
00532         int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
00533         control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
00534                                      reason);
00535         if (!authdir_mode_tests_reachability(options))
00536           control_event_bootstrap_problem(
00537                 orconn_end_reason_to_control_string(reason), reason);
00538       }
00539     }
00540   } else if (conn->hold_open_until_flushed) {
00541     /* We only set hold_open_until_flushed when we're intentionally
00542      * closing a connection. */
00543     rep_hist_note_disconnect(or_conn->identity_digest, now);
00544     control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
00545                 tls_error_to_orconn_end_reason(or_conn->tls_error));
00546   } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
00547     rep_hist_note_connection_died(or_conn->identity_digest, now);
00548     control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
00549                 tls_error_to_orconn_end_reason(or_conn->tls_error));
00550   }
00551   /* Now close all the attached circuits on it. */
00552   circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
00553                                   END_CIRC_REASON_OR_CONN_CLOSED);
00554 }
00555 
00558 int
00559 connection_or_digest_is_known_relay(const char *id_digest)
00560 {
00561   if (router_get_consensus_status_by_id(id_digest))
00562     return 1; /* It's in the consensus: "yes" */
00563   if (router_get_by_id_digest(id_digest))
00564     return 1; /* Not in the consensus, but we have a descriptor for
00565                * it. Probably it was in a recent consensus. "Yes". */
00566   return 0;
00567 }
00568 
00578 static void
00579 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
00580                                           const or_options_t *options)
00581 {
00582   int rate, burst; /* per-connection rate limiting params */
00583   if (connection_or_digest_is_known_relay(conn->identity_digest)) {
00584     /* It's in the consensus, or we have a descriptor for it meaning it
00585      * was probably in a recent consensus. It's a recognized relay:
00586      * give it full bandwidth. */
00587     rate = (int)options->BandwidthRate;
00588     burst = (int)options->BandwidthBurst;
00589   } else {
00590     /* Not a recognized relay. Squeeze it down based on the suggested
00591      * bandwidth parameters in the consensus, but allow local config
00592      * options to override. */
00593     rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
00594         networkstatus_get_param(NULL, "perconnbwrate",
00595                                 (int)options->BandwidthRate, 1, INT32_MAX);
00596     burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
00597         networkstatus_get_param(NULL, "perconnbwburst",
00598                                 (int)options->BandwidthBurst, 1, INT32_MAX);
00599   }
00600 
00601   conn->bandwidthrate = rate;
00602   conn->bandwidthburst = burst;
00603 #ifdef USE_BUFFEREVENTS
00604   {
00605     const struct timeval *tick = tor_libevent_get_one_tick_timeout();
00606     struct ev_token_bucket_cfg *cfg, *old_cfg;
00607     int64_t rate64 = (((int64_t)rate) * options->TokenBucketRefillInterval)
00608       / 1000;
00609     /* This can't overflow, since TokenBucketRefillInterval <= 1000,
00610      * and rate started out less than INT_MAX. */
00611     int rate_per_tick = (int) rate64;
00612 
00613     cfg = ev_token_bucket_cfg_new(rate_per_tick, burst, rate_per_tick,
00614                                   burst, tick);
00615     old_cfg = conn->bucket_cfg;
00616     if (conn->_base.bufev)
00617       tor_set_bufferevent_rate_limit(conn->_base.bufev, cfg);
00618     if (old_cfg)
00619       ev_token_bucket_cfg_free(old_cfg);
00620     conn->bucket_cfg = cfg;
00621     (void) reset; /* No way to do this with libevent yet. */
00622   }
00623 #else
00624   if (reset) { /* set up the token buckets to be full */
00625     conn->read_bucket = conn->write_bucket = burst;
00626     return;
00627   }
00628   /* If the new token bucket is smaller, take out the extra tokens.
00629    * (If it's larger, don't -- the buckets can grow to reach the cap.) */
00630   if (conn->read_bucket > burst)
00631     conn->read_bucket = burst;
00632   if (conn->write_bucket > burst)
00633     conn->write_bucket = burst;
00634 #endif
00635 }
00636 
00640 void
00641 connection_or_update_token_buckets(smartlist_t *conns,
00642                                    const or_options_t *options)
00643 {
00644   SMARTLIST_FOREACH(conns, connection_t *, conn,
00645   {
00646     if (connection_speaks_cells(conn))
00647       connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
00648   });
00649 }
00650 
00656 void
00657 connection_or_init_conn_from_address(or_connection_t *conn,
00658                                      const tor_addr_t *addr, uint16_t port,
00659                                      const char *id_digest,
00660                                      int started_here)
00661 {
00662   const node_t *r = node_get_by_id(id_digest);
00663   connection_or_set_identity_digest(conn, id_digest);
00664   connection_or_update_token_buckets_helper(conn, 1, get_options());
00665 
00666   conn->_base.port = port;
00667   tor_addr_copy(&conn->_base.addr, addr);
00668   tor_addr_copy(&conn->real_addr, addr);
00669   if (r) {
00670     tor_addr_port_t node_ap;
00671     node_get_pref_orport(r, &node_ap);
00672     /* XXXX proposal 186 is making this more complex.  For now, a conn
00673        is canonical when it uses the _preferred_ address. */
00674     if (tor_addr_eq(&conn->_base.addr, &node_ap.addr))
00675       conn->is_canonical = 1;
00676     if (!started_here) {
00677       /* Override the addr/port, so our log messages will make sense.
00678        * This is dangerous, since if we ever try looking up a conn by
00679        * its actual addr/port, we won't remember. Careful! */
00680       /* XXXX arma: this is stupid, and it's the reason we need real_addr
00681        * to track is_canonical properly.  What requires it? */
00682       /* XXXX <arma> i believe the reason we did this, originally, is because
00683        * we wanted to log what OR a connection was to, and if we logged the
00684        * right IP address and port 56244, that wouldn't be as helpful. now we
00685        * log the "right" port too, so we know if it's moria1 or moria2.
00686        */
00687       tor_addr_copy(&conn->_base.addr, &node_ap.addr);
00688       conn->_base.port = node_ap.port;
00689     }
00690     conn->nickname = tor_strdup(node_get_nickname(r));
00691     tor_free(conn->_base.address);
00692     conn->_base.address = tor_dup_addr(&node_ap.addr);
00693   } else {
00694     const char *n;
00695     /* If we're an authoritative directory server, we may know a
00696      * nickname for this router. */
00697     n = dirserv_get_nickname_by_digest(id_digest);
00698     if (n) {
00699       conn->nickname = tor_strdup(n);
00700     } else {
00701       conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
00702       conn->nickname[0] = '$';
00703       base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
00704                     conn->identity_digest, DIGEST_LEN);
00705     }
00706     tor_free(conn->_base.address);
00707     conn->_base.address = tor_dup_addr(addr);
00708   }
00709 }
00710 
00724 static int
00725 connection_or_is_better(time_t now,
00726                         const or_connection_t *a,
00727                         const or_connection_t *b,
00728                         int forgive_new_connections)
00729 {
00730   int newer;
00733 #define NEW_CONN_GRACE_PERIOD (15*60)
00734 
00735   if (b->is_canonical && !a->is_canonical)
00736     return 0; /* A canonical connection is better than a non-canonical
00737                * one, no matter how new it is or which has circuits. */
00738 
00739   newer = b->_base.timestamp_created < a->_base.timestamp_created;
00740 
00741   if (
00742       /* We prefer canonical connections regardless of newness. */
00743       (!b->is_canonical && a->is_canonical) ||
00744       /* If both have circuits we prefer the newer: */
00745       (b->n_circuits && a->n_circuits && newer) ||
00746       /* If neither has circuits we prefer the newer: */
00747       (!b->n_circuits && !a->n_circuits && newer))
00748     return 1;
00749 
00750   /* If one has no circuits and the other does... */
00751   if (!b->n_circuits && a->n_circuits) {
00752     /* Then it's bad, unless it's in its grace period and we're forgiving. */
00753     if (forgive_new_connections &&
00754         now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
00755       return 0;
00756     else
00757       return 1;
00758   }
00759 
00760   return 0;
00761 }
00762 
00770 or_connection_t *
00771 connection_or_get_for_extend(const char *digest,
00772                              const tor_addr_t *target_addr,
00773                              const char **msg_out,
00774                              int *launch_out)
00775 {
00776   or_connection_t *conn, *best=NULL;
00777   int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
00778   time_t now = approx_time();
00779 
00780   tor_assert(msg_out);
00781   tor_assert(launch_out);
00782 
00783   if (!orconn_identity_map) {
00784     *msg_out = "Router not connected (nothing is).  Connecting.";
00785     *launch_out = 1;
00786     return NULL;
00787   }
00788 
00789   conn = digestmap_get(orconn_identity_map, digest);
00790 
00791   for (; conn; conn = conn->next_with_same_id) {
00792     tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
00793     tor_assert(conn->_base.type == CONN_TYPE_OR);
00794     tor_assert(tor_memeq(conn->identity_digest, digest, DIGEST_LEN));
00795     if (conn->_base.marked_for_close)
00796       continue;
00797     /* Never return a connection on which the other end appears to be
00798      * a client. */
00799     if (conn->is_connection_with_client) {
00800       continue;
00801     }
00802     /* Never return a non-open connection. */
00803     if (conn->_base.state != OR_CONN_STATE_OPEN) {
00804       /* If the address matches, don't launch a new connection for this
00805        * circuit. */
00806       if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
00807         ++n_inprogress_goodaddr;
00808       continue;
00809     }
00810     /* Never return a connection that shouldn't be used for circs. */
00811     if (conn->is_bad_for_new_circs) {
00812       ++n_old;
00813       continue;
00814     }
00815     /* Never return a non-canonical connection using a recent link protocol
00816      * if the address is not what we wanted.
00817      *
00818      * (For old link protocols, we can't rely on is_canonical getting
00819      * set properly if we're talking to the right address, since we might
00820      * have an out-of-date descriptor, and we will get no NETINFO cell to
00821      * tell us about the right address.) */
00822     if (!conn->is_canonical && conn->link_proto >= 2 &&
00823         tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
00824       ++n_noncanonical;
00825       continue;
00826     }
00827 
00828     ++n_possible;
00829 
00830     if (!best) {
00831       best = conn; /* If we have no 'best' so far, this one is good enough. */
00832       continue;
00833     }
00834 
00835     if (connection_or_is_better(now, conn, best, 0))
00836       best = conn;
00837   }
00838 
00839   if (best) {
00840     *msg_out = "Connection is fine; using it.";
00841     *launch_out = 0;
00842     return best;
00843   } else if (n_inprogress_goodaddr) {
00844     *msg_out = "Connection in progress; waiting.";
00845     *launch_out = 0;
00846     return NULL;
00847   } else if (n_old || n_noncanonical) {
00848     *msg_out = "Connections all too old, or too non-canonical. "
00849       " Launching a new one.";
00850     *launch_out = 1;
00851     return NULL;
00852   } else {
00853     *msg_out = "Not connected. Connecting.";
00854     *launch_out = 1;
00855     return NULL;
00856   }
00857 }
00858 
00861 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
00862 
00880 static void
00881 connection_or_group_set_badness(or_connection_t *head, int force)
00882 {
00883   or_connection_t *or_conn = NULL, *best = NULL;
00884   int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
00885   time_t now = time(NULL);
00886 
00887   /* Pass 1: expire everything that's old, and see what the status of
00888    * everything else is. */
00889   for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
00890     if (or_conn->_base.marked_for_close ||
00891         or_conn->is_bad_for_new_circs)
00892       continue;
00893     if (force ||
00894         or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
00895           < now) {
00896       log_info(LD_OR,
00897                "Marking OR conn to %s:%d as too old for new circuits "
00898                "(fd %d, %d secs old).",
00899                or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
00900                (int)(now - or_conn->_base.timestamp_created));
00901       or_conn->is_bad_for_new_circs = 1;
00902     }
00903 
00904     if (or_conn->is_bad_for_new_circs) {
00905       ++n_old;
00906     } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
00907       ++n_inprogress;
00908     } else if (or_conn->is_canonical) {
00909       ++n_canonical;
00910     } else {
00911       ++n_other;
00912     }
00913   }
00914 
00915   /* Pass 2: We know how about how good the best connection is.
00916    * expire everything that's worse, and find the very best if we can. */
00917   for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
00918     if (or_conn->_base.marked_for_close ||
00919         or_conn->is_bad_for_new_circs)
00920       continue; /* This one doesn't need to be marked bad. */
00921     if (or_conn->_base.state != OR_CONN_STATE_OPEN)
00922       continue; /* Don't mark anything bad until we have seen what happens
00923                  * when the connection finishes. */
00924     if (n_canonical && !or_conn->is_canonical) {
00925       /* We have at least one open canonical connection to this router,
00926        * and this one is open but not canonical.  Mark it bad. */
00927       log_info(LD_OR,
00928                "Marking OR conn to %s:%d as unsuitable for new circuits: "
00929                "(fd %d, %d secs old).  It is not canonical, and we have "
00930                "another connection to that OR that is.",
00931                or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
00932                (int)(now - or_conn->_base.timestamp_created));
00933       or_conn->is_bad_for_new_circs = 1;
00934       continue;
00935     }
00936 
00937     if (!best || connection_or_is_better(now, or_conn, best, 0))
00938       best = or_conn;
00939   }
00940 
00941   if (!best)
00942     return;
00943 
00944   /* Pass 3: One connection to OR is best.  If it's canonical, mark as bad
00945    * every other open connection.  If it's non-canonical, mark as bad
00946    * every other open connection to the same address.
00947    *
00948    * XXXX This isn't optimal; if we have connections to an OR at multiple
00949    *   addresses, we'd like to pick the best _for each address_, and mark as
00950    *   bad every open connection that isn't best for its address.  But this
00951    *   can only occur in cases where the other OR is old (so we have no
00952    *   canonical connection to it), or where all the connections to the OR are
00953    *   at noncanonical addresses and we have no good direct connection (which
00954    *   means we aren't at risk of attaching circuits to it anyway).  As
00955    *   0.1.2.x dies out, the first case will go away, and the second one is
00956    *   "mostly harmless", so a fix can wait until somebody is bored.
00957    */
00958   for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
00959     if (or_conn->_base.marked_for_close ||
00960         or_conn->is_bad_for_new_circs ||
00961         or_conn->_base.state != OR_CONN_STATE_OPEN)
00962       continue;
00963     if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
00964       /* This isn't the best conn, _and_ the best conn is better than it,
00965          even when we're being forgiving. */
00966       if (best->is_canonical) {
00967         log_info(LD_OR,
00968                  "Marking OR conn to %s:%d as unsuitable for new circuits: "
00969                  "(fd %d, %d secs old).  We have a better canonical one "
00970                  "(fd %d; %d secs old).",
00971                  or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
00972                  (int)(now - or_conn->_base.timestamp_created),
00973                  best->_base.s, (int)(now - best->_base.timestamp_created));
00974         or_conn->is_bad_for_new_circs = 1;
00975       } else if (!tor_addr_compare(&or_conn->real_addr,
00976                                    &best->real_addr, CMP_EXACT)) {
00977         log_info(LD_OR,
00978                  "Marking OR conn to %s:%d as unsuitable for new circuits: "
00979                  "(fd %d, %d secs old).  We have a better one with the "
00980                  "same address (fd %d; %d secs old).",
00981                  or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
00982                  (int)(now - or_conn->_base.timestamp_created),
00983                  best->_base.s, (int)(now - best->_base.timestamp_created));
00984         or_conn->is_bad_for_new_circs = 1;
00985       }
00986     }
00987   }
00988 }
00989 
00995 void
00996 connection_or_set_bad_connections(const char *digest, int force)
00997 {
00998   if (!orconn_identity_map)
00999     return;
01000 
01001   DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
01002     if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
01003       connection_or_group_set_badness(conn, force);
01004   } DIGESTMAP_FOREACH_END;
01005 }
01006 
01013 void
01014 connection_or_connect_failed(or_connection_t *conn,
01015                              int reason, const char *msg)
01016 {
01017   control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
01018   if (!authdir_mode_tests_reachability(get_options()))
01019     control_event_bootstrap_problem(msg, reason);
01020 }
01021 
01036 or_connection_t *
01037 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
01038                       const char *id_digest)
01039 {
01040   or_connection_t *conn;
01041   const or_options_t *options = get_options();
01042   int socket_error = 0;
01043   tor_addr_t addr;
01044 
01045   int r;
01046   tor_addr_t proxy_addr;
01047   uint16_t proxy_port;
01048   int proxy_type;
01049 
01050   tor_assert(_addr);
01051   tor_assert(id_digest);
01052   tor_addr_copy(&addr, _addr);
01053 
01054   if (server_mode(options) && router_digest_is_me(id_digest)) {
01055     log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
01056     return NULL;
01057   }
01058 
01059   conn = or_connection_new(tor_addr_family(&addr));
01060 
01061   /* set up conn so it's got all the data we need to remember */
01062   connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
01063   conn->_base.state = OR_CONN_STATE_CONNECTING;
01064   control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
01065 
01066   conn->is_outgoing = 1;
01067 
01068   /* If we are using a proxy server, find it and use it. */
01069   r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
01070   if (r == 0) {
01071     conn->proxy_type = proxy_type;
01072     if (proxy_type != PROXY_NONE) {
01073       tor_addr_copy(&addr, &proxy_addr);
01074       port = proxy_port;
01075       conn->_base.proxy_state = PROXY_INFANT;
01076     }
01077   } else {
01078     /* get_proxy_addrport() might fail if we have a Bridge line that
01079        references a transport, but no ClientTransportPlugin lines
01080        defining its transport proxy. If this is the case, let's try to
01081        output a useful log message to the user. */
01082     const char *transport_name =
01083       find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
01084                                              TO_CONN(conn)->port);
01085 
01086     if (transport_name) {
01087       log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s:%u' "
01088                "using pluggable transport '%s', but we can't find a pluggable "
01089                "transport proxy supporting '%s'. This can happen if you "
01090                "haven't provided a ClientTransportPlugin line, or if "
01091                "your pluggable transport proxy stopped running.",
01092                fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port,
01093                transport_name, transport_name);
01094     } else {
01095       log_warn(LD_GENERAL, "Tried to connect to '%s:%u' through a proxy, but "
01096                "the proxy address could not be found.",
01097                fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
01098     }
01099 
01100     connection_free(TO_CONN(conn));
01101     return NULL;
01102   }
01103 
01104   switch (connection_connect(TO_CONN(conn), conn->_base.address,
01105                              &addr, port, &socket_error)) {
01106     case -1:
01107       /* If the connection failed immediately, and we're using
01108        * a proxy, our proxy is down. Don't blame the Tor server. */
01109       if (conn->_base.proxy_state == PROXY_INFANT)
01110         entry_guard_register_connect_status(conn->identity_digest,
01111                                             0, 1, time(NULL));
01112       connection_or_connect_failed(conn,
01113                                    errno_to_orconn_end_reason(socket_error),
01114                                    tor_socket_strerror(socket_error));
01115       connection_free(TO_CONN(conn));
01116       return NULL;
01117     case 0:
01118       connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
01119       /* writable indicates finish, readable indicates broken link,
01120          error indicates broken link on windows */
01121       return conn;
01122     /* case 1: fall through */
01123   }
01124 
01125   if (connection_or_finished_connecting(conn) < 0) {
01126     /* already marked for close */
01127     return NULL;
01128   }
01129   return conn;
01130 }
01131 
01140 int
01141 connection_tls_start_handshake(or_connection_t *conn, int receiving)
01142 {
01143   conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
01144   tor_assert(!conn->tls);
01145   conn->tls = tor_tls_new(conn->_base.s, receiving);
01146   if (!conn->tls) {
01147     log_warn(LD_BUG,"tor_tls_new failed. Closing.");
01148     return -1;
01149   }
01150   tor_tls_set_logged_address(conn->tls, // XXX client and relay?
01151       escaped_safe_str(conn->_base.address));
01152 
01153 #ifdef USE_BUFFEREVENTS
01154   if (connection_type_uses_bufferevent(TO_CONN(conn))) {
01155     const int filtering = get_options()->_UseFilteringSSLBufferevents;
01156     struct bufferevent *b =
01157       tor_tls_init_bufferevent(conn->tls, conn->_base.bufev, conn->_base.s,
01158                                receiving, filtering);
01159     if (!b) {
01160       log_warn(LD_BUG,"tor_tls_init_bufferevent failed. Closing.");
01161       return -1;
01162     }
01163     conn->_base.bufev = b;
01164     if (conn->bucket_cfg)
01165       tor_set_bufferevent_rate_limit(conn->_base.bufev, conn->bucket_cfg);
01166     connection_enable_rate_limiting(TO_CONN(conn));
01167 
01168     connection_configure_bufferevent_callbacks(TO_CONN(conn));
01169     bufferevent_setcb(b,
01170                       connection_handle_read_cb,
01171                       connection_handle_write_cb,
01172                       connection_or_handle_event_cb,/* overriding this one*/
01173                       TO_CONN(conn));
01174   }
01175 #endif
01176   connection_start_reading(TO_CONN(conn));
01177   log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
01178   note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
01179 
01180   IF_HAS_BUFFEREVENT(TO_CONN(conn), {
01181     /* ???? */;
01182   }) ELSE_IF_NO_BUFFEREVENT {
01183     if (connection_tls_continue_handshake(conn) < 0)
01184       return -1;
01185   }
01186   return 0;
01187 }
01188 
01191 static void
01192 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
01193 {
01194   or_connection_t *conn = _conn;
01195   (void)tls;
01196 
01197   /* Don't invoke this again. */
01198   tor_tls_set_renegotiate_callback(tls, NULL, NULL);
01199   tor_tls_block_renegotiation(tls);
01200 
01201   if (connection_tls_finish_handshake(conn) < 0) {
01202     /* XXXX_TLS double-check that it's ok to do this from inside read. */
01203     /* XXXX_TLS double-check that this verifies certificates. */
01204     connection_mark_for_close(TO_CONN(conn));
01205   }
01206 }
01207 
01213 int
01214 connection_tls_continue_handshake(or_connection_t *conn)
01215 {
01216   int result;
01217   check_no_tls_errors();
01218  again:
01219   if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
01220     // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
01221     result = tor_tls_renegotiate(conn->tls);
01222     // log_notice(LD_OR, "Result: %d", result);
01223   } else {
01224     tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
01225     // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
01226     result = tor_tls_handshake(conn->tls);
01227     // log_notice(LD_OR, "Result: %d", result);
01228   }
01229   switch (result) {
01230     CASE_TOR_TLS_ERROR_ANY:
01231     log_info(LD_OR,"tls error [%s]. breaking connection.",
01232              tor_tls_err_to_string(result));
01233       return -1;
01234     case TOR_TLS_DONE:
01235       if (! tor_tls_used_v1_handshake(conn->tls)) {
01236         if (!tor_tls_is_server(conn->tls)) {
01237           if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
01238             if (tor_tls_received_v3_certificate(conn->tls)) {
01239               log_info(LD_OR, "Client got a v3 cert!  Moving on to v3 "
01240                          "handshake.");
01241               return connection_or_launch_v3_or_handshake(conn);
01242             } else {
01243               log_debug(LD_OR, "Done with initial SSL handshake (client-side)."
01244                         " Requesting renegotiation.");
01245               conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
01246               goto again;
01247             }
01248           }
01249           // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
01250         } else {
01251           /* v2/v3 handshake, but not a client. */
01252           log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
01253                            "Expecting renegotiation or VERSIONS cell");
01254           tor_tls_set_renegotiate_callback(conn->tls,
01255                                            connection_or_tls_renegotiated_cb,
01256                                            conn);
01257           conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
01258           connection_stop_writing(TO_CONN(conn));
01259           connection_start_reading(TO_CONN(conn));
01260           return 0;
01261         }
01262       }
01263       return connection_tls_finish_handshake(conn);
01264     case TOR_TLS_WANTWRITE:
01265       connection_start_writing(TO_CONN(conn));
01266       log_debug(LD_OR,"wanted write");
01267       return 0;
01268     case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
01269       log_debug(LD_OR,"wanted read");
01270       return 0;
01271     case TOR_TLS_CLOSE:
01272       log_info(LD_OR,"tls closed. breaking connection.");
01273       return -1;
01274   }
01275   return 0;
01276 }
01277 
01278 #ifdef USE_BUFFEREVENTS
01279 static void
01280 connection_or_handle_event_cb(struct bufferevent *bufev, short event,
01281                               void *arg)
01282 {
01283   struct or_connection_t *conn = TO_OR_CONN(arg);
01284 
01285   /* XXXX cut-and-paste code; should become a function. */
01286   if (event & BEV_EVENT_CONNECTED) {
01287     if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
01288       if (tor_tls_finish_handshake(conn->tls) < 0) {
01289         log_warn(LD_OR, "Problem finishing handshake");
01290         connection_mark_for_close(TO_CONN(conn));
01291         return;
01292       }
01293     }
01294 
01295     if (! tor_tls_used_v1_handshake(conn->tls)) {
01296       if (!tor_tls_is_server(conn->tls)) {
01297         if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
01298           if (tor_tls_received_v3_certificate(conn->tls)) {
01299             log_info(LD_OR, "Client got a v3 cert!");
01300             if (connection_or_launch_v3_or_handshake(conn) < 0)
01301               connection_mark_for_close(TO_CONN(conn));
01302             return;
01303           } else {
01304             conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
01305             tor_tls_unblock_renegotiation(conn->tls);
01306             if (bufferevent_ssl_renegotiate(conn->_base.bufev)<0) {
01307               log_warn(LD_OR, "Start_renegotiating went badly.");
01308               connection_mark_for_close(TO_CONN(conn));
01309             }
01310             tor_tls_unblock_renegotiation(conn->tls);
01311             return; /* ???? */
01312           }
01313         }
01314       } else {
01315         const int handshakes = tor_tls_get_num_server_handshakes(conn->tls);
01316 
01317         if (handshakes == 1) {
01318           /* v2 or v3 handshake, as a server. Only got one handshake, so
01319            * wait for the next one. */
01320           tor_tls_set_renegotiate_callback(conn->tls,
01321                                            connection_or_tls_renegotiated_cb,
01322                                            conn);
01323           conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
01324         } else if (handshakes == 2) {
01325           /* v2 handshake, as a server.  Two handshakes happened already,
01326            * so we treat renegotiation as done.
01327            */
01328           connection_or_tls_renegotiated_cb(conn->tls, conn);
01329         } else if (handshakes > 2) {
01330           log_warn(LD_OR, "More than two handshakes done on connection. "
01331                    "Closing.");
01332           connection_mark_for_close(TO_CONN(conn));
01333         } else {
01334           log_warn(LD_BUG, "We were unexpectedly told that a connection "
01335                    "got %d handshakes. Closing.", handshakes);
01336           connection_mark_for_close(TO_CONN(conn));
01337         }
01338         return;
01339       }
01340     }
01341     connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
01342     if (connection_tls_finish_handshake(conn) < 0)
01343       connection_mark_for_close(TO_CONN(conn)); /* ???? */
01344     return;
01345   }
01346 
01347   if (event & BEV_EVENT_ERROR) {
01348     unsigned long err;
01349     while ((err = bufferevent_get_openssl_error(bufev))) {
01350       tor_tls_log_one_error(conn->tls, err, LOG_WARN, LD_OR,
01351                             "handshaking (with bufferevent)");
01352     }
01353   }
01354 
01355   connection_handle_event_cb(bufev, event, arg);
01356 }
01357 #endif
01358 
01362 int
01363 connection_or_nonopen_was_started_here(or_connection_t *conn)
01364 {
01365   tor_assert(conn->_base.type == CONN_TYPE_OR);
01366   if (!conn->tls)
01367     return 1; /* it's still in proxy states or something */
01368   if (conn->handshake_state)
01369     return conn->handshake_state->started_here;
01370   return !tor_tls_is_server(conn->tls);
01371 }
01372 
01376 void
01377 connection_or_set_circid_type(or_connection_t *conn,
01378                               crypto_pk_t *identity_rcvd)
01379 {
01380   const int started_here = connection_or_nonopen_was_started_here(conn);
01381   crypto_pk_t *our_identity =
01382     started_here ? get_tlsclient_identity_key() :
01383                    get_server_identity_key();
01384 
01385   if (identity_rcvd) {
01386     if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
01387       conn->circ_id_type = CIRC_ID_TYPE_LOWER;
01388     } else {
01389       conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
01390     }
01391   } else {
01392     conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
01393   }
01394 }
01395 
01421 static int
01422 connection_or_check_valid_tls_handshake(or_connection_t *conn,
01423                                         int started_here,
01424                                         char *digest_rcvd_out)
01425 {
01426   crypto_pk_t *identity_rcvd=NULL;
01427   const or_options_t *options = get_options();
01428   int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
01429   const char *safe_address =
01430     started_here ? conn->_base.address :
01431                    safe_str_client(conn->_base.address);
01432   const char *conn_type = started_here ? "outgoing" : "incoming";
01433   int has_cert = 0;
01434 
01435   check_no_tls_errors();
01436   has_cert = tor_tls_peer_has_cert(conn->tls);
01437   if (started_here && !has_cert) {
01438     log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
01439              "send a cert! Closing.",
01440              safe_address, conn->_base.port);
01441     return -1;
01442   } else if (!has_cert) {
01443     log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
01444               "That's ok.");
01445   }
01446   check_no_tls_errors();
01447 
01448   if (has_cert) {
01449     int v = tor_tls_verify(started_here?severity:LOG_INFO,
01450                            conn->tls, &identity_rcvd);
01451     if (started_here && v<0) {
01452       log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
01453              " has a cert but it's invalid. Closing.",
01454              safe_address, conn->_base.port);
01455         return -1;
01456     } else if (v<0) {
01457       log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
01458                "chain; ignoring.");
01459     } else {
01460       log_debug(LD_HANDSHAKE,
01461                 "The certificate seems to be valid on %s connection "
01462                 "with %s:%d", conn_type, safe_address, conn->_base.port);
01463     }
01464     check_no_tls_errors();
01465   }
01466 
01467   if (identity_rcvd) {
01468     crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
01469   } else {
01470     memset(digest_rcvd_out, 0, DIGEST_LEN);
01471   }
01472 
01473   connection_or_set_circid_type(conn, identity_rcvd);
01474   crypto_pk_free(identity_rcvd);
01475 
01476   if (started_here)
01477     return connection_or_client_learned_peer_id(conn,
01478                                      (const uint8_t*)digest_rcvd_out);
01479 
01480   return 0;
01481 }
01482 
01498 int
01499 connection_or_client_learned_peer_id(or_connection_t *conn,
01500                                      const uint8_t *peer_id)
01501 {
01502   const or_options_t *options = get_options();
01503   int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
01504 
01505   if (tor_digest_is_zero(conn->identity_digest)) {
01506     connection_or_set_identity_digest(conn, (const char*)peer_id);
01507     tor_free(conn->nickname);
01508     conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
01509     conn->nickname[0] = '$';
01510     base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
01511                   conn->identity_digest, DIGEST_LEN);
01512     log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
01513                     "its key. Hoping for the best.",
01514                     conn->nickname, conn->_base.address, conn->_base.port);
01515     /* if it's a bridge and we didn't know its identity fingerprint, now
01516      * we do -- remember it for future attempts. */
01517     learned_router_identity(&conn->_base.addr, conn->_base.port,
01518                             (const char*)peer_id);
01519   }
01520 
01521   if (tor_memneq(peer_id, conn->identity_digest, DIGEST_LEN)) {
01522     /* I was aiming for a particular digest. I didn't get it! */
01523     char seen[HEX_DIGEST_LEN+1];
01524     char expected[HEX_DIGEST_LEN+1];
01525     base16_encode(seen, sizeof(seen), (const char*)peer_id, DIGEST_LEN);
01526     base16_encode(expected, sizeof(expected), conn->identity_digest,
01527                   DIGEST_LEN);
01528     log_fn(severity, LD_HANDSHAKE,
01529            "Tried connecting to router at %s:%d, but identity key was not "
01530            "as expected: wanted %s but got %s.",
01531            conn->_base.address, conn->_base.port, expected, seen);
01532     entry_guard_register_connect_status(conn->identity_digest, 0, 1,
01533                                         time(NULL));
01534     control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
01535                                  END_OR_CONN_REASON_OR_IDENTITY);
01536     if (!authdir_mode_tests_reachability(options))
01537       control_event_bootstrap_problem(
01538                                 "Unexpected identity in router certificate",
01539                                 END_OR_CONN_REASON_OR_IDENTITY);
01540     return -1;
01541   }
01542   if (authdir_mode_tests_reachability(options)) {
01543     dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
01544                             (const char*)peer_id);
01545   }
01546 
01547   return 0;
01548 }
01549 
01563 static int
01564 connection_tls_finish_handshake(or_connection_t *conn)
01565 {
01566   char digest_rcvd[DIGEST_LEN];
01567   int started_here = connection_or_nonopen_was_started_here(conn);
01568 
01569   log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done. verifying.",
01570             started_here?"outgoing":"incoming",
01571             conn,
01572             safe_str_client(conn->_base.address));
01573 
01574   directory_set_dirty();
01575 
01576   if (connection_or_check_valid_tls_handshake(conn, started_here,
01577                                               digest_rcvd) < 0)
01578     return -1;
01579 
01580   circuit_build_times_network_is_live(&circ_times);
01581 
01582   if (tor_tls_used_v1_handshake(conn->tls)) {
01583     conn->link_proto = 1;
01584     if (!started_here) {
01585       connection_or_init_conn_from_address(conn, &conn->_base.addr,
01586                                            conn->_base.port, digest_rcvd, 0);
01587     }
01588     tor_tls_block_renegotiation(conn->tls);
01589     return connection_or_set_state_open(conn);
01590   } else {
01591     conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING_V2;
01592     if (connection_init_or_handshake_state(conn, started_here) < 0)
01593       return -1;
01594     if (!started_here) {
01595       connection_or_init_conn_from_address(conn, &conn->_base.addr,
01596                                            conn->_base.port, digest_rcvd, 0);
01597     }
01598     return connection_or_send_versions(conn, 0);
01599   }
01600 }
01601 
01608 static int
01609 connection_or_launch_v3_or_handshake(or_connection_t *conn)
01610 {
01611   tor_assert(connection_or_nonopen_was_started_here(conn));
01612   tor_assert(tor_tls_received_v3_certificate(conn->tls));
01613 
01614   circuit_build_times_network_is_live(&circ_times);
01615 
01616   conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
01617   if (connection_init_or_handshake_state(conn, 1) < 0)
01618     return -1;
01619 
01620   return connection_or_send_versions(conn, 1);
01621 }
01622 
01625 int
01626 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
01627 {
01628   or_handshake_state_t *s;
01629   if (conn->handshake_state) {
01630     log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
01631     return 0;
01632   }
01633   s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
01634   s->started_here = started_here ? 1 : 0;
01635   s->digest_sent_data = 1;
01636   s->digest_received_data = 1;
01637   return 0;
01638 }
01639 
01641 void
01642 or_handshake_state_free(or_handshake_state_t *state)
01643 {
01644   if (!state)
01645     return;
01646   crypto_digest_free(state->digest_sent);
01647   crypto_digest_free(state->digest_received);
01648   tor_cert_free(state->auth_cert);
01649   tor_cert_free(state->id_cert);
01650   memset(state, 0xBE, sizeof(or_handshake_state_t));
01651   tor_free(state);
01652 }
01653 
01663 void
01664 or_handshake_state_record_cell(or_handshake_state_t *state,
01665                                const cell_t *cell,
01666                                int incoming)
01667 {
01668   crypto_digest_t *d, **dptr;
01669   packed_cell_t packed;
01670   if (incoming) {
01671     if (!state->digest_received_data)
01672       return;
01673   } else {
01674     if (!state->digest_sent_data)
01675       return;
01676   }
01677   if (!incoming) {
01678     log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
01679              "while making a handshake digest.  But we think we are sending "
01680              "one with type %d.", (int)cell->command);
01681   }
01682   dptr = incoming ? &state->digest_received : &state->digest_sent;
01683   if (! *dptr)
01684     *dptr = crypto_digest256_new(DIGEST_SHA256);
01685 
01686   d = *dptr;
01687   /* Re-packing like this is a little inefficient, but we don't have to do
01688      this very often at all. */
01689   cell_pack(&packed, cell);
01690   crypto_digest_add_bytes(d, packed.body, sizeof(packed.body));
01691   memset(&packed, 0, sizeof(packed));
01692 }
01693 
01702 void
01703 or_handshake_state_record_var_cell(or_handshake_state_t *state,
01704                                    const var_cell_t *cell,
01705                                    int incoming)
01706 {
01707   crypto_digest_t *d, **dptr;
01708   char buf[VAR_CELL_HEADER_SIZE];
01709   if (incoming) {
01710     if (!state->digest_received_data)
01711       return;
01712   } else {
01713     if (!state->digest_sent_data)
01714       return;
01715   }
01716   dptr = incoming ? &state->digest_received : &state->digest_sent;
01717   if (! *dptr)
01718     *dptr = crypto_digest256_new(DIGEST_SHA256);
01719 
01720   d = *dptr;
01721 
01722   var_cell_pack_header(cell, buf);
01723   crypto_digest_add_bytes(d, buf, sizeof(buf));
01724   crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
01725 
01726   memset(buf, 0, sizeof(buf));
01727 }
01728 
01732 int
01733 connection_or_set_state_open(or_connection_t *conn)
01734 {
01735   int started_here = connection_or_nonopen_was_started_here(conn);
01736   time_t now = time(NULL);
01737   conn->_base.state = OR_CONN_STATE_OPEN;
01738   control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
01739 
01740   if (started_here) {
01741     circuit_build_times_network_is_live(&circ_times);
01742     rep_hist_note_connect_succeeded(conn->identity_digest, now);
01743     if (entry_guard_register_connect_status(conn->identity_digest,
01744                                             1, 0, now) < 0) {
01745       /* Close any circuits pending on this conn. We leave it in state
01746        * 'open' though, because it didn't actually *fail* -- we just
01747        * chose not to use it. (Otherwise
01748        * connection_about_to_close_connection() will call a big pile of
01749        * functions to indicate we shouldn't try it again.) */
01750       log_debug(LD_OR, "New entry guard was reachable, but closing this "
01751                 "connection so we can retry the earlier entry guards.");
01752       circuit_n_conn_done(conn, 0);
01753       return -1;
01754     }
01755     router_set_status(conn->identity_digest, 1);
01756   } else {
01757     /* only report it to the geoip module if it's not a known router */
01758     if (!router_get_by_id_digest(conn->identity_digest)) {
01759       geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &TO_CONN(conn)->addr,
01760                              now);
01761     }
01762   }
01763 
01764   or_handshake_state_free(conn->handshake_state);
01765   conn->handshake_state = NULL;
01766   IF_HAS_BUFFEREVENT(TO_CONN(conn), {
01767     connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
01768   }) ELSE_IF_NO_BUFFEREVENT {
01769     connection_start_reading(TO_CONN(conn));
01770   }
01771 
01772   circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
01773 
01774   return 0;
01775 }
01776 
01781 void
01782 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
01783 {
01784   packed_cell_t networkcell;
01785 
01786   tor_assert(cell);
01787   tor_assert(conn);
01788 
01789   cell_pack(&networkcell, cell);
01790 
01791   connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
01792 
01793   if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
01794     or_handshake_state_record_cell(conn->handshake_state, cell, 0);
01795 
01796   if (cell->command != CELL_PADDING)
01797     conn->timestamp_last_added_nonpadding = approx_time();
01798 }
01799 
01804 void
01805 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
01806                                     or_connection_t *conn)
01807 {
01808   char hdr[VAR_CELL_HEADER_SIZE];
01809   tor_assert(cell);
01810   tor_assert(conn);
01811   var_cell_pack_header(cell, hdr);
01812   connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
01813   connection_write_to_buf((char*)cell->payload,
01814                           cell->payload_len, TO_CONN(conn));
01815   if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
01816     or_handshake_state_record_var_cell(conn->handshake_state, cell, 0);
01817   if (cell->command != CELL_PADDING)
01818     conn->timestamp_last_added_nonpadding = approx_time();
01819 }
01820 
01823 static int
01824 connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
01825 {
01826   connection_t *conn = TO_CONN(or_conn);
01827   IF_HAS_BUFFEREVENT(conn, {
01828     struct evbuffer *input = bufferevent_get_input(conn->bufev);
01829     return fetch_var_cell_from_evbuffer(input, out, or_conn->link_proto);
01830   }) ELSE_IF_NO_BUFFEREVENT {
01831     return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
01832   }
01833 }
01834 
01842 static int
01843 connection_or_process_cells_from_inbuf(or_connection_t *conn)
01844 {
01845   var_cell_t *var_cell;
01846 
01847   while (1) {
01848     log_debug(LD_OR,
01849               "%d: starting, inbuf_datalen %d (%d pending in tls object).",
01850               conn->_base.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
01851               tor_tls_get_pending_bytes(conn->tls));
01852     if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
01853       if (!var_cell)
01854         return 0; /* not yet. */
01855       circuit_build_times_network_is_live(&circ_times);
01856       command_process_var_cell(var_cell, conn);
01857       var_cell_free(var_cell);
01858     } else {
01859       char buf[CELL_NETWORK_SIZE];
01860       cell_t cell;
01861       if (connection_get_inbuf_len(TO_CONN(conn))
01862           < CELL_NETWORK_SIZE) /* whole response available? */
01863         return 0; /* not yet */
01864 
01865       circuit_build_times_network_is_live(&circ_times);
01866       connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
01867 
01868       /* retrieve cell info from buf (create the host-order struct from the
01869        * network-order string) */
01870       cell_unpack(&cell, buf);
01871 
01872       command_process_cell(&cell, conn);
01873     }
01874   }
01875 }
01876 
01883 int
01884 connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
01885 {
01886   cell_t cell;
01887 
01888   tor_assert(conn);
01889 
01890   memset(&cell, 0, sizeof(cell_t));
01891   cell.circ_id = circ_id;
01892   cell.command = CELL_DESTROY;
01893   cell.payload[0] = (uint8_t) reason;
01894   log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
01895 
01896   connection_or_write_cell_to_buf(&cell, conn);
01897   return 0;
01898 }
01899 
01901 static const uint16_t or_protocol_versions[] = { 1, 2, 3 };
01903 static const int n_or_protocol_versions =
01904   (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
01905 
01908 int
01909 is_or_protocol_version_known(uint16_t v)
01910 {
01911   int i;
01912   for (i = 0; i < n_or_protocol_versions; ++i) {
01913     if (or_protocol_versions[i] == v)
01914       return 1;
01915   }
01916   return 0;
01917 }
01918 
01927 int
01928 connection_or_send_versions(or_connection_t *conn, int v3_plus)
01929 {
01930   var_cell_t *cell;
01931   int i;
01932   int n_versions = 0;
01933   const int min_version = v3_plus ? 3 : 0;
01934   const int max_version = v3_plus ? UINT16_MAX : 2;
01935   tor_assert(conn->handshake_state &&
01936              !conn->handshake_state->sent_versions_at);
01937   cell = var_cell_new(n_or_protocol_versions * 2);
01938   cell->command = CELL_VERSIONS;
01939   for (i = 0; i < n_or_protocol_versions; ++i) {
01940     uint16_t v = or_protocol_versions[i];
01941     if (v < min_version || v > max_version)
01942       continue;
01943     set_uint16(cell->payload+(2*n_versions), htons(v));
01944     ++n_versions;
01945   }
01946   cell->payload_len = n_versions * 2;
01947 
01948   connection_or_write_var_cell_to_buf(cell, conn);
01949   conn->handshake_state->sent_versions_at = time(NULL);
01950 
01951   var_cell_free(cell);
01952   return 0;
01953 }
01954 
01957 int
01958 connection_or_send_netinfo(or_connection_t *conn)
01959 {
01960   cell_t cell;
01961   time_t now = time(NULL);
01962   const routerinfo_t *me;
01963   int len;
01964   uint8_t *out;
01965 
01966   tor_assert(conn->handshake_state);
01967 
01968   memset(&cell, 0, sizeof(cell_t));
01969   cell.command = CELL_NETINFO;
01970 
01971   /* Timestamp. */
01972   set_uint32(cell.payload, htonl((uint32_t)now));
01973 
01974   /* Their address. */
01975   out = cell.payload + 4;
01976   /* We use &conn->real_addr below, unless it hasn't yet been set. If it
01977    * hasn't yet been set, we know that _base.addr hasn't been tampered with
01978    * yet either. */
01979   len = append_address_to_payload(out, !tor_addr_is_null(&conn->real_addr)
01980                                        ? &conn->real_addr : &conn->_base.addr);
01981   if (len<0)
01982     return -1;
01983   out += len;
01984 
01985   /* My address -- only include it if I'm a public relay, or if I'm a
01986    * bridge and this is an incoming connection. If I'm a bridge and this
01987    * is an outgoing connection, act like a normal client and omit it. */
01988   if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
01989       (me = router_get_my_routerinfo())) {
01990     tor_addr_t my_addr;
01991     *out++ = 1; /* only one address is supported. */
01992 
01993     tor_addr_from_ipv4h(&my_addr, me->addr);
01994     len = append_address_to_payload(out, &my_addr);
01995     if (len < 0)
01996       return -1;
01997   } else {
01998     *out = 0;
01999   }
02000 
02001   conn->handshake_state->digest_sent_data = 0;
02002   connection_or_write_cell_to_buf(&cell, conn);
02003 
02004   return 0;
02005 }
02006 
02009 int
02010 connection_or_send_certs_cell(or_connection_t *conn)
02011 {
02012   const tor_cert_t *link_cert = NULL, *id_cert = NULL;
02013   const uint8_t *link_encoded = NULL, *id_encoded = NULL;
02014   size_t link_len, id_len;
02015   var_cell_t *cell;
02016   size_t cell_len;
02017   ssize_t pos;
02018   int server_mode;
02019 
02020   tor_assert(conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
02021 
02022   if (! conn->handshake_state)
02023     return -1;
02024   server_mode = ! conn->handshake_state->started_here;
02025   if (tor_tls_get_my_certs(server_mode, &link_cert, &id_cert) < 0)
02026     return -1;
02027   tor_cert_get_der(link_cert, &link_encoded, &link_len);
02028   tor_cert_get_der(id_cert, &id_encoded, &id_len);
02029 
02030   cell_len = 1 /* 1 byte: num certs in cell */ +
02031              2 * ( 1 + 2 ) /* For each cert: 1 byte for type, 2 for length */ +
02032              link_len + id_len;
02033   cell = var_cell_new(cell_len);
02034   cell->command = CELL_CERTS;
02035   cell->payload[0] = 2;
02036   pos = 1;
02037 
02038   if (server_mode)
02039     cell->payload[pos] = OR_CERT_TYPE_TLS_LINK; /* Link cert  */
02040   else
02041     cell->payload[pos] = OR_CERT_TYPE_AUTH_1024; /* client authentication */
02042   set_uint16(&cell->payload[pos+1], htons(link_len));
02043   memcpy(&cell->payload[pos+3], link_encoded, link_len);
02044   pos += 3 + link_len;
02045 
02046   cell->payload[pos] = OR_CERT_TYPE_ID_1024; /* ID cert */
02047   set_uint16(&cell->payload[pos+1], htons(id_len));
02048   memcpy(&cell->payload[pos+3], id_encoded, id_len);
02049   pos += 3 + id_len;
02050 
02051   tor_assert(pos == (int)cell_len); /* Otherwise we just smashed the heap */
02052 
02053   connection_or_write_var_cell_to_buf(cell, conn);
02054   var_cell_free(cell);
02055 
02056   return 0;
02057 }
02058 
02061 int
02062 connection_or_send_auth_challenge_cell(or_connection_t *conn)
02063 {
02064   var_cell_t *cell;
02065   uint8_t *cp;
02066   uint8_t challenge[OR_AUTH_CHALLENGE_LEN];
02067   tor_assert(conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
02068 
02069   if (! conn->handshake_state)
02070     return -1;
02071 
02072   if (crypto_rand((char*)challenge, OR_AUTH_CHALLENGE_LEN) < 0)
02073     return -1;
02074   cell = var_cell_new(OR_AUTH_CHALLENGE_LEN + 4);
02075   cell->command = CELL_AUTH_CHALLENGE;
02076   memcpy(cell->payload, challenge, OR_AUTH_CHALLENGE_LEN);
02077   cp = cell->payload + OR_AUTH_CHALLENGE_LEN;
02078   set_uint16(cp, htons(1)); /* We recognize one authentication type. */
02079   set_uint16(cp+2, htons(AUTHTYPE_RSA_SHA256_TLSSECRET));
02080 
02081   connection_or_write_var_cell_to_buf(cell, conn);
02082   var_cell_free(cell);
02083   memset(challenge, 0, sizeof(challenge));
02084 
02085   return 0;
02086 }
02087 
02106 int
02107 connection_or_compute_authenticate_cell_body(or_connection_t *conn,
02108                                              uint8_t *out, size_t outlen,
02109                                              crypto_pk_t *signing_key,
02110                                              int server)
02111 {
02112   uint8_t *ptr;
02113 
02114   /* assert state is reasonable XXXX */
02115 
02116   if (outlen < V3_AUTH_FIXED_PART_LEN ||
02117       (!server && outlen < V3_AUTH_BODY_LEN))
02118     return -1;
02119 
02120   ptr = out;
02121 
02122   /* Type: 8 bytes. */
02123   memcpy(ptr, "AUTH0001", 8);
02124   ptr += 8;
02125 
02126   {
02127     const tor_cert_t *id_cert=NULL, *link_cert=NULL;
02128     const digests_t *my_digests, *their_digests;
02129     const uint8_t *my_id, *their_id, *client_id, *server_id;
02130     if (tor_tls_get_my_certs(0, &link_cert, &id_cert))
02131       return -1;
02132     my_digests = tor_cert_get_id_digests(id_cert);
02133     their_digests = tor_cert_get_id_digests(conn->handshake_state->id_cert);
02134     tor_assert(my_digests);
02135     tor_assert(their_digests);
02136     my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
02137     their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
02138 
02139     client_id = server ? their_id : my_id;
02140     server_id = server ? my_id : their_id;
02141 
02142     /* Client ID digest: 32 octets. */
02143     memcpy(ptr, client_id, 32);
02144     ptr += 32;
02145 
02146     /* Server ID digest: 32 octets. */
02147     memcpy(ptr, server_id, 32);
02148     ptr += 32;
02149   }
02150 
02151   {
02152     crypto_digest_t *server_d, *client_d;
02153     if (server) {
02154       server_d = conn->handshake_state->digest_sent;
02155       client_d = conn->handshake_state->digest_received;
02156     } else {
02157       client_d = conn->handshake_state->digest_sent;
02158       server_d = conn->handshake_state->digest_received;
02159     }
02160 
02161     /* Server log digest : 32 octets */
02162     crypto_digest_get_digest(server_d, (char*)ptr, 32);
02163     ptr += 32;
02164 
02165     /* Client log digest : 32 octets */
02166     crypto_digest_get_digest(client_d, (char*)ptr, 32);
02167     ptr += 32;
02168   }
02169 
02170   {
02171     /* Digest of cert used on TLS link : 32 octets. */
02172     const tor_cert_t *cert = NULL;
02173     tor_cert_t *freecert = NULL;
02174     if (server) {
02175       tor_tls_get_my_certs(1, &cert, NULL);
02176     } else {
02177       freecert = tor_tls_get_peer_cert(conn->tls);
02178       cert = freecert;
02179     }
02180     if (!cert)
02181       return -1;
02182     memcpy(ptr, tor_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
02183 
02184     if (freecert)
02185       tor_cert_free(freecert);
02186     ptr += 32;
02187   }
02188 
02189   /* HMAC of clientrandom and serverrandom using master key : 32 octets */
02190   tor_tls_get_tlssecrets(conn->tls, ptr);
02191   ptr += 32;
02192 
02193   tor_assert(ptr - out == V3_AUTH_FIXED_PART_LEN);
02194 
02195   if (server)
02196     return V3_AUTH_FIXED_PART_LEN; // ptr-out
02197 
02198   /* Time: 8 octets. */
02199   {
02200     uint64_t now = time(NULL);
02201     if ((time_t)now < 0)
02202       return -1;
02203     set_uint32(ptr, htonl((uint32_t)(now>>32)));
02204     set_uint32(ptr+4, htonl((uint32_t)now));
02205     ptr += 8;
02206   }
02207 
02208   /* Nonce: 16 octets. */
02209   crypto_rand((char*)ptr, 16);
02210   ptr += 16;
02211 
02212   tor_assert(ptr - out == V3_AUTH_BODY_LEN);
02213 
02214   if (!signing_key)
02215     return V3_AUTH_BODY_LEN; // ptr - out
02216 
02217   {
02218     int siglen;
02219     char d[32];
02220     crypto_digest256(d, (char*)out, ptr-out, DIGEST_SHA256);
02221     siglen = crypto_pk_private_sign(signing_key,
02222                                     (char*)ptr, outlen - (ptr-out),
02223                                     d, 32);
02224     if (siglen < 0)
02225       return -1;
02226 
02227     ptr += siglen;
02228     tor_assert(ptr <= out+outlen);
02229     return (int)(ptr - out);
02230   }
02231 }
02232 
02235 int
02236 connection_or_send_authenticate_cell(or_connection_t *conn, int authtype)
02237 {
02238   var_cell_t *cell;
02239   crypto_pk_t *pk = tor_tls_get_my_client_auth_key();
02240   int authlen;
02241   size_t cell_maxlen;
02242   /* XXXX make sure we're actually supposed to send this! */
02243 
02244   if (!pk) {
02245     log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
02246     return -1;
02247   }
02248   if (authtype != AUTHTYPE_RSA_SHA256_TLSSECRET) {
02249     log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
02250              "authentication type %d", authtype);
02251     return -1;
02252   }
02253 
02254   cell_maxlen = 4 + /* overhead */
02255     V3_AUTH_BODY_LEN + /* Authentication body */
02256     crypto_pk_keysize(pk) + /* Max signature length */
02257     16 /* add a few extra bytes just in case. */;
02258 
02259   cell = var_cell_new(cell_maxlen);
02260   cell->command = CELL_AUTHENTICATE;
02261   set_uint16(cell->payload, htons(AUTHTYPE_RSA_SHA256_TLSSECRET));
02262   /* skip over length ; we don't know that yet. */
02263 
02264   authlen = connection_or_compute_authenticate_cell_body(conn,
02265                                                          cell->payload+4,
02266                                                          cell_maxlen-4,
02267                                                          pk,
02268                                                          0 /* not server */);
02269   if (authlen < 0) {
02270     log_warn(LD_BUG, "Unable to compute authenticate cell!");
02271     var_cell_free(cell);
02272     return -1;
02273   }
02274   tor_assert(authlen + 4 <= cell->payload_len);
02275   set_uint16(cell->payload+2, htons(authlen));
02276   cell->payload_len = authlen + 4;
02277 
02278   connection_or_write_var_cell_to_buf(cell, conn);
02279   var_cell_free(cell);
02280 
02281   return 0;
02282 }
02283