connection_or.c 54 KB

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