connection_edge.c 106 KB

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