connection_or.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_or.c
  8. * \brief Functions to handle OR connections, TLS handshaking, and
  9. * cells on the network.
  10. **/
  11. #include "or.h"
  12. #include "buffers.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "command.h"
  16. #include "config.h"
  17. #include "connection.h"
  18. #include "connection_or.h"
  19. #include "control.h"
  20. #include "dirserv.h"
  21. #include "geoip.h"
  22. #include "main.h"
  23. #include "networkstatus.h"
  24. #include "nodelist.h"
  25. #include "reasons.h"
  26. #include "relay.h"
  27. #include "rephist.h"
  28. #include "router.h"
  29. #include "routerlist.h"
  30. #ifdef USE_BUFFEREVENTS
  31. #include <event2/bufferevent_ssl.h>
  32. #endif
  33. static int connection_tls_finish_handshake(or_connection_t *conn);
  34. static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
  35. static int connection_or_send_versions(or_connection_t *conn);
  36. static int connection_init_or_handshake_state(or_connection_t *conn,
  37. int started_here);
  38. static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
  39. int started_here,
  40. char *digest_rcvd_out);
  41. static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
  42. #ifdef USE_BUFFEREVENTS
  43. static void connection_or_handle_event_cb(struct bufferevent *bufev,
  44. short event, void *arg);
  45. #include <event2/buffer.h>/*XXXX REMOVE */
  46. #endif
  47. /**************************************************************/
  48. /** Map from identity digest of connected OR or desired OR to a connection_t
  49. * with that identity digest. If there is more than one such connection_t,
  50. * they form a linked list, with next_with_same_id as the next pointer. */
  51. static digestmap_t *orconn_identity_map = NULL;
  52. /** If conn is listed in orconn_identity_map, remove it, and clear
  53. * conn->identity_digest. Otherwise do nothing. */
  54. void
  55. connection_or_remove_from_identity_map(or_connection_t *conn)
  56. {
  57. or_connection_t *tmp;
  58. tor_assert(conn);
  59. if (!orconn_identity_map)
  60. return;
  61. tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
  62. if (!tmp) {
  63. if (!tor_digest_is_zero(conn->identity_digest)) {
  64. log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
  65. "trying to remove it.",
  66. conn->nickname ? conn->nickname : "NULL");
  67. }
  68. return;
  69. }
  70. if (conn == tmp) {
  71. if (conn->next_with_same_id)
  72. digestmap_set(orconn_identity_map, conn->identity_digest,
  73. conn->next_with_same_id);
  74. else
  75. digestmap_remove(orconn_identity_map, conn->identity_digest);
  76. } else {
  77. while (tmp->next_with_same_id) {
  78. if (tmp->next_with_same_id == conn) {
  79. tmp->next_with_same_id = conn->next_with_same_id;
  80. break;
  81. }
  82. tmp = tmp->next_with_same_id;
  83. }
  84. }
  85. memset(conn->identity_digest, 0, DIGEST_LEN);
  86. conn->next_with_same_id = NULL;
  87. }
  88. /** Remove all entries from the identity-to-orconn map, and clear
  89. * all identities in OR conns.*/
  90. void
  91. connection_or_clear_identity_map(void)
  92. {
  93. smartlist_t *conns = get_connection_array();
  94. SMARTLIST_FOREACH(conns, connection_t *, conn,
  95. {
  96. if (conn->type == CONN_TYPE_OR) {
  97. or_connection_t *or_conn = TO_OR_CONN(conn);
  98. memset(or_conn->identity_digest, 0, DIGEST_LEN);
  99. or_conn->next_with_same_id = NULL;
  100. }
  101. });
  102. digestmap_free(orconn_identity_map, NULL);
  103. orconn_identity_map = NULL;
  104. }
  105. /** Change conn->identity_digest to digest, and add conn into
  106. * orconn_digest_map. */
  107. static void
  108. connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
  109. {
  110. or_connection_t *tmp;
  111. tor_assert(conn);
  112. tor_assert(digest);
  113. if (!orconn_identity_map)
  114. orconn_identity_map = digestmap_new();
  115. if (tor_memeq(conn->identity_digest, digest, DIGEST_LEN))
  116. return;
  117. /* If the identity was set previously, remove the old mapping. */
  118. if (! tor_digest_is_zero(conn->identity_digest))
  119. connection_or_remove_from_identity_map(conn);
  120. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  121. /* If we're setting the ID to zero, don't add a mapping. */
  122. if (tor_digest_is_zero(digest))
  123. return;
  124. tmp = digestmap_set(orconn_identity_map, digest, conn);
  125. conn->next_with_same_id = tmp;
  126. #if 1
  127. /* Testing code to check for bugs in representation. */
  128. for (; tmp; tmp = tmp->next_with_same_id) {
  129. tor_assert(tor_memeq(tmp->identity_digest, digest, DIGEST_LEN));
  130. tor_assert(tmp != conn);
  131. }
  132. #endif
  133. }
  134. /**************************************************************/
  135. /** Map from a string describing what a non-open OR connection was doing when
  136. * failed, to an intptr_t describing the count of connections that failed that
  137. * way. Note that the count is stored _as_ the pointer.
  138. */
  139. static strmap_t *broken_connection_counts;
  140. /** If true, do not record information in <b>broken_connection_counts</b>. */
  141. static int disable_broken_connection_counts = 0;
  142. /** Record that an OR connection failed in <b>state</b>. */
  143. static void
  144. note_broken_connection(const char *state)
  145. {
  146. void *ptr;
  147. intptr_t val;
  148. if (disable_broken_connection_counts)
  149. return;
  150. if (!broken_connection_counts)
  151. broken_connection_counts = strmap_new();
  152. ptr = strmap_get(broken_connection_counts, state);
  153. val = (intptr_t)ptr;
  154. val++;
  155. ptr = (void*)val;
  156. strmap_set(broken_connection_counts, state, ptr);
  157. }
  158. /** Forget all recorded states for failed connections. If
  159. * <b>stop_recording</b> is true, don't record any more. */
  160. void
  161. clear_broken_connection_map(int stop_recording)
  162. {
  163. if (broken_connection_counts)
  164. strmap_free(broken_connection_counts, NULL);
  165. broken_connection_counts = NULL;
  166. if (stop_recording)
  167. disable_broken_connection_counts = 1;
  168. }
  169. /** Write a detailed description the state of <b>orconn</b> into the
  170. * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
  171. * only the OR-conn level state but also the TLS state. It's useful for
  172. * diagnosing broken handshakes. */
  173. static void
  174. connection_or_get_state_description(or_connection_t *orconn,
  175. char *buf, size_t buflen)
  176. {
  177. connection_t *conn = TO_CONN(orconn);
  178. const char *conn_state;
  179. char tls_state[256];
  180. tor_assert(conn->type == CONN_TYPE_OR);
  181. conn_state = conn_state_to_string(conn->type, conn->state);
  182. tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
  183. tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
  184. }
  185. /** Record the current state of <b>orconn</b> as the state of a broken
  186. * connection. */
  187. static void
  188. connection_or_note_state_when_broken(or_connection_t *orconn)
  189. {
  190. char buf[256];
  191. if (disable_broken_connection_counts)
  192. return;
  193. connection_or_get_state_description(orconn, buf, sizeof(buf));
  194. log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
  195. note_broken_connection(buf);
  196. }
  197. /** Helper type used to sort connection states and find the most frequent. */
  198. typedef struct broken_state_count_t {
  199. intptr_t count;
  200. const char *state;
  201. } broken_state_count_t;
  202. /** Helper function used to sort broken_state_count_t by frequency. */
  203. static int
  204. broken_state_count_compare(const void **a_ptr, const void **b_ptr)
  205. {
  206. const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
  207. return b->count - a->count;
  208. }
  209. /** Upper limit on the number of different states to report for connection
  210. * failure. */
  211. #define MAX_REASONS_TO_REPORT 10
  212. /** Report a list of the top states for failed OR connections at log level
  213. * <b>severity</b>, in log domain <b>domain</b>. */
  214. void
  215. connection_or_report_broken_states(int severity, int domain)
  216. {
  217. int total = 0;
  218. smartlist_t *items;
  219. if (!broken_connection_counts || disable_broken_connection_counts)
  220. return;
  221. items = smartlist_create();
  222. STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
  223. broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
  224. total += c->count = (intptr_t)countptr;
  225. c->state = state;
  226. smartlist_add(items, c);
  227. } STRMAP_FOREACH_END;
  228. smartlist_sort(items, broken_state_count_compare);
  229. log(severity, domain, "%d connections have failed%s", total,
  230. smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
  231. SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
  232. if (c_sl_idx > MAX_REASONS_TO_REPORT)
  233. break;
  234. log(severity, domain,
  235. " %d connections died in state %s", (int)c->count, c->state);
  236. } SMARTLIST_FOREACH_END(c);
  237. SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
  238. smartlist_free(items);
  239. }
  240. /**************************************************************/
  241. /** Pack the cell_t host-order structure <b>src</b> into network-order
  242. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  243. * wire format.
  244. *
  245. * Note that this function doesn't touch <b>dst</b>-\>next: the caller
  246. * should set it or clear it as appropriate.
  247. */
  248. void
  249. cell_pack(packed_cell_t *dst, const cell_t *src)
  250. {
  251. char *dest = dst->body;
  252. set_uint16(dest, htons(src->circ_id));
  253. *(uint8_t*)(dest+2) = src->command;
  254. memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
  255. }
  256. /** Unpack the network-order buffer <b>src</b> into a host-order
  257. * cell_t structure <b>dest</b>.
  258. */
  259. static void
  260. cell_unpack(cell_t *dest, const char *src)
  261. {
  262. dest->circ_id = ntohs(get_uint16(src));
  263. dest->command = *(uint8_t*)(src+2);
  264. memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
  265. }
  266. /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
  267. * bytes of <b>hdr_out</b>. */
  268. void
  269. var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
  270. {
  271. set_uint16(hdr_out, htons(cell->circ_id));
  272. set_uint8(hdr_out+2, cell->command);
  273. set_uint16(hdr_out+3, htons(cell->payload_len));
  274. }
  275. /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
  276. * payload space. */
  277. var_cell_t *
  278. var_cell_new(uint16_t payload_len)
  279. {
  280. size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
  281. var_cell_t *cell = tor_malloc(size);
  282. cell->payload_len = payload_len;
  283. cell->command = 0;
  284. cell->circ_id = 0;
  285. return cell;
  286. }
  287. /** Release all space held by <b>cell</b>. */
  288. void
  289. var_cell_free(var_cell_t *cell)
  290. {
  291. tor_free(cell);
  292. }
  293. /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
  294. int
  295. connection_or_reached_eof(or_connection_t *conn)
  296. {
  297. log_info(LD_OR,"OR connection reached EOF. Closing.");
  298. connection_mark_for_close(TO_CONN(conn));
  299. return 0;
  300. }
  301. /** Handle any new bytes that have come in on connection <b>conn</b>.
  302. * If conn is in 'open' state, hand it to
  303. * connection_or_process_cells_from_inbuf()
  304. * (else do nothing).
  305. */
  306. int
  307. connection_or_process_inbuf(or_connection_t *conn)
  308. {
  309. int ret;
  310. tor_assert(conn);
  311. switch (conn->_base.state) {
  312. case OR_CONN_STATE_PROXY_HANDSHAKING:
  313. ret = connection_read_proxy_handshake(TO_CONN(conn));
  314. /* start TLS after handshake completion, or deal with error */
  315. if (ret == 1) {
  316. tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
  317. if (connection_tls_start_handshake(conn, 0) < 0)
  318. ret = -1;
  319. }
  320. if (ret < 0) {
  321. connection_mark_for_close(TO_CONN(conn));
  322. }
  323. return ret;
  324. #ifdef USE_BUFFEREVENTS
  325. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  326. if (tor_tls_server_got_renegotiate(conn->tls))
  327. connection_or_tls_renegotiated_cb(conn->tls, conn);
  328. if (conn->_base.marked_for_close)
  329. return 0;
  330. /* fall through. */
  331. #endif
  332. case OR_CONN_STATE_OPEN:
  333. case OR_CONN_STATE_OR_HANDSHAKING:
  334. return connection_or_process_cells_from_inbuf(conn);
  335. default:
  336. return 0; /* don't do anything */
  337. }
  338. }
  339. /** When adding cells to an OR connection's outbuf, keep adding until the
  340. * outbuf is at least this long, or we run out of cells. */
  341. #define OR_CONN_HIGHWATER (32*1024)
  342. /** Add cells to an OR connection's outbuf whenever the outbuf's data length
  343. * drops below this size. */
  344. #define OR_CONN_LOWWATER (16*1024)
  345. /** Called whenever we have flushed some data on an or_conn: add more data
  346. * from active circuits. */
  347. int
  348. connection_or_flushed_some(or_connection_t *conn)
  349. {
  350. size_t datalen = connection_get_outbuf_len(TO_CONN(conn));
  351. /* If we're under the low water mark, add cells until we're just over the
  352. * high water mark. */
  353. if (datalen < OR_CONN_LOWWATER) {
  354. ssize_t n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, CELL_NETWORK_SIZE);
  355. time_t now = approx_time();
  356. while (conn->active_circuits && n > 0) {
  357. int flushed;
  358. flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
  359. n -= flushed;
  360. }
  361. }
  362. return 0;
  363. }
  364. /** Connection <b>conn</b> has finished writing and has no bytes left on
  365. * its outbuf.
  366. *
  367. * Otherwise it's in state "open": stop writing and return.
  368. *
  369. * If <b>conn</b> is broken, mark it for close and return -1, else
  370. * return 0.
  371. */
  372. int
  373. connection_or_finished_flushing(or_connection_t *conn)
  374. {
  375. tor_assert(conn);
  376. assert_connection_ok(TO_CONN(conn),0);
  377. switch (conn->_base.state) {
  378. case OR_CONN_STATE_PROXY_HANDSHAKING:
  379. case OR_CONN_STATE_OPEN:
  380. case OR_CONN_STATE_OR_HANDSHAKING:
  381. break;
  382. default:
  383. log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
  384. tor_fragile_assert();
  385. return -1;
  386. }
  387. return 0;
  388. }
  389. /** Connected handler for OR connections: begin the TLS handshake.
  390. */
  391. int
  392. connection_or_finished_connecting(or_connection_t *or_conn)
  393. {
  394. const int proxy_type = or_conn->proxy_type;
  395. connection_t *conn;
  396. tor_assert(or_conn);
  397. conn = TO_CONN(or_conn);
  398. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  399. log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
  400. conn->address,conn->port);
  401. control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
  402. if (proxy_type != PROXY_NONE) {
  403. /* start proxy handshake */
  404. if (connection_proxy_connect(conn, proxy_type) < 0) {
  405. connection_mark_for_close(conn);
  406. return -1;
  407. }
  408. connection_start_reading(conn);
  409. conn->state = OR_CONN_STATE_PROXY_HANDSHAKING;
  410. return 0;
  411. }
  412. if (connection_tls_start_handshake(or_conn, 0) < 0) {
  413. /* TLS handshaking error of some kind. */
  414. connection_mark_for_close(conn);
  415. return -1;
  416. }
  417. return 0;
  418. }
  419. /* Called when we're about to finally unlink and free an OR connection:
  420. * perform necessary accounting and cleanup */
  421. void
  422. connection_or_about_to_close(or_connection_t *or_conn)
  423. {
  424. time_t now = time(NULL);
  425. connection_t *conn = TO_CONN(or_conn);
  426. /* Remember why we're closing this connection. */
  427. if (conn->state != OR_CONN_STATE_OPEN) {
  428. /* Inform any pending (not attached) circs that they should
  429. * give up. */
  430. circuit_n_conn_done(TO_OR_CONN(conn), 0);
  431. /* now mark things down as needed */
  432. if (connection_or_nonopen_was_started_here(or_conn)) {
  433. const or_options_t *options = get_options();
  434. connection_or_note_state_when_broken(or_conn);
  435. rep_hist_note_connect_failed(or_conn->identity_digest, now);
  436. entry_guard_register_connect_status(or_conn->identity_digest,0,
  437. !options->HTTPSProxy, now);
  438. if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
  439. int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
  440. control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
  441. reason);
  442. if (!authdir_mode_tests_reachability(options))
  443. control_event_bootstrap_problem(
  444. orconn_end_reason_to_control_string(reason), reason);
  445. }
  446. }
  447. } else if (conn->hold_open_until_flushed) {
  448. /* We only set hold_open_until_flushed when we're intentionally
  449. * closing a connection. */
  450. rep_hist_note_disconnect(or_conn->identity_digest, now);
  451. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  452. tls_error_to_orconn_end_reason(or_conn->tls_error));
  453. } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
  454. rep_hist_note_connection_died(or_conn->identity_digest, now);
  455. control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
  456. tls_error_to_orconn_end_reason(or_conn->tls_error));
  457. }
  458. /* Now close all the attached circuits on it. */
  459. circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
  460. END_CIRC_REASON_OR_CONN_CLOSED);
  461. }
  462. /** Return 1 if identity digest <b>id_digest</b> is known to be a
  463. * currently or recently running relay. Otherwise return 0. */
  464. int
  465. connection_or_digest_is_known_relay(const char *id_digest)
  466. {
  467. if (router_get_consensus_status_by_id(id_digest))
  468. return 1; /* It's in the consensus: "yes" */
  469. if (router_get_by_id_digest(id_digest))
  470. return 1; /* Not in the consensus, but we have a descriptor for
  471. * it. Probably it was in a recent consensus. "Yes". */
  472. return 0;
  473. }
  474. /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
  475. * relay, we will rely on the global read and write buckets, so give it
  476. * per-conn limits that are big enough they'll never matter. But if it's
  477. * not a known relay, first check if we set PerConnBwRate/Burst, then
  478. * check if the consensus sets them, else default to 'big enough'.
  479. *
  480. * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
  481. * clip the bucket if it happens to be <em>too</em> full.
  482. */
  483. static void
  484. connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
  485. const or_options_t *options)
  486. {
  487. int rate, burst; /* per-connection rate limiting params */
  488. if (connection_or_digest_is_known_relay(conn->identity_digest)) {
  489. /* It's in the consensus, or we have a descriptor for it meaning it
  490. * was probably in a recent consensus. It's a recognized relay:
  491. * give it full bandwidth. */
  492. rate = (int)options->BandwidthRate;
  493. burst = (int)options->BandwidthBurst;
  494. } else {
  495. /* Not a recognized relay. Squeeze it down based on the suggested
  496. * bandwidth parameters in the consensus, but allow local config
  497. * options to override. */
  498. rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
  499. networkstatus_get_param(NULL, "perconnbwrate",
  500. (int)options->BandwidthRate, 1, INT32_MAX);
  501. burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
  502. networkstatus_get_param(NULL, "perconnbwburst",
  503. (int)options->BandwidthBurst, 1, INT32_MAX);
  504. }
  505. conn->bandwidthrate = rate;
  506. conn->bandwidthburst = burst;
  507. #ifdef USE_BUFFEREVENTS
  508. {
  509. const struct timeval *tick = tor_libevent_get_one_tick_timeout();
  510. struct ev_token_bucket_cfg *cfg, *old_cfg;
  511. int rate_per_tick = rate / TOR_LIBEVENT_TICKS_PER_SECOND;
  512. cfg = ev_token_bucket_cfg_new(rate_per_tick, burst, rate_per_tick,
  513. burst, tick);
  514. old_cfg = conn->bucket_cfg;
  515. if (conn->_base.bufev)
  516. bufferevent_set_rate_limit(conn->_base.bufev, cfg);
  517. if (old_cfg)
  518. ev_token_bucket_cfg_free(old_cfg);
  519. conn->bucket_cfg = cfg;
  520. (void) reset; /* No way to do this with libevent yet. */
  521. }
  522. #else
  523. if (reset) { /* set up the token buckets to be full */
  524. conn->read_bucket = conn->write_bucket = burst;
  525. return;
  526. }
  527. /* If the new token bucket is smaller, take out the extra tokens.
  528. * (If it's larger, don't -- the buckets can grow to reach the cap.) */
  529. if (conn->read_bucket > burst)
  530. conn->read_bucket = burst;
  531. if (conn->write_bucket > burst)
  532. conn->write_bucket = burst;
  533. #endif
  534. }
  535. /** Either our set of relays or our per-conn rate limits have changed.
  536. * Go through all the OR connections and update their token buckets to make
  537. * sure they don't exceed their maximum values. */
  538. void
  539. connection_or_update_token_buckets(smartlist_t *conns,
  540. const or_options_t *options)
  541. {
  542. SMARTLIST_FOREACH(conns, connection_t *, conn,
  543. {
  544. if (connection_speaks_cells(conn))
  545. connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
  546. });
  547. }
  548. /** If we don't necessarily know the router we're connecting to, but we
  549. * have an addr/port/id_digest, then fill in as much as we can. Start
  550. * by checking to see if this describes a router we know. */
  551. static void
  552. connection_or_init_conn_from_address(or_connection_t *conn,
  553. const tor_addr_t *addr, uint16_t port,
  554. const char *id_digest,
  555. int started_here)
  556. {
  557. const node_t *r = node_get_by_id(id_digest);
  558. connection_or_set_identity_digest(conn, id_digest);
  559. connection_or_update_token_buckets_helper(conn, 1, get_options());
  560. conn->_base.port = port;
  561. tor_addr_copy(&conn->_base.addr, addr);
  562. tor_addr_copy(&conn->real_addr, addr);
  563. if (r) {
  564. tor_addr_t node_addr;
  565. node_get_addr(r, &node_addr);
  566. /* XXXX proposal 118 will make this more complex. */
  567. if (tor_addr_eq(&conn->_base.addr, &node_addr))
  568. conn->is_canonical = 1;
  569. if (!started_here) {
  570. /* Override the addr/port, so our log messages will make sense.
  571. * This is dangerous, since if we ever try looking up a conn by
  572. * its actual addr/port, we won't remember. Careful! */
  573. /* XXXX arma: this is stupid, and it's the reason we need real_addr
  574. * to track is_canonical properly. What requires it? */
  575. /* XXXX <arma> i believe the reason we did this, originally, is because
  576. * we wanted to log what OR a connection was to, and if we logged the
  577. * right IP address and port 56244, that wouldn't be as helpful. now we
  578. * log the "right" port too, so we know if it's moria1 or moria2.
  579. */
  580. tor_addr_copy(&conn->_base.addr, &node_addr);
  581. conn->_base.port = node_get_orport(r);
  582. }
  583. conn->nickname = tor_strdup(node_get_nickname(r));
  584. tor_free(conn->_base.address);
  585. conn->_base.address = tor_dup_addr(&node_addr);
  586. } else {
  587. const char *n;
  588. /* If we're an authoritative directory server, we may know a
  589. * nickname for this router. */
  590. n = dirserv_get_nickname_by_digest(id_digest);
  591. if (n) {
  592. conn->nickname = tor_strdup(n);
  593. } else {
  594. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  595. conn->nickname[0] = '$';
  596. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  597. conn->identity_digest, DIGEST_LEN);
  598. }
  599. tor_free(conn->_base.address);
  600. conn->_base.address = tor_dup_addr(addr);
  601. }
  602. }
  603. /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
  604. *
  605. * A more canonical connection is always better than a less canonical
  606. * connection. That aside, a connection is better if it has circuits and the
  607. * other does not, or if it was created more recently.
  608. *
  609. * Requires that both input connections are open; not is_bad_for_new_circs,
  610. * and not impossibly non-canonical.
  611. *
  612. * If <b>forgive_new_connections</b> is true, then we do not call
  613. * <b>a</b>better than <b>b</b> simply because b has no circuits,
  614. * unless b is also relatively old.
  615. */
  616. static int
  617. connection_or_is_better(time_t now,
  618. const or_connection_t *a,
  619. const or_connection_t *b,
  620. int forgive_new_connections)
  621. {
  622. int newer;
  623. /** Do not definitively deprecate a new connection with no circuits on it
  624. * until this much time has passed. */
  625. #define NEW_CONN_GRACE_PERIOD (15*60)
  626. if (b->is_canonical && !a->is_canonical)
  627. return 0; /* A canonical connection is better than a non-canonical
  628. * one, no matter how new it is or which has circuits. */
  629. newer = b->_base.timestamp_created < a->_base.timestamp_created;
  630. if (
  631. /* We prefer canonical connections regardless of newness. */
  632. (!b->is_canonical && a->is_canonical) ||
  633. /* If both have circuits we prefer the newer: */
  634. (b->n_circuits && a->n_circuits && newer) ||
  635. /* If neither has circuits we prefer the newer: */
  636. (!b->n_circuits && !a->n_circuits && newer))
  637. return 1;
  638. /* If one has no circuits and the other does... */
  639. if (!b->n_circuits && a->n_circuits) {
  640. /* Then it's bad, unless it's in its grace period and we're forgiving. */
  641. if (forgive_new_connections &&
  642. now < b->_base.timestamp_created + NEW_CONN_GRACE_PERIOD)
  643. return 0;
  644. else
  645. return 1;
  646. }
  647. return 0;
  648. }
  649. /** Return the OR connection we should use to extend a circuit to the router
  650. * whose identity is <b>digest</b>, and whose address we believe (or have been
  651. * told in an extend cell) is <b>target_addr</b>. If there is no good
  652. * connection, set *<b>msg_out</b> to a message describing the connection's
  653. * state and our next action, and set <b>launch_out</b> to a boolean for
  654. * whether we should launch a new connection or not.
  655. */
  656. or_connection_t *
  657. connection_or_get_for_extend(const char *digest,
  658. const tor_addr_t *target_addr,
  659. const char **msg_out,
  660. int *launch_out)
  661. {
  662. or_connection_t *conn, *best=NULL;
  663. int n_inprogress_goodaddr = 0, n_old = 0, n_noncanonical = 0, n_possible = 0;
  664. time_t now = approx_time();
  665. tor_assert(msg_out);
  666. tor_assert(launch_out);
  667. if (!orconn_identity_map) {
  668. *msg_out = "Router not connected (nothing is). Connecting.";
  669. *launch_out = 1;
  670. return NULL;
  671. }
  672. conn = digestmap_get(orconn_identity_map, digest);
  673. for (; conn; conn = conn->next_with_same_id) {
  674. tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
  675. tor_assert(conn->_base.type == CONN_TYPE_OR);
  676. tor_assert(tor_memeq(conn->identity_digest, digest, DIGEST_LEN));
  677. if (conn->_base.marked_for_close)
  678. continue;
  679. /* Never return a non-open connection. */
  680. if (conn->_base.state != OR_CONN_STATE_OPEN) {
  681. /* If the address matches, don't launch a new connection for this
  682. * circuit. */
  683. if (!tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT))
  684. ++n_inprogress_goodaddr;
  685. continue;
  686. }
  687. /* Never return a connection that shouldn't be used for circs. */
  688. if (conn->is_bad_for_new_circs) {
  689. ++n_old;
  690. continue;
  691. }
  692. /* Never return a non-canonical connection using a recent link protocol
  693. * if the address is not what we wanted.
  694. *
  695. * (For old link protocols, we can't rely on is_canonical getting
  696. * set properly if we're talking to the right address, since we might
  697. * have an out-of-date descriptor, and we will get no NETINFO cell to
  698. * tell us about the right address.) */
  699. if (!conn->is_canonical && conn->link_proto >= 2 &&
  700. tor_addr_compare(&conn->real_addr, target_addr, CMP_EXACT)) {
  701. ++n_noncanonical;
  702. continue;
  703. }
  704. ++n_possible;
  705. if (!best) {
  706. best = conn; /* If we have no 'best' so far, this one is good enough. */
  707. continue;
  708. }
  709. if (connection_or_is_better(now, conn, best, 0))
  710. best = conn;
  711. }
  712. if (best) {
  713. *msg_out = "Connection is fine; using it.";
  714. *launch_out = 0;
  715. return best;
  716. } else if (n_inprogress_goodaddr) {
  717. *msg_out = "Connection in progress; waiting.";
  718. *launch_out = 0;
  719. return NULL;
  720. } else if (n_old || n_noncanonical) {
  721. *msg_out = "Connections all too old, or too non-canonical. "
  722. " Launching a new one.";
  723. *launch_out = 1;
  724. return NULL;
  725. } else {
  726. *msg_out = "Not connected. Connecting.";
  727. *launch_out = 1;
  728. return NULL;
  729. }
  730. }
  731. /** How old do we let a connection to an OR get before deciding it's
  732. * too old for new circuits? */
  733. #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
  734. /** Given the head of the linked list for all the or_connections with a given
  735. * identity, set elements of that list as is_bad_for_new_circs as
  736. * appropriate. Helper for connection_or_set_bad_connections().
  737. *
  738. * Specifically, we set the is_bad_for_new_circs flag on:
  739. * - all connections if <b>force</b> is true.
  740. * - all connections that are too old.
  741. * - all open non-canonical connections for which a canonical connection
  742. * exists to the same router.
  743. * - all open canonical connections for which a 'better' canonical
  744. * connection exists to the same router.
  745. * - all open non-canonical connections for which a 'better' non-canonical
  746. * connection exists to the same router at the same address.
  747. *
  748. * See connection_or_is_better() for our idea of what makes one OR connection
  749. * better than another.
  750. */
  751. static void
  752. connection_or_group_set_badness(or_connection_t *head, int force)
  753. {
  754. or_connection_t *or_conn = NULL, *best = NULL;
  755. int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
  756. time_t now = time(NULL);
  757. /* Pass 1: expire everything that's old, and see what the status of
  758. * everything else is. */
  759. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  760. if (or_conn->_base.marked_for_close ||
  761. or_conn->is_bad_for_new_circs)
  762. continue;
  763. if (force ||
  764. or_conn->_base.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
  765. < now) {
  766. log_info(LD_OR,
  767. "Marking OR conn to %s:%d as too old for new circuits "
  768. "(fd %d, %d secs old).",
  769. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  770. (int)(now - or_conn->_base.timestamp_created));
  771. or_conn->is_bad_for_new_circs = 1;
  772. }
  773. if (or_conn->is_bad_for_new_circs) {
  774. ++n_old;
  775. } else if (or_conn->_base.state != OR_CONN_STATE_OPEN) {
  776. ++n_inprogress;
  777. } else if (or_conn->is_canonical) {
  778. ++n_canonical;
  779. } else {
  780. ++n_other;
  781. }
  782. }
  783. /* Pass 2: We know how about how good the best connection is.
  784. * expire everything that's worse, and find the very best if we can. */
  785. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  786. if (or_conn->_base.marked_for_close ||
  787. or_conn->is_bad_for_new_circs)
  788. continue; /* This one doesn't need to be marked bad. */
  789. if (or_conn->_base.state != OR_CONN_STATE_OPEN)
  790. continue; /* Don't mark anything bad until we have seen what happens
  791. * when the connection finishes. */
  792. if (n_canonical && !or_conn->is_canonical) {
  793. /* We have at least one open canonical connection to this router,
  794. * and this one is open but not canonical. Mark it bad. */
  795. log_info(LD_OR,
  796. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  797. "(fd %d, %d secs old). It is not canonical, and we have "
  798. "another connection to that OR that is.",
  799. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  800. (int)(now - or_conn->_base.timestamp_created));
  801. or_conn->is_bad_for_new_circs = 1;
  802. continue;
  803. }
  804. if (!best || connection_or_is_better(now, or_conn, best, 0))
  805. best = or_conn;
  806. }
  807. if (!best)
  808. return;
  809. /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
  810. * every other open connection. If it's non-canonical, mark as bad
  811. * every other open connection to the same address.
  812. *
  813. * XXXX This isn't optimal; if we have connections to an OR at multiple
  814. * addresses, we'd like to pick the best _for each address_, and mark as
  815. * bad every open connection that isn't best for its address. But this
  816. * can only occur in cases where the other OR is old (so we have no
  817. * canonical connection to it), or where all the connections to the OR are
  818. * at noncanonical addresses and we have no good direct connection (which
  819. * means we aren't at risk of attaching circuits to it anyway). As
  820. * 0.1.2.x dies out, the first case will go away, and the second one is
  821. * "mostly harmless", so a fix can wait until somebody is bored.
  822. */
  823. for (or_conn = head; or_conn; or_conn = or_conn->next_with_same_id) {
  824. if (or_conn->_base.marked_for_close ||
  825. or_conn->is_bad_for_new_circs ||
  826. or_conn->_base.state != OR_CONN_STATE_OPEN)
  827. continue;
  828. if (or_conn != best && connection_or_is_better(now, best, or_conn, 1)) {
  829. /* This isn't the best conn, _and_ the best conn is better than it,
  830. even when we're being forgiving. */
  831. if (best->is_canonical) {
  832. log_info(LD_OR,
  833. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  834. "(fd %d, %d secs old). We have a better canonical one "
  835. "(fd %d; %d secs old).",
  836. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  837. (int)(now - or_conn->_base.timestamp_created),
  838. best->_base.s, (int)(now - best->_base.timestamp_created));
  839. or_conn->is_bad_for_new_circs = 1;
  840. } else if (!tor_addr_compare(&or_conn->real_addr,
  841. &best->real_addr, CMP_EXACT)) {
  842. log_info(LD_OR,
  843. "Marking OR conn to %s:%d as unsuitable for new circuits: "
  844. "(fd %d, %d secs old). We have a better one with the "
  845. "same address (fd %d; %d secs old).",
  846. or_conn->_base.address, or_conn->_base.port, or_conn->_base.s,
  847. (int)(now - or_conn->_base.timestamp_created),
  848. best->_base.s, (int)(now - best->_base.timestamp_created));
  849. or_conn->is_bad_for_new_circs = 1;
  850. }
  851. }
  852. }
  853. }
  854. /** Go through all the OR connections (or if <b>digest</b> is non-NULL, just
  855. * the OR connections with that digest), and set the is_bad_for_new_circs
  856. * flag based on the rules in connection_or_group_set_badness() (or just
  857. * always set it if <b>force</b> is true).
  858. */
  859. void
  860. connection_or_set_bad_connections(const char *digest, int force)
  861. {
  862. if (!orconn_identity_map)
  863. return;
  864. DIGESTMAP_FOREACH(orconn_identity_map, identity, or_connection_t *, conn) {
  865. if (!digest || tor_memeq(digest, conn->identity_digest, DIGEST_LEN))
  866. connection_or_group_set_badness(conn, force);
  867. } DIGESTMAP_FOREACH_END;
  868. }
  869. /** <b>conn</b> is in the 'connecting' state, and it failed to complete
  870. * a TCP connection. Send notifications appropriately.
  871. *
  872. * <b>reason</b> specifies the or_conn_end_reason for the failure;
  873. * <b>msg</b> specifies the strerror-style error message.
  874. */
  875. void
  876. connection_or_connect_failed(or_connection_t *conn,
  877. int reason, const char *msg)
  878. {
  879. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
  880. if (!authdir_mode_tests_reachability(get_options()))
  881. control_event_bootstrap_problem(msg, reason);
  882. }
  883. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  884. * handshake with an OR with identity digest <b>id_digest</b>.
  885. *
  886. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  887. * return that connection. If the connect() is in progress, set the
  888. * new conn's state to 'connecting' and return it. If connect() succeeds,
  889. * call connection_tls_start_handshake() on it.
  890. *
  891. * This function is called from router_retry_connections(), for
  892. * ORs connecting to ORs, and circuit_establish_circuit(), for
  893. * OPs connecting to ORs.
  894. *
  895. * Return the launched conn, or NULL if it failed.
  896. */
  897. or_connection_t *
  898. connection_or_connect(const tor_addr_t *_addr, uint16_t port,
  899. const char *id_digest)
  900. {
  901. or_connection_t *conn;
  902. const or_options_t *options = get_options();
  903. int socket_error = 0;
  904. tor_addr_t addr;
  905. int r;
  906. tor_addr_t proxy_addr;
  907. uint16_t proxy_port;
  908. int proxy_type;
  909. tor_assert(_addr);
  910. tor_assert(id_digest);
  911. tor_addr_copy(&addr, _addr);
  912. if (server_mode(options) && router_digest_is_me(id_digest)) {
  913. log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
  914. return NULL;
  915. }
  916. conn = or_connection_new(AF_INET);
  917. /* set up conn so it's got all the data we need to remember */
  918. connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
  919. conn->_base.state = OR_CONN_STATE_CONNECTING;
  920. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
  921. /* If we are using a proxy server, find it and use it. */
  922. r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
  923. if (r == 0) {
  924. conn->proxy_type = proxy_type;
  925. if (proxy_type != PROXY_NONE) {
  926. tor_addr_copy(&addr, &proxy_addr);
  927. port = proxy_port;
  928. conn->_base.proxy_state = PROXY_INFANT;
  929. }
  930. } else {
  931. log_warn(LD_GENERAL, "Tried to connect through proxy, but proxy address "
  932. "could not be found.");
  933. connection_free(TO_CONN(conn));
  934. return NULL;
  935. }
  936. switch (connection_connect(TO_CONN(conn), conn->_base.address,
  937. &addr, port, &socket_error)) {
  938. case -1:
  939. /* If the connection failed immediately, and we're using
  940. * a proxy, our proxy is down. Don't blame the Tor server. */
  941. if (conn->_base.proxy_state == PROXY_INFANT)
  942. entry_guard_register_connect_status(conn->identity_digest,
  943. 0, 1, time(NULL));
  944. connection_or_connect_failed(conn,
  945. errno_to_orconn_end_reason(socket_error),
  946. tor_socket_strerror(socket_error));
  947. connection_free(TO_CONN(conn));
  948. return NULL;
  949. case 0:
  950. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  951. /* writable indicates finish, readable indicates broken link,
  952. error indicates broken link on windows */
  953. return conn;
  954. /* case 1: fall through */
  955. }
  956. if (connection_or_finished_connecting(conn) < 0) {
  957. /* already marked for close */
  958. return NULL;
  959. }
  960. return conn;
  961. }
  962. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  963. * we initiated the connection, else it's 1.
  964. *
  965. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
  966. * pass <b>conn</b> to connection_tls_continue_handshake().
  967. *
  968. * Return -1 if <b>conn</b> is broken, else return 0.
  969. */
  970. int
  971. connection_tls_start_handshake(or_connection_t *conn, int receiving)
  972. {
  973. conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
  974. tor_assert(!conn->tls);
  975. conn->tls = tor_tls_new(conn->_base.s, receiving);
  976. tor_tls_set_logged_address(conn->tls, // XXX client and relay?
  977. escaped_safe_str(conn->_base.address));
  978. if (!conn->tls) {
  979. log_warn(LD_BUG,"tor_tls_new failed. Closing.");
  980. return -1;
  981. }
  982. #ifdef USE_BUFFEREVENTS
  983. if (connection_type_uses_bufferevent(TO_CONN(conn))) {
  984. const int filtering = get_options()->_UseFilteringSSLBufferevents;
  985. struct bufferevent *b =
  986. tor_tls_init_bufferevent(conn->tls, conn->_base.bufev, conn->_base.s,
  987. receiving, filtering);
  988. if (!b) {
  989. log_warn(LD_BUG,"tor_tls_init_bufferevent failed. Closing.");
  990. return -1;
  991. }
  992. conn->_base.bufev = b;
  993. if (conn->bucket_cfg)
  994. bufferevent_set_rate_limit(conn->_base.bufev, conn->bucket_cfg);
  995. connection_enable_rate_limiting(TO_CONN(conn));
  996. connection_configure_bufferevent_callbacks(TO_CONN(conn));
  997. bufferevent_setcb(b,
  998. connection_handle_read_cb,
  999. connection_handle_write_cb,
  1000. connection_or_handle_event_cb,/* overriding this one*/
  1001. TO_CONN(conn));
  1002. }
  1003. #endif
  1004. connection_start_reading(TO_CONN(conn));
  1005. log_debug(LD_HANDSHAKE,"starting TLS handshake on fd %d", conn->_base.s);
  1006. note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
  1007. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  1008. /* ???? */;
  1009. }) ELSE_IF_NO_BUFFEREVENT {
  1010. if (connection_tls_continue_handshake(conn) < 0)
  1011. return -1;
  1012. }
  1013. return 0;
  1014. }
  1015. /** Invoked on the server side from inside tor_tls_read() when the server
  1016. * gets a successful TLS renegotiation from the client. */
  1017. static void
  1018. connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
  1019. {
  1020. or_connection_t *conn = _conn;
  1021. (void)tls;
  1022. /* Don't invoke this again. */
  1023. tor_tls_set_renegotiate_callback(tls, NULL, NULL);
  1024. tor_tls_block_renegotiation(tls);
  1025. if (connection_tls_finish_handshake(conn) < 0) {
  1026. /* XXXX_TLS double-check that it's ok to do this from inside read. */
  1027. /* XXXX_TLS double-check that this verifies certificates. */
  1028. connection_mark_for_close(TO_CONN(conn));
  1029. }
  1030. }
  1031. /** Move forward with the tls handshake. If it finishes, hand
  1032. * <b>conn</b> to connection_tls_finish_handshake().
  1033. *
  1034. * Return -1 if <b>conn</b> is broken, else return 0.
  1035. */
  1036. int
  1037. connection_tls_continue_handshake(or_connection_t *conn)
  1038. {
  1039. int result;
  1040. check_no_tls_errors();
  1041. again:
  1042. if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  1043. // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
  1044. result = tor_tls_renegotiate(conn->tls);
  1045. // log_notice(LD_OR, "Result: %d", result);
  1046. } else {
  1047. tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
  1048. // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
  1049. result = tor_tls_handshake(conn->tls);
  1050. // log_notice(LD_OR, "Result: %d", result);
  1051. }
  1052. switch (result) {
  1053. CASE_TOR_TLS_ERROR_ANY:
  1054. log_info(LD_OR,"tls error [%s]. breaking connection.",
  1055. tor_tls_err_to_string(result));
  1056. return -1;
  1057. case TOR_TLS_DONE:
  1058. if (! tor_tls_used_v1_handshake(conn->tls)) {
  1059. if (!tor_tls_is_server(conn->tls)) {
  1060. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  1061. log_debug(LD_OR, "Done with initial SSL handshake (client-side). "
  1062. "Requesting renegotiation.");
  1063. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  1064. goto again;
  1065. }
  1066. // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
  1067. } else {
  1068. /* improved handshake, but not a client. */
  1069. log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
  1070. "Expecting renegotiation.");
  1071. tor_tls_set_renegotiate_callback(conn->tls,
  1072. connection_or_tls_renegotiated_cb,
  1073. conn);
  1074. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  1075. connection_stop_writing(TO_CONN(conn));
  1076. connection_start_reading(TO_CONN(conn));
  1077. return 0;
  1078. }
  1079. }
  1080. return connection_tls_finish_handshake(conn);
  1081. case TOR_TLS_WANTWRITE:
  1082. connection_start_writing(TO_CONN(conn));
  1083. log_debug(LD_OR,"wanted write");
  1084. return 0;
  1085. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  1086. log_debug(LD_OR,"wanted read");
  1087. return 0;
  1088. case TOR_TLS_CLOSE:
  1089. log_info(LD_OR,"tls closed. breaking connection.");
  1090. return -1;
  1091. }
  1092. return 0;
  1093. }
  1094. #ifdef USE_BUFFEREVENTS
  1095. static void
  1096. connection_or_handle_event_cb(struct bufferevent *bufev, short event,
  1097. void *arg)
  1098. {
  1099. struct or_connection_t *conn = TO_OR_CONN(arg);
  1100. /* XXXX cut-and-paste code; should become a function. */
  1101. if (event & BEV_EVENT_CONNECTED) {
  1102. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  1103. if (tor_tls_finish_handshake(conn->tls) < 0) {
  1104. log_warn(LD_OR, "Problem finishing handshake");
  1105. connection_mark_for_close(TO_CONN(conn));
  1106. return;
  1107. }
  1108. }
  1109. if (! tor_tls_used_v1_handshake(conn->tls)) {
  1110. if (!tor_tls_is_server(conn->tls)) {
  1111. if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
  1112. conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
  1113. tor_tls_unblock_renegotiation(conn->tls);
  1114. if (bufferevent_ssl_renegotiate(conn->_base.bufev)<0) {
  1115. log_warn(LD_OR, "Start_renegotiating went badly.");
  1116. connection_mark_for_close(TO_CONN(conn));
  1117. }
  1118. tor_tls_unblock_renegotiation(conn->tls);
  1119. return; /* ???? */
  1120. }
  1121. } else if (tor_tls_get_num_server_handshakes(conn->tls) == 1) {
  1122. /* improved handshake, as a server. Only got one handshake, so
  1123. * wait for the next one. */
  1124. tor_tls_set_renegotiate_callback(conn->tls,
  1125. connection_or_tls_renegotiated_cb,
  1126. conn);
  1127. conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
  1128. /* return 0; */
  1129. return; /* ???? */
  1130. } else {
  1131. const int handshakes = tor_tls_get_num_server_handshakes(conn->tls);
  1132. tor_assert(handshakes >= 2);
  1133. if (handshakes == 2) {
  1134. /* improved handshake, as a server. Two handshakes happened already,
  1135. * so we treat renegotiation as done.
  1136. */
  1137. connection_or_tls_renegotiated_cb(conn->tls, conn);
  1138. } else {
  1139. log_warn(LD_OR, "More than two handshakes done on connection. "
  1140. "Closing.");
  1141. connection_mark_for_close(TO_CONN(conn));
  1142. }
  1143. return;
  1144. }
  1145. }
  1146. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1147. if (connection_tls_finish_handshake(conn) < 0)
  1148. connection_mark_for_close(TO_CONN(conn)); /* ???? */
  1149. return;
  1150. }
  1151. if (event & BEV_EVENT_ERROR) {
  1152. unsigned long err;
  1153. while ((err = bufferevent_get_openssl_error(bufev))) {
  1154. tor_tls_log_one_error(conn->tls, err, LOG_WARN, LD_OR,
  1155. "handshaking (with bufferevent)");
  1156. }
  1157. }
  1158. connection_handle_event_cb(bufev, event, arg);
  1159. }
  1160. #endif
  1161. /** Return 1 if we initiated this connection, or 0 if it started
  1162. * out as an incoming connection.
  1163. */
  1164. int
  1165. connection_or_nonopen_was_started_here(or_connection_t *conn)
  1166. {
  1167. tor_assert(conn->_base.type == CONN_TYPE_OR);
  1168. if (!conn->tls)
  1169. return 1; /* it's still in proxy states or something */
  1170. if (conn->handshake_state)
  1171. return conn->handshake_state->started_here;
  1172. return !tor_tls_is_server(conn->tls);
  1173. }
  1174. /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
  1175. * return -1 if he is lying, broken, or otherwise something is wrong.
  1176. *
  1177. * If we initiated this connection (<b>started_here</b> is true), make sure
  1178. * the other side sent a correctly formed certificate. If I initiated the
  1179. * connection, make sure it's the right guy.
  1180. *
  1181. * Otherwise (if we _didn't_ initiate this connection), it's okay for
  1182. * the certificate to be weird or absent.
  1183. *
  1184. * If we return 0, and the certificate is as expected, write a hash of the
  1185. * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
  1186. * space in it.
  1187. * If the certificate is invalid or missing on an incoming connection,
  1188. * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
  1189. * (If we return -1, the contents of this buffer are undefined.)
  1190. *
  1191. * As side effects,
  1192. * 1) Set conn->circ_id_type according to tor-spec.txt.
  1193. * 2) If we're an authdirserver and we initiated the connection: drop all
  1194. * descriptors that claim to be on that IP/port but that aren't
  1195. * this guy; and note that this guy is reachable.
  1196. * 3) If this is a bridge and we didn't configure its identity
  1197. * fingerprint, remember the keyid we just learned.
  1198. */
  1199. static int
  1200. connection_or_check_valid_tls_handshake(or_connection_t *conn,
  1201. int started_here,
  1202. char *digest_rcvd_out)
  1203. {
  1204. crypto_pk_env_t *identity_rcvd=NULL;
  1205. const or_options_t *options = get_options();
  1206. int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
  1207. const char *safe_address =
  1208. started_here ? conn->_base.address :
  1209. safe_str_client(conn->_base.address);
  1210. const char *conn_type = started_here ? "outgoing" : "incoming";
  1211. crypto_pk_env_t *our_identity =
  1212. started_here ? get_tlsclient_identity_key() :
  1213. get_server_identity_key();
  1214. int has_cert = 0, has_identity=0;
  1215. check_no_tls_errors();
  1216. has_cert = tor_tls_peer_has_cert(conn->tls);
  1217. if (started_here && !has_cert) {
  1218. log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
  1219. "send a cert! Closing.",
  1220. safe_address, conn->_base.port);
  1221. return -1;
  1222. } else if (!has_cert) {
  1223. log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
  1224. "That's ok.");
  1225. }
  1226. check_no_tls_errors();
  1227. if (has_cert) {
  1228. int v = tor_tls_verify(started_here?severity:LOG_INFO,
  1229. conn->tls, &identity_rcvd);
  1230. if (started_here && v<0) {
  1231. log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
  1232. " has a cert but it's invalid. Closing.",
  1233. safe_address, conn->_base.port);
  1234. return -1;
  1235. } else if (v<0) {
  1236. log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
  1237. "chain; ignoring.");
  1238. } else {
  1239. log_debug(LD_HANDSHAKE,
  1240. "The certificate seems to be valid on %s connection "
  1241. "with %s:%d", conn_type, safe_address, conn->_base.port);
  1242. }
  1243. check_no_tls_errors();
  1244. }
  1245. if (identity_rcvd) {
  1246. has_identity = 1;
  1247. crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
  1248. if (crypto_pk_cmp_keys(our_identity, identity_rcvd)<0) {
  1249. conn->circ_id_type = CIRC_ID_TYPE_LOWER;
  1250. } else {
  1251. conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
  1252. }
  1253. crypto_free_pk_env(identity_rcvd);
  1254. } else {
  1255. memset(digest_rcvd_out, 0, DIGEST_LEN);
  1256. conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
  1257. }
  1258. if (started_here && tor_digest_is_zero(conn->identity_digest)) {
  1259. connection_or_set_identity_digest(conn, digest_rcvd_out);
  1260. tor_free(conn->nickname);
  1261. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  1262. conn->nickname[0] = '$';
  1263. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  1264. conn->identity_digest, DIGEST_LEN);
  1265. log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
  1266. "its key. Hoping for the best.",
  1267. conn->nickname, conn->_base.address, conn->_base.port);
  1268. /* if it's a bridge and we didn't know its identity fingerprint, now
  1269. * we do -- remember it for future attempts. */
  1270. learned_router_identity(&conn->_base.addr, conn->_base.port,
  1271. digest_rcvd_out);
  1272. }
  1273. if (started_here) {
  1274. int as_advertised = 1;
  1275. tor_assert(has_cert);
  1276. tor_assert(has_identity);
  1277. if (tor_memneq(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
  1278. /* I was aiming for a particular digest. I didn't get it! */
  1279. char seen[HEX_DIGEST_LEN+1];
  1280. char expected[HEX_DIGEST_LEN+1];
  1281. base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
  1282. base16_encode(expected, sizeof(expected), conn->identity_digest,
  1283. DIGEST_LEN);
  1284. log_fn(severity, LD_HANDSHAKE,
  1285. "Tried connecting to router at %s:%d, but identity key was not "
  1286. "as expected: wanted %s but got %s.",
  1287. conn->_base.address, conn->_base.port, expected, seen);
  1288. entry_guard_register_connect_status(conn->identity_digest, 0, 1,
  1289. time(NULL));
  1290. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
  1291. END_OR_CONN_REASON_OR_IDENTITY);
  1292. if (!authdir_mode_tests_reachability(options))
  1293. control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
  1294. as_advertised = 0;
  1295. }
  1296. if (authdir_mode_tests_reachability(options)) {
  1297. dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
  1298. digest_rcvd_out, as_advertised);
  1299. }
  1300. if (!as_advertised)
  1301. return -1;
  1302. }
  1303. return 0;
  1304. }
  1305. /** The tls handshake is finished.
  1306. *
  1307. * Make sure we are happy with the person we just handshaked with.
  1308. *
  1309. * If he initiated the connection, make sure he's not already connected,
  1310. * then initialize conn from the information in router.
  1311. *
  1312. * If all is successful, call circuit_n_conn_done() to handle events
  1313. * that have been pending on the <tls handshake completion. Also set the
  1314. * directory to be dirty (only matters if I'm an authdirserver).
  1315. */
  1316. static int
  1317. connection_tls_finish_handshake(or_connection_t *conn)
  1318. {
  1319. char digest_rcvd[DIGEST_LEN];
  1320. int started_here = connection_or_nonopen_was_started_here(conn);
  1321. log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done. verifying.",
  1322. started_here?"outgoing":"incoming",
  1323. conn,
  1324. safe_str_client(conn->_base.address));
  1325. directory_set_dirty();
  1326. if (connection_or_check_valid_tls_handshake(conn, started_here,
  1327. digest_rcvd) < 0)
  1328. return -1;
  1329. circuit_build_times_network_is_live(&circ_times);
  1330. if (tor_tls_used_v1_handshake(conn->tls)) {
  1331. conn->link_proto = 1;
  1332. if (!started_here) {
  1333. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  1334. conn->_base.port, digest_rcvd, 0);
  1335. }
  1336. tor_tls_block_renegotiation(conn->tls);
  1337. return connection_or_set_state_open(conn);
  1338. } else {
  1339. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
  1340. if (connection_init_or_handshake_state(conn, started_here) < 0)
  1341. return -1;
  1342. if (!started_here) {
  1343. connection_or_init_conn_from_address(conn, &conn->_base.addr,
  1344. conn->_base.port, digest_rcvd, 0);
  1345. }
  1346. return connection_or_send_versions(conn);
  1347. }
  1348. }
  1349. /** Allocate a new connection handshake state for the connection
  1350. * <b>conn</b>. Return 0 on success, -1 on failure. */
  1351. static int
  1352. connection_init_or_handshake_state(or_connection_t *conn, int started_here)
  1353. {
  1354. or_handshake_state_t *s;
  1355. s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
  1356. s->started_here = started_here ? 1 : 0;
  1357. return 0;
  1358. }
  1359. /** Free all storage held by <b>state</b>. */
  1360. void
  1361. or_handshake_state_free(or_handshake_state_t *state)
  1362. {
  1363. if (!state)
  1364. return;
  1365. memset(state, 0xBE, sizeof(or_handshake_state_t));
  1366. tor_free(state);
  1367. }
  1368. /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
  1369. * as appropriate. Called when we are done with all TLS and OR handshaking.
  1370. */
  1371. int
  1372. connection_or_set_state_open(or_connection_t *conn)
  1373. {
  1374. int started_here = connection_or_nonopen_was_started_here(conn);
  1375. time_t now = time(NULL);
  1376. conn->_base.state = OR_CONN_STATE_OPEN;
  1377. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
  1378. if (started_here) {
  1379. circuit_build_times_network_is_live(&circ_times);
  1380. rep_hist_note_connect_succeeded(conn->identity_digest, now);
  1381. if (entry_guard_register_connect_status(conn->identity_digest,
  1382. 1, 0, now) < 0) {
  1383. /* Close any circuits pending on this conn. We leave it in state
  1384. * 'open' though, because it didn't actually *fail* -- we just
  1385. * chose not to use it. (Otherwise
  1386. * connection_about_to_close_connection() will call a big pile of
  1387. * functions to indicate we shouldn't try it again.) */
  1388. log_debug(LD_OR, "New entry guard was reachable, but closing this "
  1389. "connection so we can retry the earlier entry guards.");
  1390. circuit_n_conn_done(conn, 0);
  1391. return -1;
  1392. }
  1393. router_set_status(conn->identity_digest, 1);
  1394. } else {
  1395. /* only report it to the geoip module if it's not a known router */
  1396. if (!router_get_by_id_digest(conn->identity_digest)) {
  1397. if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
  1398. /*XXXX IP6 support ipv6 geoip.*/
  1399. uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
  1400. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
  1401. }
  1402. }
  1403. }
  1404. or_handshake_state_free(conn->handshake_state);
  1405. conn->handshake_state = NULL;
  1406. IF_HAS_BUFFEREVENT(TO_CONN(conn), {
  1407. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1408. }) ELSE_IF_NO_BUFFEREVENT {
  1409. connection_start_reading(TO_CONN(conn));
  1410. }
  1411. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  1412. return 0;
  1413. }
  1414. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
  1415. * For cells that use or affect a circuit, this should only be called by
  1416. * connection_or_flush_from_first_active_circuit().
  1417. */
  1418. void
  1419. connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
  1420. {
  1421. packed_cell_t networkcell;
  1422. tor_assert(cell);
  1423. tor_assert(conn);
  1424. cell_pack(&networkcell, cell);
  1425. connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
  1426. if (cell->command != CELL_PADDING)
  1427. conn->timestamp_last_added_nonpadding = approx_time();
  1428. }
  1429. /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
  1430. * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
  1431. * affect a circuit.
  1432. */
  1433. void
  1434. connection_or_write_var_cell_to_buf(const var_cell_t *cell,
  1435. or_connection_t *conn)
  1436. {
  1437. char hdr[VAR_CELL_HEADER_SIZE];
  1438. tor_assert(cell);
  1439. tor_assert(conn);
  1440. var_cell_pack_header(cell, hdr);
  1441. connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
  1442. connection_write_to_buf((char*)cell->payload,
  1443. cell->payload_len, TO_CONN(conn));
  1444. if (cell->command != CELL_PADDING)
  1445. conn->timestamp_last_added_nonpadding = approx_time();
  1446. }
  1447. /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
  1448. * inbuf. Return values as for fetch_var_cell_from_buf(). */
  1449. static int
  1450. connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
  1451. {
  1452. connection_t *conn = TO_CONN(or_conn);
  1453. IF_HAS_BUFFEREVENT(conn, {
  1454. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  1455. return fetch_var_cell_from_evbuffer(input, out, or_conn->link_proto);
  1456. }) ELSE_IF_NO_BUFFEREVENT {
  1457. return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
  1458. }
  1459. }
  1460. /** Process cells from <b>conn</b>'s inbuf.
  1461. *
  1462. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  1463. * and hand it to command_process_cell().
  1464. *
  1465. * Always return 0.
  1466. */
  1467. static int
  1468. connection_or_process_cells_from_inbuf(or_connection_t *conn)
  1469. {
  1470. var_cell_t *var_cell;
  1471. while (1) {
  1472. log_debug(LD_OR,
  1473. "%d: starting, inbuf_datalen %d (%d pending in tls object).",
  1474. conn->_base.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
  1475. tor_tls_get_pending_bytes(conn->tls));
  1476. if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
  1477. if (!var_cell)
  1478. return 0; /* not yet. */
  1479. circuit_build_times_network_is_live(&circ_times);
  1480. command_process_var_cell(var_cell, conn);
  1481. var_cell_free(var_cell);
  1482. } else {
  1483. char buf[CELL_NETWORK_SIZE];
  1484. cell_t cell;
  1485. if (connection_get_inbuf_len(TO_CONN(conn))
  1486. < CELL_NETWORK_SIZE) /* whole response available? */
  1487. return 0; /* not yet */
  1488. circuit_build_times_network_is_live(&circ_times);
  1489. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
  1490. /* retrieve cell info from buf (create the host-order struct from the
  1491. * network-order string) */
  1492. cell_unpack(&cell, buf);
  1493. command_process_cell(&cell, conn);
  1494. }
  1495. }
  1496. }
  1497. /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  1498. * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
  1499. * we may want to propagate reasons from other cells.
  1500. *
  1501. * Return 0.
  1502. */
  1503. int
  1504. connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
  1505. {
  1506. cell_t cell;
  1507. tor_assert(conn);
  1508. memset(&cell, 0, sizeof(cell_t));
  1509. cell.circ_id = circ_id;
  1510. cell.command = CELL_DESTROY;
  1511. cell.payload[0] = (uint8_t) reason;
  1512. log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
  1513. connection_or_write_cell_to_buf(&cell, conn);
  1514. return 0;
  1515. }
  1516. /** Array of recognized link protocol versions. */
  1517. static const uint16_t or_protocol_versions[] = { 1, 2 };
  1518. /** Number of versions in <b>or_protocol_versions</b>. */
  1519. static const int n_or_protocol_versions =
  1520. (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
  1521. /** Return true iff <b>v</b> is a link protocol version that this Tor
  1522. * implementation believes it can support. */
  1523. int
  1524. is_or_protocol_version_known(uint16_t v)
  1525. {
  1526. int i;
  1527. for (i = 0; i < n_or_protocol_versions; ++i) {
  1528. if (or_protocol_versions[i] == v)
  1529. return 1;
  1530. }
  1531. return 0;
  1532. }
  1533. /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
  1534. * link protocol versions that this Tor can support. */
  1535. static int
  1536. connection_or_send_versions(or_connection_t *conn)
  1537. {
  1538. var_cell_t *cell;
  1539. int i;
  1540. tor_assert(conn->handshake_state &&
  1541. !conn->handshake_state->sent_versions_at);
  1542. cell = var_cell_new(n_or_protocol_versions * 2);
  1543. cell->command = CELL_VERSIONS;
  1544. for (i = 0; i < n_or_protocol_versions; ++i) {
  1545. uint16_t v = or_protocol_versions[i];
  1546. set_uint16(cell->payload+(2*i), htons(v));
  1547. }
  1548. connection_or_write_var_cell_to_buf(cell, conn);
  1549. conn->handshake_state->sent_versions_at = time(NULL);
  1550. var_cell_free(cell);
  1551. return 0;
  1552. }
  1553. /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
  1554. * about their address, our address, and the current time. */
  1555. int
  1556. connection_or_send_netinfo(or_connection_t *conn)
  1557. {
  1558. cell_t cell;
  1559. time_t now = time(NULL);
  1560. const routerinfo_t *me;
  1561. int len;
  1562. uint8_t *out;
  1563. memset(&cell, 0, sizeof(cell_t));
  1564. cell.command = CELL_NETINFO;
  1565. /* Timestamp. */
  1566. set_uint32(cell.payload, htonl((uint32_t)now));
  1567. /* Their address. */
  1568. out = cell.payload + 4;
  1569. len = append_address_to_payload(out, &conn->_base.addr);
  1570. if (len<0)
  1571. return -1;
  1572. out += len;
  1573. /* My address. */
  1574. if ((me = router_get_my_routerinfo())) {
  1575. tor_addr_t my_addr;
  1576. *out++ = 1; /* only one address is supported. */
  1577. tor_addr_from_ipv4h(&my_addr, me->addr);
  1578. len = append_address_to_payload(out, &my_addr);
  1579. if (len < 0)
  1580. return -1;
  1581. } else {
  1582. *out = 0;
  1583. }
  1584. connection_or_write_cell_to_buf(&cell, conn);
  1585. return 0;
  1586. }