connection_edge.c 90 KB

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