connection_or.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_or.c
  8. * \brief Functions to handle OR connections, TLS handshaking, and
  9. * cells on the network.
  10. **/
  11. #include "or.h"
  12. #include "buffers.h"
  13. #include "circuitbuild.h"
  14. #include "command.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_or.h"
  18. #include "control.h"
  19. #include "dirserv.h"
  20. #include "geoip.h"
  21. #include "main.h"
  22. #include "networkstatus.h"
  23. #include "nodelist.h"
  24. #include "reasons.h"
  25. #include "relay.h"
  26. #include "rephist.h"
  27. #include "router.h"
  28. #include "routerlist.h"
  29. #ifdef USE_BUFFEREVENTS
  30. #include <event2/bufferevent_ssl.h>
  31. #endif
  32. static int connection_tls_finish_handshake(or_connection_t *conn);
  33. static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
  34. static int connection_or_send_versions(or_connection_t *conn);
  35. static int connection_init_or_handshake_state(or_connection_t *conn,
  36. int started_here);
  37. static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
  38. int started_here,
  39. char *digest_rcvd_out);
  40. static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
  41. #ifdef USE_BUFFEREVENTS
  42. static void connection_or_handle_event_cb(struct bufferevent *bufev,
  43. short event, void *arg);
  44. #include <event2/buffer.h>/*XXXX REMOVE */
  45. #endif
  46. /**************************************************************/
  47. /** Map from identity digest of connected OR or desired OR to a connection_t
  48. * with that identity digest. If there is more than one such connection_t,
  49. * they form a linked list, with next_with_same_id as the next pointer. */
  50. static digestmap_t *orconn_identity_map = NULL;
  51. /** If conn is listed in orconn_identity_map, remove it, and clear
  52. * conn->identity_digest. Otherwise do nothing. */
  53. void
  54. connection_or_remove_from_identity_map(or_connection_t *conn)
  55. {
  56. or_connection_t *tmp;
  57. tor_assert(conn);
  58. if (!orconn_identity_map)
  59. return;
  60. tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
  61. if (!tmp) {
  62. if (!tor_digest_is_zero(conn->identity_digest)) {
  63. log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
  64. "trying to remove it.",
  65. conn->nickname ? conn->nickname : "NULL");
  66. }
  67. return;
  68. }
  69. if (conn == tmp) {
  70. if (conn->next_with_same_id)
  71. digestmap_set(orconn_identity_map, conn->identity_digest,
  72. conn->next_with_same_id);
  73. else
  74. digestmap_remove(orconn_identity_map, conn->identity_digest);
  75. } else {
  76. while (tmp->next_with_same_id) {
  77. if (tmp->next_with_same_id == conn) {
  78. tmp->next_with_same_id = conn->next_with_same_id;
  79. break;
  80. }
  81. tmp = tmp->next_with_same_id;
  82. }
  83. }
  84. memset(conn->identity_digest, 0, DIGEST_LEN);
  85. conn->next_with_same_id = NULL;
  86. }
  87. /** Remove all entries from the identity-to-orconn map, and clear
  88. * all identities in OR conns.*/
  89. void
  90. connection_or_clear_identity_map(void)
  91. {
  92. smartlist_t *conns = get_connection_array();
  93. SMARTLIST_FOREACH(conns, connection_t *, conn,
  94. {
  95. if (conn->type == CONN_TYPE_OR) {
  96. or_connection_t *or_conn = TO_OR_CONN(conn);
  97. memset(or_conn->identity_digest, 0, DIGEST_LEN);
  98. or_conn->next_with_same_id = NULL;
  99. }
  100. });
  101. digestmap_free(orconn_identity_map, NULL);
  102. orconn_identity_map = NULL;
  103. }
  104. /** Change conn->identity_digest to digest, and add conn into
  105. * orconn_digest_map. */
  106. static void
  107. connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
  108. {
  109. or_connection_t *tmp;
  110. tor_assert(conn);
  111. tor_assert(digest);
  112. if (!orconn_identity_map)
  113. orconn_identity_map = digestmap_new();
  114. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN))
  115. return;
  116. /* If the identity was set previously, remove the old mapping. */
  117. if (! tor_digest_is_zero(conn->identity_digest))
  118. connection_or_remove_from_identity_map(conn);
  119. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  120. /* If we're setting the ID to zero, don't add a mapping. */
  121. if (tor_digest_is_zero(digest))
  122. return;
  123. tmp = digestmap_set(orconn_identity_map, digest, conn);
  124. conn->next_with_same_id = tmp;
  125. #if 1
  126. /* Testing code to check for bugs in representation. */
  127. for (; tmp; tmp = tmp->next_with_same_id) {
  128. tor_assert(!memcmp(tmp->identity_digest, digest, DIGEST_LEN));
  129. tor_assert(tmp != conn);
  130. }
  131. #endif
  132. }
  133. /** Pack the cell_t host-order structure <b>src</b> into network-order
  134. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  135. * wire format.
  136. *
  137. * Note that this function doesn't touch <b>dst</b>-\>next: the caller
  138. * should set it or clear it as appropriate.
  139. */
  140. void
  141. cell_pack(packed_cell_t *dst, const cell_t *src)
  142. {
  143. char *dest = dst->body;
  144. set_uint16(dest, htons(src->circ_id));
  145. *(uint8_t*)(dest+2) = src->command;
  146. memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
  147. }
  148. /** Unpack the network-order buffer <b>src</b> into a host-order
  149. * cell_t structure <b>dest</b>.
  150. */
  151. static void
  152. cell_unpack(cell_t *dest, const char *src)
  153. {
  154. dest->circ_id = ntohs(get_uint16(src));
  155. dest->command = *(uint8_t*)(src+2);
  156. memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
  157. }
  158. /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
  159. * bytes of <b>hdr_out</b>. */
  160. void
  161. var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
  162. {
  163. set_uint16(hdr_out, htons(cell->circ_id));
  164. set_uint8(hdr_out+2, cell->command);
  165. set_uint16(hdr_out+3, htons(cell->payload_len));
  166. }
  167. /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
  168. * payload space. */
  169. var_cell_t *
  170. var_cell_new(uint16_t payload_len)
  171. {
  172. var_cell_t *cell = tor_malloc(sizeof(var_cell_t)+payload_len-1);
  173. cell->payload_len = payload_len;
  174. cell->command = 0;
  175. cell->circ_id = 0;
  176. return cell;
  177. }
  178. /** Release all space held by <b>cell</b>. */
  179. void
  180. var_cell_free(var_cell_t *cell)
  181. {
  182. tor_free(cell);
  183. }
  184. /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
  185. int
  186. connection_or_reached_eof(or_connection_t *conn)
  187. {
  188. log_info(LD_OR,"OR connection reached EOF. Closing.");
  189. connection_mark_for_close(TO_CONN(conn));
  190. return 0;
  191. }
  192. /** Handle any new bytes that have come in on connection <b>conn</b>.
  193. * If conn is in 'open' state, hand it to
  194. * connection_or_process_cells_from_inbuf()
  195. * (else do nothing).
  196. */
  197. int
  198. connection_or_process_inbuf(or_connection_t *conn)
  199. {
  200. int ret;
  201. tor_assert(conn);
  202. switch (conn->_base.state) {
  203. case OR_CONN_STATE_PROXY_HANDSHAKING:
  204. ret = connection_read_proxy_handshake(TO_CONN(conn));
  205. /* start TLS after handshake completion, or deal with error */
  206. if (ret == 1) {
  207. tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
  208. if (connection_tls_start_handshake(conn, 0) < 0)
  209. ret = -1;
  210. }
  211. if (ret < 0) {
  212. connection_mark_for_close(TO_CONN(conn));
  213. }
  214. return ret;
  215. #ifdef USE_BUFFEREVENTS
  216. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  217. if (tor_tls_server_got_renegotiate(conn->tls))
  218. connection_or_tls_renegotiated_cb(conn->tls, conn);
  219. if (conn->_base.marked_for_close)
  220. return 0;
  221. /* fall through. */
  222. #endif
  223. case OR_CONN_STATE_OPEN:
  224. case OR_CONN_STATE_OR_HANDSHAKING:
  225. return connection_or_process_cells_from_inbuf(conn);
  226. default:
  227. return 0; /* don't do anything */
  228. }
  229. }
  230. /** When adding cells to an OR connection's outbuf, keep adding until the
  231. * outbuf is at least this long, or we run out of cells. */
  232. #define OR_CONN_HIGHWATER (32*1024)
  233. /** Add cells to an OR connection's outbuf whenever the outbuf's data length
  234. * drops below this size. */
  235. #define OR_CONN_LOWWATER (16*1024)
  236. /** Called whenever we have flushed some data on an or_conn: add more data
  237. * from active circuits. */
  238. int
  239. connection_or_flushed_some(or_connection_t *conn)
  240. {
  241. size_t datalen = connection_get_outbuf_len(TO_CONN(conn));
  242. /* If we're under the low water mark, add cells until we're just over the
  243. * high water mark. */
  244. if (datalen < OR_CONN_LOWWATER) {
  245. ssize_t n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, CELL_NETWORK_SIZE);
  246. time_t now = approx_time();
  247. while (conn->active_circuits && n > 0) {
  248. int flushed;
  249. flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
  250. n -= flushed;
  251. }
  252. }
  253. return 0;
  254. }
  255. /** Connection <b>conn</b> has finished writing and has no bytes left on
  256. * its outbuf.
  257. *
  258. * Otherwise it's in state "open": stop writing and return.
  259. *
  260. * If <b>conn</b> is broken, mark it for close and return -1, else
  261. * return 0.
  262. */
  263. int
  264. connection_or_finished_flushing(or_connection_t *conn)
  265. {
  266. tor_assert(conn);
  267. assert_connection_ok(TO_CONN(conn),0);
  268. switch (conn->_base.state) {
  269. case OR_CONN_STATE_PROXY_HANDSHAKING:
  270. case OR_CONN_STATE_OPEN:
  271. case OR_CONN_STATE_OR_HANDSHAKING:
  272. break;
  273. default:
  274. log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
  275. tor_fragile_assert();
  276. return -1;
  277. }
  278. return 0;
  279. }
  280. /** Connected handler for OR connections: begin the TLS handshake.
  281. */
  282. int
  283. connection_or_finished_connecting(or_connection_t *or_conn)
  284. {
  285. int proxy_type;
  286. connection_t *conn;
  287. tor_assert(or_conn);
  288. conn = TO_CONN(or_conn);
  289. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  290. log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
  291. conn->address,conn->port);
  292. control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
  293. proxy_type = PROXY_NONE;
  294. if (get_options()->HTTPSProxy)
  295. proxy_type = PROXY_CONNECT;
  296. else if (get_options()->Socks4Proxy)
  297. proxy_type = PROXY_SOCKS4;
  298. else if (get_options()->Socks5Proxy)
  299. proxy_type = PROXY_SOCKS5;
  300. if (proxy_type != PROXY_NONE) {
  301. /* start proxy handshake */
  302. if (connection_proxy_connect(conn, proxy_type) < 0) {
  303. connection_mark_for_close(conn);
  304. return -1;
  305. }
  306. connection_start_reading(conn);
  307. conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
  308. return 0;
  309. }
  310. if (connection_tls_start_handshake(or_conn, 0) < 0) {
  311. /* TLS handshaking error of some kind. */
  312. connection_mark_for_close(conn);
  313. return -1;
  314. }
  315. return 0;
  316. }
  317. /** Return 1 if identity digest <b>id_digest</b> is known to be a
  318. * currently or recently running relay. Otherwise return 0. */
  319. int
  320. connection_or_digest_is_known_relay(const char *id_digest)
  321. {
  322. if (router_get_consensus_status_by_id(id_digest))
  323. return 1; /* It's in the consensus: "yes" */
  324. if (router_get_by_id_digest(id_digest))
  325. return 1; /* Not in the consensus, but we have a descriptor for
  326. * it. Probably it was in a recent consensus. "Yes". */
  327. return 0;
  328. }
  329. /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
  330. * relay, we will rely on the global read and write buckets, so give it
  331. * per-conn limits that are big enough they'll never matter. But if it's
  332. * not a known relay, first check if we set PerConnBwRate/Burst, then
  333. * check if the consensus sets them, else default to 'big enough'.
  334. */
  335. static void
  336. connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
  337. or_options_t *options)
  338. {
  339. int rate, burst; /* per-connection rate limiting params */
  340. if (connection_or_digest_is_known_relay(conn->identity_digest)) {
  341. /* It's in the consensus, or we have a descriptor for it meaning it
  342. * was probably in a recent consensus. It's a recognized relay:
  343. * give it full bandwidth. */
  344. rate = (int)options->BandwidthRate;
  345. burst = (int)options->BandwidthBurst;
  346. } else {
  347. /* Not a recognized relay. Squeeze it down based on the suggested
  348. * bandwidth parameters in the consensus, but allow local config
  349. * options to override. */
  350. rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
  351. (int)networkstatus_get_param(NULL, "perconnbwrate",
  352. (int)options->BandwidthRate);
  353. burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
  354. (int)networkstatus_get_param(NULL, "perconnbwburst",
  355. (int)options->BandwidthBurst);
  356. }
  357. conn->bandwidthrate = rate;
  358. conn->bandwidthburst = burst;
  359. #ifdef USE_BUFFEREVENTS
  360. {
  361. const struct timeval *tick = tor_libevent_get_one_tick_timeout();
  362. struct ev_token_bucket_cfg *cfg, *old_cfg;
  363. int rate_per_tick = rate / TOR_LIBEVENT_TICKS_PER_SECOND;
  364. cfg = ev_token_bucket_cfg_new(rate_per_tick, burst, rate_per_tick,
  365. burst, tick);
  366. old_cfg = conn->bucket_cfg;
  367. if (conn->_base.bufev)
  368. bufferevent_set_rate_limit(conn->_base.bufev, cfg);
  369. if (old_cfg)
  370. ev_token_bucket_cfg_free(old_cfg);
  371. conn->bucket_cfg = cfg;
  372. (void) reset; /* No way to do this with libevent yet. */
  373. }
  374. #else
  375. if (reset) { /* set up the token buckets to be full */
  376. conn->read_bucket = conn->write_bucket = burst;
  377. return;
  378. }
  379. /* If the new token bucket is smaller, take out the extra tokens.
  380. * (If it's larger, don't -- the buckets can grow to reach the cap.) */
  381. if (conn->read_bucket > burst)
  382. conn->read_bucket = burst;
  383. if (conn->write_bucket > burst)
  384. conn->write_bucket = burst;
  385. #endif
  386. }
  387. /** Either our set of relays or our per-conn rate limits have changed.
  388. * Go through all the OR connections and update their token buckets. */
  389. void
  390. connection_or_update_token_buckets(smartlist_t *conns, or_options_t *options)
  391. {
  392. SMARTLIST_FOREACH(conns, connection_t *, conn,
  393. {
  394. if (connection_speaks_cells(conn))
  395. connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
  396. });
  397. }
  398. /** If we don't necessarily know the router we're connecting to, but we
  399. * have an addr/port/id_digest, then fill in as much as we can. Start
  400. * by checking to see if this describes a router we know. */
  401. static void
  402. connection_or_init_conn_from_address(or_connection_t *conn,
  403. const tor_addr_t *addr, uint16_t port,
  404. const char *id_digest,
  405. int started_here)
  406. {
  407. const node_t *r = node_get_by_id(id_digest);
  408. connection_or_set_identity_digest(conn, id_digest);
  409. connection_or_update_token_buckets_helper(conn, 1, get_options());
  410. conn->_base.port = port;
  411. tor_addr_copy(&conn->_base.addr, addr);
  412. tor_addr_copy(&conn->real_addr, addr);
  413. if (r) {
  414. tor_addr_t node_addr;
  415. node_get_addr(r, &node_addr);
  416. /* XXXX proposal 118 will make this more complex. */
  417. if (tor_addr_eq(&conn->_base.addr, &node_addr))
  418. conn->is_canonical = 1;
  419. if (!started_here) {
  420. /* Override the addr/port, so our log messages will make sense.
  421. * This is dangerous, since if we ever try looking up a conn by
  422. * its actual addr/port, we won't remember. Careful! */
  423. /* XXXX arma: this is stupid, and it's the reason we need real_addr
  424. * to track is_canonical properly. What requires it? */
  425. /* XXXX <arma> i believe the reason we did this, originally, is because
  426. * we wanted to log what OR a connection was to, and if we logged the
  427. * right IP address and port 56244, that wouldn't be as helpful. now we
  428. * log the "right" port too, so we know if it's moria1 or moria2.
  429. */
  430. tor_addr_copy(&conn->_base.addr, &node_addr);
  431. conn->_base.port = node_get_orport(r);
  432. }
  433. conn->nickname = tor_strdup(node_get_nickname(r));
  434. tor_free(conn->_base.address);
  435. conn->_base.address = tor_dup_addr(&node_addr);
  436. } else {
  437. const char *n;
  438. /* If we're an authoritative directory server, we may know a
  439. * nickname for this router. */
  440. n = dirserv_get_nickname_by_digest(id_digest);
  441. if (n) {
  442. conn->nickname = tor_strdup(n);
  443. } else {
  444. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  445. conn->nickname[0] = '$';
  446. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  447. conn->identity_digest, DIGEST_LEN);
  448. }
  449. tor_free(conn->_base.address);
  450. conn->_base.address = tor_dup_addr(addr);
  451. }
  452. }
  453. /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
  454. *
  455. * A more canonical connection is always better than a less canonical
  456. * connection. That aside, a connection is better if it has circuits and the
  457. * other does not, or if it was created more recently.
  458. *
  459. * Requires that both input connections are open; not is_bad_for_new_circs,
  460. * and not impossibly non-canonical.
  461. *
  462. * If </b>forgive_new_connections</b> is true, then we do not call
  463. * <b>a</b>better than <b>b</b> simply because b has no circuits,
  464. * unless b is also relatively old.
  465. */
  466. static int
  467. connection_or_is_better(time_t now,
  468. const or_connection_t *a,
  469. const or_connection_t *b,
  470. int forgive_new_connections)
  471. {
  472. int newer;
  473. /** Do not definitively deprecate a new connection with no circuits on it
  474. * until this much time has passed. */
  475. #define NEW_CONN_GRACE_PERIOD (15*60)
  476. if (b->is_canonical && !a->is_canonical)
  477. return 0; /* A canonical connection is better than a non-canonical
  478. * one, no matter how new it is or which has circuits. */
  479. newer = b->_base.timestamp_created < a->_base.timestamp_created;
  480. if (
  481. /* We prefer canonical connections regardless of newness. */
  482. (!b->is_canonical && a->is_canonical) ||
  483. /* If both have circuits we prefer the newer: */
  484. (b->n_circuits && a->n_circuits && newer) ||
  485. /* If neither has circuits we prefer the newer: */
  486. (!b->n_circuits && !a->n_circuits && newer))
  487. return 1;
  488. /* If one has no circuits and the other does... */
  489. if (!b->n_circuits && a->n_circuits) {
  490. /* Then it's bad, unless it's in its grace period and we're forgiving. */
  491. if (forgive_new_connections &&
  492. now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
  493. return 0;
  494. else
  495. return 1;
  496. }
  497. return 0;
  498. }
  499. /** Return the OR connection we should use to extend a circuit to the router
  500. * whose identity is <b>digest</b>, and whose address we believe (or have been
  501. * told in an extend cell) is <b>target_addr</b>. If there is no good
  502. * connection, set *<b>msg_out</b> to a message describing the connection's
  503. * state and our next action, and set <b>launch_out</b> to a boolean for
  504. * whether we should launch a new connection or not.
  505. */
  506. or_connection_t *
  507. connection_or_get_for_extend(const char *digest,
  508. const tor_addr_t *target_addr,
  509. const char **msg_out,
  510. int *launch_out)
  511. {
  512. or_connection_t *conn, *best=NULL;
  513. int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
  514. time_t now = approx_time();
  515. tor_assert(msg_out);
  516. tor_assert(launch_out);
  517. if (!orconn_identity_map) {
  518. *msg_out = "Router not connected (nothing is). Connecting.";
  519. *launch_out = 1;
  520. return NULL;
  521. }
  522. conn = digestmap_get(orconn_identity_map, digest);
  523. for (; conn; conn = conn->next_with_same_id) {
  524. tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
  525. tor_assert(conn->_base.type == CONN_TYPE_OR);
  526. tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
  527. if (conn->_base.marked_for_close)
  528. continue;
  529. /* Never return a non-open connection. */
  530. if (conn->_base.state != OR_CONN_STATE_OPEN) {
  531. /* If the address matches, don't launch a new connection for this
  532. * circuit. */
  533. if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
  534. ++n_inprogress_goodaddr;
  535. continue;
  536. }
  537. /* Never return a connection that shouldn't be used for circs. */
  538. if (conn->is_bad_for_new_circs) {
  539. ++n_old;
  540. continue;
  541. }
  542. /* Never return a non-canonical connection using a recent link protocol
  543. * if the address is not what we wanted.
  544. *
  545. * (For old link protocols, we can't rely on is_canonical getting
  546. * set properly if we're talking to the right address, since we might
  547. * have an out-of-date descriptor, and we will get no NETINFO cell to
  548. * tell us about the right address.) */
  549. if (!conn->is_canonical && conn->link_proto >= 2 &&
  550. tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
  551. ++n_noncanonical;
  552. continue;
  553. }
  554. ++n_possible;
  555. if (!best) {
  556. best = conn; /* If we have no 'best' so far, this one is good enough. */
  557. continue;
  558. }
  559. if (connection_or_is_better(now, conn, best, 0))
  560. best = conn;
  561. }
  562. if (best) {
  563. *msg_out = "Connection is fine; using it.";
  564. *launch_out = 0;
  565. return best;
  566. } else if (n_inprogress_goodaddr) {
  567. *msg_out = "Connection in progress; waiting.";
  568. *launch_out = 0;
  569. return NULL;
  570. } else if (n_old || n_noncanonical) {
  571. *msg_out = "Connections all too old, or too non-canonical. "
  572. " Launching a new one.";
  573. *launch_out = 1;
  574. return NULL;
  575. } else {
  576. *msg_out = "Not connected. Connecting.";
  577. *launch_out = 1;
  578. return NULL;
  579. }
  580. }
  581. /** How old do we let a connection to an OR get before deciding it's
  582. * too old for new circuits? */
  583. #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
  584. /** Given the head of the linked list for all the or_connections with a given
  585. * identity, set elements of that list as is_bad_for_new_circs as
  586. * appropriate. Helper for connection_or_set_bad_connections().
  587. *
  588. * Specifically, we set the is_bad_for_new_circs flag on:
  589. * - all connections if <b>force</b> is true.
  590. * - all connections that are too old.
  591. * - all open non-canonical connections for which a canonical connection
  592. * exists to the same router.
  593. * - all open canonical connections for which a 'better' canonical
  594. * connection exists to the same router.
  595. * - all open non-canonical connections for which a 'better' non-canonical
  596. * connection exists to the same router at the same address.
  597. *
  598. * See connection_or_is_better() for our idea of what makes one OR connection
  599. * better than another.
  600. */
  601. static void
  602. connection_or_group_set_badness(or_connection_t *head, int force)
  603. {
  604. or_connection_t *or_conn = NULL, *best = NULL;
  605. int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
  606. time_t now = time(NULL);
  607. /* Pass 1: expire everything that's old, and see what the status of
  608. * everything else is. */
  609. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  610. if (or_conn->_base.marked_for_close ||
  611. or_conn->is_bad_for_new_circs)
  612. continue;
  613. if (force ||
  614. or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
  615. < now) {
  616. log_info(LD_OR,
  617. "Marking OR conn to %s:%d as too old for new circuits "
  618. "(fd %d, %d secs old).",
  619. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  620. (int)(now - or_conn->_base.timestamp_created));
  621. or_conn->is_bad_for_new_circs = 1;
  622. }
  623. if (or_conn->is_bad_for_new_circs) {
  624. ++n_old;
  625. } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
  626. ++n_inprogress;
  627. } else if (or_conn->is_canonical) {
  628. ++n_canonical;
  629. } else {
  630. ++n_other;
  631. }
  632. }
  633. /* Pass 2: We know how about how good the best connection is.
  634. * expire everything that's worse, and find the very best if we can. */
  635. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  636. if (or_conn->_base.marked_for_close ||
  637. or_conn->is_bad_for_new_circs)
  638. continue; /* This one doesn't need to be marked bad. */
  639. if (or_conn->_base.state != OR_CONN_STATE_OPEN)
  640. continue; /* Don't mark anything bad until we have seen what happens
  641. * when the connection finishes. */
  642. if (n_canonical && !or_conn->is_canonical) {
  643. /* We have at least one open canonical connection to this router,
  644. * and this one is open but not canonical. Mark it bad. */
  645. log_info(LD_OR,
  646. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  647. "(fd %d, %d secs old). It is not canonical, and we have "
  648. "another connection to that OR that is.",
  649. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  650. (int)(now - or_conn->_base.timestamp_created));
  651. or_conn->is_bad_for_new_circs = 1;
  652. continue;
  653. }
  654. if (!best || connection_or_is_better(now, or_conn, best, 0))
  655. best = or_conn;
  656. }
  657. if (!best)
  658. return;
  659. /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
  660. * every other open connection. If it's non-canonical, mark as bad
  661. * every other open connection to the same address.
  662. *
  663. * XXXX This isn't optimal; if we have connections to an OR at multiple
  664. * addresses, we'd like to pick the best _for each address_, and mark as
  665. * bad every open connection that isn't best for its address. But this
  666. * can only occur in cases where the other OR is old (so we have no
  667. * canonical connection to it), or where all the connections to the OR are
  668. * at noncanonical addresses and we have no good direct connection (which
  669. * means we aren't at risk of attaching circuits to it anyway). As
  670. * 0.1.2.x dies out, the first case will go away, and the second one is
  671. * "mostly harmless", so a fix can wait until somebody is bored.
  672. */
  673. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  674. if (or_conn->_base.marked_for_close ||
  675. or_conn->is_bad_for_new_circs ||
  676. or_conn->_base.state != OR_CONN_STATE_OPEN)
  677. continue;
  678. if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
  679. /* This isn't the best conn, _and_ the best conn is better than it,
  680. even when we're being forgiving. */
  681. if (best->is_canonical) {
  682. log_info(LD_OR,
  683. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  684. "(fd %d, %d secs old). We have a better canonical one "
  685. "(fd %d; %d secs old).",
  686. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  687. (int)(now - or_conn->_base.timestamp_created),
  688. best->_base.s, (int)(now - best->_base.timestamp_created));
  689. or_conn->is_bad_for_new_circs = 1;
  690. } else if (!tor_addr_compare(&or_conn->real_addr,
  691. &best->real_addr, CMP_EXACT)) {
  692. log_info(LD_OR,
  693. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  694. "(fd %d, %d secs old). We have a better one with the "
  695. "same address (fd %d; %d secs old).",
  696. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  697. (int)(now - or_conn->_base.timestamp_created),
  698. best->_base.s, (int)(now - best->_base.timestamp_created));
  699. or_conn->is_bad_for_new_circs = 1;
  700. }
  701. }
  702. }
  703. }
  704. /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
  705. * the OR connections with that digest), and set the is_bad_for_new_circs
  706. * flag based on the rules in connection_or_group_set_badness() (or just
  707. * always set it if <b>force</b> is true).
  708. */
  709. void
  710. connection_or_set_bad_connections(const char *digest, int force)
  711. {
  712. if (!orconn_identity_map)
  713. return;
  714. DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
  715. if (!digest || !memcmp(digest, conn->identity_digest, DIGEST_LEN))
  716. connection_or_group_set_badness(conn, force);
  717. } DIGESTMAP_FOREACH_END;
  718. }
  719. /** <b>conn</b> is in the 'connecting' state, and it failed to complete
  720. * a TCP connection. Send notifications appropriately.
  721. *
  722. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  723. * <b>msg</b> specifies the strerror-style error message.
  724. */
  725. void
  726. connection_or_connect_failed(or_connection_t *conn,
  727. int reason, const char *msg)
  728. {
  729. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
  730. if (!authdir_mode_tests_reachability(get_options()))
  731. control_event_bootstrap_problem(msg, reason);
  732. }
  733. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  734. * handshake with an OR with identity digest <b>id_digest</b>.
  735. *
  736. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  737. * return that connection. If the connect() is in progress, set the
  738. * new conn's state to 'connecting' and return it. If connect() succeeds,
  739. * call connection_tls_start_handshake() on it.
  740. *
  741. * This function is called from router_retry_connections(), for
  742. * ORs connecting to ORs, and circuit_establish_circuit(), for
  743. * OPs connecting to ORs.
  744. *
  745. * Return the launched conn, or NULL if it failed.
  746. */
  747. or_connection_t *
  748. connection_or_connect(const tor_addr_t *_addr, uint16_t port,
  749. const char *id_digest)
  750. {
  751. or_connection_t *conn;
  752. or_options_t *options = get_options();
  753. int socket_error = 0;
  754. int using_proxy = 0;
  755. tor_addr_t addr;
  756. tor_assert(_addr);
  757. tor_assert(id_digest);
  758. tor_addr_copy(&addr, _addr);
  759. if (server_mode(options) && router_digest_is_me(id_digest)) {
  760. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  761. return NULL;
  762. }
  763. conn = or_connection_new(AF_INET);
  764. /* set up conn so it's got all the data we need to remember */
  765. connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
  766. conn->_base.state = OR_CONN_STATE_CONNECTING;
  767. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  768. /* use a proxy server if available */
  769. if (options->HTTPSProxy) {
  770. using_proxy = 1;
  771. tor_addr_copy(&addr, &options->HTTPSProxyAddr);
  772. port = options->HTTPSProxyPort;
  773. } else if (options->Socks4Proxy) {
  774. using_proxy = 1;
  775. tor_addr_copy(&addr, &options->Socks4ProxyAddr);
  776. port = options->Socks4ProxyPort;
  777. } else if (options->Socks5Proxy) {
  778. using_proxy = 1;
  779. tor_addr_copy(&addr, &options->Socks5ProxyAddr);
  780. port = options->Socks5ProxyPort;
  781. }
  782. switch (connection_connect(TO_CONN(conn), conn->_base.address,
  783. &addr, port, &socket_error)) {
  784. case -1:
  785. /* If the connection failed immediately, and we're using
  786. * a proxy, our proxy is down. Don't blame the Tor server. */
  787. if (!using_proxy)
  788. entry_guard_register_connect_status(conn->identity_digest,
  789. 0, 1, time(NULL));
  790. connection_or_connect_failed(conn,
  791. errno_to_orconn_end_reason(socket_error),
  792. tor_socket_strerror(socket_error));
  793. connection_free(TO_CONN(conn));
  794. return NULL;
  795. case 0:
  796. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  797. /* writable indicates finish, readable indicates broken link,
  798. error indicates broken link on windows */
  799. return conn;
  800. /* case 1: fall through */
  801. }
  802. if (connection_or_finished_connecting(conn) < 0) {
  803. /* already marked for close */
  804. return NULL;
  805. }
  806. return conn;
  807. }
  808. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  809. * we initiated the connection, else it's 1.
  810. *
  811. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  812. * pass <b>conn</b> to connection_tls_continue_handshake().
  813. *
  814. * Return -1 if <b>conn</b> is broken, else return 0.
  815. */
  816. int
  817. connection_tls_start_handshake(or_connection_t *conn, int receiving)
  818. {
  819. conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
  820. tor_assert(!conn->tls);
  821. conn->tls = tor_tls_new(conn->_base.s, receiving);
  822. tor_tls_set_logged_address(conn->tls, // XXX client and relay?
  823. escaped_safe_str(conn->_base.address));
  824. if (!conn->tls) {
  825. log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  826. return -1;
  827. }
  828. #ifdef USE_BUFFEREVENTS
  829. if (connection_type_uses_bufferevent(TO_CONN(conn))) {
  830. const int filtering = get_options()->_UseFilteringSSLBufferevents;
  831. struct bufferevent *b =
  832. tor_tls_init_bufferevent(conn->tls, conn->_base.bufev, conn->_base.s,
  833. receiving, filtering);
  834. if (!b) {
  835. log_warn(LD_BUG,"tor_tls_init_bufferevent failed. Closing.");
  836. return -1;
  837. }
  838. conn->_base.bufev = b;
  839. if (conn->bucket_cfg)
  840. bufferevent_set_rate_limit(conn->_base.bufev, conn->bucket_cfg);
  841. connection_enable_rate_limiting(TO_CONN(conn));
  842. connection_configure_bufferevent_callbacks(TO_CONN(conn));
  843. bufferevent_setcb(b,
  844. connection_handle_read_cb,
  845. connection_handle_write_cb,
  846. connection_or_handle_event_cb,/* overriding this one*/
  847. TO_CONN(conn));
  848. }
  849. #endif
  850. connection_start_reading(TO_CONN(conn));
  851. log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
  852. note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
  853. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  854. /* ???? */;
  855. }) ELSE_IF_NO_BUFFEREVENT {
  856. if (connection_tls_continue_handshake(conn) < 0)
  857. return -1;
  858. }
  859. return 0;
  860. }
  861. /** Invoked on the server side from inside tor_tls_read() when the server
  862. * gets a successful TLS renegotiation from the client. */
  863. static void
  864. connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
  865. {
  866. or_connection_t *conn = _conn;
  867. (void)tls;
  868. /* Don't invoke this again. */
  869. tor_tls_set_renegotiate_callback(tls, NULL, NULL);
  870. tor_tls_block_renegotiation(tls);
  871. if (connection_tls_finish_handshake(conn) < 0) {
  872. /* XXXX_TLS double-check that it's ok to do this from inside read. */
  873. /* XXXX_TLS double-check that this verifies certificates. */
  874. connection_mark_for_close(TO_CONN(conn));
  875. }
  876. }
  877. /** Move forward with the tls handshake. If it finishes, hand
  878. * <b>conn</b> to connection_tls_finish_handshake().
  879. *
  880. * Return -1 if <b>conn</b> is broken, else return 0.
  881. */
  882. int
  883. connection_tls_continue_handshake(or_connection_t *conn)
  884. {
  885. int result;
  886. check_no_tls_errors();
  887. again:
  888. if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  889. // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
  890. result = tor_tls_renegotiate(conn->tls);
  891. // log_notice(LD_OR, "Result: %d", result);
  892. } else {
  893. tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
  894. // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
  895. result = tor_tls_handshake(conn->tls);
  896. // log_notice(LD_OR, "Result: %d", result);
  897. }
  898. switch (result) {
  899. CASE_TOR_TLS_ERROR_ANY:
  900. log_info(LD_OR,"tls error [%s]. breaking connection.",
  901. tor_tls_err_to_string(result));
  902. return -1;
  903. case TOR_TLS_DONE:
  904. if (! tor_tls_used_v1_handshake(conn->tls)) {
  905. if (!tor_tls_is_server(conn->tls)) {
  906. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  907. // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
  908. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  909. goto again;
  910. }
  911. // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
  912. } else {
  913. /* improved handshake, but not a client. */
  914. tor_tls_set_renegotiate_callback(conn->tls,
  915. connection_or_tls_renegotiated_cb,
  916. conn);
  917. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  918. connection_stop_writing(TO_CONN(conn));
  919. connection_start_reading(TO_CONN(conn));
  920. return 0;
  921. }
  922. }
  923. return connection_tls_finish_handshake(conn);
  924. case TOR_TLS_WANTWRITE:
  925. connection_start_writing(TO_CONN(conn));
  926. log_debug(LD_OR,"wanted write");
  927. return 0;
  928. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  929. log_debug(LD_OR,"wanted read");
  930. return 0;
  931. case TOR_TLS_CLOSE:
  932. log_info(LD_OR,"tls closed. breaking connection.");
  933. return -1;
  934. }
  935. return 0;
  936. }
  937. #ifdef USE_BUFFEREVENTS
  938. static void
  939. connection_or_handle_event_cb(struct bufferevent *bufev, short event,
  940. void *arg)
  941. {
  942. struct or_connection_t *conn = TO_OR_CONN(arg);
  943. /* XXXX cut-and-paste code; should become a function. */
  944. if (event & BEV_EVENT_CONNECTED) {
  945. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  946. if (tor_tls_finish_handshake(conn->tls) < 0) {
  947. log_warn(LD_OR, "Problem finishing handshake");
  948. connection_mark_for_close(TO_CONN(conn));
  949. return;
  950. }
  951. }
  952. if (! tor_tls_used_v1_handshake(conn->tls)) {
  953. if (!tor_tls_is_server(conn->tls)) {
  954. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  955. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  956. tor_tls_unblock_renegotiation(conn->tls);
  957. if (bufferevent_ssl_renegotiate(conn->_base.bufev)<0) {
  958. log_warn(LD_OR, "Start_renegotiating went badly.");
  959. connection_mark_for_close(TO_CONN(conn));
  960. }
  961. tor_tls_unblock_renegotiation(conn->tls);
  962. return; /* ???? */
  963. }
  964. } else if (tor_tls_get_num_server_handshakes(conn->tls) == 1) {
  965. /* improved handshake, as a server. Only got one handshake, so
  966. * wait for the next one. */
  967. tor_tls_set_renegotiate_callback(conn->tls,
  968. connection_or_tls_renegotiated_cb,
  969. conn);
  970. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  971. /* return 0; */
  972. return; /* ???? */
  973. } else {
  974. const int handshakes = tor_tls_get_num_server_handshakes(conn->tls);
  975. tor_assert(handshakes >= 2);
  976. if (handshakes == 2) {
  977. /* improved handshake, as a server. Two handshakes happened already,
  978. * so we treat renegotiation as done.
  979. */
  980. connection_or_tls_renegotiated_cb(conn->tls, conn);
  981. } else {
  982. log_warn(LD_OR, "More than two handshakes done on connection. "
  983. "Closing.");
  984. connection_mark_for_close(TO_CONN(conn));
  985. }
  986. return;
  987. }
  988. }
  989. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  990. if (connection_tls_finish_handshake(conn) < 0)
  991. connection_mark_for_close(TO_CONN(conn)); /* ???? */
  992. return;
  993. }
  994. if (event & BEV_EVENT_ERROR) {
  995. unsigned long err;
  996. while ((err = bufferevent_get_openssl_error(bufev))) {
  997. tor_tls_log_one_error(conn->tls, err, LOG_WARN, LD_OR,
  998. "handshaking (with bufferevent)");
  999. }
  1000. }
  1001. connection_handle_event_cb(bufev, event, arg);
  1002. }
  1003. #endif
  1004. /** Return 1 if we initiated this connection, or 0 if it started
  1005. * out as an incoming connection.
  1006. */
  1007. int
  1008. connection_or_nonopen_was_started_here(or_connection_t *conn)
  1009. {
  1010. tor_assert(conn->_base.type == CONN_TYPE_OR);
  1011. if (!conn->tls)
  1012. return 1; /* it's still in proxy states or something */
  1013. if (conn->handshake_state)
  1014. return conn->handshake_state->started_here;
  1015. return !tor_tls_is_server(conn->tls);
  1016. }
  1017. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  1018. * return -1 if he is lying, broken, or otherwise something is wrong.
  1019. *
  1020. * If we initiated this connection (<b>started_here</b> is true), make sure
  1021. * the other side sent a correctly formed certificate. If I initiated the
  1022. * connection, make sure it's the right guy.
  1023. *
  1024. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  1025. * the certificate to be weird or absent.
  1026. *
  1027. * If we return 0, and the certificate is as expected, write a hash of the
  1028. * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
  1029. * space in it.
  1030. * If the certificate is invalid or missing on an incoming connection,
  1031. * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
  1032. * (If we return -1, the contents of this buffer are undefined.)
  1033. *
  1034. * As side effects,
  1035. * 1) Set conn->circ_id_type according to tor-spec.txt.
  1036. * 2) If we're an authdirserver and we initiated the connection: drop all
  1037. * descriptors that claim to be on that IP/port but that aren't
  1038. * this guy; and note that this guy is reachable.
  1039. * 3) If this is a bridge and we didn't configure its identity
  1040. * fingerprint, remember the keyid we just learned.
  1041. */
  1042. static int
  1043. connection_or_check_valid_tls_handshake(or_connection_t *conn,
  1044. int started_here,
  1045. char *digest_rcvd_out)
  1046. {
  1047. crypto_pk_env_t *identity_rcvd=NULL;
  1048. or_options_t *options = get_options();
  1049. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  1050. const char *safe_address =
  1051. started_here ? conn->_base.address :
  1052. safe_str_client(conn->_base.address);
  1053. const char *conn_type = started_here ? "outgoing" : "incoming";
  1054. crypto_pk_env_t *our_identity =
  1055. started_here ? get_tlsclient_identity_key() :
  1056. get_server_identity_key();
  1057. int has_cert = 0, has_identity=0;
  1058. check_no_tls_errors();
  1059. has_cert = tor_tls_peer_has_cert(conn->tls);
  1060. if (started_here && !has_cert) {
  1061. log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
  1062. "send a cert! Closing.",
  1063. safe_address, conn->_base.port);
  1064. return -1;
  1065. } else if (!has_cert) {
  1066. log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
  1067. "That's ok.");
  1068. }
  1069. check_no_tls_errors();
  1070. if (has_cert) {
  1071. int v = tor_tls_verify(started_here?severity:LOG_INFO,
  1072. conn->tls, &identity_rcvd);
  1073. if (started_here && v<0) {
  1074. log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
  1075. " has a cert but it's invalid. Closing.",
  1076. safe_address, conn->_base.port);
  1077. return -1;
  1078. } else if (v<0) {
  1079. log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
  1080. "chain; ignoring.");
  1081. } else {
  1082. log_debug(LD_HANDSHAKE,
  1083. "The certificate seems to be valid on %s connection "
  1084. "with %s:%d", conn_type, safe_address, conn->_base.port);
  1085. }
  1086. check_no_tls_errors();
  1087. }
  1088. if (identity_rcvd) {
  1089. has_identity = 1;
  1090. crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
  1091. if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
  1092. conn->circ_id_type = CIRC_ID_TYPE_LOWER;
  1093. } else {
  1094. conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
  1095. }
  1096. crypto_free_pk_env(identity_rcvd);
  1097. } else {
  1098. memset(digest_rcvd_out, 0, DIGEST_LEN);
  1099. conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
  1100. }
  1101. if (started_here && tor_digest_is_zero(conn->identity_digest)) {
  1102. connection_or_set_identity_digest(conn, digest_rcvd_out);
  1103. tor_free(conn->nickname);
  1104. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  1105. conn->nickname[0] = '$';
  1106. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  1107. conn->identity_digest, DIGEST_LEN);
  1108. log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
  1109. "its key. Hoping for the best.",
  1110. conn->nickname, conn->_base.address, conn->_base.port);
  1111. /* if it's a bridge and we didn't know its identity fingerprint, now
  1112. * we do -- remember it for future attempts. */
  1113. learned_router_identity(&conn->_base.addr, conn->_base.port,
  1114. digest_rcvd_out);
  1115. }
  1116. if (started_here) {
  1117. int as_advertised = 1;
  1118. tor_assert(has_cert);
  1119. tor_assert(has_identity);
  1120. if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
  1121. /* I was aiming for a particular digest. I didn't get it! */
  1122. char seen[HEX_DIGEST_LEN+1];
  1123. char expected[HEX_DIGEST_LEN+1];
  1124. base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
  1125. base16_encode(expected, sizeof(expected), conn->identity_digest,
  1126. DIGEST_LEN);
  1127. log_fn(severity, LD_HANDSHAKE,
  1128. "Tried connecting to router at %s:%d, but identity key was not "
  1129. "as expected: wanted %s but got %s.",
  1130. conn->_base.address, conn->_base.port, expected, seen);
  1131. entry_guard_register_connect_status(conn->identity_digest, 0, 1,
  1132. time(NULL));
  1133. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  1134. END_OR_CONN_REASON_OR_IDENTITY);
  1135. if (!authdir_mode_tests_reachability(options))
  1136. control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
  1137. as_advertised = 0;
  1138. }
  1139. if (authdir_mode_tests_reachability(options)) {
  1140. /* We initiated this connection to address:port. Drop all routers
  1141. * with the same address:port and a different key.
  1142. */
  1143. dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
  1144. digest_rcvd_out, as_advertised);
  1145. }
  1146. if (!as_advertised)
  1147. return -1;
  1148. }
  1149. return 0;
  1150. }
  1151. /** The tls handshake is finished.
  1152. *
  1153. * Make sure we are happy with the person we just handshaked with.
  1154. *
  1155. * If he initiated the connection, make sure he's not already connected,
  1156. * then initialize conn from the information in router.
  1157. *
  1158. * If all is successful, call circuit_n_conn_done() to handle events
  1159. * that have been pending on the <tls handshake completion. Also set the
  1160. * directory to be dirty (only matters if I'm an authdirserver).
  1161. */
  1162. static int
  1163. connection_tls_finish_handshake(or_connection_t *conn)
  1164. {
  1165. char digest_rcvd[DIGEST_LEN];
  1166. int started_here = connection_or_nonopen_was_started_here(conn);
  1167. log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done. verifying.",
  1168. started_here?"outgoing":"incoming",
  1169. conn,
  1170. safe_str_client(conn->_base.address));
  1171. directory_set_dirty();
  1172. if (connection_or_check_valid_tls_handshake(conn, started_here,
  1173. digest_rcvd) < 0)
  1174. return -1;
  1175. circuit_build_times_network_is_live(&circ_times);
  1176. if (tor_tls_used_v1_handshake(conn->tls)) {
  1177. conn->link_proto = 1;
  1178. if (!started_here) {
  1179. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  1180. conn->_base.port, digest_rcvd, 0);
  1181. }
  1182. tor_tls_block_renegotiation(conn->tls);
  1183. return connection_or_set_state_open(conn);
  1184. } else {
  1185. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
  1186. if (connection_init_or_handshake_state(conn, started_here) < 0)
  1187. return -1;
  1188. if (!started_here) {
  1189. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  1190. conn->_base.port, digest_rcvd, 0);
  1191. }
  1192. return connection_or_send_versions(conn);
  1193. }
  1194. }
  1195. /** Allocate a new connection handshake state for the connection
  1196. * <b>conn</b>. Return 0 on success, -1 on failure. */
  1197. static int
  1198. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  1199. {
  1200. or_handshake_state_t *s;
  1201. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  1202. s->started_here = started_here ? 1 : 0;
  1203. return 0;
  1204. }
  1205. /** Free all storage held by <b>state</b>. */
  1206. void
  1207. or_handshake_state_free(or_handshake_state_t *state)
  1208. {
  1209. if (!state)
  1210. return;
  1211. memset(state, 0xBE, sizeof(or_handshake_state_t));
  1212. tor_free(state);
  1213. }
  1214. /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
  1215. * as appropriate. Called when we are done with all TLS and OR handshaking.
  1216. */
  1217. int
  1218. connection_or_set_state_open(or_connection_t *conn)
  1219. {
  1220. int started_here = connection_or_nonopen_was_started_here(conn);
  1221. time_t now = time(NULL);
  1222. conn->_base.state = OR_CONN_STATE_OPEN;
  1223. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  1224. if (started_here) {
  1225. circuit_build_times_network_is_live(&circ_times);
  1226. rep_hist_note_connect_succeeded(conn->identity_digest, now);
  1227. if (entry_guard_register_connect_status(conn->identity_digest,
  1228. 1, 0, now) < 0) {
  1229. /* Close any circuits pending on this conn. We leave it in state
  1230. * 'open' though, because it didn't actually *fail* -- we just
  1231. * chose not to use it. (Otherwise
  1232. * connection_about_to_close_connection() will call a big pile of
  1233. * functions to indicate we shouldn't try it again.) */
  1234. log_debug(LD_OR, "New entry guard was reachable, but closing this "
  1235. "connection so we can retry the earlier entry guards.");
  1236. circuit_n_conn_done(conn, 0);
  1237. return -1;
  1238. }
  1239. router_set_status(conn->identity_digest, 1);
  1240. } else {
  1241. /* only report it to the geoip module if it's not a known router */
  1242. if (!router_get_by_id_digest(conn->identity_digest)) {
  1243. if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
  1244. /*XXXX IP6 support ipv6 geoip.*/
  1245. uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
  1246. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
  1247. }
  1248. }
  1249. }
  1250. or_handshake_state_free(conn->handshake_state);
  1251. conn->handshake_state = NULL;
  1252. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  1253. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1254. }) ELSE_IF_NO_BUFFEREVENT {
  1255. connection_start_reading(TO_CONN(conn));
  1256. }
  1257. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  1258. return 0;
  1259. }
  1260. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  1261. * For cells that use or affect a circuit, this should only be called by
  1262. * connection_or_flush_from_first_active_circuit().
  1263. */
  1264. void
  1265. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  1266. {
  1267. packed_cell_t networkcell;
  1268. tor_assert(cell);
  1269. tor_assert(conn);
  1270. cell_pack(&networkcell, cell);
  1271. connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
  1272. if (cell->command != CELL_PADDING)
  1273. conn->timestamp_last_added_nonpadding = approx_time();
  1274. }
  1275. /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
  1276. * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
  1277. * affect a circuit.
  1278. */
  1279. void
  1280. connection_or_write_var_cell_to_buf(const var_cell_t *cell,
  1281. or_connection_t *conn)
  1282. {
  1283. char hdr[VAR_CELL_HEADER_SIZE];
  1284. tor_assert(cell);
  1285. tor_assert(conn);
  1286. var_cell_pack_header(cell, hdr);
  1287. connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
  1288. connection_write_to_buf((char*)cell->payload,
  1289. cell->payload_len, TO_CONN(conn));
  1290. if (cell->command != CELL_PADDING)
  1291. conn->timestamp_last_added_nonpadding = approx_time();
  1292. }
  1293. /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
  1294. * inbuf. Return values as for fetch_var_cell_from_buf(). */
  1295. static int
  1296. connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
  1297. {
  1298. connection_t *conn = TO_CONN(or_conn);
  1299. IF_HAS_BUFFEREVENT(conn, {
  1300. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  1301. return fetch_var_cell_from_evbuffer(input, out, or_conn->link_proto);
  1302. }) ELSE_IF_NO_BUFFEREVENT {
  1303. return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
  1304. }
  1305. }
  1306. /** Process cells from <b>conn</b>'s inbuf.
  1307. *
  1308. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  1309. * and hand it to command_process_cell().
  1310. *
  1311. * Always return 0.
  1312. */
  1313. static int
  1314. connection_or_process_cells_from_inbuf(or_connection_t *conn)
  1315. {
  1316. var_cell_t *var_cell;
  1317. while (1) {
  1318. log_debug(LD_OR,
  1319. "%d: starting, inbuf_datalen %d (%d pending in tls object).",
  1320. conn->_base.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
  1321. tor_tls_get_pending_bytes(conn->tls));
  1322. if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
  1323. if (!var_cell)
  1324. return 0; /* not yet. */
  1325. circuit_build_times_network_is_live(&circ_times);
  1326. command_process_var_cell(var_cell, conn);
  1327. var_cell_free(var_cell);
  1328. } else {
  1329. char buf[CELL_NETWORK_SIZE];
  1330. cell_t cell;
  1331. if (connection_get_inbuf_len(TO_CONN(conn))
  1332. < CELL_NETWORK_SIZE) /* whole response available? */
  1333. return 0; /* not yet */
  1334. circuit_build_times_network_is_live(&circ_times);
  1335. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
  1336. /* retrieve cell info from buf (create the host-order struct from the
  1337. * network-order string) */
  1338. cell_unpack(&cell, buf);
  1339. command_process_cell(&cell, conn);
  1340. }
  1341. }
  1342. }
  1343. /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  1344. * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
  1345. * we may want to propagate reasons from other cells.
  1346. *
  1347. * Return 0.
  1348. */
  1349. int
  1350. connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
  1351. {
  1352. cell_t cell;
  1353. tor_assert(conn);
  1354. memset(&cell, 0, sizeof(cell_t));
  1355. cell.circ_id = circ_id;
  1356. cell.command = CELL_DESTROY;
  1357. cell.payload[0] = (uint8_t) reason;
  1358. log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
  1359. connection_or_write_cell_to_buf(&cell, conn);
  1360. return 0;
  1361. }
  1362. /** Array of recognized link protocol versions. */
  1363. static const uint16_t or_protocol_versions[] = { 1, 2 };
  1364. /** Number of versions in <b>or_protocol_versions</b>. */
  1365. static const int n_or_protocol_versions =
  1366. (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
  1367. /** Return true iff <b>v</b> is a link protocol version that this Tor
  1368. * implementation believes it can support. */
  1369. int
  1370. is_or_protocol_version_known(uint16_t v)
  1371. {
  1372. int i;
  1373. for (i = 0; i < n_or_protocol_versions; ++i) {
  1374. if (or_protocol_versions[i] == v)
  1375. return 1;
  1376. }
  1377. return 0;
  1378. }
  1379. /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
  1380. * link protocol versions that this Tor can support. */
  1381. static int
  1382. connection_or_send_versions(or_connection_t *conn)
  1383. {
  1384. var_cell_t *cell;
  1385. int i;
  1386. tor_assert(conn->handshake_state &&
  1387. !conn->handshake_state->sent_versions_at);
  1388. cell = var_cell_new(n_or_protocol_versions * 2);
  1389. cell->command = CELL_VERSIONS;
  1390. for (i = 0; i < n_or_protocol_versions; ++i) {
  1391. uint16_t v = or_protocol_versions[i];
  1392. set_uint16(cell->payload+(2*i), htons(v));
  1393. }
  1394. connection_or_write_var_cell_to_buf(cell, conn);
  1395. conn->handshake_state->sent_versions_at = time(NULL);
  1396. var_cell_free(cell);
  1397. return 0;
  1398. }
  1399. /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
  1400. * about their address, our address, and the current time. */
  1401. int
  1402. connection_or_send_netinfo(or_connection_t *conn)
  1403. {
  1404. cell_t cell;
  1405. time_t now = time(NULL);
  1406. const routerinfo_t *me;
  1407. int len;
  1408. uint8_t *out;
  1409. memset(&cell, 0, sizeof(cell_t));
  1410. cell.command = CELL_NETINFO;
  1411. /* Timestamp. */
  1412. set_uint32(cell.payload, htonl((uint32_t)now));
  1413. /* Their address. */
  1414. out = cell.payload + 4;
  1415. len = append_address_to_payload(out, &conn->_base.addr);
  1416. if (len<0)
  1417. return -1;
  1418. out += len;
  1419. /* My address. */
  1420. if ((me = router_get_my_routerinfo())) {
  1421. tor_addr_t my_addr;
  1422. *out++ = 1; /* only one address is supported. */
  1423. tor_addr_from_ipv4h(&my_addr, me->addr);
  1424. len = append_address_to_payload(out, &my_addr);
  1425. if (len < 0)
  1426. return -1;
  1427. out += len;
  1428. } else {
  1429. *out++ = 0;
  1430. }
  1431. connection_or_write_cell_to_buf(&cell, conn);
  1432. return 0;
  1433. }