connection_or.c 48 KB

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