connection_edge.c 125 KB

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