connection_or.c 47 KB

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