connection_edge.c 88 KB

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