connection_or.c 54 KB

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