connection_or.c 53 KB

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