connection_edge.c 106 KB

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