connection_or.c 47 KB

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