connection_or.c 47 KB

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