connection_or.c 49 KB

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