connection_edge.c 93 KB

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