connection_or.c 46 KB

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