connection_edge.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_edge_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file connection_edge.c
  10. * \brief Handle edge streams.
  11. **/
  12. #include "or.h"
  13. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  14. #include <linux/netfilter_ipv4.h>
  15. #define TRANS_NETFILTER
  16. #endif
  17. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  18. #include <net/if.h>
  19. #include <net/pfvar.h>
  20. #define TRANS_PF
  21. #endif
  22. /* List of exit_redirect_t */
  23. static smartlist_t *redirect_exit_list = NULL;
  24. static int connection_ap_handshake_process_socks(edge_connection_t *conn);
  25. static int connection_ap_process_natd(edge_connection_t *conn);
  26. static int connection_exit_connect_dir(edge_connection_t *exit_conn);
  27. /** An AP stream has failed/finished. If it hasn't already sent back
  28. * a socks reply, send one now (based on endreason). Also set
  29. * has_sent_end to 1, and mark the conn.
  30. */
  31. void
  32. _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
  33. int line, const char *file)
  34. {
  35. tor_assert(conn->_base.type == CONN_TYPE_AP);
  36. conn->_base.edge_has_sent_end = 1; /* no circ yet */
  37. if (conn->_base.marked_for_close) {
  38. /* This call will warn as appropriate. */
  39. _connection_mark_for_close(TO_CONN(conn), line, file);
  40. return;
  41. }
  42. if (!conn->socks_request->has_finished) {
  43. if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
  44. log_warn(LD_BUG,
  45. "Bug: stream (marked at %s:%d) sending two socks replies?",
  46. file, line);
  47. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
  48. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  49. else
  50. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  51. 0, NULL, -1);
  52. }
  53. _connection_mark_for_close(TO_CONN(conn), line, file);
  54. conn->_base.hold_open_until_flushed = 1;
  55. conn->end_reason = endreason;
  56. }
  57. /** There was an EOF. Send an end and mark the connection for close.
  58. */
  59. int
  60. connection_edge_reached_eof(edge_connection_t *conn)
  61. {
  62. if (buf_datalen(conn->_base.inbuf) &&
  63. connection_state_is_open(TO_CONN(conn))) {
  64. /* it still has stuff to process. don't let it die yet. */
  65. return 0;
  66. }
  67. log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
  68. if (!conn->_base.marked_for_close) {
  69. /* only mark it if not already marked. it's possible to
  70. * get the 'end' right around when the client hangs up on us. */
  71. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  72. if (conn->socks_request) /* eof, so don't send a socks reply back */
  73. conn->socks_request->has_finished = 1;
  74. connection_mark_for_close(TO_CONN(conn));
  75. }
  76. return 0;
  77. }
  78. /** Handle new bytes on conn->inbuf based on state:
  79. * - If it's waiting for socks info, try to read another step of the
  80. * socks handshake out of conn->inbuf.
  81. * - If it's waiting for the original destination, fetch it.
  82. * - If it's open, then package more relay cells from the stream.
  83. * - Else, leave the bytes on inbuf alone for now.
  84. *
  85. * Mark and return -1 if there was an unexpected error with the conn,
  86. * else return 0.
  87. */
  88. int
  89. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  90. {
  91. tor_assert(conn);
  92. switch (conn->_base.state) {
  93. case AP_CONN_STATE_SOCKS_WAIT:
  94. if (connection_ap_handshake_process_socks(conn) < 0) {
  95. /* already marked */
  96. return -1;
  97. }
  98. return 0;
  99. case AP_CONN_STATE_NATD_WAIT:
  100. if (connection_ap_process_natd(conn) < 0) {
  101. /* already marked */
  102. return -1;
  103. }
  104. return 0;
  105. case AP_CONN_STATE_OPEN:
  106. case EXIT_CONN_STATE_OPEN:
  107. if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
  108. /* (We already sent an end cell if possible) */
  109. connection_mark_for_close(TO_CONN(conn));
  110. return -1;
  111. }
  112. return 0;
  113. case EXIT_CONN_STATE_CONNECTING:
  114. case AP_CONN_STATE_RENDDESC_WAIT:
  115. case AP_CONN_STATE_CIRCUIT_WAIT:
  116. case AP_CONN_STATE_CONNECT_WAIT:
  117. case AP_CONN_STATE_RESOLVE_WAIT:
  118. case AP_CONN_STATE_CONTROLLER_WAIT:
  119. log_info(LD_EDGE,
  120. "data from edge while in '%s' state. Leaving it on buffer.",
  121. conn_state_to_string(conn->_base.type, conn->_base.state));
  122. return 0;
  123. }
  124. log_warn(LD_BUG,"Bug: Got unexpected state %d. Closing.",conn->_base.state);
  125. tor_fragile_assert();
  126. connection_edge_end(conn, END_STREAM_REASON_INTERNAL, conn->cpath_layer);
  127. connection_mark_for_close(TO_CONN(conn));
  128. return -1;
  129. }
  130. /** This edge needs to be closed, because its circuit has closed.
  131. * Mark it for close and return 0.
  132. */
  133. int
  134. connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn)
  135. {
  136. if (!conn->_base.marked_for_close) {
  137. log_info(LD_EDGE,
  138. "CircID %d: At an edge. Marking connection for close.", circ_id);
  139. if (conn->_base.type == CONN_TYPE_AP) {
  140. connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
  141. } else {
  142. /* closing the circuit, nothing to send an END to */
  143. conn->_base.edge_has_sent_end = 1;
  144. conn->end_reason = END_STREAM_REASON_DESTROY;
  145. connection_mark_for_close(TO_CONN(conn));
  146. conn->_base.hold_open_until_flushed = 1;
  147. }
  148. }
  149. conn->cpath_layer = NULL;
  150. conn->on_circuit = NULL;
  151. return 0;
  152. }
  153. /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
  154. * with a destination of cpath_layer. (If cpath_layer is NULL, the
  155. * destination is the circuit's origin.) Mark the relay end cell as
  156. * closing because of <b>reason</b>.
  157. *
  158. * Return -1 if this function has already been called on this conn,
  159. * else return 0.
  160. */
  161. int
  162. connection_edge_end(edge_connection_t *conn, char reason,
  163. crypt_path_t *cpath_layer)
  164. {
  165. char payload[RELAY_PAYLOAD_SIZE];
  166. size_t payload_len=1;
  167. circuit_t *circ;
  168. if (conn->_base.edge_has_sent_end) {
  169. log_warn(LD_BUG,"Harmless bug: Calling connection_edge_end (reason %d) "
  170. "on an already ended stream?", reason);
  171. tor_fragile_assert();
  172. return -1;
  173. }
  174. if (conn->_base.marked_for_close) {
  175. log_warn(LD_BUG,
  176. "Bug: called on conn that's already marked for close at %s:%d.",
  177. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  178. return 0;
  179. }
  180. payload[0] = reason;
  181. if (reason == END_STREAM_REASON_EXITPOLICY &&
  182. !connection_edge_is_rendezvous_stream(conn)) {
  183. set_uint32(payload+1, htonl(conn->_base.addr));
  184. set_uint32(payload+5, htonl(dns_clip_ttl(conn->address_ttl)));
  185. payload_len += 8;
  186. }
  187. circ = circuit_get_by_edge_conn(conn);
  188. if (circ && !circ->marked_for_close) {
  189. log_debug(LD_EDGE,"Marking conn (fd %d) and sending end.",conn->_base.s);
  190. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  191. payload, payload_len, cpath_layer);
  192. } else {
  193. log_debug(LD_EDGE,"Marking conn (fd %d); no circ to send end.",
  194. conn->_base.s);
  195. }
  196. conn->_base.edge_has_sent_end = 1;
  197. conn->end_reason = reason;
  198. return 0;
  199. }
  200. /** An error has just occured on an operation on an edge connection
  201. * <b>conn</b>. Extract the errno; convert it to an end reason, and send
  202. * an appropriate relay end cell to <b>cpath_layer</b>.
  203. **/
  204. int
  205. connection_edge_end_errno(edge_connection_t *conn, crypt_path_t *cpath_layer)
  206. {
  207. uint8_t reason;
  208. tor_assert(conn);
  209. reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->_base.s));
  210. return connection_edge_end(conn, reason, cpath_layer);
  211. }
  212. /** Connection <b>conn</b> has finished writing and has no bytes left on
  213. * its outbuf.
  214. *
  215. * If it's in state 'open', stop writing, consider responding with a
  216. * sendme, and return.
  217. * Otherwise, stop writing and return.
  218. *
  219. * If <b>conn</b> is broken, mark it for close and return -1, else
  220. * return 0.
  221. */
  222. int
  223. connection_edge_finished_flushing(edge_connection_t *conn)
  224. {
  225. tor_assert(conn);
  226. switch (conn->_base.state) {
  227. case AP_CONN_STATE_OPEN:
  228. case EXIT_CONN_STATE_OPEN:
  229. connection_stop_writing(TO_CONN(conn));
  230. connection_edge_consider_sending_sendme(conn);
  231. return 0;
  232. case AP_CONN_STATE_SOCKS_WAIT:
  233. case AP_CONN_STATE_NATD_WAIT:
  234. case AP_CONN_STATE_RENDDESC_WAIT:
  235. case AP_CONN_STATE_CIRCUIT_WAIT:
  236. case AP_CONN_STATE_CONNECT_WAIT:
  237. case AP_CONN_STATE_CONTROLLER_WAIT:
  238. connection_stop_writing(TO_CONN(conn));
  239. return 0;
  240. default:
  241. log_warn(LD_BUG,"BUG: called in unexpected state %d.",conn->_base.state);
  242. tor_fragile_assert();
  243. return -1;
  244. }
  245. return 0;
  246. }
  247. /** Connected handler for exit connections: start writing pending
  248. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  249. * any pending data that may have been received. */
  250. int
  251. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  252. {
  253. char valbuf[INET_NTOA_BUF_LEN];
  254. connection_t *conn;
  255. struct in_addr in;
  256. tor_assert(edge_conn);
  257. tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
  258. conn = TO_CONN(edge_conn);
  259. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  260. in.s_addr = htonl(conn->addr);
  261. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  262. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  263. escaped_safe_str(conn->address),conn->port,safe_str(valbuf));
  264. conn->state = EXIT_CONN_STATE_OPEN;
  265. connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
  266. if (connection_wants_to_flush(conn)) /* in case there are any queued relay
  267. * cells */
  268. connection_start_writing(conn);
  269. /* deliver a 'connected' relay cell back through the circuit. */
  270. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  271. if (connection_edge_send_command(edge_conn,
  272. circuit_get_by_edge_conn(edge_conn),
  273. RELAY_COMMAND_CONNECTED, NULL, 0,
  274. edge_conn->cpath_layer) < 0)
  275. return 0; /* circuit is closed, don't continue */
  276. } else {
  277. char connected_payload[8];
  278. set_uint32(connected_payload, htonl(conn->addr));
  279. set_uint32(connected_payload+4,
  280. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  281. if (connection_edge_send_command(edge_conn,
  282. circuit_get_by_edge_conn(edge_conn),
  283. RELAY_COMMAND_CONNECTED,
  284. connected_payload, 8,
  285. edge_conn->cpath_layer) < 0)
  286. return 0; /* circuit is closed, don't continue */
  287. }
  288. tor_assert(edge_conn->package_window > 0);
  289. /* in case the server has written anything */
  290. return connection_edge_process_inbuf(edge_conn, 1);
  291. }
  292. /** Define a schedule for how long to wait between retrying
  293. * application connections. Rather than waiting a fixed amount of
  294. * time between each retry, we wait only 5 seconds for the first,
  295. * 10 seconds for the second, and 15 seconds for each retry after
  296. * that. Hopefully this will improve the expected user experience. */
  297. static int
  298. compute_socks_timeout(edge_connection_t *conn)
  299. {
  300. if (conn->num_socks_retries == 0)
  301. return 5;
  302. if (conn->num_socks_retries == 1)
  303. return 10;
  304. return 15;
  305. }
  306. /** Find all general-purpose AP streams waiting for a response that sent their
  307. * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
  308. * mark their current circuit as unsuitable for new streams. Then call
  309. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  310. * available) or launch a new one.
  311. *
  312. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  313. * retry attempt).
  314. */
  315. void
  316. connection_ap_expire_beginning(void)
  317. {
  318. connection_t **carray;
  319. edge_connection_t *conn;
  320. circuit_t *circ;
  321. const char *nickname;
  322. int n, i;
  323. time_t now = time(NULL);
  324. or_options_t *options = get_options();
  325. int severity;
  326. int cutoff;
  327. get_connection_array(&carray, &n);
  328. for (i = 0; i < n; ++i) {
  329. if (carray[i]->type != CONN_TYPE_AP)
  330. continue;
  331. conn = TO_EDGE_CONN(carray[i]);
  332. /* if it's an internal bridge connection, don't yell its status. */
  333. severity = (!conn->_base.addr && !conn->_base.port)
  334. ? LOG_INFO : LOG_NOTICE;
  335. if (conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT) {
  336. if (now - conn->_base.timestamp_lastread >= options->SocksTimeout) {
  337. log_fn(severity, LD_APP, "Closing unattached stream.");
  338. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  339. }
  340. continue;
  341. }
  342. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT &&
  343. conn->_base.state != AP_CONN_STATE_CONNECT_WAIT)
  344. continue;
  345. cutoff = compute_socks_timeout(conn);
  346. if (now - conn->_base.timestamp_lastread < cutoff)
  347. continue;
  348. circ = circuit_get_by_edge_conn(conn);
  349. if (!circ) { /* it's vanished? */
  350. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  351. safe_str(conn->socks_request->address));
  352. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  353. continue;
  354. }
  355. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  356. if (now - conn->_base.timestamp_lastread > options->SocksTimeout) {
  357. log_fn(severity, LD_REND,
  358. "Rend stream is %d seconds late. Giving up on address"
  359. " '%s.onion'.",
  360. (int)(now - conn->_base.timestamp_lastread),
  361. safe_str(conn->socks_request->address));
  362. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT,
  363. conn->cpath_layer);
  364. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  365. }
  366. continue;
  367. }
  368. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  369. nickname = build_state_get_exit_nickname(
  370. TO_ORIGIN_CIRCUIT(circ)->build_state);
  371. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  372. "We tried for %d seconds to connect to '%s' using exit '%s'."
  373. " Retrying on a new circuit.",
  374. (int)(now - conn->_base.timestamp_lastread),
  375. safe_str(conn->socks_request->address),
  376. nickname ? nickname : "*unnamed*");
  377. /* send an end down the circuit */
  378. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  379. /* un-mark it as ending, since we're going to reuse it */
  380. conn->_base.edge_has_sent_end = 0;
  381. conn->end_reason = 0;
  382. /* kludge to make us not try this circuit again, yet to allow
  383. * current streams on it to survive if they can: make it
  384. * unattractive to use for new streams */
  385. tor_assert(circ->timestamp_dirty);
  386. circ->timestamp_dirty -= options->MaxCircuitDirtiness;
  387. /* give our stream another 'cutoff' seconds to try */
  388. conn->_base.timestamp_lastread += cutoff;
  389. if (conn->num_socks_retries < 250) /* avoid overflow */
  390. conn->num_socks_retries++;
  391. /* move it back into 'pending' state, and try to attach. */
  392. if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
  393. END_STREAM_REASON_TIMEOUT)<0) {
  394. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  395. }
  396. } /* end for */
  397. }
  398. /** Tell any AP streams that are waiting for a new circuit that one is
  399. * available.
  400. */
  401. void
  402. connection_ap_attach_pending(void)
  403. {
  404. connection_t **carray;
  405. connection_t *conn;
  406. edge_connection_t *edge_conn;
  407. int n, i;
  408. get_connection_array(&carray, &n);
  409. for (i = 0; i < n; ++i) {
  410. conn = carray[i];
  411. if (conn->marked_for_close ||
  412. conn->type != CONN_TYPE_AP ||
  413. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  414. continue;
  415. edge_conn = TO_EDGE_CONN(conn);
  416. if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
  417. connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_CANT_ATTACH);
  418. }
  419. }
  420. }
  421. /** A circuit failed to finish on its last hop <b>info</b>. If there
  422. * are any streams waiting with this exit node in mind, but they
  423. * don't absolutely require it, make them give up on it.
  424. */
  425. void
  426. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  427. {
  428. connection_t **carray;
  429. connection_t *conn;
  430. edge_connection_t *edge_conn;
  431. routerinfo_t *r1, *r2;
  432. int n, i;
  433. get_connection_array(&carray, &n);
  434. for (i = 0; i < n; ++i) {
  435. conn = carray[i];
  436. if (conn->marked_for_close ||
  437. conn->type != CONN_TYPE_AP ||
  438. !conn->chosen_exit_optional)
  439. continue;
  440. edge_conn = TO_EDGE_CONN(conn);
  441. r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
  442. r2 = router_get_by_nickname(info->nickname, 0);
  443. if (r1 && r2 && r1==r2) {
  444. tor_assert(edge_conn->socks_request);
  445. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  446. safe_str(edge_conn->chosen_exit_name),
  447. escaped_safe_str(edge_conn->socks_request->address));
  448. conn->chosen_exit_optional = 0;
  449. tor_free(edge_conn->chosen_exit_name); /* clears it */
  450. }
  451. }
  452. }
  453. /** The AP connection <b>conn</b> has just failed while attaching or
  454. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  455. * might work. Detach the circuit, and either reattach it, launch a
  456. * new circuit, tell the controller, or give up as a appropriate.
  457. *
  458. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  459. */
  460. int
  461. connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
  462. int reason)
  463. {
  464. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  465. conn->_base.timestamp_lastread = time(NULL);
  466. if (! get_options()->LeaveStreamsUnattached) {
  467. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  468. circuit_detach_stream(TO_CIRCUIT(circ),conn);
  469. return connection_ap_handshake_attach_circuit(conn);
  470. } else {
  471. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  472. circuit_detach_stream(TO_CIRCUIT(circ),conn);
  473. return 0;
  474. }
  475. }
  476. /** A client-side struct to remember requests to rewrite addresses
  477. * to new addresses. These structs are stored in the hash table
  478. * "addressmap" below.
  479. *
  480. * There are 5 ways to set an address mapping:
  481. * - A MapAddress command from the controller [permanent]
  482. * - An AddressMap directive in the torrc [permanent]
  483. * - When a TrackHostExits torrc directive is triggered [temporary]
  484. * - When a dns resolve succeeds [temporary]
  485. * - When a dns resolve fails [temporary]
  486. *
  487. * When an addressmap request is made but one is already registered,
  488. * the new one is replaced only if the currently registered one has
  489. * no "new_address" (that is, it's in the process of dns resolve),
  490. * or if the new one is permanent (expires==0 or 1).
  491. *
  492. * (We overload the 'expires' field, using "0" for mappings set via
  493. * the configuration file, "1" for mappings set from the control
  494. * interface, and other values for DNS mappings that can expire.)
  495. */
  496. typedef struct {
  497. char *new_address;
  498. time_t expires;
  499. int num_resolve_failures;
  500. } addressmap_entry_t;
  501. /** Entry for mapping addresses to which virtual address we mapped them to. */
  502. typedef struct {
  503. char *ipv4_address;
  504. char *hostname_address;
  505. } virtaddress_entry_t;
  506. /** A hash table to store client-side address rewrite instructions. */
  507. static strmap_t *addressmap=NULL;
  508. /**
  509. * Table mapping addresses to which virtual address, if any, we
  510. * assigned them to.
  511. *
  512. * We maintain the following invariant: if [A,B] is in
  513. * virtaddress_reversemap, then B must be a virtual address, and [A,B]
  514. * must be in addressmap. We do not require that the converse hold:
  515. * if it fails, then we could end up mapping two virtual addresses to
  516. * the same address, which is no disaster.
  517. **/
  518. static strmap_t *virtaddress_reversemap=NULL;
  519. /** Initialize addressmap. */
  520. void
  521. addressmap_init(void)
  522. {
  523. addressmap = strmap_new();
  524. virtaddress_reversemap = strmap_new();
  525. }
  526. /** Free the memory associated with the addressmap entry <b>_ent</b>. */
  527. static void
  528. addressmap_ent_free(void *_ent)
  529. {
  530. addressmap_entry_t *ent = _ent;
  531. tor_free(ent->new_address);
  532. tor_free(ent);
  533. }
  534. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
  535. static void
  536. addressmap_virtaddress_ent_free(void *_ent)
  537. {
  538. virtaddress_entry_t *ent = _ent;
  539. tor_free(ent->ipv4_address);
  540. tor_free(ent->hostname_address);
  541. tor_free(ent);
  542. }
  543. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
  544. static void
  545. addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
  546. {
  547. if (ent && ent->new_address &&
  548. address_is_in_virtual_range(ent->new_address)) {
  549. virtaddress_entry_t *ve =
  550. strmap_get(virtaddress_reversemap, ent->new_address);
  551. /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
  552. if (ve) {
  553. if (!strcmp(address, ve->ipv4_address))
  554. tor_free(ve->ipv4_address);
  555. if (!strcmp(address, ve->hostname_address))
  556. tor_free(ve->hostname_address);
  557. if (!ve->ipv4_address && !ve->hostname_address) {
  558. tor_free(ve);
  559. strmap_remove(virtaddress_reversemap, ent->new_address);
  560. }
  561. }
  562. }
  563. }
  564. /* DOCDOC */
  565. static void
  566. addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
  567. {
  568. addressmap_virtaddress_remove(address, ent);
  569. addressmap_ent_free(ent);
  570. }
  571. /** Remove all entries from the addressmap that were set via the
  572. * configuration file or the command line. */
  573. void
  574. addressmap_clear_configured(void)
  575. {
  576. addressmap_get_mappings(NULL, 0, 0);
  577. }
  578. /** Remove all entries from the addressmap that are set to expire, ever. */
  579. void
  580. addressmap_clear_transient(void)
  581. {
  582. addressmap_get_mappings(NULL, 2, TIME_MAX);
  583. }
  584. /** Clean out entries from the addressmap cache that were
  585. * added long enough ago that they are no longer valid.
  586. */
  587. void
  588. addressmap_clean(time_t now)
  589. {
  590. addressmap_get_mappings(NULL, 2, now);
  591. }
  592. /** Free all the elements in the addressmap, and free the addressmap
  593. * itself. */
  594. void
  595. addressmap_free_all(void)
  596. {
  597. if (addressmap) {
  598. strmap_free(addressmap, addressmap_ent_free);
  599. addressmap = NULL;
  600. }
  601. if (virtaddress_reversemap) {
  602. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
  603. virtaddress_reversemap = NULL;
  604. }
  605. }
  606. /** Look at address, and rewrite it until it doesn't want any
  607. * more rewrites; but don't get into an infinite loop.
  608. * Don't write more than maxlen chars into address.
  609. */
  610. void
  611. addressmap_rewrite(char *address, size_t maxlen)
  612. {
  613. addressmap_entry_t *ent;
  614. int rewrites;
  615. for (rewrites = 0; rewrites < 16; rewrites++) {
  616. ent = strmap_get(addressmap, address);
  617. if (!ent || !ent->new_address)
  618. return; /* done, no rewrite needed */
  619. log_info(LD_APP, "Addressmap: rewriting '%s' to '%s'",
  620. safe_str(address), safe_str(ent->new_address));
  621. strlcpy(address, ent->new_address, maxlen);
  622. }
  623. log_warn(LD_CONFIG,
  624. "Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
  625. safe_str(address));
  626. /* it's fine to rewrite a rewrite, but don't loop forever */
  627. }
  628. /** Return 1 if <b>address</b> is already registered, else return 0 */
  629. int
  630. addressmap_have_mapping(const char *address)
  631. {
  632. return strmap_get_lc(addressmap, address) ? 1 : 0;
  633. }
  634. /** Register a request to map <b>address</b> to <b>new_address</b>,
  635. * which will expire on <b>expires</b> (or 0 if never expires from
  636. * config file, 1 if never expires from controller, 2 if never expires
  637. * (virtual address mapping) from the controller.)
  638. *
  639. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  640. * free as appropriate. We will leave address alone.
  641. *
  642. * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
  643. * any mappings that exist from <b>address</b>.
  644. */
  645. void
  646. addressmap_register(const char *address, char *new_address, time_t expires)
  647. {
  648. addressmap_entry_t *ent;
  649. ent = strmap_get(addressmap, address);
  650. if (!new_address || !strcasecmp(address,new_address)) {
  651. /* Remove the mapping, if any. */
  652. tor_free(new_address);
  653. if (ent) {
  654. addressmap_ent_remove(address,ent);
  655. strmap_remove(addressmap, address);
  656. }
  657. return;
  658. }
  659. if (!ent) { /* make a new one and register it */
  660. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  661. strmap_set(addressmap, address, ent);
  662. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  663. if (expires > 1) {
  664. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  665. "since it's already mapped to '%s'",
  666. safe_str(address), safe_str(new_address), safe_str(ent->new_address));
  667. tor_free(new_address);
  668. return;
  669. }
  670. if (address_is_in_virtual_range(ent->new_address) &&
  671. expires != 2) {
  672. /* XXX This isn't the perfect test; we want to avoid removing
  673. * mappings set from the control interface _as virtual mapping */
  674. addressmap_virtaddress_remove(address, ent);
  675. }
  676. tor_free(ent->new_address);
  677. } /* else { we have an in-progress resolve with no mapping. } */
  678. ent->new_address = new_address;
  679. ent->expires = expires==2 ? 1 : expires;
  680. ent->num_resolve_failures = 0;
  681. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  682. safe_str(address), safe_str(ent->new_address));
  683. control_event_address_mapped(address, ent->new_address, expires);
  684. }
  685. /** An attempt to resolve <b>address</b> failed at some OR.
  686. * Increment the number of resolve failures we have on record
  687. * for it, and then return that number.
  688. */
  689. int
  690. client_dns_incr_failures(const char *address)
  691. {
  692. addressmap_entry_t *ent = strmap_get(addressmap, address);
  693. if (!ent) {
  694. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  695. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  696. strmap_set(addressmap,address,ent);
  697. }
  698. ++ent->num_resolve_failures;
  699. log_info(LD_APP, "Address %s now has %d resolve failures.",
  700. safe_str(address), ent->num_resolve_failures);
  701. return ent->num_resolve_failures;
  702. }
  703. /** If <b>address</b> is in the client dns addressmap, reset
  704. * the number of resolve failures we have on record for it.
  705. * This is used when we fail a stream because it won't resolve:
  706. * otherwise future attempts on that address will only try once.
  707. */
  708. void
  709. client_dns_clear_failures(const char *address)
  710. {
  711. addressmap_entry_t *ent = strmap_get(addressmap, address);
  712. if (ent)
  713. ent->num_resolve_failures = 0;
  714. }
  715. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  716. * We can now use this in subsequent streams via addressmap_rewrite()
  717. * so we can more correctly choose an exit that will allow <b>address</b>.
  718. *
  719. * If <b>exitname</b> is defined, then append the addresses with
  720. * ".exitname.exit" before registering the mapping.
  721. *
  722. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  723. * <b>ttl</b>seconds; otherwise, we use the default.
  724. */
  725. void
  726. client_dns_set_addressmap(const char *address, uint32_t val,
  727. const char *exitname,
  728. int ttl)
  729. {
  730. struct in_addr in;
  731. /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
  732. char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  733. /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
  734. char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  735. char valbuf[INET_NTOA_BUF_LEN];
  736. tor_assert(address);
  737. tor_assert(val);
  738. if (ttl<0)
  739. ttl = DEFAULT_DNS_TTL;
  740. else
  741. ttl = dns_clip_ttl(ttl);
  742. if (tor_inet_aton(address, &in))
  743. return; /* If address was an IP address already, don't add a mapping. */
  744. in.s_addr = htonl(val);
  745. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  746. if (exitname) {
  747. /* XXXX fails to ever get attempts to get an exit address of
  748. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  749. * won't make strict RFC952-compliant applications (like us) barf. */
  750. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  751. "%s.%s.exit", address, exitname);
  752. tor_snprintf(extendedval, sizeof(extendedval),
  753. "%s.%s.exit", valbuf, exitname);
  754. } else {
  755. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  756. "%s", address);
  757. tor_snprintf(extendedval, sizeof(extendedval),
  758. "%s", valbuf);
  759. }
  760. addressmap_register(extendedaddress, tor_strdup(extendedval),
  761. time(NULL) + ttl);
  762. }
  763. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  764. * These addresses should map to localhost, so even if the
  765. * application accidentally tried to connect to them directly (not
  766. * via Tor), it wouldn't get too far astray.
  767. *
  768. * Eventually, we should probably make this configurable.
  769. */
  770. static uint32_t virtual_addr_network = 0x7fc00000u;
  771. static uint32_t virtual_addr_netmask = 0xffc00000u;
  772. static int virtual_addr_netmask_bits = 10;
  773. static uint32_t next_virtual_addr = 0x7fc00000u;
  774. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  775. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  776. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  777. * string and return -1 on failure. If validate_only is false, sets the
  778. * actual virtual address range to the parsed value. */
  779. int
  780. parse_virtual_addr_network(const char *val, int validate_only,
  781. char **msg)
  782. {
  783. uint32_t addr, mask;
  784. uint16_t port_min, port_max;
  785. int bits;
  786. if (parse_addr_and_port_range(val, &addr, &mask, &port_min, &port_max)) {
  787. if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
  788. return -1;
  789. }
  790. if (port_min != 1 || port_max != 65535) {
  791. if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
  792. return -1;
  793. }
  794. bits = addr_mask_get_bits(mask);
  795. if (bits < 0) {
  796. if (msg) *msg = tor_strdup("VirtualAddressNetwork must have a mask that "
  797. "can be expressed as a prefix");
  798. return -1;
  799. }
  800. if (bits > 16) {
  801. if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
  802. "network or larger");
  803. return -1;
  804. }
  805. if (validate_only)
  806. return 0;
  807. virtual_addr_network = addr & mask;
  808. virtual_addr_netmask = mask;
  809. virtual_addr_netmask_bits = bits;
  810. if ((next_virtual_addr & mask) != addr)
  811. next_virtual_addr = addr;
  812. return 0;
  813. }
  814. /**
  815. * Return true iff <b>addr</b> is likely to have been returned by
  816. * client_dns_get_unused_address.
  817. **/
  818. int
  819. address_is_in_virtual_range(const char *address)
  820. {
  821. struct in_addr in;
  822. tor_assert(address);
  823. if (!strcasecmpend(address, ".virtual")) {
  824. return 1;
  825. } else if (tor_inet_aton(address, &in)) {
  826. uint32_t addr = ntohl(in.s_addr);
  827. if ((addr & virtual_addr_netmask) == virtual_addr_network)
  828. return 1;
  829. }
  830. return 0;
  831. }
  832. /** Return a newly allocated string holding an address of <b>type</b>
  833. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  834. * and that is very unlikely to be the address of any real host.
  835. */
  836. static char *
  837. addressmap_get_virtual_address(int type)
  838. {
  839. char buf[64];
  840. struct in_addr in;
  841. if (type == RESOLVED_TYPE_HOSTNAME) {
  842. char rand[10];
  843. do {
  844. crypto_rand(rand, sizeof(rand));
  845. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  846. strlcat(buf, ".virtual", sizeof(buf));
  847. } while (strmap_get(addressmap, buf));
  848. return tor_strdup(buf);
  849. } else if (type == RESOLVED_TYPE_IPV4) {
  850. // This is an imperfect estimate of how many addresses are available, but
  851. // that's ok.
  852. uint32_t available = 1u << (32-virtual_addr_netmask_bits);
  853. while (available) {
  854. /* Don't hand out any .0 or .255 address. */
  855. while ((next_virtual_addr & 0xff) == 0 ||
  856. (next_virtual_addr & 0xff) == 0xff) {
  857. ++next_virtual_addr;
  858. }
  859. in.s_addr = htonl(next_virtual_addr);
  860. tor_inet_ntoa(&in, buf, sizeof(buf));
  861. if (!strmap_get(addressmap, buf))
  862. break;
  863. ++next_virtual_addr;
  864. --available;
  865. log_notice(LD_CONFIG, "%d addrs available", (int)available);
  866. if (! --available) {
  867. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  868. return NULL;
  869. }
  870. if ((next_virtual_addr & virtual_addr_netmask) != virtual_addr_network)
  871. next_virtual_addr = virtual_addr_network;
  872. }
  873. return tor_strdup(buf);
  874. } else {
  875. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  876. return NULL;
  877. }
  878. }
  879. /** A controller has requested that we map some address of type
  880. * <b>type</b> to the address <b>new_address</b>. Choose an address
  881. * that is unlikely to be used, and map it, and return it in a newly
  882. * allocated string. If another address of the same type is already
  883. * mapped to <b>new_address</b>, try to return a copy of that address.
  884. *
  885. * The string in <b>new_address</b> may be freed, or inserted into a map
  886. * as appropriate.
  887. **/
  888. const char *
  889. addressmap_register_virtual_address(int type, char *new_address)
  890. {
  891. char **addrp;
  892. virtaddress_entry_t *vent;
  893. tor_assert(new_address);
  894. tor_assert(addressmap);
  895. tor_assert(virtaddress_reversemap);
  896. vent = strmap_get(virtaddress_reversemap, new_address);
  897. if (!vent) {
  898. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  899. strmap_set(virtaddress_reversemap, new_address, vent);
  900. }
  901. addrp = (type == RESOLVED_TYPE_IPV4) ?
  902. &vent->ipv4_address : &vent->hostname_address;
  903. if (*addrp) {
  904. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  905. if (ent && ent->new_address &&
  906. !strcasecmp(new_address, ent->new_address)) {
  907. tor_free(new_address);
  908. return tor_strdup(*addrp);
  909. } else
  910. log_warn(LD_BUG,
  911. "Internal confusion: I thought that '%s' was mapped to by "
  912. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  913. safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
  914. ent?safe_str(ent->new_address):"(nothing)");
  915. }
  916. tor_free(*addrp);
  917. *addrp = addressmap_get_virtual_address(type);
  918. addressmap_register(*addrp, new_address, 2);
  919. #if 0
  920. {
  921. /* Try to catch possible bugs */
  922. addressmap_entry_t *ent;
  923. ent = strmap_get(addressmap, *addrp);
  924. tor_assert(ent);
  925. tor_assert(!strcasecmp(ent->new_address,new_address));
  926. vent = strmap_get(virtaddress_reversemap, new_address);
  927. tor_assert(vent);
  928. tor_assert(!strcasecmp(*addrp,
  929. (type == RESOLVED_TYPE_IPV4) ?
  930. vent->ipv4_address : vent->hostname_address));
  931. log_fn(LOG_INFO, "Map from %s to %s okay.",
  932. safe_str(*addrp),safe_str(new_address));
  933. }
  934. #endif
  935. return *addrp;
  936. }
  937. /** Return 1 if <b>address</b> has funny characters in it like
  938. * colons. Return 0 if it's fine.
  939. */
  940. static int
  941. address_is_invalid_destination(const char *address)
  942. {
  943. /* FFFF should flesh this out */
  944. if (strchr(address,':'))
  945. return 1;
  946. return 0;
  947. }
  948. /** Iterate over all address mappings which have expiry times between
  949. * min_expires and max_expires, inclusive. If sl is provided, add an
  950. * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
  951. * remove the mappings.
  952. */
  953. void
  954. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  955. time_t max_expires)
  956. {
  957. strmap_iter_t *iter;
  958. const char *key;
  959. void *_val;
  960. addressmap_entry_t *val;
  961. if (!addressmap)
  962. addressmap_init();
  963. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  964. strmap_iter_get(iter, &key, &_val);
  965. val = _val;
  966. if (val->expires >= min_expires && val->expires <= max_expires) {
  967. if (!sl) {
  968. iter = strmap_iter_next_rmv(addressmap,iter);
  969. addressmap_ent_remove(key, val);
  970. continue;
  971. } else if (val->new_address) {
  972. size_t len = strlen(key)+strlen(val->new_address)+2;
  973. char *line = tor_malloc(len);
  974. tor_snprintf(line, len, "%s %s", key, val->new_address);
  975. smartlist_add(sl, line);
  976. }
  977. }
  978. iter = strmap_iter_next(addressmap,iter);
  979. }
  980. }
  981. /* Connection <b>conn</b> just finished its socks handshake, or the
  982. * controller asked us to take care of it. If <b>circ</b> is defined,
  983. * then that's where we'll want to attach it. Otherwise we have to
  984. * figure it out ourselves.
  985. *
  986. * First, parse whether it's a .exit address, remap it, and so on. Then
  987. * it's for a general circuit, try to attach it to a circuit (or launch
  988. * one as needed), else if it's for a rendezvous circuit, fetch a
  989. * rendezvous descriptor first (or attach/launch a circuit if the
  990. * rendezvous descriptor is already here and fresh enough).
  991. */
  992. int
  993. connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
  994. origin_circuit_t *circ)
  995. {
  996. socks_request_t *socks = conn->socks_request;
  997. hostname_type_t addresstype;
  998. tor_strlower(socks->address); /* normalize it */
  999. log_debug(LD_APP,"Client asked for %s:%d",
  1000. safe_str(socks->address),
  1001. socks->port);
  1002. /* For address map controls, remap the address */
  1003. addressmap_rewrite(socks->address, sizeof(socks->address));
  1004. if (address_is_in_virtual_range(socks->address)) {
  1005. /* This address was probably handed out by client_dns_get_unmapped_address,
  1006. * but the mapping was discarded for some reason. We *don't* want to send
  1007. * the address through Tor; that's likely to fail, and may leak
  1008. * information.
  1009. */
  1010. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1011. socks->address); /* don't safe_str() this yet. */
  1012. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  1013. return -1;
  1014. }
  1015. /* Parse the address provided by SOCKS. Modify it in-place if it
  1016. * specifies a hidden-service (.onion) or particular exit node (.exit).
  1017. */
  1018. addresstype = parse_extended_hostname(socks->address);
  1019. if (addresstype == BAD_HOSTNAME) {
  1020. log_warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
  1021. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1022. return -1;
  1023. }
  1024. if (addresstype == EXIT_HOSTNAME) {
  1025. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  1026. * node, and conn->address to hold only the address portion.*/
  1027. char *s = strrchr(socks->address,'.');
  1028. if (s) {
  1029. if (s[1] != '\0') {
  1030. conn->chosen_exit_name = tor_strdup(s+1);
  1031. *s = 0;
  1032. } else {
  1033. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1034. safe_str(socks->address));
  1035. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1036. return -1;
  1037. }
  1038. } else {
  1039. routerinfo_t *r;
  1040. conn->chosen_exit_name = tor_strdup(socks->address);
  1041. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  1042. *socks->address = 0;
  1043. if (r) {
  1044. strlcpy(socks->address, r->address, sizeof(socks->address));
  1045. } else {
  1046. log_warn(LD_APP,
  1047. "Unrecognized server in exit address '%s.exit'. Refusing.",
  1048. safe_str(socks->address));
  1049. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1050. return -1;
  1051. }
  1052. }
  1053. }
  1054. if (addresstype != ONION_HOSTNAME) {
  1055. /* not a hidden-service request (i.e. normal or .exit) */
  1056. if (address_is_invalid_destination(socks->address)) {
  1057. log_warn(LD_APP,
  1058. "Destination '%s' seems to be an invalid hostname. Failing.",
  1059. safe_str(socks->address));
  1060. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1061. return -1;
  1062. }
  1063. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1064. uint32_t answer;
  1065. struct in_addr in;
  1066. /* Reply to resolves immediately if we can. */
  1067. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  1068. log_warn(LD_APP,"Address to be resolved is too large. Failing.");
  1069. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1070. 0,NULL,-1);
  1071. connection_mark_unattached_ap(conn,
  1072. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1073. return -1;
  1074. }
  1075. if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
  1076. answer = in.s_addr; /* leave it in network order */
  1077. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  1078. (char*)&answer,-1);
  1079. connection_mark_unattached_ap(conn,
  1080. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1081. return 0;
  1082. }
  1083. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  1084. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1085. if (socks->port == 0) {
  1086. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1087. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1088. return -1;
  1089. }
  1090. if (!conn->chosen_exit_name && !circ) {
  1091. /* see if we can find a suitable enclave exit */
  1092. routerinfo_t *r =
  1093. router_find_exact_exit_enclave(socks->address, socks->port);
  1094. if (r) {
  1095. log_info(LD_APP,
  1096. "Redirecting address %s to exit at enclave router %s",
  1097. safe_str(socks->address), r->nickname);
  1098. /* use the hex digest, not nickname, in case there are two
  1099. routers with this nickname */
  1100. conn->chosen_exit_name =
  1101. tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
  1102. conn->_base.chosen_exit_optional = 1;
  1103. }
  1104. }
  1105. /* help predict this next time */
  1106. rep_hist_note_used_port(socks->port, time(NULL));
  1107. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1108. // XXXX NM Do anything here?
  1109. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  1110. } else {
  1111. tor_fragile_assert();
  1112. }
  1113. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1114. if ((circ &&
  1115. connection_ap_handshake_attach_chosen_circuit(conn, circ) < 0) ||
  1116. (!circ &&
  1117. connection_ap_handshake_attach_circuit(conn) < 0)) {
  1118. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1119. return -1;
  1120. }
  1121. return 0;
  1122. } else {
  1123. /* it's a hidden-service request */
  1124. rend_cache_entry_t *entry;
  1125. int r;
  1126. if (socks->command != SOCKS_COMMAND_CONNECT) {
  1127. /* if it's a resolve request, fail it right now, rather than
  1128. * building all the circuits and then realizing it won't work. */
  1129. log_warn(LD_APP,
  1130. "Resolve requests to hidden services not allowed. Failing.");
  1131. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1132. 0,NULL,-1);
  1133. connection_mark_unattached_ap(conn,
  1134. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1135. return -1;
  1136. }
  1137. if (circ) {
  1138. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1139. "supported for .onion addresses currently. Failing.");
  1140. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1141. return -1;
  1142. }
  1143. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  1144. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1145. safe_str(conn->rend_query));
  1146. /* see if we already have it cached */
  1147. r = rend_cache_lookup_entry(conn->rend_query, -1, &entry);
  1148. if (r<0) {
  1149. log_warn(LD_BUG,"Bug: Invalid service name '%s'",
  1150. safe_str(conn->rend_query));
  1151. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1152. return -1;
  1153. }
  1154. if (r==0) {
  1155. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1156. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1157. safe_str(conn->rend_query));
  1158. rend_client_refetch_renddesc(conn->rend_query);
  1159. } else { /* r > 0 */
  1160. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  1161. if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  1162. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1163. log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
  1164. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1165. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1166. return -1;
  1167. }
  1168. } else {
  1169. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1170. log_info(LD_REND, "Stale descriptor %s. Refetching.",
  1171. safe_str(conn->rend_query));
  1172. rend_client_refetch_renddesc(conn->rend_query);
  1173. }
  1174. }
  1175. return 0;
  1176. }
  1177. return 0; /* unreached but keeps the compiler happy */
  1178. }
  1179. #ifdef TRANS_PF
  1180. static int pf_socket = -1;
  1181. static int
  1182. get_pf_socket(void)
  1183. {
  1184. int pf;
  1185. /* Ideally, this should be opened before dropping privs. */
  1186. if (pf_socket >= 0)
  1187. return pf_socket;
  1188. #ifdef OPENBSD
  1189. /* only works on OpenBSD */
  1190. pf = open("/dev/pf", O_RDONLY);
  1191. #else
  1192. /* works on NetBSD and FreeBSD */
  1193. pf = open("/dev/pf", O_RDWR);
  1194. #endif
  1195. if (pf < 0) {
  1196. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1197. return -1;
  1198. }
  1199. pf_socket = pf;
  1200. }
  1201. #endif
  1202. /** Fetch the original destination address and port from a
  1203. * system-specific interface and put them into a
  1204. * socks_request_t as if they came from a socks request.
  1205. *
  1206. * Return -1 if an error prevents fetching the destination,
  1207. * else return 0.
  1208. */
  1209. static int
  1210. connection_ap_get_original_destination(edge_connection_t *conn,
  1211. socks_request_t *req)
  1212. {
  1213. #ifdef TRANS_NETFILTER
  1214. /* Linux 2.4+ */
  1215. struct sockaddr_in orig_dst;
  1216. socklen_t orig_dst_len = sizeof(orig_dst);
  1217. char tmpbuf[INET_NTOA_BUF_LEN];
  1218. if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
  1219. (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
  1220. int e = tor_socket_errno(conn->_base.s);
  1221. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1222. return -1;
  1223. }
  1224. tor_inet_ntoa(&orig_dst.sin_addr, tmpbuf, sizeof(tmpbuf));
  1225. strlcpy(req->address, tmpbuf, sizeof(req->address));
  1226. req->port = ntohs(orig_dst.sin_port);
  1227. return 0;
  1228. #elif defined(TRANS_PF)
  1229. struct sockaddr_in proxy_addr;
  1230. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1231. char tmpbuf[INET_NTOA_BUF_LEN];
  1232. struct pfioc_natlook pnl;
  1233. int pf = -1;
  1234. if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
  1235. &proxy_addr_len) < 0) {
  1236. int e = tor_socket_errno(conn->_base.s);
  1237. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1238. "failed: %s", tor_socket_strerror(e));
  1239. return -1;
  1240. }
  1241. memset(&pnl, 0, sizeof(pnl));
  1242. pnl.af = AF_INET;
  1243. pnl.proto = IPPROTO_TCP;
  1244. pnl.direction = PF_OUT;
  1245. pnl.saddr.v4.s_addr = htonl(conn->_base.addr);
  1246. pnl.sport = htons(conn->_base.port);
  1247. pnl.daddr.v4.s_addr = proxy_addr.sin_addr.s_addr;
  1248. pnl.dport = proxy_addr.sin_port;
  1249. pf = get_pf_socket();
  1250. if (pf<0)
  1251. return -1;
  1252. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1253. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1254. return -1;
  1255. }
  1256. tor_inet_ntoa(&pnl.rdaddr.v4, tmpbuf, sizeof(tmpbuf));
  1257. strlcpy(req->address, tmpbuf, sizeof(req->address));
  1258. req->port = ntohs(pnl.rdport);
  1259. return 0;
  1260. #else
  1261. (void)conn;
  1262. (void)req;
  1263. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  1264. "transparent proxy method was configured.");
  1265. return -1;
  1266. #endif
  1267. }
  1268. /** connection_edge_process_inbuf() found a conn in state
  1269. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1270. * the socks handshake.
  1271. *
  1272. * If the handshake is complete, send it to
  1273. * connection_ap_handshake_rewrite_and_attach().
  1274. *
  1275. * Return -1 if an unexpected error with conn (and it should be marked
  1276. * for close), else return 0.
  1277. */
  1278. static int
  1279. connection_ap_handshake_process_socks(edge_connection_t *conn)
  1280. {
  1281. socks_request_t *socks;
  1282. int sockshere;
  1283. or_options_t *options = get_options();
  1284. tor_assert(conn);
  1285. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1286. tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
  1287. tor_assert(conn->socks_request);
  1288. socks = conn->socks_request;
  1289. log_debug(LD_APP,"entered.");
  1290. sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
  1291. options->TestSocks, options->SafeSocks);
  1292. if (sockshere == 0) {
  1293. if (socks->replylen) {
  1294. connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
  1295. /* zero it out so we can do another round of negotiation */
  1296. socks->replylen = 0;
  1297. } else {
  1298. log_debug(LD_APP,"socks handshake not all here yet.");
  1299. }
  1300. return 0;
  1301. } else if (sockshere == -1) {
  1302. if (socks->replylen) { /* we should send reply back */
  1303. log_debug(LD_APP,"reply is already set for us. Using it.");
  1304. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
  1305. END_STREAM_REASON_SOCKSPROTOCOL);
  1306. } else {
  1307. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1308. connection_ap_handshake_socks_reply(conn, NULL, 0,
  1309. END_STREAM_REASON_SOCKSPROTOCOL);
  1310. }
  1311. connection_mark_unattached_ap(conn,
  1312. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1313. return -1;
  1314. } /* else socks handshake is done, continue processing */
  1315. if (socks->command == SOCKS_COMMAND_CONNECT)
  1316. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1317. else
  1318. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  1319. if (options->LeaveStreamsUnattached) {
  1320. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1321. return 0;
  1322. }
  1323. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1324. }
  1325. /** connection_init_accepted_conn() found a new trans AP conn.
  1326. * Get the original destination and send it to
  1327. * connection_ap_handshake_rewrite_and_attach().
  1328. *
  1329. * Return -1 if an unexpected error with conn (and it should be marked
  1330. * for close), else return 0.
  1331. */
  1332. int
  1333. connection_ap_process_transparent(edge_connection_t *conn)
  1334. {
  1335. socks_request_t *socks;
  1336. or_options_t *options = get_options();
  1337. tor_assert(conn);
  1338. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1339. tor_assert(conn->socks_request);
  1340. socks = conn->socks_request;
  1341. /* pretend that a socks handshake completed so we don't try to
  1342. * send a socks reply down a transparent conn */
  1343. socks->command = SOCKS_COMMAND_CONNECT;
  1344. socks->has_finished = 1;
  1345. log_debug(LD_APP,"entered.");
  1346. if (connection_ap_get_original_destination(conn, socks) < 0) {
  1347. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  1348. connection_mark_unattached_ap(conn,
  1349. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  1350. return -1;
  1351. }
  1352. /* we have the original destination */
  1353. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1354. if (options->LeaveStreamsUnattached) {
  1355. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1356. return 0;
  1357. }
  1358. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1359. }
  1360. /** connection_edge_process_inbuf() found a conn in state
  1361. * natd_wait. See if conn->inbuf has the right bytes to proceed.
  1362. * See libalias(3) and ProxyEncodeTcpStream() in alias_proxy.c for
  1363. * the encoding form of the original destination.
  1364. *
  1365. * If the original destination is complete, send it to
  1366. * connection_ap_handshake_rewrite_and_attach().
  1367. *
  1368. * Return -1 if an unexpected error with conn (and it should be marked
  1369. * for close), else return 0.
  1370. */
  1371. static int
  1372. connection_ap_process_natd(edge_connection_t *conn)
  1373. {
  1374. char tmp_buf[36], *tbuf, *daddr;
  1375. size_t tlen = 30;
  1376. int err, port_ok;
  1377. socks_request_t *socks;
  1378. or_options_t *options = get_options();
  1379. tor_assert(conn);
  1380. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1381. tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
  1382. tor_assert(conn->socks_request);
  1383. socks = conn->socks_request;
  1384. log_debug(LD_APP,"entered.");
  1385. /* look for LF-terminated "[DEST ip_addr port]"
  1386. * where ip_addr is a dotted-quad and port is in string form */
  1387. err = fetch_from_buf_line_lf(conn->_base.inbuf, tmp_buf, &tlen);
  1388. if (err == 0)
  1389. return 0;
  1390. if (err < 0) {
  1391. log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
  1392. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1393. return -1;
  1394. }
  1395. if (strcmpstart(tmp_buf, "[DEST ")) {
  1396. log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
  1397. "said: '%s'",
  1398. escaped(tmp_buf));
  1399. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1400. return -1;
  1401. }
  1402. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  1403. while (*tbuf != '\0' && *tbuf != ' ')
  1404. tbuf++;
  1405. *tbuf = '\0';
  1406. tbuf++;
  1407. /* pretend that a socks handshake completed so we don't try to
  1408. * send a socks reply down a natd conn */
  1409. strlcpy(socks->address, daddr, sizeof(socks->address));
  1410. socks->port = (uint16_t) tor_parse_long(tbuf, 10, 1, 65535, &port_ok, NULL);
  1411. if (!port_ok) {
  1412. log_warn(LD_APP,"Natd handshake failed; port '%s' is ill-formed or out "
  1413. "of range.", escaped(tbuf));
  1414. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1415. return -1;
  1416. }
  1417. socks->command = SOCKS_COMMAND_CONNECT;
  1418. socks->has_finished = 1;
  1419. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1420. if (options->LeaveStreamsUnattached) {
  1421. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1422. return 0;
  1423. }
  1424. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1425. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1426. }
  1427. /** Iterate over the two bytes of stream_id until we get one that is not
  1428. * already in use; return it. Return 0 if can't get a unique stream_id.
  1429. */
  1430. static uint16_t
  1431. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  1432. {
  1433. edge_connection_t *tmpconn;
  1434. uint16_t test_stream_id;
  1435. uint32_t attempts=0;
  1436. again:
  1437. test_stream_id = circ->next_stream_id++;
  1438. if (++attempts > 1<<16) {
  1439. /* Make sure we don't loop forever if all stream_id's are used. */
  1440. log_warn(LD_APP,"No unused stream IDs. Failing.");
  1441. return 0;
  1442. }
  1443. if (test_stream_id == 0)
  1444. goto again;
  1445. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1446. if (tmpconn->stream_id == test_stream_id)
  1447. goto again;
  1448. return test_stream_id;
  1449. }
  1450. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1451. * socks_request field, and send it down circ.
  1452. *
  1453. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1454. */
  1455. int
  1456. connection_ap_handshake_send_begin(edge_connection_t *ap_conn,
  1457. origin_circuit_t *circ)
  1458. {
  1459. char payload[CELL_PAYLOAD_SIZE];
  1460. int payload_len;
  1461. tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
  1462. tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1463. tor_assert(ap_conn->socks_request);
  1464. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1465. if (ap_conn->stream_id==0) {
  1466. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1467. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  1468. return -1;
  1469. }
  1470. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1471. (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1472. ap_conn->socks_request->address : "",
  1473. ap_conn->socks_request->port);
  1474. payload_len = strlen(payload)+1;
  1475. log_debug(LD_APP,
  1476. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  1477. if (connection_edge_send_command(ap_conn, TO_CIRCUIT(circ),
  1478. RELAY_COMMAND_BEGIN,
  1479. payload, payload_len,
  1480. ap_conn->cpath_layer) < 0)
  1481. return -1; /* circuit is closed, don't continue */
  1482. ap_conn->package_window = STREAMWINDOW_START;
  1483. ap_conn->deliver_window = STREAMWINDOW_START;
  1484. ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
  1485. log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
  1486. ap_conn->_base.s, circ->_base.n_circ_id);
  1487. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  1488. return 0;
  1489. }
  1490. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1491. * socks_request field, and send it down circ.
  1492. *
  1493. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1494. */
  1495. int
  1496. connection_ap_handshake_send_resolve(edge_connection_t *ap_conn,
  1497. origin_circuit_t *circ)
  1498. {
  1499. int payload_len, command;
  1500. const char *string_addr;
  1501. char inaddr_buf[32];
  1502. command = ap_conn->socks_request->command;
  1503. tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
  1504. tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1505. tor_assert(ap_conn->socks_request);
  1506. tor_assert(command == SOCKS_COMMAND_RESOLVE ||
  1507. command == SOCKS_COMMAND_RESOLVE_PTR);
  1508. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1509. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1510. if (ap_conn->stream_id==0) {
  1511. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1512. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  1513. return -1;
  1514. }
  1515. if (command == SOCKS_COMMAND_RESOLVE) {
  1516. string_addr = ap_conn->socks_request->address;
  1517. payload_len = strlen(string_addr)+1;
  1518. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  1519. } else {
  1520. struct in_addr in;
  1521. uint32_t a;
  1522. if (tor_inet_aton(ap_conn->socks_request->address, &in) == 0) {
  1523. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1524. return -1;
  1525. }
  1526. a = ntohl(in.s_addr);
  1527. tor_snprintf(inaddr_buf, sizeof(inaddr_buf), "%d.%d.%d.%d.in-addr.arpa",
  1528. (int)(uint8_t)((a )&0xff),
  1529. (int)(uint8_t)((a>>8 )&0xff),
  1530. (int)(uint8_t)((a>>16)&0xff),
  1531. (int)(uint8_t)((a>>24)&0xff));
  1532. string_addr = inaddr_buf;
  1533. payload_len = strlen(inaddr_buf)+1;
  1534. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  1535. }
  1536. log_debug(LD_APP,
  1537. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  1538. if (connection_edge_send_command(ap_conn, TO_CIRCUIT(circ),
  1539. RELAY_COMMAND_RESOLVE,
  1540. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  1541. return -1; /* circuit is closed, don't continue */
  1542. ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
  1543. log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
  1544. ap_conn->_base.s, circ->_base.n_circ_id);
  1545. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  1546. return 0;
  1547. }
  1548. /** Make an AP connection_t, do a socketpair and attach one side
  1549. * to the conn, connection_add it, initialize it to circuit_wait,
  1550. * and call connection_ap_handshake_attach_circuit(conn) on it.
  1551. *
  1552. * Return the other end of the socketpair, or -1 if error.
  1553. */
  1554. int
  1555. connection_ap_make_bridge(char *address, uint16_t port)
  1556. {
  1557. int fd[2];
  1558. edge_connection_t *conn;
  1559. int err;
  1560. log_info(LD_APP,"Making AP bridge to %s:%d ...",safe_str(address),port);
  1561. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
  1562. log_warn(LD_NET,
  1563. "Couldn't construct socketpair (%s). Network down? Delaying.",
  1564. tor_socket_strerror(-err));
  1565. return -1;
  1566. }
  1567. tor_assert(fd[0] >= 0);
  1568. tor_assert(fd[1] >= 0);
  1569. set_socket_nonblocking(fd[0]);
  1570. set_socket_nonblocking(fd[1]);
  1571. conn = TO_EDGE_CONN(connection_new(CONN_TYPE_AP));
  1572. conn->_base.s = fd[0];
  1573. /* populate conn->socks_request */
  1574. /* leave version at zero, so the socks_reply is empty */
  1575. conn->socks_request->socks_version = 0;
  1576. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  1577. strlcpy(conn->socks_request->address, address,
  1578. sizeof(conn->socks_request->address));
  1579. conn->socks_request->port = port;
  1580. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  1581. conn->_base.address = tor_strdup("(local bridge)");
  1582. conn->_base.addr = 0;
  1583. conn->_base.port = 0;
  1584. if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
  1585. connection_free(TO_CONN(conn)); /* this closes fd[0] */
  1586. tor_close_socket(fd[1]);
  1587. return -1;
  1588. }
  1589. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1590. connection_start_reading(TO_CONN(conn));
  1591. /* attaching to a dirty circuit is fine */
  1592. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1593. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1594. tor_close_socket(fd[1]);
  1595. return -1;
  1596. }
  1597. log_info(LD_APP,"... AP bridge created and connected.");
  1598. return fd[1];
  1599. }
  1600. /** Send an answer to an AP connection that has requested a DNS lookup
  1601. * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or
  1602. * -1 for unreachable; the answer should be in the format specified
  1603. * in the socks extensions document.
  1604. **/
  1605. void
  1606. connection_ap_handshake_socks_resolved(edge_connection_t *conn,
  1607. int answer_type,
  1608. size_t answer_len,
  1609. const char *answer,
  1610. int ttl)
  1611. {
  1612. char buf[384];
  1613. size_t replylen;
  1614. if (answer_type == RESOLVED_TYPE_IPV4) {
  1615. uint32_t a = ntohl(get_uint32(answer));
  1616. if (a)
  1617. client_dns_set_addressmap(conn->socks_request->address, a,
  1618. conn->chosen_exit_name, ttl);
  1619. }
  1620. if (conn->socks_request->socks_version == 4) {
  1621. buf[0] = 0x00; /* version */
  1622. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1623. buf[1] = 90; /* "Granted" */
  1624. set_uint16(buf+2, 0);
  1625. memcpy(buf+4, answer, 4); /* address */
  1626. replylen = SOCKS4_NETWORK_LEN;
  1627. } else {
  1628. buf[1] = 91; /* "error" */
  1629. memset(buf+2, 0, 6);
  1630. replylen = SOCKS4_NETWORK_LEN;
  1631. }
  1632. } else {
  1633. /* SOCKS5 */
  1634. buf[0] = 0x05; /* version */
  1635. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1636. buf[1] = SOCKS5_SUCCEEDED;
  1637. buf[2] = 0; /* reserved */
  1638. buf[3] = 0x01; /* IPv4 address type */
  1639. memcpy(buf+4, answer, 4); /* address */
  1640. set_uint16(buf+8, 0); /* port == 0. */
  1641. replylen = 10;
  1642. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1643. buf[1] = SOCKS5_SUCCEEDED;
  1644. buf[2] = 0; /* reserved */
  1645. buf[3] = 0x04; /* IPv6 address type */
  1646. memcpy(buf+4, answer, 16); /* address */
  1647. set_uint16(buf+20, 0); /* port == 0. */
  1648. replylen = 22;
  1649. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  1650. buf[1] = SOCKS5_SUCCEEDED;
  1651. buf[2] = 0; /* reserved */
  1652. buf[3] = 0x03; /* Domainname address type */
  1653. buf[4] = (char)answer_len;
  1654. memcpy(buf+5, answer, answer_len); /* address */
  1655. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  1656. replylen = 5+answer_len+2;
  1657. } else {
  1658. buf[1] = SOCKS5_HOST_UNREACHABLE;
  1659. memset(buf+2, 0, 8);
  1660. replylen = 10;
  1661. }
  1662. }
  1663. connection_ap_handshake_socks_reply(conn, buf, replylen,
  1664. (answer_type == RESOLVED_TYPE_IPV4 ||
  1665. answer_type == RESOLVED_TYPE_IPV6) ?
  1666. 0 : END_STREAM_REASON_RESOLVEFAILED);
  1667. }
  1668. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  1669. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  1670. * handshaking.
  1671. *
  1672. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  1673. * to conn and return, else reply based on <b>status</b>.
  1674. *
  1675. * If <b>reply</b> is undefined, <b>status</b> can't be 0.
  1676. * DOCDOC endreason
  1677. */
  1678. void
  1679. connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
  1680. size_t replylen, int endreason)
  1681. {
  1682. char buf[256];
  1683. socks5_reply_status_t status =
  1684. connection_edge_end_reason_socks5_response(endreason);
  1685. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  1686. control_event_stream_status(conn,
  1687. status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  1688. endreason);
  1689. if (conn->socks_request->has_finished) {
  1690. log_warn(LD_BUG, "Harmless bug: duplicate calls to "
  1691. "connection_ap_handshake_socks_reply.");
  1692. return;
  1693. }
  1694. if (replylen) { /* we already have a reply in mind */
  1695. connection_write_to_buf(reply, replylen, TO_CONN(conn));
  1696. conn->socks_request->has_finished = 1;
  1697. return;
  1698. }
  1699. if (conn->socks_request->socks_version == 4) {
  1700. memset(buf,0,SOCKS4_NETWORK_LEN);
  1701. #define SOCKS4_GRANTED 90
  1702. #define SOCKS4_REJECT 91
  1703. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  1704. /* leave version, destport, destip zero */
  1705. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
  1706. } else if (conn->socks_request->socks_version == 5) {
  1707. buf[0] = 5; /* version 5 */
  1708. buf[1] = (char)status;
  1709. buf[2] = 0;
  1710. buf[3] = 1; /* ipv4 addr */
  1711. memset(buf+4,0,6); /* Set external addr/port to 0.
  1712. The spec doesn't seem to say what to do here. -RD */
  1713. connection_write_to_buf(buf,10,TO_CONN(conn));
  1714. }
  1715. /* If socks_version isn't 4 or 5, don't send anything.
  1716. * This can happen in the case of AP bridges. */
  1717. conn->socks_request->has_finished = 1;
  1718. return;
  1719. }
  1720. /** A relay 'begin' cell has arrived, and either we are an exit hop
  1721. * for the circuit, or we are the origin and it is a rendezvous begin.
  1722. *
  1723. * Launch a new exit connection and initialize things appropriately.
  1724. *
  1725. * If it's a rendezvous stream, call connection_exit_connect() on
  1726. * it.
  1727. *
  1728. * For general streams, call dns_resolve() on it first, and only call
  1729. * connection_exit_connect() if the dns answer is already known.
  1730. *
  1731. * Note that we don't call connection_add() on the new stream! We wait
  1732. * for connection_exit_connect() to do that.
  1733. *
  1734. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  1735. * Else return 0.
  1736. */
  1737. int
  1738. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  1739. {
  1740. edge_connection_t *n_stream;
  1741. relay_header_t rh;
  1742. char *address=NULL;
  1743. uint16_t port;
  1744. char end_payload[1];
  1745. assert_circuit_ok(circ);
  1746. relay_header_unpack(&rh, cell->payload);
  1747. /* Note: we have to use relay_send_command_from_edge here, not
  1748. * connection_edge_end or connection_edge_send_command, since those require
  1749. * that we have a stream connected to a circuit, and we don't connect to a
  1750. * circuit until we have a pending/successful resolve. */
  1751. if (!server_mode(get_options()) &&
  1752. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1753. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1754. "Relay begin cell at non-server. Closing.");
  1755. end_payload[0] = END_STREAM_REASON_EXITPOLICY;
  1756. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1757. end_payload, 1, NULL);
  1758. return 0;
  1759. }
  1760. if (rh.command == RELAY_COMMAND_BEGIN) {
  1761. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  1762. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1763. "Relay begin cell has no \\0. Closing.");
  1764. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1765. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1766. end_payload, 1, NULL);
  1767. return 0;
  1768. }
  1769. if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
  1770. &address,NULL,&port)<0) {
  1771. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1772. "Unable to parse addr:port in relay begin cell. Closing.");
  1773. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1774. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1775. end_payload, 1, NULL);
  1776. return 0;
  1777. }
  1778. if (port==0) {
  1779. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1780. "Missing port in relay begin cell. Closing.");
  1781. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1782. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1783. end_payload, 1, NULL);
  1784. tor_free(address);
  1785. return 0;
  1786. }
  1787. #if 0
  1788. if (!tor_strisprint(address)) {
  1789. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1790. "Non-printing characters in address %s in relay "
  1791. "begin cell. Closing.", escaped(address));
  1792. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1793. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1794. end_payload, 1, NULL);
  1795. tor_free(address);
  1796. return 0;
  1797. }
  1798. #endif
  1799. if (!CIRCUIT_IS_ORIGIN(circ) && TO_OR_CIRCUIT(circ)->is_first_hop) {
  1800. /* Don't let clients use us as a single-hop proxy; it attracts attackers
  1801. * and users who'd be better off with, well, single-hop proxies.
  1802. */
  1803. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1804. "Attempt to open a stream on first hop of circuit. Closing.");
  1805. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1806. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1807. end_payload, 1, NULL);
  1808. tor_free(address);
  1809. return 0;
  1810. }
  1811. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1812. or_options_t *options = get_options();
  1813. port = options->DirPort; /* not actually used to open a connection */
  1814. if (!port || circ->purpose != CIRCUIT_PURPOSE_OR) {
  1815. end_payload[0] = END_STREAM_REASON_NOTDIRECTORY;
  1816. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1817. end_payload, 1, NULL);
  1818. return 0;
  1819. }
  1820. address = tor_strdup("127.0.0.1");
  1821. } else {
  1822. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  1823. end_payload[0] = END_STREAM_REASON_INTERNAL;
  1824. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1825. end_payload, 1, NULL);
  1826. return 0;
  1827. }
  1828. log_debug(LD_EXIT,"Creating new exit connection.");
  1829. n_stream = TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT));
  1830. n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
  1831. n_stream->stream_id = rh.stream_id;
  1832. n_stream->_base.port = port;
  1833. /* leave n_stream->s at -1, because it's not yet valid */
  1834. n_stream->package_window = STREAMWINDOW_START;
  1835. n_stream->deliver_window = STREAMWINDOW_START;
  1836. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1837. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1838. log_debug(LD_REND,"begin is for rendezvous. configuring stream.");
  1839. n_stream->_base.address = tor_strdup("(rendezvous)");
  1840. n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
  1841. strlcpy(n_stream->rend_query, origin_circ->rend_query,
  1842. sizeof(n_stream->rend_query));
  1843. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  1844. assert_circuit_ok(circ);
  1845. if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
  1846. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  1847. n_stream->_base.port);
  1848. end_payload[0] = END_STREAM_REASON_EXITPOLICY;
  1849. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1850. end_payload, 1, NULL);
  1851. connection_free(TO_CONN(n_stream));
  1852. /* knock the whole thing down, somebody screwed up */
  1853. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  1854. tor_free(address);
  1855. return 0;
  1856. }
  1857. assert_circuit_ok(circ);
  1858. log_debug(LD_REND,"Finished assigning addr/port");
  1859. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  1860. /* add it into the linked list of n_streams on this circuit */
  1861. n_stream->next_stream = origin_circ->p_streams;
  1862. n_stream->on_circuit = circ;
  1863. origin_circ->p_streams = n_stream;
  1864. assert_circuit_ok(circ);
  1865. connection_exit_connect(n_stream);
  1866. tor_free(address);
  1867. return 0;
  1868. }
  1869. tor_strlower(address);
  1870. n_stream->_base.address = address;
  1871. n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1872. /* default to failed, change in dns_resolve if it turns out not to fail */
  1873. if (we_are_hibernating()) {
  1874. end_payload[0] = END_STREAM_REASON_HIBERNATING;
  1875. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1876. end_payload, 1, NULL);
  1877. connection_free(TO_CONN(n_stream));
  1878. return 0;
  1879. }
  1880. log_debug(LD_EXIT,"about to start the dns_resolve().");
  1881. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1882. n_stream->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1883. n_stream->on_circuit = circ;
  1884. TO_OR_CIRCUIT(circ)->n_streams = n_stream;
  1885. return connection_exit_connect_dir(n_stream);
  1886. }
  1887. /* send it off to the gethostbyname farm */
  1888. switch (dns_resolve(n_stream, NULL)) {
  1889. case 1: /* resolve worked */
  1890. /* add it into the linked list of n_streams on this circuit */
  1891. n_stream->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1892. n_stream->on_circuit = circ;
  1893. TO_OR_CIRCUIT(circ)->n_streams = n_stream;
  1894. assert_circuit_ok(circ);
  1895. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  1896. connection_exit_connect(n_stream);
  1897. return 0;
  1898. case -1: /* resolve failed */
  1899. end_payload[0] = END_STREAM_REASON_RESOLVEFAILED;
  1900. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1901. end_payload, 1, NULL);
  1902. /* n_stream got freed. don't touch it. */
  1903. break;
  1904. case 0: /* resolve added to pending list */
  1905. /* add it into the linked list of resolving_streams on this circuit */
  1906. n_stream->next_stream = TO_OR_CIRCUIT(circ)->resolving_streams;
  1907. n_stream->on_circuit = circ;
  1908. TO_OR_CIRCUIT(circ)->resolving_streams = n_stream;
  1909. assert_circuit_ok(circ);
  1910. ;
  1911. }
  1912. return 0;
  1913. }
  1914. /**
  1915. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  1916. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  1917. */
  1918. int
  1919. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  1920. {
  1921. edge_connection_t *dummy_conn;
  1922. relay_header_t rh;
  1923. assert_circuit_ok(TO_CIRCUIT(circ));
  1924. relay_header_unpack(&rh, cell->payload);
  1925. /* This 'dummy_conn' only exists to remember the stream ID
  1926. * associated with the resolve request; and to make the
  1927. * implementation of dns.c more uniform. (We really only need to
  1928. * remember the circuit, the stream ID, and the hostname to be
  1929. * resolved; but if we didn't store them in a connection like this,
  1930. * the housekeeping in dns.c would get way more complicated.)
  1931. */
  1932. dummy_conn = TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT));
  1933. dummy_conn->stream_id = rh.stream_id;
  1934. dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  1935. rh.length);
  1936. dummy_conn->_base.port = 0;
  1937. dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1938. dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
  1939. /* send it off to the gethostbyname farm */
  1940. switch (dns_resolve(dummy_conn, circ)) {
  1941. case -1: /* Impossible to resolve; a resolved cell was sent. */
  1942. /* Connection freed; don't touch it. */
  1943. return 0;
  1944. case 1: /* The result was cached; a resolved cell was sent. */
  1945. if (!dummy_conn->_base.marked_for_close)
  1946. connection_free(TO_CONN(dummy_conn));
  1947. return 0;
  1948. case 0: /* resolve added to pending list */
  1949. dummy_conn->next_stream = circ->resolving_streams;
  1950. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  1951. circ->resolving_streams = dummy_conn;
  1952. assert_circuit_ok(TO_CIRCUIT(circ));
  1953. break;
  1954. }
  1955. return 0;
  1956. }
  1957. /** Connect to conn's specified addr and port. If it worked, conn
  1958. * has now been added to the connection_array.
  1959. *
  1960. * Send back a connected cell. Include the resolved IP of the destination
  1961. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  1962. * streams must not reveal what IP they connected to.)
  1963. */
  1964. void
  1965. connection_exit_connect(edge_connection_t *edge_conn)
  1966. {
  1967. uint32_t addr;
  1968. uint16_t port;
  1969. connection_t *conn = TO_CONN(edge_conn);
  1970. if (!connection_edge_is_rendezvous_stream(edge_conn) &&
  1971. router_compare_to_my_exit_policy(edge_conn)) {
  1972. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  1973. escaped_safe_str(conn->address), conn->port);
  1974. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY,
  1975. edge_conn->cpath_layer);
  1976. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  1977. connection_free(conn);
  1978. return;
  1979. }
  1980. addr = conn->addr;
  1981. port = conn->port;
  1982. if (redirect_exit_list) {
  1983. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
  1984. {
  1985. if ((addr&r->mask)==(r->addr&r->mask) &&
  1986. (r->port_min <= port) && (port <= r->port_max)) {
  1987. struct in_addr in;
  1988. if (r->is_redirect) {
  1989. char tmpbuf[INET_NTOA_BUF_LEN];
  1990. addr = r->addr_dest;
  1991. port = r->port_dest;
  1992. in.s_addr = htonl(addr);
  1993. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  1994. log_debug(LD_EXIT, "Redirecting connection from %s:%d to %s:%d",
  1995. escaped_safe_str(conn->address), conn->port,
  1996. safe_str(tmpbuf), port);
  1997. }
  1998. break;
  1999. }
  2000. });
  2001. }
  2002. log_debug(LD_EXIT,"about to try connecting");
  2003. switch (connection_connect(conn, conn->address, addr, port)) {
  2004. case -1:
  2005. connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
  2006. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2007. connection_free(conn);
  2008. return;
  2009. case 0:
  2010. conn->state = EXIT_CONN_STATE_CONNECTING;
  2011. connection_watch_events(conn, EV_WRITE | EV_READ);
  2012. /* writable indicates finish;
  2013. * readable/error indicates broken link in windowsland. */
  2014. return;
  2015. /* case 1: fall through */
  2016. }
  2017. conn->state = EXIT_CONN_STATE_OPEN;
  2018. if (connection_wants_to_flush(conn)) {
  2019. /* in case there are any queued data cells */
  2020. log_warn(LD_BUG,"Bug: newly connected conn had data waiting!");
  2021. // connection_start_writing(conn);
  2022. }
  2023. connection_watch_events(conn, EV_READ);
  2024. /* also, deliver a 'connected' cell back through the circuit. */
  2025. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  2026. /* rendezvous stream */
  2027. /* don't send an address back! */
  2028. connection_edge_send_command(edge_conn,
  2029. circuit_get_by_edge_conn(edge_conn),
  2030. RELAY_COMMAND_CONNECTED,
  2031. NULL, 0, edge_conn->cpath_layer);
  2032. } else { /* normal stream */
  2033. /* This must be the original address, not the redirected address. */
  2034. char connected_payload[8];
  2035. set_uint32(connected_payload, htonl(conn->addr));
  2036. set_uint32(connected_payload+4,
  2037. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  2038. connection_edge_send_command(edge_conn,
  2039. circuit_get_by_edge_conn(edge_conn),
  2040. RELAY_COMMAND_CONNECTED,
  2041. connected_payload, 8, edge_conn->cpath_layer);
  2042. }
  2043. }
  2044. /** Given an exit conn that should attach to us as a directory server, open a
  2045. * bridge connection with a socketpair, create a new directory conn, and join
  2046. * them together. Return 0 on success (or if there was an error we could send
  2047. * back an end cell for). Return -(some circuit end reason) if the circuit
  2048. * needs to be torn down. Either connects exit_conn, frees it, or marks it,
  2049. * as appropriate.
  2050. */
  2051. static int
  2052. connection_exit_connect_dir(edge_connection_t *exit_conn)
  2053. {
  2054. int fd[2];
  2055. int err;
  2056. dir_connection_t *dir_conn = NULL;
  2057. log_info(LD_EXIT, "Opening dir bridge");
  2058. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
  2059. log_warn(LD_NET,
  2060. "Couldn't construct socketpair (%s). "
  2061. "Network down? Out of sockets?",
  2062. tor_socket_strerror(-err));
  2063. connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
  2064. exit_conn->cpath_layer);
  2065. connection_free(TO_CONN(exit_conn));
  2066. return 0;
  2067. }
  2068. tor_assert(fd[0] >= 0);
  2069. tor_assert(fd[1] >= 0);
  2070. set_socket_nonblocking(fd[0]);
  2071. set_socket_nonblocking(fd[1]);
  2072. exit_conn->_base.s = fd[0];
  2073. exit_conn->_base.state = EXIT_CONN_STATE_OPEN;
  2074. dir_conn = TO_DIR_CONN(connection_new(CONN_TYPE_DIR));
  2075. dir_conn->_base.s = fd[1];
  2076. dir_conn->_base.addr = 0x7f000001;
  2077. dir_conn->_base.port = 0;
  2078. dir_conn->_base.address = tor_strdup("Tor network");
  2079. dir_conn->_base.type = CONN_TYPE_DIR;
  2080. dir_conn->_base.purpose = DIR_PURPOSE_SERVER;
  2081. dir_conn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  2082. if (connection_add(TO_CONN(exit_conn))<0) {
  2083. connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
  2084. exit_conn->cpath_layer);
  2085. connection_free(TO_CONN(exit_conn));
  2086. connection_free(TO_CONN(dir_conn));
  2087. return 0;
  2088. }
  2089. if (connection_add(TO_CONN(dir_conn))<0) {
  2090. connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
  2091. exit_conn->cpath_layer);
  2092. connection_close_immediate(TO_CONN(exit_conn));
  2093. connection_mark_for_close(TO_CONN(exit_conn));
  2094. connection_free(TO_CONN(dir_conn));
  2095. return 0;
  2096. }
  2097. connection_start_reading(TO_CONN(dir_conn));
  2098. connection_start_reading(TO_CONN(exit_conn));
  2099. if (connection_edge_send_command(exit_conn,
  2100. circuit_get_by_edge_conn(exit_conn),
  2101. RELAY_COMMAND_CONNECTED, NULL, 0,
  2102. exit_conn->cpath_layer) < 0) {
  2103. connection_mark_for_close(TO_CONN(exit_conn));
  2104. connection_mark_for_close(TO_CONN(dir_conn));
  2105. return 0;
  2106. }
  2107. return 0;
  2108. }
  2109. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  2110. * it is a general stream.
  2111. */
  2112. int
  2113. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  2114. {
  2115. tor_assert(conn);
  2116. if (*conn->rend_query) /* XXX */
  2117. return 1;
  2118. return 0;
  2119. }
  2120. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  2121. * to exit from it, or 0 if it probably will not allow it.
  2122. * (We might be uncertain if conn's destination address has not yet been
  2123. * resolved.)
  2124. */
  2125. int
  2126. connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
  2127. {
  2128. tor_assert(conn);
  2129. tor_assert(conn->_base.type == CONN_TYPE_AP);
  2130. tor_assert(conn->socks_request);
  2131. tor_assert(exit);
  2132. #if 0
  2133. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  2134. exit->nickname, safe_str(conn->socks_request->address),
  2135. conn->socks_request->port);
  2136. #endif
  2137. /* If a particular exit node has been requested for the new connection,
  2138. * make sure the exit node of the existing circuit matches exactly.
  2139. */
  2140. if (conn->chosen_exit_name) {
  2141. if (router_get_by_nickname(conn->chosen_exit_name, 1) != exit) {
  2142. /* doesn't match */
  2143. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  2144. // conn->chosen_exit_name, exit->nickname);
  2145. return 0;
  2146. }
  2147. }
  2148. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  2149. struct in_addr in;
  2150. uint32_t addr = 0;
  2151. addr_policy_result_t r;
  2152. if (tor_inet_aton(conn->socks_request->address, &in))
  2153. addr = ntohl(in.s_addr);
  2154. r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
  2155. exit->exit_policy);
  2156. if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
  2157. return 0;
  2158. } else { /* Some kind of a resolve. */
  2159. /* Can't support reverse lookups without eventdns. */
  2160. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
  2161. exit->has_old_dnsworkers)
  2162. return 0;
  2163. /* Don't send DNS requests to non-exit servers by default. */
  2164. if (policy_is_reject_star(exit->exit_policy))
  2165. return 0;
  2166. }
  2167. return 1;
  2168. }
  2169. /** Make connection redirection follow the provided list of
  2170. * exit_redirect_t */
  2171. void
  2172. set_exit_redirects(smartlist_t *lst)
  2173. {
  2174. if (redirect_exit_list) {
  2175. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
  2176. smartlist_free(redirect_exit_list);
  2177. }
  2178. redirect_exit_list = lst;
  2179. }
  2180. /** If address is of the form "y.onion" with a well-formed handle y:
  2181. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2182. *
  2183. * If address is of the form "y.exit":
  2184. * Put a NUL after y and return EXIT_HOSTNAME.
  2185. *
  2186. * Otherwise:
  2187. * Return NORMAL_HOSTNAME and change nothing.
  2188. */
  2189. hostname_type_t
  2190. parse_extended_hostname(char *address)
  2191. {
  2192. char *s;
  2193. char query[REND_SERVICE_ID_LEN+1];
  2194. s = strrchr(address,'.');
  2195. if (!s)
  2196. return NORMAL_HOSTNAME; /* no dot, thus normal */
  2197. if (!strcmp(s+1,"exit")) {
  2198. *s = 0; /* nul-terminate it */
  2199. return EXIT_HOSTNAME; /* .exit */
  2200. }
  2201. if (strcmp(s+1,"onion"))
  2202. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  2203. /* so it is .onion */
  2204. *s = 0; /* nul-terminate it */
  2205. if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >=
  2206. REND_SERVICE_ID_LEN+1)
  2207. goto failed;
  2208. if (rend_valid_service_id(query)) {
  2209. return ONION_HOSTNAME; /* success */
  2210. }
  2211. failed:
  2212. /* otherwise, return to previous state and return 0 */
  2213. *s = '.';
  2214. return BAD_HOSTNAME;
  2215. }