connection_or.c 75 KB

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