connection_edge.c 101 KB

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