connection_or.c 59 KB

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