connection_edge.c 102 KB

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