connection_or.c 47 KB

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