connection_or.c 47 KB

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