connection_or.c 45 KB

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