connection_edge.c 101 KB

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