connection_edge.c 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599
  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-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_edge.c
  8. * \brief Handle edge streams.
  9. *
  10. * An edge_connection_t is a subtype of a connection_t, and represents two
  11. * critical concepts in Tor: a stream, and an edge connection. From the Tor
  12. * protocol's point of view, a stream is a bi-directional channel that is
  13. * multiplexed on a single circuit. Each stream on a circuit is identified
  14. * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
  15. * Streams are created in response to client requests.
  16. *
  17. * An edge connection is one thing that can implement a stream: it is either a
  18. * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
  19. * exit connection.
  20. *
  21. * Not every instance of edge_connection_t truly represents an edge connction,
  22. * however. (Sorry!) We also create edge_connection_t objects for streams that
  23. * we will not be handling with TCP. The types of these streams are:
  24. * <ul>
  25. * <li>DNS lookup streams, created on the client side in response to
  26. * a UDP DNS request received on a DNSPort, or a RESOLVE command
  27. * on a controller.
  28. * <li>DNS lookup streams, created on the exit side in response to
  29. * a RELAY_RESOLVE cell from a client.
  30. * <li>Tunneled directory streams, created on the directory cache side
  31. * in response to a RELAY_BEGIN_DIR cell. These streams attach directly
  32. * to a dir_connection_t object without ever using TCP.
  33. * </ul>
  34. *
  35. * This module handles general-purpose functionality having to do with
  36. * edge_connection_t. On the client side, it accepts various types of
  37. * application requests on SocksPorts, TransPorts, and NATDPorts, and
  38. * creates streams appropriately.
  39. *
  40. * This module is also responsible for implementing stream isolation:
  41. * ensuring that streams that should not be linkable to one another are
  42. * kept to different circuits.
  43. *
  44. * On the exit side, this module handles the various stream-creating
  45. * type of RELAY cells by launching appropriate outgoing connections,
  46. * DNS requests, or directory connection objects.
  47. *
  48. * And for all edge connections, this module is responsible for handling
  49. * incoming and outdoing data as it arrives or leaves in the relay.c
  50. * module. (Outgoing data will be packaged in
  51. * connection_edge_process_inbuf() as it calls
  52. * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
  53. * cells is applied in connection_edge_process_relay_cell().)
  54. **/
  55. #define CONNECTION_EDGE_PRIVATE
  56. #include "core/or/or.h"
  57. #include "lib/err/backtrace.h"
  58. #include "app/config/config.h"
  59. #include "core/mainloop/connection.h"
  60. #include "core/mainloop/mainloop.h"
  61. #include "core/mainloop/netstatus.h"
  62. #include "core/or/channel.h"
  63. #include "core/or/circuitbuild.h"
  64. #include "core/or/circuitlist.h"
  65. #include "core/or/circuituse.h"
  66. #include "core/or/circuitpadding.h"
  67. #include "core/or/connection_edge.h"
  68. #include "core/or/connection_or.h"
  69. #include "core/or/policies.h"
  70. #include "core/or/reasons.h"
  71. #include "core/or/relay.h"
  72. #include "core/or/sendme.h"
  73. #include "core/proto/proto_http.h"
  74. #include "core/proto/proto_socks.h"
  75. #include "feature/client/addressmap.h"
  76. #include "feature/client/circpathbias.h"
  77. #include "feature/client/dnsserv.h"
  78. #include "feature/control/control_events.h"
  79. #include "feature/dircache/dirserv.h"
  80. #include "feature/dircommon/directory.h"
  81. #include "feature/hibernate/hibernate.h"
  82. #include "feature/hs/hs_cache.h"
  83. #include "feature/hs/hs_circuit.h"
  84. #include "feature/hs/hs_client.h"
  85. #include "feature/hs/hs_common.h"
  86. #include "feature/nodelist/describe.h"
  87. #include "feature/nodelist/networkstatus.h"
  88. #include "feature/nodelist/nodelist.h"
  89. #include "feature/nodelist/routerlist.h"
  90. #include "feature/nodelist/routerset.h"
  91. #include "feature/relay/dns.h"
  92. #include "feature/relay/router.h"
  93. #include "feature/relay/routermode.h"
  94. #include "feature/rend/rendclient.h"
  95. #include "feature/rend/rendcommon.h"
  96. #include "feature/rend/rendservice.h"
  97. #include "feature/stats/predict_ports.h"
  98. #include "feature/stats/rephist.h"
  99. #include "lib/buf/buffers.h"
  100. #include "lib/crypt_ops/crypto_util.h"
  101. #include "core/or/cell_st.h"
  102. #include "core/or/cpath_build_state_st.h"
  103. #include "feature/dircommon/dir_connection_st.h"
  104. #include "core/or/entry_connection_st.h"
  105. #include "core/or/extend_info_st.h"
  106. #include "feature/nodelist/node_st.h"
  107. #include "core/or/or_circuit_st.h"
  108. #include "core/or/origin_circuit_st.h"
  109. #include "core/or/half_edge_st.h"
  110. #include "core/or/socks_request_st.h"
  111. #include "lib/evloop/compat_libevent.h"
  112. #ifdef HAVE_LINUX_TYPES_H
  113. #include <linux/types.h>
  114. #endif
  115. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  116. #include <linux/netfilter_ipv4.h>
  117. #define TRANS_NETFILTER
  118. #define TRANS_NETFILTER_IPV4
  119. #endif
  120. #ifdef HAVE_LINUX_IF_H
  121. #include <linux/if.h>
  122. #endif
  123. #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
  124. #include <linux/netfilter_ipv6/ip6_tables.h>
  125. #if defined(IP6T_SO_ORIGINAL_DST)
  126. #define TRANS_NETFILTER
  127. #define TRANS_NETFILTER_IPV6
  128. #endif
  129. #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
  130. #ifdef HAVE_FCNTL_H
  131. #include <fcntl.h>
  132. #endif
  133. #ifdef HAVE_SYS_IOCTL_H
  134. #include <sys/ioctl.h>
  135. #endif
  136. #ifdef HAVE_SYS_PARAM_H
  137. #include <sys/param.h>
  138. #endif
  139. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  140. #include <net/if.h>
  141. #include <net/pfvar.h>
  142. #define TRANS_PF
  143. #endif
  144. #ifdef IP_TRANSPARENT
  145. #define TRANS_TPROXY
  146. #endif
  147. #define SOCKS4_GRANTED 90
  148. #define SOCKS4_REJECT 91
  149. static int connection_ap_handshake_process_socks(entry_connection_t *conn);
  150. static int connection_ap_process_natd(entry_connection_t *conn);
  151. static int connection_exit_connect_dir(edge_connection_t *exitconn);
  152. static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
  153. static int connection_ap_supports_optimistic_data(const entry_connection_t *);
  154. /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
  155. * invalid. */
  156. edge_connection_t *
  157. TO_EDGE_CONN(connection_t *c)
  158. {
  159. tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
  160. c->magic == ENTRY_CONNECTION_MAGIC);
  161. return DOWNCAST(edge_connection_t, c);
  162. }
  163. entry_connection_t *
  164. TO_ENTRY_CONN(connection_t *c)
  165. {
  166. tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
  167. return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
  168. }
  169. entry_connection_t *
  170. EDGE_TO_ENTRY_CONN(edge_connection_t *c)
  171. {
  172. tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
  173. return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
  174. }
  175. /** An AP stream has failed/finished. If it hasn't already sent back
  176. * a socks reply, send one now (based on endreason). Also set
  177. * has_sent_end to 1, and mark the conn.
  178. */
  179. MOCK_IMPL(void,
  180. connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
  181. int line, const char *file))
  182. {
  183. connection_t *base_conn = ENTRY_TO_CONN(conn);
  184. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  185. tor_assert(base_conn->type == CONN_TYPE_AP);
  186. ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
  187. /* If this is a rendezvous stream and it is failing without ever
  188. * being attached to a circuit, assume that an attempt to connect to
  189. * the destination hidden service has just ended.
  190. *
  191. * XXXX This condition doesn't limit to only streams failing
  192. * without ever being attached. That sloppiness should be harmless,
  193. * but we should fix it someday anyway. */
  194. if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
  195. connection_edge_is_rendezvous_stream(edge_conn)) {
  196. if (edge_conn->rend_data) {
  197. rend_client_note_connection_attempt_ended(edge_conn->rend_data);
  198. }
  199. }
  200. if (base_conn->marked_for_close) {
  201. /* This call will warn as appropriate. */
  202. connection_mark_for_close_(base_conn, line, file);
  203. return;
  204. }
  205. if (!conn->socks_request->has_finished) {
  206. if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
  207. log_warn(LD_BUG,
  208. "stream (marked at %s:%d) sending two socks replies?",
  209. file, line);
  210. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  211. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  212. else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  213. connection_ap_handshake_socks_resolved(conn,
  214. RESOLVED_TYPE_ERROR_TRANSIENT,
  215. 0, NULL, -1, -1);
  216. else /* unknown or no handshake at all. send no response. */
  217. conn->socks_request->has_finished = 1;
  218. }
  219. connection_mark_and_flush_(base_conn, line, file);
  220. ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
  221. }
  222. /** There was an EOF. Send an end and mark the connection for close.
  223. */
  224. int
  225. connection_edge_reached_eof(edge_connection_t *conn)
  226. {
  227. if (connection_get_inbuf_len(TO_CONN(conn)) &&
  228. connection_state_is_open(TO_CONN(conn))) {
  229. /* it still has stuff to process. don't let it die yet. */
  230. return 0;
  231. }
  232. log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
  233. conn->base_.s);
  234. if (!conn->base_.marked_for_close) {
  235. /* only mark it if not already marked. it's possible to
  236. * get the 'end' right around when the client hangs up on us. */
  237. connection_edge_end(conn, END_STREAM_REASON_DONE);
  238. if (conn->base_.type == CONN_TYPE_AP) {
  239. /* eof, so don't send a socks reply back */
  240. if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
  241. EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  242. }
  243. connection_mark_for_close(TO_CONN(conn));
  244. }
  245. return 0;
  246. }
  247. /** Handle new bytes on conn->inbuf based on state:
  248. * - If it's waiting for socks info, try to read another step of the
  249. * socks handshake out of conn->inbuf.
  250. * - If it's waiting for the original destination, fetch it.
  251. * - If it's open, then package more relay cells from the stream.
  252. * - Else, leave the bytes on inbuf alone for now.
  253. *
  254. * Mark and return -1 if there was an unexpected error with the conn,
  255. * else return 0.
  256. */
  257. int
  258. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  259. {
  260. tor_assert(conn);
  261. switch (conn->base_.state) {
  262. case AP_CONN_STATE_SOCKS_WAIT:
  263. if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
  264. /* already marked */
  265. return -1;
  266. }
  267. return 0;
  268. case AP_CONN_STATE_NATD_WAIT:
  269. if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  270. /* already marked */
  271. return -1;
  272. }
  273. return 0;
  274. case AP_CONN_STATE_HTTP_CONNECT_WAIT:
  275. if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  276. return -1;
  277. }
  278. return 0;
  279. case AP_CONN_STATE_OPEN:
  280. if (! conn->base_.linked) {
  281. note_user_activity(approx_time());
  282. }
  283. /* falls through. */
  284. case EXIT_CONN_STATE_OPEN:
  285. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
  286. /* (We already sent an end cell if possible) */
  287. connection_mark_for_close(TO_CONN(conn));
  288. return -1;
  289. }
  290. return 0;
  291. case AP_CONN_STATE_CONNECT_WAIT:
  292. if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
  293. log_info(LD_EDGE,
  294. "data from edge while in '%s' state. Sending it anyway. "
  295. "package_partial=%d, buflen=%ld",
  296. conn_state_to_string(conn->base_.type, conn->base_.state),
  297. package_partial,
  298. (long)connection_get_inbuf_len(TO_CONN(conn)));
  299. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
  300. /* (We already sent an end cell if possible) */
  301. connection_mark_for_close(TO_CONN(conn));
  302. return -1;
  303. }
  304. return 0;
  305. }
  306. /* Fall through if the connection is on a circuit without optimistic
  307. * data support. */
  308. /* Falls through. */
  309. case EXIT_CONN_STATE_CONNECTING:
  310. case AP_CONN_STATE_RENDDESC_WAIT:
  311. case AP_CONN_STATE_CIRCUIT_WAIT:
  312. case AP_CONN_STATE_RESOLVE_WAIT:
  313. case AP_CONN_STATE_CONTROLLER_WAIT:
  314. log_info(LD_EDGE,
  315. "data from edge while in '%s' state. Leaving it on buffer.",
  316. conn_state_to_string(conn->base_.type, conn->base_.state));
  317. return 0;
  318. }
  319. log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
  320. tor_fragile_assert();
  321. connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
  322. connection_mark_for_close(TO_CONN(conn));
  323. return -1;
  324. }
  325. /** This edge needs to be closed, because its circuit has closed.
  326. * Mark it for close and return 0.
  327. */
  328. int
  329. connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
  330. {
  331. if (!conn->base_.marked_for_close) {
  332. log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
  333. (unsigned) circ_id);
  334. if (conn->base_.type == CONN_TYPE_AP) {
  335. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  336. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
  337. control_event_stream_bandwidth(conn);
  338. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  339. END_STREAM_REASON_DESTROY);
  340. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  341. } else {
  342. /* closing the circuit, nothing to send an END to */
  343. conn->edge_has_sent_end = 1;
  344. conn->end_reason = END_STREAM_REASON_DESTROY;
  345. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  346. connection_mark_and_flush(TO_CONN(conn));
  347. }
  348. }
  349. conn->cpath_layer = NULL;
  350. conn->on_circuit = NULL;
  351. return 0;
  352. }
  353. /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
  354. * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
  355. * is not a client connection, set the relay end cell's reason for closing
  356. * as <b>reason</b> */
  357. static int
  358. relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
  359. uint8_t reason, crypt_path_t *cpath_layer)
  360. {
  361. char payload[1];
  362. if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  363. /* Never send the server an informative reason code; it doesn't need to
  364. * know why the client stream is failing. */
  365. reason = END_STREAM_REASON_MISC;
  366. }
  367. payload[0] = (char) reason;
  368. /* Note: we have to use relay_send_command_from_edge here, not
  369. * connection_edge_end or connection_edge_send_command, since those require
  370. * that we have a stream connected to a circuit, and we don't connect to a
  371. * circuit until we have a pending/successful resolve. */
  372. return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
  373. payload, 1, cpath_layer);
  374. }
  375. /* If the connection <b>conn</b> is attempting to connect to an external
  376. * destination that is an hidden service and the reason is a connection
  377. * refused or timeout, log it so the operator can take appropriate actions.
  378. * The log statement is a rate limited warning. */
  379. static void
  380. warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
  381. {
  382. tor_assert(conn);
  383. if (conn->base_.type == CONN_TYPE_EXIT &&
  384. connection_edge_is_rendezvous_stream(conn) &&
  385. (reason == END_STREAM_REASON_CONNECTREFUSED ||
  386. reason == END_STREAM_REASON_TIMEOUT)) {
  387. #define WARN_FAILED_HS_CONNECTION 300
  388. static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
  389. char *m;
  390. if ((m = rate_limit_log(&warn_limit, approx_time()))) {
  391. log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
  392. (conn->base_.socket_family == AF_UNIX) ?
  393. safe_str(conn->base_.address) :
  394. safe_str(fmt_addrport(&conn->base_.addr, conn->base_.port)),
  395. stream_end_reason_to_string(reason));
  396. tor_free(m);
  397. }
  398. }
  399. }
  400. /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
  401. * remember that we've done so. If this is not a client connection, set the
  402. * relay end cell's reason for closing as <b>reason</b>.
  403. *
  404. * Return -1 if this function has already been called on this conn,
  405. * else return 0.
  406. */
  407. int
  408. connection_edge_end(edge_connection_t *conn, uint8_t reason)
  409. {
  410. char payload[RELAY_PAYLOAD_SIZE];
  411. size_t payload_len=1;
  412. circuit_t *circ;
  413. uint8_t control_reason = reason;
  414. if (conn->edge_has_sent_end) {
  415. log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
  416. "on an already ended stream?", reason);
  417. tor_fragile_assert();
  418. return -1;
  419. }
  420. if (conn->base_.marked_for_close) {
  421. log_warn(LD_BUG,
  422. "called on conn that's already marked for close at %s:%d.",
  423. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  424. return 0;
  425. }
  426. circ = circuit_get_by_edge_conn(conn);
  427. if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  428. /* If this is a client circuit, don't send the server an informative
  429. * reason code; it doesn't need to know why the client stream is
  430. * failing. */
  431. reason = END_STREAM_REASON_MISC;
  432. }
  433. payload[0] = (char)reason;
  434. if (reason == END_STREAM_REASON_EXITPOLICY &&
  435. !connection_edge_is_rendezvous_stream(conn)) {
  436. int addrlen;
  437. if (tor_addr_family(&conn->base_.addr) == AF_INET) {
  438. set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
  439. addrlen = 4;
  440. } else {
  441. memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
  442. addrlen = 16;
  443. }
  444. set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
  445. payload_len += 4+addrlen;
  446. }
  447. if (circ && !circ->marked_for_close) {
  448. log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
  449. conn->base_.s);
  450. if (CIRCUIT_IS_ORIGIN(circ)) {
  451. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  452. connection_half_edge_add(conn, origin_circ);
  453. }
  454. connection_edge_send_command(conn, RELAY_COMMAND_END,
  455. payload, payload_len);
  456. /* We'll log warn if the connection was an hidden service and couldn't be
  457. * made because the service wasn't available. */
  458. warn_if_hs_unreachable(conn, control_reason);
  459. } else {
  460. log_debug(LD_EDGE,"No circ to send end on conn "
  461. "(fd "TOR_SOCKET_T_FORMAT").",
  462. conn->base_.s);
  463. }
  464. conn->edge_has_sent_end = 1;
  465. conn->end_reason = control_reason;
  466. return 0;
  467. }
  468. /**
  469. * Helper function for bsearch.
  470. *
  471. * As per smartlist_bsearch, return < 0 if key preceeds member,
  472. * > 0 if member preceeds key, and 0 if they are equal.
  473. *
  474. * This is equivalent to subtraction of the values of key - member
  475. * (why does no one ever say that explicitly?).
  476. */
  477. static int
  478. connection_half_edge_compare_bsearch(const void *key, const void **member)
  479. {
  480. const half_edge_t *e2;
  481. tor_assert(key);
  482. tor_assert(member && *(half_edge_t**)member);
  483. e2 = *(const half_edge_t **)member;
  484. return *(const streamid_t*)key - e2->stream_id;
  485. }
  486. /** Total number of half_edge_t objects allocated */
  487. static size_t n_half_conns_allocated = 0;
  488. /**
  489. * Add a half-closed connection to the list, to watch for activity.
  490. *
  491. * These connections are removed from the list upon receiving an end
  492. * cell.
  493. */
  494. STATIC void
  495. connection_half_edge_add(const edge_connection_t *conn,
  496. origin_circuit_t *circ)
  497. {
  498. half_edge_t *half_conn = NULL;
  499. int insert_at = 0;
  500. int ignored;
  501. /* Double-check for re-insertion. This should not happen,
  502. * but this check is cheap compared to the sort anyway */
  503. if (connection_half_edge_find_stream_id(circ->half_streams,
  504. conn->stream_id)) {
  505. log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
  506. conn->stream_id, circ->global_identifier);
  507. return;
  508. }
  509. half_conn = tor_malloc_zero(sizeof(half_edge_t));
  510. ++n_half_conns_allocated;
  511. if (!circ->half_streams) {
  512. circ->half_streams = smartlist_new();
  513. }
  514. half_conn->stream_id = conn->stream_id;
  515. // How many sendme's should I expect?
  516. half_conn->sendmes_pending =
  517. (STREAMWINDOW_START-conn->package_window)/STREAMWINDOW_INCREMENT;
  518. // Is there a connected cell pending?
  519. half_conn->connected_pending = conn->base_.state ==
  520. AP_CONN_STATE_CONNECT_WAIT;
  521. /* Data should only arrive if we're not waiting on a resolved cell.
  522. * It can arrive after waiting on connected, because of optimistic
  523. * data. */
  524. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  525. // How many more data cells can arrive on this id?
  526. half_conn->data_pending = conn->deliver_window;
  527. }
  528. insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
  529. connection_half_edge_compare_bsearch,
  530. &ignored);
  531. smartlist_insert(circ->half_streams, insert_at, half_conn);
  532. }
  533. /** Release space held by <b>he</b> */
  534. void
  535. half_edge_free_(half_edge_t *he)
  536. {
  537. if (!he)
  538. return;
  539. --n_half_conns_allocated;
  540. tor_free(he);
  541. }
  542. /** Return the number of bytes devoted to storing info on half-open streams. */
  543. size_t
  544. half_streams_get_total_allocation(void)
  545. {
  546. return n_half_conns_allocated * sizeof(half_edge_t);
  547. }
  548. /**
  549. * Find a stream_id_t in the list in O(lg(n)).
  550. *
  551. * Returns NULL if the list is empty or element is not found.
  552. * Returns a pointer to the element if found.
  553. */
  554. STATIC half_edge_t *
  555. connection_half_edge_find_stream_id(const smartlist_t *half_conns,
  556. streamid_t stream_id)
  557. {
  558. if (!half_conns)
  559. return NULL;
  560. return smartlist_bsearch(half_conns, &stream_id,
  561. connection_half_edge_compare_bsearch);
  562. }
  563. /**
  564. * Check if this stream_id is in a half-closed state. If so,
  565. * check if it still has data cells pending, and decrement that
  566. * window if so.
  567. *
  568. * Return 1 if the data window was not empty.
  569. * Return 0 otherwise.
  570. */
  571. int
  572. connection_half_edge_is_valid_data(const smartlist_t *half_conns,
  573. streamid_t stream_id)
  574. {
  575. half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
  576. stream_id);
  577. if (!half)
  578. return 0;
  579. if (half->data_pending > 0) {
  580. half->data_pending--;
  581. return 1;
  582. }
  583. return 0;
  584. }
  585. /**
  586. * Check if this stream_id is in a half-closed state. If so,
  587. * check if it still has a connected cell pending, and decrement
  588. * that window if so.
  589. *
  590. * Return 1 if the connected window was not empty.
  591. * Return 0 otherwise.
  592. */
  593. int
  594. connection_half_edge_is_valid_connected(const smartlist_t *half_conns,
  595. streamid_t stream_id)
  596. {
  597. half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
  598. stream_id);
  599. if (!half)
  600. return 0;
  601. if (half->connected_pending) {
  602. half->connected_pending = 0;
  603. return 1;
  604. }
  605. return 0;
  606. }
  607. /**
  608. * Check if this stream_id is in a half-closed state. If so,
  609. * check if it still has sendme cells pending, and decrement that
  610. * window if so.
  611. *
  612. * Return 1 if the sendme window was not empty.
  613. * Return 0 otherwise.
  614. */
  615. int
  616. connection_half_edge_is_valid_sendme(const smartlist_t *half_conns,
  617. streamid_t stream_id)
  618. {
  619. half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
  620. stream_id);
  621. if (!half)
  622. return 0;
  623. if (half->sendmes_pending > 0) {
  624. half->sendmes_pending--;
  625. return 1;
  626. }
  627. return 0;
  628. }
  629. /**
  630. * Check if this stream_id is in a half-closed state. If so, remove
  631. * it from the list. No other data should come after the END cell.
  632. *
  633. * Return 1 if stream_id was in half-closed state.
  634. * Return 0 otherwise.
  635. */
  636. int
  637. connection_half_edge_is_valid_end(smartlist_t *half_conns,
  638. streamid_t stream_id)
  639. {
  640. half_edge_t *half;
  641. int found, remove_idx;
  642. if (!half_conns)
  643. return 0;
  644. remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
  645. connection_half_edge_compare_bsearch,
  646. &found);
  647. if (!found)
  648. return 0;
  649. half = smartlist_get(half_conns, remove_idx);
  650. smartlist_del_keeporder(half_conns, remove_idx);
  651. half_edge_free(half);
  652. return 1;
  653. }
  654. /**
  655. * Streams that were used to send a RESOLVE cell are closed
  656. * when they get the RESOLVED, without an end. So treat
  657. * a RESOLVED just like an end, and remove from the list.
  658. */
  659. int
  660. connection_half_edge_is_valid_resolved(smartlist_t *half_conns,
  661. streamid_t stream_id)
  662. {
  663. return connection_half_edge_is_valid_end(half_conns, stream_id);
  664. }
  665. /** An error has just occurred on an operation on an edge connection
  666. * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
  667. * appropriate relay end cell to the other end of the connection's circuit.
  668. **/
  669. int
  670. connection_edge_end_errno(edge_connection_t *conn)
  671. {
  672. uint8_t reason;
  673. tor_assert(conn);
  674. reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
  675. return connection_edge_end(conn, reason);
  676. }
  677. /** We just wrote some data to <b>conn</b>; act appropriately.
  678. *
  679. * (That is, if it's open, consider sending a stream-level sendme cell if we
  680. * have just flushed enough.)
  681. */
  682. int
  683. connection_edge_flushed_some(edge_connection_t *conn)
  684. {
  685. switch (conn->base_.state) {
  686. case AP_CONN_STATE_OPEN:
  687. if (! conn->base_.linked) {
  688. note_user_activity(approx_time());
  689. }
  690. /* falls through. */
  691. case EXIT_CONN_STATE_OPEN:
  692. sendme_connection_edge_consider_sending(conn);
  693. break;
  694. }
  695. return 0;
  696. }
  697. /** Connection <b>conn</b> has finished writing and has no bytes left on
  698. * its outbuf.
  699. *
  700. * If it's in state 'open', stop writing, consider responding with a
  701. * sendme, and return.
  702. * Otherwise, stop writing and return.
  703. *
  704. * If <b>conn</b> is broken, mark it for close and return -1, else
  705. * return 0.
  706. */
  707. int
  708. connection_edge_finished_flushing(edge_connection_t *conn)
  709. {
  710. tor_assert(conn);
  711. switch (conn->base_.state) {
  712. case AP_CONN_STATE_OPEN:
  713. case EXIT_CONN_STATE_OPEN:
  714. sendme_connection_edge_consider_sending(conn);
  715. return 0;
  716. case AP_CONN_STATE_SOCKS_WAIT:
  717. case AP_CONN_STATE_NATD_WAIT:
  718. case AP_CONN_STATE_RENDDESC_WAIT:
  719. case AP_CONN_STATE_CIRCUIT_WAIT:
  720. case AP_CONN_STATE_CONNECT_WAIT:
  721. case AP_CONN_STATE_CONTROLLER_WAIT:
  722. case AP_CONN_STATE_RESOLVE_WAIT:
  723. case AP_CONN_STATE_HTTP_CONNECT_WAIT:
  724. return 0;
  725. default:
  726. log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
  727. tor_fragile_assert();
  728. return -1;
  729. }
  730. return 0;
  731. }
  732. /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
  733. * able to generate. */
  734. /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
  735. #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
  736. /** Set the buffer at <b>payload_out</b> -- which must have at least
  737. * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
  738. * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
  739. * that the name resolution that led us to <b>addr</b> will be valid for
  740. * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
  741. * success. */
  742. STATIC int
  743. connected_cell_format_payload(uint8_t *payload_out,
  744. const tor_addr_t *addr,
  745. uint32_t ttl)
  746. {
  747. const sa_family_t family = tor_addr_family(addr);
  748. int connected_payload_len;
  749. /* should be needless */
  750. memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
  751. if (family == AF_INET) {
  752. set_uint32(payload_out, tor_addr_to_ipv4n(addr));
  753. connected_payload_len = 4;
  754. } else if (family == AF_INET6) {
  755. set_uint32(payload_out, 0);
  756. set_uint8(payload_out + 4, 6);
  757. memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
  758. connected_payload_len = 21;
  759. } else {
  760. return -1;
  761. }
  762. set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
  763. connected_payload_len += 4;
  764. tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
  765. return connected_payload_len;
  766. }
  767. /* This is an onion service client connection: Export the client circuit ID
  768. * according to the HAProxy proxy protocol. */
  769. STATIC void
  770. export_hs_client_circuit_id(edge_connection_t *edge_conn,
  771. hs_circuit_id_protocol_t protocol)
  772. {
  773. /* We only support HAProxy right now. */
  774. if (protocol != HS_CIRCUIT_ID_PROTOCOL_HAPROXY)
  775. return;
  776. char *buf = NULL;
  777. const char dst_ipv6[] = "::1";
  778. /* See RFC4193 regarding fc00::/7 */
  779. const char src_ipv6_prefix[] = "fc00:dead:beef:4dad:";
  780. uint16_t dst_port = 0;
  781. uint16_t src_port = 1; /* default value */
  782. uint32_t gid = 0; /* default value */
  783. /* Generate a GID and source port for this client */
  784. if (edge_conn->on_circuit != NULL) {
  785. gid = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit)->global_identifier;
  786. src_port = gid & 0x0000ffff;
  787. }
  788. /* Grab the original dest port from the hs ident */
  789. if (edge_conn->hs_ident) {
  790. dst_port = edge_conn->hs_ident->orig_virtual_port;
  791. }
  792. /* Build the string */
  793. tor_asprintf(&buf, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
  794. src_ipv6_prefix,
  795. gid >> 16, gid & 0x0000ffff,
  796. dst_ipv6, src_port, dst_port);
  797. connection_buf_add(buf, strlen(buf), TO_CONN(edge_conn));
  798. tor_free(buf);
  799. }
  800. /** Connected handler for exit connections: start writing pending
  801. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  802. * any pending data that may have been received. */
  803. int
  804. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  805. {
  806. connection_t *conn;
  807. tor_assert(edge_conn);
  808. tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
  809. conn = TO_CONN(edge_conn);
  810. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  811. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  812. escaped_safe_str(conn->address), conn->port,
  813. safe_str(fmt_and_decorate_addr(&conn->addr)));
  814. rep_hist_note_exit_stream_opened(conn->port);
  815. conn->state = EXIT_CONN_STATE_OPEN;
  816. connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  817. if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
  818. * cells */
  819. connection_start_writing(conn);
  820. /* deliver a 'connected' relay cell back through the circuit. */
  821. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  822. if (connection_edge_send_command(edge_conn,
  823. RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
  824. return 0; /* circuit is closed, don't continue */
  825. } else {
  826. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  827. int connected_payload_len =
  828. connected_cell_format_payload(connected_payload, &conn->addr,
  829. edge_conn->address_ttl);
  830. if (connected_payload_len < 0)
  831. return -1;
  832. if (connection_edge_send_command(edge_conn,
  833. RELAY_COMMAND_CONNECTED,
  834. (char*)connected_payload, connected_payload_len) < 0)
  835. return 0; /* circuit is closed, don't continue */
  836. }
  837. tor_assert(edge_conn->package_window > 0);
  838. /* in case the server has written anything */
  839. return connection_edge_process_inbuf(edge_conn, 1);
  840. }
  841. /** A list of all the entry_connection_t * objects that are not marked
  842. * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
  843. *
  844. * (Right now, we check in several places to make sure that this list is
  845. * correct. When it's incorrect, we'll fix it, and log a BUG message.)
  846. */
  847. static smartlist_t *pending_entry_connections = NULL;
  848. static int untried_pending_connections = 0;
  849. /**
  850. * Mainloop event to tell us to scan for pending connections that can
  851. * be attached.
  852. */
  853. static mainloop_event_t *attach_pending_entry_connections_ev = NULL;
  854. /** Common code to connection_(ap|exit)_about_to_close. */
  855. static void
  856. connection_edge_about_to_close(edge_connection_t *edge_conn)
  857. {
  858. if (!edge_conn->edge_has_sent_end) {
  859. connection_t *conn = TO_CONN(edge_conn);
  860. log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
  861. "hasn't sent end yet?",
  862. conn->marked_for_close_file, conn->marked_for_close);
  863. tor_fragile_assert();
  864. }
  865. }
  866. /** Called when we're about to finally unlink and free an AP (client)
  867. * connection: perform necessary accounting and cleanup */
  868. void
  869. connection_ap_about_to_close(entry_connection_t *entry_conn)
  870. {
  871. circuit_t *circ;
  872. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
  873. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  874. connection_edge_about_to_close(edge_conn);
  875. if (entry_conn->socks_request->has_finished == 0) {
  876. /* since conn gets removed right after this function finishes,
  877. * there's no point trying to send back a reply at this point. */
  878. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
  879. " back a socks reply.",
  880. conn->marked_for_close_file, conn->marked_for_close);
  881. }
  882. if (!edge_conn->end_reason) {
  883. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  884. " set end_reason.",
  885. conn->marked_for_close_file, conn->marked_for_close);
  886. }
  887. if (entry_conn->dns_server_request) {
  888. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  889. " replied to DNS request.",
  890. conn->marked_for_close_file, conn->marked_for_close);
  891. dnsserv_reject_request(entry_conn);
  892. }
  893. if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
  894. smartlist_remove(pending_entry_connections, entry_conn);
  895. }
  896. #if 1
  897. /* Check to make sure that this isn't in pending_entry_connections if it
  898. * didn't actually belong there. */
  899. if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
  900. connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
  901. "about_to_close");
  902. }
  903. #endif /* 1 */
  904. control_event_stream_bandwidth(edge_conn);
  905. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  906. edge_conn->end_reason);
  907. circ = circuit_get_by_edge_conn(edge_conn);
  908. if (circ)
  909. circuit_detach_stream(circ, edge_conn);
  910. }
  911. /** Called when we're about to finally unlink and free an exit
  912. * connection: perform necessary accounting and cleanup */
  913. void
  914. connection_exit_about_to_close(edge_connection_t *edge_conn)
  915. {
  916. circuit_t *circ;
  917. connection_t *conn = TO_CONN(edge_conn);
  918. connection_edge_about_to_close(edge_conn);
  919. circ = circuit_get_by_edge_conn(edge_conn);
  920. if (circ)
  921. circuit_detach_stream(circ, edge_conn);
  922. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  923. connection_dns_remove(edge_conn);
  924. }
  925. }
  926. /** Define a schedule for how long to wait between retrying
  927. * application connections. Rather than waiting a fixed amount of
  928. * time between each retry, we wait 10 seconds each for the first
  929. * two tries, and 15 seconds for each retry after
  930. * that. Hopefully this will improve the expected user experience. */
  931. static int
  932. compute_retry_timeout(entry_connection_t *conn)
  933. {
  934. int timeout = get_options()->CircuitStreamTimeout;
  935. if (timeout) /* if our config options override the default, use them */
  936. return timeout;
  937. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  938. return 10;
  939. return 15;
  940. }
  941. /** Find all general-purpose AP streams waiting for a response that sent their
  942. * begin/resolve cell too long ago. Detach from their current circuit, and
  943. * mark their current circuit as unsuitable for new streams. Then call
  944. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  945. * available) or launch a new one.
  946. *
  947. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  948. * retry attempt).
  949. */
  950. void
  951. connection_ap_expire_beginning(void)
  952. {
  953. edge_connection_t *conn;
  954. entry_connection_t *entry_conn;
  955. circuit_t *circ;
  956. time_t now = time(NULL);
  957. const or_options_t *options = get_options();
  958. int severity;
  959. int cutoff;
  960. int seconds_idle, seconds_since_born;
  961. smartlist_t *conns = get_connection_array();
  962. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  963. if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
  964. continue;
  965. entry_conn = TO_ENTRY_CONN(base_conn);
  966. conn = ENTRY_TO_EDGE_CONN(entry_conn);
  967. /* if it's an internal linked connection, don't yell its status. */
  968. severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
  969. ? LOG_INFO : LOG_NOTICE;
  970. seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
  971. seconds_since_born = (int)( now - base_conn->timestamp_created );
  972. if (base_conn->state == AP_CONN_STATE_OPEN)
  973. continue;
  974. /* We already consider SocksTimeout in
  975. * connection_ap_handshake_attach_circuit(), but we need to consider
  976. * it here too because controllers that put streams in controller_wait
  977. * state never ask Tor to attach the circuit. */
  978. if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
  979. if (seconds_since_born >= options->SocksTimeout) {
  980. log_fn(severity, LD_APP,
  981. "Tried for %d seconds to get a connection to %s:%d. "
  982. "Giving up. (%s)",
  983. seconds_since_born,
  984. safe_str_client(entry_conn->socks_request->address),
  985. entry_conn->socks_request->port,
  986. conn_state_to_string(CONN_TYPE_AP, base_conn->state));
  987. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  988. }
  989. continue;
  990. }
  991. /* We're in state connect_wait or resolve_wait now -- waiting for a
  992. * reply to our relay cell. See if we want to retry/give up. */
  993. cutoff = compute_retry_timeout(entry_conn);
  994. if (seconds_idle < cutoff)
  995. continue;
  996. circ = circuit_get_by_edge_conn(conn);
  997. if (!circ) { /* it's vanished? */
  998. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  999. safe_str_client(entry_conn->socks_request->address));
  1000. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  1001. continue;
  1002. }
  1003. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  1004. if (seconds_idle >= options->SocksTimeout) {
  1005. log_fn(severity, LD_REND,
  1006. "Rend stream is %d seconds late. Giving up on address"
  1007. " '%s.onion'.",
  1008. seconds_idle,
  1009. safe_str_client(entry_conn->socks_request->address));
  1010. /* Roll back path bias use state so that we probe the circuit
  1011. * if nothing else succeeds on it */
  1012. pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
  1013. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  1014. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  1015. }
  1016. continue;
  1017. }
  1018. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  1019. circ->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
  1020. circ->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
  1021. circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  1022. circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  1023. log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
  1024. "The purpose on the circuit was %s; it was in state %s, "
  1025. "path_state %s.",
  1026. circuit_purpose_to_string(circ->purpose),
  1027. circuit_state_to_string(circ->state),
  1028. CIRCUIT_IS_ORIGIN(circ) ?
  1029. pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
  1030. "none");
  1031. }
  1032. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  1033. "We tried for %d seconds to connect to '%s' using exit %s."
  1034. " Retrying on a new circuit.",
  1035. seconds_idle,
  1036. safe_str_client(entry_conn->socks_request->address),
  1037. conn->cpath_layer ?
  1038. extend_info_describe(conn->cpath_layer->extend_info):
  1039. "*unnamed*");
  1040. /* send an end down the circuit */
  1041. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  1042. /* un-mark it as ending, since we're going to reuse it */
  1043. conn->edge_has_sent_end = 0;
  1044. conn->end_reason = 0;
  1045. /* make us not try this circuit again, but allow
  1046. * current streams on it to survive if they can */
  1047. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  1048. /* give our stream another 'cutoff' seconds to try */
  1049. conn->base_.timestamp_last_read_allowed += cutoff;
  1050. if (entry_conn->num_socks_retries < 250) /* avoid overflow */
  1051. entry_conn->num_socks_retries++;
  1052. /* move it back into 'pending' state, and try to attach. */
  1053. if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
  1054. END_STREAM_REASON_TIMEOUT)<0) {
  1055. if (!base_conn->marked_for_close)
  1056. connection_mark_unattached_ap(entry_conn,
  1057. END_STREAM_REASON_CANT_ATTACH);
  1058. }
  1059. } SMARTLIST_FOREACH_END(base_conn);
  1060. }
  1061. /**
  1062. * As connection_ap_attach_pending, but first scans the entire connection
  1063. * array to see if any elements are missing.
  1064. */
  1065. void
  1066. connection_ap_rescan_and_attach_pending(void)
  1067. {
  1068. entry_connection_t *entry_conn;
  1069. smartlist_t *conns = get_connection_array();
  1070. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  1071. pending_entry_connections = smartlist_new();
  1072. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1073. if (conn->marked_for_close ||
  1074. conn->type != CONN_TYPE_AP ||
  1075. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  1076. continue;
  1077. entry_conn = TO_ENTRY_CONN(conn);
  1078. tor_assert(entry_conn);
  1079. if (! smartlist_contains(pending_entry_connections, entry_conn)) {
  1080. log_warn(LD_BUG, "Found a connection %p that was supposed to be "
  1081. "in pending_entry_connections, but wasn't. No worries; "
  1082. "adding it.",
  1083. pending_entry_connections);
  1084. untried_pending_connections = 1;
  1085. connection_ap_mark_as_pending_circuit(entry_conn);
  1086. }
  1087. } SMARTLIST_FOREACH_END(conn);
  1088. connection_ap_attach_pending(1);
  1089. }
  1090. #ifdef DEBUGGING_17659
  1091. #define UNMARK() do { \
  1092. entry_conn->marked_pending_circ_line = 0; \
  1093. entry_conn->marked_pending_circ_file = 0; \
  1094. } while (0)
  1095. #else /* !defined(DEBUGGING_17659) */
  1096. #define UNMARK() do { } while (0)
  1097. #endif /* defined(DEBUGGING_17659) */
  1098. /** Tell any AP streams that are listed as waiting for a new circuit to try
  1099. * again. If there is an available circuit for a stream, attach it. Otherwise,
  1100. * launch a new circuit.
  1101. *
  1102. * If <b>retry</b> is false, only check the list if it contains at least one
  1103. * streams that we have not yet tried to attach to a circuit.
  1104. */
  1105. void
  1106. connection_ap_attach_pending(int retry)
  1107. {
  1108. if (PREDICT_UNLIKELY(!pending_entry_connections)) {
  1109. return;
  1110. }
  1111. if (untried_pending_connections == 0 && !retry)
  1112. return;
  1113. /* Don't allow any modifications to list while we are iterating over
  1114. * it. We'll put streams back on this list if we can't attach them
  1115. * immediately. */
  1116. smartlist_t *pending = pending_entry_connections;
  1117. pending_entry_connections = smartlist_new();
  1118. SMARTLIST_FOREACH_BEGIN(pending,
  1119. entry_connection_t *, entry_conn) {
  1120. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  1121. tor_assert(conn && entry_conn);
  1122. if (conn->marked_for_close) {
  1123. UNMARK();
  1124. continue;
  1125. }
  1126. if (conn->magic != ENTRY_CONNECTION_MAGIC) {
  1127. log_warn(LD_BUG, "%p has impossible magic value %u.",
  1128. entry_conn, (unsigned)conn->magic);
  1129. UNMARK();
  1130. continue;
  1131. }
  1132. if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  1133. log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
  1134. "is %s. Why is it on pending_entry_connections?",
  1135. entry_conn,
  1136. conn_state_to_string(conn->type, conn->state));
  1137. UNMARK();
  1138. continue;
  1139. }
  1140. /* Okay, we're through the sanity checks. Try to handle this stream. */
  1141. if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
  1142. if (!conn->marked_for_close)
  1143. connection_mark_unattached_ap(entry_conn,
  1144. END_STREAM_REASON_CANT_ATTACH);
  1145. }
  1146. if (! conn->marked_for_close &&
  1147. conn->type == CONN_TYPE_AP &&
  1148. conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
  1149. /* Is it still waiting for a circuit? If so, we didn't attach it,
  1150. * so it's still pending. Put it back on the list.
  1151. */
  1152. if (!smartlist_contains(pending_entry_connections, entry_conn)) {
  1153. smartlist_add(pending_entry_connections, entry_conn);
  1154. continue;
  1155. }
  1156. }
  1157. /* If we got here, then we either closed the connection, or
  1158. * we attached it. */
  1159. UNMARK();
  1160. } SMARTLIST_FOREACH_END(entry_conn);
  1161. smartlist_free(pending);
  1162. untried_pending_connections = 0;
  1163. }
  1164. static void
  1165. attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
  1166. {
  1167. (void)ev;
  1168. (void)arg;
  1169. connection_ap_attach_pending(0);
  1170. }
  1171. /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
  1172. *
  1173. * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
  1174. * should not already be pending a circuit. The circuit will get
  1175. * launched or the connection will get attached the next time we
  1176. * call connection_ap_attach_pending().
  1177. */
  1178. void
  1179. connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
  1180. const char *fname, int lineno)
  1181. {
  1182. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  1183. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1184. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  1185. if (conn->marked_for_close)
  1186. return;
  1187. if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
  1188. pending_entry_connections = smartlist_new();
  1189. }
  1190. if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
  1191. attach_pending_entry_connections_ev = mainloop_event_postloop_new(
  1192. attach_pending_entry_connections_cb, NULL);
  1193. }
  1194. if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
  1195. entry_conn))) {
  1196. log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
  1197. "(Called from %s:%d.)",
  1198. entry_conn, fname, lineno);
  1199. #ifdef DEBUGGING_17659
  1200. const char *f2 = entry_conn->marked_pending_circ_file;
  1201. log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
  1202. f2 ? f2 : "<NULL>",
  1203. entry_conn->marked_pending_circ_line);
  1204. #endif /* defined(DEBUGGING_17659) */
  1205. log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
  1206. return;
  1207. }
  1208. #ifdef DEBUGGING_17659
  1209. entry_conn->marked_pending_circ_line = (uint16_t) lineno;
  1210. entry_conn->marked_pending_circ_file = fname;
  1211. #endif
  1212. untried_pending_connections = 1;
  1213. smartlist_add(pending_entry_connections, entry_conn);
  1214. mainloop_event_activate(attach_pending_entry_connections_ev);
  1215. }
  1216. /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
  1217. void
  1218. connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
  1219. {
  1220. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  1221. return;
  1222. UNMARK();
  1223. smartlist_remove(pending_entry_connections, entry_conn);
  1224. }
  1225. /** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
  1226. * function will remove the entry connection from the waiting for a circuit
  1227. * list (pending_entry_connections).
  1228. *
  1229. * This pattern is used across the code base because a connection in state
  1230. * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
  1231. void
  1232. connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
  1233. {
  1234. tor_assert(entry_conn);
  1235. connection_ap_mark_as_non_pending_circuit(entry_conn);
  1236. ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
  1237. }
  1238. /* DOCDOC */
  1239. void
  1240. connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
  1241. const char *where)
  1242. {
  1243. if (pending_entry_connections &&
  1244. smartlist_contains(pending_entry_connections, entry_conn)) {
  1245. log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
  1246. entry_conn, where);
  1247. connection_ap_mark_as_non_pending_circuit(entry_conn);
  1248. }
  1249. }
  1250. /** Tell any AP streams that are waiting for a one-hop tunnel to
  1251. * <b>failed_digest</b> that they are going to fail. */
  1252. /* XXXX We should get rid of this function, and instead attach
  1253. * one-hop streams to circ->p_streams so they get marked in
  1254. * circuit_mark_for_close like normal p_streams. */
  1255. void
  1256. connection_ap_fail_onehop(const char *failed_digest,
  1257. cpath_build_state_t *build_state)
  1258. {
  1259. entry_connection_t *entry_conn;
  1260. char digest[DIGEST_LEN];
  1261. smartlist_t *conns = get_connection_array();
  1262. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1263. if (conn->marked_for_close ||
  1264. conn->type != CONN_TYPE_AP ||
  1265. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  1266. continue;
  1267. entry_conn = TO_ENTRY_CONN(conn);
  1268. if (!entry_conn->want_onehop)
  1269. continue;
  1270. if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
  1271. tor_memneq(digest, failed_digest, DIGEST_LEN))
  1272. continue;
  1273. if (tor_digest_is_zero(digest)) {
  1274. /* we don't know the digest; have to compare addr:port */
  1275. tor_addr_t addr;
  1276. if (!build_state || !build_state->chosen_exit ||
  1277. !entry_conn->socks_request) {
  1278. continue;
  1279. }
  1280. if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
  1281. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  1282. build_state->chosen_exit->port != entry_conn->socks_request->port)
  1283. continue;
  1284. }
  1285. log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
  1286. "just failed.", entry_conn->chosen_exit_name,
  1287. entry_conn->socks_request->address);
  1288. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  1289. } SMARTLIST_FOREACH_END(conn);
  1290. }
  1291. /** A circuit failed to finish on its last hop <b>info</b>. If there
  1292. * are any streams waiting with this exit node in mind, but they
  1293. * don't absolutely require it, make them give up on it.
  1294. */
  1295. void
  1296. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  1297. {
  1298. entry_connection_t *entry_conn;
  1299. const node_t *r1, *r2;
  1300. smartlist_t *conns = get_connection_array();
  1301. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1302. if (conn->marked_for_close ||
  1303. conn->type != CONN_TYPE_AP ||
  1304. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  1305. continue;
  1306. entry_conn = TO_ENTRY_CONN(conn);
  1307. if (!entry_conn->chosen_exit_optional &&
  1308. !entry_conn->chosen_exit_retries)
  1309. continue;
  1310. r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
  1311. NNF_NO_WARN_UNNAMED);
  1312. r2 = node_get_by_id(info->identity_digest);
  1313. if (!r1 || !r2 || r1 != r2)
  1314. continue;
  1315. tor_assert(entry_conn->socks_request);
  1316. if (entry_conn->chosen_exit_optional) {
  1317. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  1318. safe_str_client(entry_conn->chosen_exit_name),
  1319. escaped_safe_str_client(entry_conn->socks_request->address));
  1320. entry_conn->chosen_exit_optional = 0;
  1321. tor_free(entry_conn->chosen_exit_name); /* clears it */
  1322. /* if this port is dangerous, warn or reject it now that we don't
  1323. * think it'll be using an enclave. */
  1324. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  1325. }
  1326. if (entry_conn->chosen_exit_retries) {
  1327. if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
  1328. clear_trackexithost_mappings(entry_conn->chosen_exit_name);
  1329. tor_free(entry_conn->chosen_exit_name); /* clears it */
  1330. /* if this port is dangerous, warn or reject it now that we don't
  1331. * think it'll be using an enclave. */
  1332. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  1333. }
  1334. }
  1335. } SMARTLIST_FOREACH_END(conn);
  1336. }
  1337. /** The AP connection <b>conn</b> has just failed while attaching or
  1338. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  1339. * might work. Detach the circuit, and either reattach it, launch a
  1340. * new circuit, tell the controller, or give up as appropriate.
  1341. *
  1342. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  1343. */
  1344. int
  1345. connection_ap_detach_retriable(entry_connection_t *conn,
  1346. origin_circuit_t *circ,
  1347. int reason)
  1348. {
  1349. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  1350. ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
  1351. /* Roll back path bias use state so that we probe the circuit
  1352. * if nothing else succeeds on it */
  1353. pathbias_mark_use_rollback(circ);
  1354. if (conn->pending_optimistic_data) {
  1355. buf_set_to_copy(&conn->sending_optimistic_data,
  1356. conn->pending_optimistic_data);
  1357. }
  1358. if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
  1359. /* If we're attaching streams ourself, or if this connection is
  1360. * a tunneled directory connection, then just attach it. */
  1361. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1362. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  1363. connection_ap_mark_as_pending_circuit(conn);
  1364. } else {
  1365. CONNECTION_AP_EXPECT_NONPENDING(conn);
  1366. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1367. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  1368. }
  1369. return 0;
  1370. }
  1371. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  1372. * reject depending on our config options. */
  1373. static int
  1374. consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
  1375. {
  1376. const or_options_t *options = get_options();
  1377. int reject = smartlist_contains_int_as_string(
  1378. options->RejectPlaintextPorts, port);
  1379. if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
  1380. log_warn(LD_APP, "Application request to port %d: this port is "
  1381. "commonly used for unencrypted protocols. Please make sure "
  1382. "you don't send anything you would mind the rest of the "
  1383. "Internet reading!%s", port, reject ? " Closing." : "");
  1384. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  1385. port, reject ? "REJECT" : "WARN");
  1386. }
  1387. if (reject) {
  1388. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  1389. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1390. return -1;
  1391. }
  1392. return 0;
  1393. }
  1394. /** How many times do we try connecting with an exit configured via
  1395. * TrackHostExits before concluding that it won't work any more and trying a
  1396. * different one? */
  1397. #define TRACKHOSTEXITS_RETRIES 5
  1398. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  1399. * asked us to leave streams unattached. Return 0 in that case.
  1400. *
  1401. * See connection_ap_handshake_rewrite_and_attach()'s
  1402. * documentation for arguments and return value.
  1403. */
  1404. MOCK_IMPL(int,
  1405. connection_ap_rewrite_and_attach_if_allowed,(entry_connection_t *conn,
  1406. origin_circuit_t *circ,
  1407. crypt_path_t *cpath))
  1408. {
  1409. const or_options_t *options = get_options();
  1410. if (options->LeaveStreamsUnattached) {
  1411. CONNECTION_AP_EXPECT_NONPENDING(conn);
  1412. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1413. return 0;
  1414. }
  1415. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  1416. }
  1417. /* Try to perform any map-based rewriting of the target address in
  1418. * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
  1419. * conn->socks_request.address as appropriate.
  1420. */
  1421. STATIC void
  1422. connection_ap_handshake_rewrite(entry_connection_t *conn,
  1423. rewrite_result_t *out)
  1424. {
  1425. socks_request_t *socks = conn->socks_request;
  1426. const or_options_t *options = get_options();
  1427. tor_addr_t addr_tmp;
  1428. /* Initialize all the fields of 'out' to reasonable defaults */
  1429. out->automap = 0;
  1430. out->exit_source = ADDRMAPSRC_NONE;
  1431. out->map_expires = TIME_MAX;
  1432. out->end_reason = 0;
  1433. out->should_close = 0;
  1434. out->orig_address[0] = 0;
  1435. /* We convert all incoming addresses to lowercase. */
  1436. tor_strlower(socks->address);
  1437. /* Remember the original address. */
  1438. strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
  1439. log_debug(LD_APP,"Client asked for %s:%d",
  1440. safe_str_client(socks->address),
  1441. socks->port);
  1442. /* Check for whether this is a .exit address. By default, those are
  1443. * disallowed when they're coming straight from the client, but you're
  1444. * allowed to have them in MapAddress commands and so forth. */
  1445. if (!strcmpend(socks->address, ".exit")) {
  1446. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  1447. "security risks.");
  1448. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1449. escaped(socks->address));
  1450. out->end_reason = END_STREAM_REASON_TORPROTOCOL;
  1451. out->should_close = 1;
  1452. return;
  1453. }
  1454. /* Remember the original address so we can tell the user about what
  1455. * they actually said, not just what it turned into. */
  1456. /* XXX yes, this is the same as out->orig_address above. One is
  1457. * in the output, and one is in the connection. */
  1458. if (! conn->original_dest_address) {
  1459. /* Is the 'if' necessary here? XXXX */
  1460. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  1461. }
  1462. /* First, apply MapAddress and MAPADDRESS mappings. We need to do
  1463. * these only for non-reverse lookups, since they don't exist for those.
  1464. * We also need to do this before we consider automapping, since we might
  1465. * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
  1466. * we'd need to automap it. */
  1467. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1468. const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
  1469. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1470. rewrite_flags, &out->map_expires, &out->exit_source)) {
  1471. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1472. REMAP_STREAM_SOURCE_CACHE);
  1473. }
  1474. }
  1475. /* Now see if we need to create or return an existing Hostname->IP
  1476. * automapping. Automapping happens when we're asked to resolve a
  1477. * hostname, and AutomapHostsOnResolve is set, and the hostname has a
  1478. * suffix listed in AutomapHostsSuffixes. It's a handy feature
  1479. * that lets you have Tor assign e.g. IPv6 addresses for .onion
  1480. * names, and return them safely from DNSPort.
  1481. */
  1482. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  1483. tor_addr_parse(&addr_tmp, socks->address)<0 &&
  1484. options->AutomapHostsOnResolve) {
  1485. /* Check the suffix... */
  1486. out->automap = addressmap_address_should_automap(socks->address, options);
  1487. if (out->automap) {
  1488. /* If we get here, then we should apply an automapping for this. */
  1489. const char *new_addr;
  1490. /* We return an IPv4 address by default, or an IPv6 address if we
  1491. * are allowed to do so. */
  1492. int addr_type = RESOLVED_TYPE_IPV4;
  1493. if (conn->socks_request->socks_version != 4) {
  1494. if (!conn->entry_cfg.ipv4_traffic ||
  1495. (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
  1496. conn->entry_cfg.prefer_ipv6_virtaddr)
  1497. addr_type = RESOLVED_TYPE_IPV6;
  1498. }
  1499. /* Okay, register the target address as automapped, and find the new
  1500. * address we're supposed to give as a resolve answer. (Return a cached
  1501. * value if we've looked up this address before.
  1502. */
  1503. new_addr = addressmap_register_virtual_address(
  1504. addr_type, tor_strdup(socks->address));
  1505. if (! new_addr) {
  1506. log_warn(LD_APP, "Unable to automap address %s",
  1507. escaped_safe_str(socks->address));
  1508. out->end_reason = END_STREAM_REASON_INTERNAL;
  1509. out->should_close = 1;
  1510. return;
  1511. }
  1512. log_info(LD_APP, "Automapping %s to %s",
  1513. escaped_safe_str_client(socks->address),
  1514. safe_str_client(new_addr));
  1515. strlcpy(socks->address, new_addr, sizeof(socks->address));
  1516. }
  1517. }
  1518. /* Now handle reverse lookups, if they're in the cache. This doesn't
  1519. * happen too often, since client-side DNS caching is off by default,
  1520. * and very deprecated. */
  1521. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1522. unsigned rewrite_flags = 0;
  1523. if (conn->entry_cfg.use_cached_ipv4_answers)
  1524. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1525. if (conn->entry_cfg.use_cached_ipv6_answers)
  1526. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1527. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  1528. rewrite_flags, &out->map_expires)) {
  1529. char *result = tor_strdup(socks->address);
  1530. /* remember _what_ is supposed to have been resolved. */
  1531. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  1532. out->orig_address);
  1533. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1534. strlen(result), (uint8_t*)result,
  1535. -1,
  1536. out->map_expires);
  1537. tor_free(result);
  1538. out->end_reason = END_STREAM_REASON_DONE |
  1539. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1540. out->should_close = 1;
  1541. return;
  1542. }
  1543. /* Hang on, did we find an answer saying that this is a reverse lookup for
  1544. * an internal address? If so, we should reject it if we're configured to
  1545. * do so. */
  1546. if (options->ClientDNSRejectInternalAddresses) {
  1547. /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
  1548. tor_addr_t addr;
  1549. int ok;
  1550. ok = tor_addr_parse_PTR_name(
  1551. &addr, socks->address, AF_UNSPEC, 1);
  1552. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  1553. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  1554. 0, NULL, -1, TIME_MAX);
  1555. out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
  1556. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1557. out->should_close = 1;
  1558. return;
  1559. }
  1560. }
  1561. }
  1562. /* If we didn't automap it before, then this is still the address that
  1563. * came straight from the user, mapped according to any
  1564. * MapAddress/MAPADDRESS commands. Now apply other mappings,
  1565. * including previously registered Automap entries (IP back to
  1566. * hostname), TrackHostExits entries, and client-side DNS cache
  1567. * entries (if they're turned on).
  1568. */
  1569. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1570. !out->automap) {
  1571. unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
  1572. addressmap_entry_source_t exit_source2;
  1573. if (conn->entry_cfg.use_cached_ipv4_answers)
  1574. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1575. if (conn->entry_cfg.use_cached_ipv6_answers)
  1576. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1577. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1578. rewrite_flags, &out->map_expires, &exit_source2)) {
  1579. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1580. REMAP_STREAM_SOURCE_CACHE);
  1581. }
  1582. if (out->exit_source == ADDRMAPSRC_NONE) {
  1583. /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
  1584. * the original source of a .exit. */
  1585. out->exit_source = exit_source2;
  1586. }
  1587. }
  1588. /* Check to see whether we're about to use an address in the virtual
  1589. * range without actually having gotten it from an Automap. */
  1590. if (!out->automap && address_is_in_virtual_range(socks->address)) {
  1591. /* This address was probably handed out by
  1592. * client_dns_get_unmapped_address, but the mapping was discarded for some
  1593. * reason. Or the user typed in a virtual address range manually. We
  1594. * *don't* want to send the address through Tor; that's likely to fail,
  1595. * and may leak information.
  1596. */
  1597. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1598. safe_str_client(socks->address));
  1599. out->end_reason = END_STREAM_REASON_INTERNAL;
  1600. out->should_close = 1;
  1601. return;
  1602. }
  1603. }
  1604. /** We just received a SOCKS request in <b>conn</b> to an onion address of type
  1605. * <b>addresstype</b>. Start connecting to the onion service. */
  1606. static int
  1607. connection_ap_handle_onion(entry_connection_t *conn,
  1608. socks_request_t *socks,
  1609. origin_circuit_t *circ,
  1610. hostname_type_t addresstype)
  1611. {
  1612. time_t now = approx_time();
  1613. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1614. /* If .onion address requests are disabled, refuse the request */
  1615. if (!conn->entry_cfg.onion_traffic) {
  1616. log_warn(LD_APP, "Onion address %s requested from a port with .onion "
  1617. "disabled", safe_str_client(socks->address));
  1618. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1619. return -1;
  1620. }
  1621. /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
  1622. * for hidden service addresses. */
  1623. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1624. /* if it's a resolve request, fail it right now, rather than
  1625. * building all the circuits and then realizing it won't work. */
  1626. log_warn(LD_APP,
  1627. "Resolve requests to hidden services not allowed. Failing.");
  1628. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1629. 0,NULL,-1,TIME_MAX);
  1630. connection_mark_unattached_ap(conn,
  1631. END_STREAM_REASON_SOCKSPROTOCOL |
  1632. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1633. return -1;
  1634. }
  1635. /* If we were passed a circuit, then we need to fail. .onion addresses
  1636. * only work when we launch our own circuits for now. */
  1637. if (circ) {
  1638. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1639. "supported for .onion addresses currently. Failing.");
  1640. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1641. return -1;
  1642. }
  1643. /* Interface: Regardless of HS version after the block below we should have
  1644. set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
  1645. const char *onion_address = NULL;
  1646. int rend_cache_lookup_result = -ENOENT;
  1647. int descriptor_is_usable = 0;
  1648. if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
  1649. rend_cache_entry_t *entry = NULL;
  1650. /* Look up if we have client authorization configured for this hidden
  1651. * service. If we do, associate it with the rend_data. */
  1652. rend_service_authorization_t *client_auth =
  1653. rend_client_lookup_service_authorization(socks->address);
  1654. const uint8_t *cookie = NULL;
  1655. rend_auth_type_t auth_type = REND_NO_AUTH;
  1656. if (client_auth) {
  1657. log_info(LD_REND, "Using previously configured client authorization "
  1658. "for hidden service request.");
  1659. auth_type = client_auth->auth_type;
  1660. cookie = client_auth->descriptor_cookie;
  1661. }
  1662. /* Fill in the rend_data field so we can start doing a connection to
  1663. * a hidden service. */
  1664. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
  1665. rend_data_client_create(socks->address, NULL, (char *) cookie,
  1666. auth_type);
  1667. if (rend_data == NULL) {
  1668. return -1;
  1669. }
  1670. onion_address = rend_data_get_address(rend_data);
  1671. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1672. safe_str_client(onion_address));
  1673. rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
  1674. &entry);
  1675. if (!rend_cache_lookup_result && entry) {
  1676. descriptor_is_usable = rend_client_any_intro_points_usable(entry);
  1677. }
  1678. } else { /* it's a v3 hidden service */
  1679. tor_assert(addresstype == ONION_V3_HOSTNAME);
  1680. const hs_descriptor_t *cached_desc = NULL;
  1681. int retval;
  1682. /* Create HS conn identifier with HS pubkey */
  1683. hs_ident_edge_conn_t *hs_conn_ident =
  1684. tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
  1685. retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
  1686. NULL, NULL);
  1687. if (retval < 0) {
  1688. log_warn(LD_GENERAL, "failed to parse hs address");
  1689. tor_free(hs_conn_ident);
  1690. return -1;
  1691. }
  1692. ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
  1693. onion_address = socks->address;
  1694. /* Check the v3 desc cache */
  1695. cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
  1696. if (cached_desc) {
  1697. rend_cache_lookup_result = 0;
  1698. descriptor_is_usable =
  1699. hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
  1700. cached_desc);
  1701. log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
  1702. (descriptor_is_usable) ? "usable" : "unusable",
  1703. safe_str_client(onion_address),
  1704. (descriptor_is_usable) ? "Not fetching." : "Refecting.");
  1705. } else {
  1706. rend_cache_lookup_result = -ENOENT;
  1707. }
  1708. }
  1709. /* Lookup the given onion address. If invalid, stop right now.
  1710. * Otherwise, we might have it in the cache or not. */
  1711. unsigned int refetch_desc = 0;
  1712. if (rend_cache_lookup_result < 0) {
  1713. switch (-rend_cache_lookup_result) {
  1714. case EINVAL:
  1715. /* We should already have rejected this address! */
  1716. log_warn(LD_BUG,"Invalid service name '%s'",
  1717. safe_str_client(onion_address));
  1718. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1719. return -1;
  1720. case ENOENT:
  1721. /* We didn't have this; we should look it up. */
  1722. log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
  1723. safe_str_client(onion_address));
  1724. refetch_desc = 1;
  1725. break;
  1726. default:
  1727. log_warn(LD_BUG, "Unknown cache lookup error %d",
  1728. rend_cache_lookup_result);
  1729. return -1;
  1730. }
  1731. }
  1732. /* Help predict that we'll want to do hidden service circuits in the
  1733. * future. We're not sure if it will need a stable circuit yet, but
  1734. * we know we'll need *something*. */
  1735. rep_hist_note_used_internal(now, 0, 1);
  1736. /* Now we have a descriptor but is it usable or not? If not, refetch.
  1737. * Also, a fetch could have been requested if the onion address was not
  1738. * found in the cache previously. */
  1739. if (refetch_desc || !descriptor_is_usable) {
  1740. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  1741. connection_ap_mark_as_non_pending_circuit(conn);
  1742. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1743. if (addresstype == ONION_V2_HOSTNAME) {
  1744. tor_assert(edge_conn->rend_data);
  1745. rend_client_refetch_v2_renddesc(edge_conn->rend_data);
  1746. /* Whatever the result of the refetch, we don't go further. */
  1747. return 0;
  1748. } else {
  1749. tor_assert(addresstype == ONION_V3_HOSTNAME);
  1750. tor_assert(edge_conn->hs_ident);
  1751. /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
  1752. * went and act accordingly. */
  1753. int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
  1754. switch (ret) {
  1755. case HS_CLIENT_FETCH_MISSING_INFO:
  1756. /* Keeping the connection in descriptor wait state is fine because
  1757. * once we get enough dirinfo or a new live consensus, the HS client
  1758. * subsystem is notified and every connection in that state will
  1759. * trigger a fetch for the service key. */
  1760. case HS_CLIENT_FETCH_LAUNCHED:
  1761. case HS_CLIENT_FETCH_PENDING:
  1762. case HS_CLIENT_FETCH_HAVE_DESC:
  1763. return 0;
  1764. case HS_CLIENT_FETCH_ERROR:
  1765. case HS_CLIENT_FETCH_NO_HSDIRS:
  1766. case HS_CLIENT_FETCH_NOT_ALLOWED:
  1767. /* Can't proceed further and better close the SOCKS request. */
  1768. return -1;
  1769. }
  1770. }
  1771. }
  1772. /* We have the descriptor! So launch a connection to the HS. */
  1773. log_info(LD_REND, "Descriptor is here. Great.");
  1774. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1775. /* We'll try to attach it at the next event loop, or whenever
  1776. * we call connection_ap_attach_pending() */
  1777. connection_ap_mark_as_pending_circuit(conn);
  1778. return 0;
  1779. }
  1780. /** Connection <b>conn</b> just finished its socks handshake, or the
  1781. * controller asked us to take care of it. If <b>circ</b> is defined,
  1782. * then that's where we'll want to attach it. Otherwise we have to
  1783. * figure it out ourselves.
  1784. *
  1785. * First, parse whether it's a .exit address, remap it, and so on. Then
  1786. * if it's for a general circuit, try to attach it to a circuit (or launch
  1787. * one as needed), else if it's for a rendezvous circuit, fetch a
  1788. * rendezvous descriptor first (or attach/launch a circuit if the
  1789. * rendezvous descriptor is already here and fresh enough).
  1790. *
  1791. * The stream will exit from the hop
  1792. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1793. * <b>cpath</b> is NULL.
  1794. */
  1795. int
  1796. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  1797. origin_circuit_t *circ,
  1798. crypt_path_t *cpath)
  1799. {
  1800. socks_request_t *socks = conn->socks_request;
  1801. const or_options_t *options = get_options();
  1802. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1803. time_t now = time(NULL);
  1804. rewrite_result_t rr;
  1805. /* First we'll do the rewrite part. Let's see if we get a reasonable
  1806. * answer.
  1807. */
  1808. memset(&rr, 0, sizeof(rr));
  1809. connection_ap_handshake_rewrite(conn,&rr);
  1810. if (rr.should_close) {
  1811. /* connection_ap_handshake_rewrite told us to close the connection:
  1812. * either because it sent back an answer, or because it sent back an
  1813. * error */
  1814. connection_mark_unattached_ap(conn, rr.end_reason);
  1815. if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
  1816. return 0;
  1817. else
  1818. return -1;
  1819. }
  1820. const time_t map_expires = rr.map_expires;
  1821. const int automap = rr.automap;
  1822. const addressmap_entry_source_t exit_source = rr.exit_source;
  1823. /* Now, we parse the address to see if it's an .onion or .exit or
  1824. * other special address.
  1825. */
  1826. const hostname_type_t addresstype = parse_extended_hostname(socks->address);
  1827. /* Now see whether the hostname is bogus. This could happen because of an
  1828. * onion hostname whose format we don't recognize. */
  1829. if (addresstype == BAD_HOSTNAME) {
  1830. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1831. escaped(socks->address));
  1832. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1833. return -1;
  1834. }
  1835. /* If this is a .exit hostname, strip off the .name.exit part, and
  1836. * see whether we're willing to connect there, and and otherwise handle the
  1837. * .exit address.
  1838. *
  1839. * We'll set chosen_exit_name and/or close the connection as appropriate.
  1840. */
  1841. if (addresstype == EXIT_HOSTNAME) {
  1842. /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
  1843. * not ExcludeExitNodes. */
  1844. routerset_t *excludeset = options->StrictNodes ?
  1845. options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
  1846. const node_t *node = NULL;
  1847. /* If this .exit was added by an AUTOMAP, then it came straight from
  1848. * a user. That's not safe. */
  1849. if (exit_source == ADDRMAPSRC_AUTOMAP) {
  1850. /* Whoops; this one is stale. It must have gotten added earlier?
  1851. * (Probably this is not possible, since AllowDotExit no longer
  1852. * exists.) */
  1853. log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
  1854. safe_str_client(socks->address));
  1855. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1856. escaped(socks->address));
  1857. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1858. tor_assert_nonfatal_unreached();
  1859. return -1;
  1860. }
  1861. /* Double-check to make sure there are no .exits coming from
  1862. * impossible/weird sources. */
  1863. if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
  1864. /* It shouldn't be possible to get a .exit address from any of these
  1865. * sources. */
  1866. log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
  1867. ".exit part. Refusing.",
  1868. safe_str_client(socks->address));
  1869. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1870. escaped(socks->address));
  1871. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1872. return -1;
  1873. }
  1874. tor_assert(!automap);
  1875. /* Now, find the character before the .(name) part.
  1876. * (The ".exit" part got stripped off by "parse_extended_hostname").
  1877. *
  1878. * We're going to put the exit name into conn->chosen_exit_name, and
  1879. * look up a node correspondingly. */
  1880. char *s = strrchr(socks->address,'.');
  1881. if (s) {
  1882. /* The address was of the form "(stuff).(name).exit */
  1883. if (s[1] != '\0') {
  1884. /* Looks like a real .exit one. */
  1885. conn->chosen_exit_name = tor_strdup(s+1);
  1886. node = node_get_by_nickname(conn->chosen_exit_name, 0);
  1887. if (exit_source == ADDRMAPSRC_TRACKEXIT) {
  1888. /* We 5 tries before it expires the addressmap */
  1889. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1890. }
  1891. *s = 0;
  1892. } else {
  1893. /* Oops, the address was (stuff)..exit. That's not okay. */
  1894. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1895. safe_str_client(socks->address));
  1896. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1897. escaped(socks->address));
  1898. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1899. return -1;
  1900. }
  1901. } else {
  1902. /* It looks like they just asked for "foo.exit". That's a special
  1903. * form that means (foo's address).foo.exit. */
  1904. conn->chosen_exit_name = tor_strdup(socks->address);
  1905. node = node_get_by_nickname(conn->chosen_exit_name, 0);
  1906. if (node) {
  1907. *socks->address = 0;
  1908. node_get_address_string(node, socks->address, sizeof(socks->address));
  1909. }
  1910. }
  1911. /* Now make sure that the chosen exit exists... */
  1912. if (!node) {
  1913. log_warn(LD_APP,
  1914. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1915. safe_str_client(socks->address));
  1916. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1917. return -1;
  1918. }
  1919. /* ...and make sure that it isn't excluded. */
  1920. if (routerset_contains_node(excludeset, node)) {
  1921. log_warn(LD_APP,
  1922. "Excluded relay in exit address '%s.exit'. Refusing.",
  1923. safe_str_client(socks->address));
  1924. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1925. return -1;
  1926. }
  1927. /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1928. Bar is not listed in it? I say yes, but our revised manpage branch
  1929. implies no. */
  1930. }
  1931. /* Now, we handle everything that isn't a .onion address. */
  1932. if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
  1933. /* Not a hidden-service request. It's either a hostname or an IP,
  1934. * possibly with a .exit that we stripped off. We're going to check
  1935. * if we're allowed to connect/resolve there, and then launch the
  1936. * appropriate request. */
  1937. /* Check for funny characters in the address. */
  1938. if (address_is_invalid_destination(socks->address, 1)) {
  1939. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1940. escaped(socks->address));
  1941. log_warn(LD_APP,
  1942. "Destination '%s' seems to be an invalid hostname. Failing.",
  1943. safe_str_client(socks->address));
  1944. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1945. return -1;
  1946. }
  1947. /* socks->address is a non-onion hostname or IP address.
  1948. * If we can't do any non-onion requests, refuse the connection.
  1949. * If we have a hostname but can't do DNS, refuse the connection.
  1950. * If we have an IP address, but we can't use that address family,
  1951. * refuse the connection.
  1952. *
  1953. * If we can do DNS requests, and we can use at least one address family,
  1954. * then we have to resolve the address first. Then we'll know if it
  1955. * resolves to a usable address family. */
  1956. /* First, check if all non-onion traffic is disabled */
  1957. if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
  1958. && !conn->entry_cfg.ipv6_traffic) {
  1959. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
  1960. "or IP address %s because Port has OnionTrafficOnly set (or "
  1961. "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
  1962. safe_str_client(socks->address));
  1963. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1964. return -1;
  1965. }
  1966. /* Then check if we have a hostname or IP address, and whether DNS or
  1967. * the IP address family are permitted. Reject if not. */
  1968. tor_addr_t dummy_addr;
  1969. int socks_family = tor_addr_parse(&dummy_addr, socks->address);
  1970. /* family will be -1 for a non-onion hostname that's not an IP */
  1971. if (socks_family == -1) {
  1972. if (!conn->entry_cfg.dns_request) {
  1973. log_warn(LD_APP, "Refusing to connect to hostname %s "
  1974. "because Port has NoDNSRequest set.",
  1975. safe_str_client(socks->address));
  1976. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1977. return -1;
  1978. }
  1979. } else if (socks_family == AF_INET) {
  1980. if (!conn->entry_cfg.ipv4_traffic) {
  1981. log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
  1982. "Port has NoIPv4Traffic set.",
  1983. safe_str_client(socks->address));
  1984. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1985. return -1;
  1986. }
  1987. } else if (socks_family == AF_INET6) {
  1988. if (!conn->entry_cfg.ipv6_traffic) {
  1989. log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
  1990. "Port has NoIPv6Traffic set.",
  1991. safe_str_client(socks->address));
  1992. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1993. return -1;
  1994. }
  1995. } else {
  1996. tor_assert_nonfatal_unreached_once();
  1997. }
  1998. /* See if this is a hostname lookup that we can answer immediately.
  1999. * (For example, an attempt to look up the IP address for an IP address.)
  2000. */
  2001. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  2002. tor_addr_t answer;
  2003. /* Reply to resolves immediately if we can. */
  2004. if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
  2005. /* remember _what_ is supposed to have been resolved. */
  2006. strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
  2007. connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
  2008. map_expires);
  2009. connection_mark_unattached_ap(conn,
  2010. END_STREAM_REASON_DONE |
  2011. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2012. return 0;
  2013. }
  2014. tor_assert(!automap);
  2015. rep_hist_note_used_resolve(now); /* help predict this next time */
  2016. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  2017. /* Now see if this is a connect request that we can reject immediately */
  2018. tor_assert(!automap);
  2019. /* Don't allow connections to port 0. */
  2020. if (socks->port == 0) {
  2021. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  2022. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  2023. return -1;
  2024. }
  2025. /* You can't make connections to internal addresses, by default.
  2026. * Exceptions are begindir requests (where the address is meaningless),
  2027. * or cases where you've hand-configured a particular exit, thereby
  2028. * making the local address meaningful. */
  2029. if (options->ClientRejectInternalAddresses &&
  2030. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  2031. /* If we reach this point then we don't want to allow internal
  2032. * addresses. Check if we got one. */
  2033. tor_addr_t addr;
  2034. if (tor_addr_hostname_is_local(socks->address) ||
  2035. (tor_addr_parse(&addr, socks->address) >= 0 &&
  2036. tor_addr_is_internal(&addr, 0))) {
  2037. /* If this is an explicit private address with no chosen exit node,
  2038. * then we really don't want to try to connect to it. That's
  2039. * probably an error. */
  2040. if (conn->is_transparent_ap) {
  2041. #define WARN_INTRVL_LOOP 300
  2042. static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
  2043. char *m;
  2044. if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
  2045. log_warn(LD_NET,
  2046. "Rejecting request for anonymous connection to private "
  2047. "address %s on a TransPort or NATDPort. Possible loop "
  2048. "in your NAT rules?%s", safe_str_client(socks->address),
  2049. m);
  2050. tor_free(m);
  2051. }
  2052. } else {
  2053. #define WARN_INTRVL_PRIV 300
  2054. static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
  2055. char *m;
  2056. if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
  2057. log_warn(LD_NET,
  2058. "Rejecting SOCKS request for anonymous connection to "
  2059. "private address %s.%s",
  2060. safe_str_client(socks->address),m);
  2061. tor_free(m);
  2062. }
  2063. }
  2064. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  2065. return -1;
  2066. }
  2067. } /* end "if we should check for internal addresses" */
  2068. /* Okay. We're still doing a CONNECT, and it wasn't a private
  2069. * address. Here we do special handling for literal IP addresses,
  2070. * to see if we should reject this preemptively, and to set up
  2071. * fields in conn->entry_cfg to tell the exit what AF we want. */
  2072. {
  2073. tor_addr_t addr;
  2074. /* XXX Duplicate call to tor_addr_parse. */
  2075. if (tor_addr_parse(&addr, socks->address) >= 0) {
  2076. /* If we reach this point, it's an IPv4 or an IPv6 address. */
  2077. sa_family_t family = tor_addr_family(&addr);
  2078. if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
  2079. (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
  2080. /* You can't do an IPv4 address on a v6-only socks listener,
  2081. * or vice versa. */
  2082. log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
  2083. "family that this listener does not support.");
  2084. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2085. return -1;
  2086. } else if (family == AF_INET6 && socks->socks_version == 4) {
  2087. /* You can't make a socks4 request to an IPv6 address. Socks4
  2088. * doesn't support that. */
  2089. log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
  2090. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2091. return -1;
  2092. } else if (socks->socks_version == 4 &&
  2093. !conn->entry_cfg.ipv4_traffic) {
  2094. /* You can't do any kind of Socks4 request when IPv4 is forbidden.
  2095. *
  2096. * XXX raise this check outside the enclosing block? */
  2097. log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
  2098. "no IPv4 traffic supported.");
  2099. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2100. return -1;
  2101. } else if (family == AF_INET6) {
  2102. /* Tell the exit: we won't accept any ipv4 connection to an IPv6
  2103. * address. */
  2104. conn->entry_cfg.ipv4_traffic = 0;
  2105. } else if (family == AF_INET) {
  2106. /* Tell the exit: we won't accept any ipv6 connection to an IPv4
  2107. * address. */
  2108. conn->entry_cfg.ipv6_traffic = 0;
  2109. }
  2110. }
  2111. }
  2112. /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
  2113. if (socks->socks_version == 4)
  2114. conn->entry_cfg.ipv6_traffic = 0;
  2115. /* Still handling CONNECT. Now, check for exit enclaves. (Which we
  2116. * don't do on BEGIN_DIR, or when there is a chosen exit.)
  2117. *
  2118. * TODO: Should we remove this? Exit enclaves are nutty and don't
  2119. * work very well
  2120. */
  2121. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  2122. /* see if we can find a suitable enclave exit */
  2123. const node_t *r =
  2124. router_find_exact_exit_enclave(socks->address, socks->port);
  2125. if (r) {
  2126. log_info(LD_APP,
  2127. "Redirecting address %s to exit at enclave router %s",
  2128. safe_str_client(socks->address), node_describe(r));
  2129. /* use the hex digest, not nickname, in case there are two
  2130. routers with this nickname */
  2131. conn->chosen_exit_name =
  2132. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  2133. conn->chosen_exit_optional = 1;
  2134. }
  2135. }
  2136. /* Still handling CONNECT: warn or reject if it's using a dangerous
  2137. * port. */
  2138. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  2139. if (consider_plaintext_ports(conn, socks->port) < 0)
  2140. return -1;
  2141. /* Remember the port so that we will predict that more requests
  2142. there will happen in the future. */
  2143. if (!conn->use_begindir) {
  2144. /* help predict this next time */
  2145. rep_hist_note_used_port(now, socks->port);
  2146. }
  2147. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  2148. rep_hist_note_used_resolve(now); /* help predict this next time */
  2149. /* no extra processing needed */
  2150. } else {
  2151. /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
  2152. tor_fragile_assert();
  2153. }
  2154. /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
  2155. * address, and decided not to reject it for any number of reasons. Now
  2156. * mark the connection as waiting for a circuit, and try to attach it!
  2157. */
  2158. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2159. /* If we were given a circuit to attach to, try to attach. Otherwise,
  2160. * try to find a good one and attach to that. */
  2161. int rv;
  2162. if (circ) {
  2163. rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
  2164. } else {
  2165. /* We'll try to attach it at the next event loop, or whenever
  2166. * we call connection_ap_attach_pending() */
  2167. connection_ap_mark_as_pending_circuit(conn);
  2168. rv = 0;
  2169. }
  2170. /* If the above function returned 0 then we're waiting for a circuit.
  2171. * if it returned 1, we're attached. Both are okay. But if it returned
  2172. * -1, there was an error, so make sure the connection is marked, and
  2173. * return -1. */
  2174. if (rv < 0) {
  2175. if (!base_conn->marked_for_close)
  2176. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  2177. return -1;
  2178. }
  2179. return 0;
  2180. } else {
  2181. /* If we get here, it's a request for a .onion address! */
  2182. tor_assert(addresstype == ONION_V2_HOSTNAME ||
  2183. addresstype == ONION_V3_HOSTNAME);
  2184. tor_assert(!automap);
  2185. return connection_ap_handle_onion(conn, socks, circ, addresstype);
  2186. }
  2187. return 0; /* unreached but keeps the compiler happy */
  2188. }
  2189. #ifdef TRANS_PF
  2190. static int pf_socket = -1;
  2191. int
  2192. get_pf_socket(void)
  2193. {
  2194. int pf;
  2195. /* This should be opened before dropping privileges. */
  2196. if (pf_socket >= 0)
  2197. return pf_socket;
  2198. #if defined(OpenBSD)
  2199. /* only works on OpenBSD */
  2200. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  2201. #else
  2202. /* works on NetBSD and FreeBSD */
  2203. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  2204. #endif /* defined(OpenBSD) */
  2205. if (pf < 0) {
  2206. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  2207. return -1;
  2208. }
  2209. pf_socket = pf;
  2210. return pf_socket;
  2211. }
  2212. #endif /* defined(TRANS_PF) */
  2213. #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
  2214. defined(TRANS_TPROXY)
  2215. /** Try fill in the address of <b>req</b> from the socket configured
  2216. * with <b>conn</b>. */
  2217. static int
  2218. destination_from_socket(entry_connection_t *conn, socks_request_t *req)
  2219. {
  2220. struct sockaddr_storage orig_dst;
  2221. socklen_t orig_dst_len = sizeof(orig_dst);
  2222. tor_addr_t addr;
  2223. #ifdef TRANS_TPROXY
  2224. if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
  2225. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  2226. &orig_dst_len) < 0) {
  2227. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2228. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  2229. return -1;
  2230. }
  2231. goto done;
  2232. }
  2233. #endif /* defined(TRANS_TPROXY) */
  2234. #ifdef TRANS_NETFILTER
  2235. int rv = -1;
  2236. switch (ENTRY_TO_CONN(conn)->socket_family) {
  2237. #ifdef TRANS_NETFILTER_IPV4
  2238. case AF_INET:
  2239. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  2240. (struct sockaddr*)&orig_dst, &orig_dst_len);
  2241. break;
  2242. #endif /* defined(TRANS_NETFILTER_IPV4) */
  2243. #ifdef TRANS_NETFILTER_IPV6
  2244. case AF_INET6:
  2245. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
  2246. (struct sockaddr*)&orig_dst, &orig_dst_len);
  2247. break;
  2248. #endif /* defined(TRANS_NETFILTER_IPV6) */
  2249. default:
  2250. log_warn(LD_BUG,
  2251. "Received transparent data from an unsuported socket family %d",
  2252. ENTRY_TO_CONN(conn)->socket_family);
  2253. return -1;
  2254. }
  2255. if (rv < 0) {
  2256. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2257. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  2258. return -1;
  2259. }
  2260. goto done;
  2261. #elif defined(TRANS_PF)
  2262. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  2263. &orig_dst_len) < 0) {
  2264. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2265. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  2266. return -1;
  2267. }
  2268. goto done;
  2269. #else
  2270. (void)conn;
  2271. (void)req;
  2272. log_warn(LD_BUG, "Unable to determine destination from socket.");
  2273. return -1;
  2274. #endif /* defined(TRANS_NETFILTER) || ... */
  2275. done:
  2276. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  2277. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  2278. return 0;
  2279. }
  2280. #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
  2281. #ifdef TRANS_PF
  2282. static int
  2283. destination_from_pf(entry_connection_t *conn, socks_request_t *req)
  2284. {
  2285. struct sockaddr_storage proxy_addr;
  2286. socklen_t proxy_addr_len = sizeof(proxy_addr);
  2287. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  2288. struct pfioc_natlook pnl;
  2289. tor_addr_t addr;
  2290. int pf = -1;
  2291. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  2292. &proxy_addr_len) < 0) {
  2293. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2294. log_warn(LD_NET, "getsockname() to determine transocks destination "
  2295. "failed: %s", tor_socket_strerror(e));
  2296. return -1;
  2297. }
  2298. #ifdef __FreeBSD__
  2299. if (get_options()->TransProxyType_parsed == TPT_IPFW) {
  2300. /* ipfw(8) is used and in this case getsockname returned the original
  2301. destination */
  2302. if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
  2303. tor_fragile_assert();
  2304. return -1;
  2305. }
  2306. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  2307. return 0;
  2308. }
  2309. #endif /* defined(__FreeBSD__) */
  2310. memset(&pnl, 0, sizeof(pnl));
  2311. pnl.proto = IPPROTO_TCP;
  2312. pnl.direction = PF_OUT;
  2313. if (proxy_sa->sa_family == AF_INET) {
  2314. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  2315. pnl.af = AF_INET;
  2316. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  2317. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  2318. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  2319. pnl.dport = sin->sin_port;
  2320. } else if (proxy_sa->sa_family == AF_INET6) {
  2321. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  2322. pnl.af = AF_INET6;
  2323. const struct in6_addr *dest_in6 =
  2324. tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr);
  2325. if (BUG(!dest_in6))
  2326. return -1;
  2327. memcpy(&pnl.saddr.v6, dest_in6, sizeof(struct in6_addr));
  2328. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  2329. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  2330. pnl.dport = sin6->sin6_port;
  2331. } else {
  2332. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  2333. (int)proxy_sa->sa_family);
  2334. return -1;
  2335. }
  2336. pf = get_pf_socket();
  2337. if (pf<0)
  2338. return -1;
  2339. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  2340. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  2341. return -1;
  2342. }
  2343. if (pnl.af == AF_INET) {
  2344. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  2345. } else if (pnl.af == AF_INET6) {
  2346. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  2347. } else {
  2348. tor_fragile_assert();
  2349. return -1;
  2350. }
  2351. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  2352. req->port = ntohs(pnl.rdport);
  2353. return 0;
  2354. }
  2355. #endif /* defined(TRANS_PF) */
  2356. /** Fetch the original destination address and port from a
  2357. * system-specific interface and put them into a
  2358. * socks_request_t as if they came from a socks request.
  2359. *
  2360. * Return -1 if an error prevents fetching the destination,
  2361. * else return 0.
  2362. */
  2363. static int
  2364. connection_ap_get_original_destination(entry_connection_t *conn,
  2365. socks_request_t *req)
  2366. {
  2367. #ifdef TRANS_NETFILTER
  2368. return destination_from_socket(conn, req);
  2369. #elif defined(TRANS_PF)
  2370. const or_options_t *options = get_options();
  2371. if (options->TransProxyType_parsed == TPT_PF_DIVERT)
  2372. return destination_from_socket(conn, req);
  2373. if (options->TransProxyType_parsed == TPT_DEFAULT ||
  2374. options->TransProxyType_parsed == TPT_IPFW)
  2375. return destination_from_pf(conn, req);
  2376. (void)conn;
  2377. (void)req;
  2378. log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
  2379. options->TransProxyType);
  2380. return -1;
  2381. #else
  2382. (void)conn;
  2383. (void)req;
  2384. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  2385. "transparent proxy method was configured.");
  2386. return -1;
  2387. #endif /* defined(TRANS_NETFILTER) || ... */
  2388. }
  2389. /** connection_edge_process_inbuf() found a conn in state
  2390. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  2391. * the socks handshake.
  2392. *
  2393. * If the handshake is complete, send it to
  2394. * connection_ap_handshake_rewrite_and_attach().
  2395. *
  2396. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  2397. * else return 0.
  2398. */
  2399. static int
  2400. connection_ap_handshake_process_socks(entry_connection_t *conn)
  2401. {
  2402. socks_request_t *socks;
  2403. int sockshere;
  2404. const or_options_t *options = get_options();
  2405. int had_reply = 0;
  2406. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2407. tor_assert(conn);
  2408. tor_assert(base_conn->type == CONN_TYPE_AP);
  2409. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  2410. tor_assert(conn->socks_request);
  2411. socks = conn->socks_request;
  2412. log_debug(LD_APP,"entered.");
  2413. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  2414. options->TestSocks, options->SafeSocks);
  2415. if (socks->replylen) {
  2416. had_reply = 1;
  2417. connection_buf_add((const char*)socks->reply, socks->replylen,
  2418. base_conn);
  2419. socks->replylen = 0;
  2420. if (sockshere == -1) {
  2421. /* An invalid request just got a reply, no additional
  2422. * one is necessary. */
  2423. socks->has_finished = 1;
  2424. }
  2425. }
  2426. if (sockshere == 0) {
  2427. log_debug(LD_APP,"socks handshake not all here yet.");
  2428. return 0;
  2429. } else if (sockshere == -1) {
  2430. if (!had_reply) {
  2431. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  2432. connection_ap_handshake_socks_reply(conn, NULL, 0,
  2433. END_STREAM_REASON_SOCKSPROTOCOL);
  2434. }
  2435. connection_mark_unattached_ap(conn,
  2436. END_STREAM_REASON_SOCKSPROTOCOL |
  2437. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2438. return -1;
  2439. } /* else socks handshake is done, continue processing */
  2440. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  2441. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2442. else
  2443. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  2444. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2445. }
  2446. /** connection_init_accepted_conn() found a new trans AP conn.
  2447. * Get the original destination and send it to
  2448. * connection_ap_handshake_rewrite_and_attach().
  2449. *
  2450. * Return -1 if an unexpected error with conn (and it should be marked
  2451. * for close), else return 0.
  2452. */
  2453. int
  2454. connection_ap_process_transparent(entry_connection_t *conn)
  2455. {
  2456. socks_request_t *socks;
  2457. tor_assert(conn);
  2458. tor_assert(conn->socks_request);
  2459. socks = conn->socks_request;
  2460. /* pretend that a socks handshake completed so we don't try to
  2461. * send a socks reply down a transparent conn */
  2462. socks->command = SOCKS_COMMAND_CONNECT;
  2463. socks->has_finished = 1;
  2464. log_debug(LD_APP,"entered.");
  2465. if (connection_ap_get_original_destination(conn, socks) < 0) {
  2466. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  2467. connection_mark_unattached_ap(conn,
  2468. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  2469. return -1;
  2470. }
  2471. /* we have the original destination */
  2472. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2473. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2474. }
  2475. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  2476. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  2477. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  2478. * form of the original destination.
  2479. *
  2480. * If the original destination is complete, send it to
  2481. * connection_ap_handshake_rewrite_and_attach().
  2482. *
  2483. * Return -1 if an unexpected error with conn (and it should be marked
  2484. * for close), else return 0.
  2485. */
  2486. static int
  2487. connection_ap_process_natd(entry_connection_t *conn)
  2488. {
  2489. char tmp_buf[36], *tbuf, *daddr;
  2490. size_t tlen = 30;
  2491. int err, port_ok;
  2492. socks_request_t *socks;
  2493. tor_assert(conn);
  2494. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  2495. tor_assert(conn->socks_request);
  2496. socks = conn->socks_request;
  2497. log_debug(LD_APP,"entered.");
  2498. /* look for LF-terminated "[DEST ip_addr port]"
  2499. * where ip_addr is a dotted-quad and port is in string form */
  2500. err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  2501. if (err == 0)
  2502. return 0;
  2503. if (err < 0) {
  2504. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  2505. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2506. return -1;
  2507. }
  2508. if (strcmpstart(tmp_buf, "[DEST ")) {
  2509. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2510. "said: %s",
  2511. escaped(tmp_buf));
  2512. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2513. return -1;
  2514. }
  2515. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  2516. if (!(tbuf = strchr(tbuf, ' '))) {
  2517. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2518. "said: %s",
  2519. escaped(tmp_buf));
  2520. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2521. return -1;
  2522. }
  2523. *tbuf++ = '\0';
  2524. /* pretend that a socks handshake completed so we don't try to
  2525. * send a socks reply down a natd conn */
  2526. strlcpy(socks->address, daddr, sizeof(socks->address));
  2527. socks->port = (uint16_t)
  2528. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  2529. if (!port_ok) {
  2530. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  2531. "of range.", escaped(tbuf));
  2532. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2533. return -1;
  2534. }
  2535. socks->command = SOCKS_COMMAND_CONNECT;
  2536. socks->has_finished = 1;
  2537. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2538. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2539. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2540. }
  2541. static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
  2542. "HTTP/1.0 405 Method Not Allowed\r\n"
  2543. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  2544. "<html>\n"
  2545. "<head>\n"
  2546. "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
  2547. "</head>\n"
  2548. "<body>\n"
  2549. "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
  2550. "<p>\n"
  2551. "It appears you have configured your web browser to use this Tor port as\n"
  2552. "an HTTP proxy.\n"
  2553. "</p><p>\n"
  2554. "This is not correct: This port is configured as a CONNECT tunnel, not\n"
  2555. "an HTTP proxy. Please configure your client accordingly. You can also\n"
  2556. "use HTTPS; then the client should automatically use HTTP CONNECT."
  2557. "</p>\n"
  2558. "<p>\n"
  2559. "See <a href=\"https://www.torproject.org/documentation.html\">"
  2560. "https://www.torproject.org/documentation.html</a> for more "
  2561. "information.\n"
  2562. "</p>\n"
  2563. "</body>\n"
  2564. "</html>\n";
  2565. /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
  2566. * but we have not yet received a full HTTP CONNECT request. Try to parse an
  2567. * HTTP CONNECT request from the connection's inbuf. On success, set up the
  2568. * connection's socks_request field and try to attach the connection. On
  2569. * failure, send an HTTP reply, and mark the connection.
  2570. */
  2571. STATIC int
  2572. connection_ap_process_http_connect(entry_connection_t *conn)
  2573. {
  2574. if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
  2575. return -1;
  2576. char *headers = NULL, *body = NULL;
  2577. char *command = NULL, *addrport = NULL;
  2578. char *addr = NULL;
  2579. size_t bodylen = 0;
  2580. const char *errmsg = NULL;
  2581. int rv = 0;
  2582. const int http_status =
  2583. fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
  2584. &body, &bodylen, 1024, 0);
  2585. if (http_status < 0) {
  2586. /* Bad http status */
  2587. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2588. goto err;
  2589. } else if (http_status == 0) {
  2590. /* no HTTP request yet. */
  2591. goto done;
  2592. }
  2593. const int cmd_status = parse_http_command(headers, &command, &addrport);
  2594. if (cmd_status < 0) {
  2595. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2596. goto err;
  2597. }
  2598. tor_assert(command);
  2599. tor_assert(addrport);
  2600. if (strcasecmp(command, "connect")) {
  2601. errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
  2602. goto err;
  2603. }
  2604. tor_assert(conn->socks_request);
  2605. socks_request_t *socks = conn->socks_request;
  2606. uint16_t port;
  2607. if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
  2608. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2609. goto err;
  2610. }
  2611. if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
  2612. errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
  2613. goto err;
  2614. }
  2615. /* Abuse the 'username' and 'password' fields here. They are already an
  2616. * abuse. */
  2617. {
  2618. char *authorization = http_get_header(headers, "Proxy-Authorization: ");
  2619. if (authorization) {
  2620. socks->username = authorization; // steal reference
  2621. socks->usernamelen = strlen(authorization);
  2622. }
  2623. char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
  2624. if (isolation) {
  2625. socks->password = isolation; // steal reference
  2626. socks->passwordlen = strlen(isolation);
  2627. }
  2628. }
  2629. socks->command = SOCKS_COMMAND_CONNECT;
  2630. socks->listener_type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
  2631. strlcpy(socks->address, addr, sizeof(socks->address));
  2632. socks->port = port;
  2633. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2634. rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2635. // XXXX send a "100 Continue" message?
  2636. goto done;
  2637. err:
  2638. if (BUG(errmsg == NULL))
  2639. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2640. log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
  2641. connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
  2642. /* Mark it as "has_finished" so that we don't try to send an extra socks
  2643. * reply. */
  2644. conn->socks_request->has_finished = 1;
  2645. connection_mark_unattached_ap(conn,
  2646. END_STREAM_REASON_HTTPPROTOCOL|
  2647. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2648. done:
  2649. tor_free(headers);
  2650. tor_free(body);
  2651. tor_free(command);
  2652. tor_free(addrport);
  2653. tor_free(addr);
  2654. return rv;
  2655. }
  2656. /** Iterate over the two bytes of stream_id until we get one that is not
  2657. * already in use; return it. Return 0 if can't get a unique stream_id.
  2658. */
  2659. streamid_t
  2660. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  2661. {
  2662. edge_connection_t *tmpconn;
  2663. streamid_t test_stream_id;
  2664. uint32_t attempts=0;
  2665. again:
  2666. test_stream_id = circ->next_stream_id++;
  2667. if (++attempts > 1<<16) {
  2668. /* Make sure we don't loop forever if all stream_id's are used. */
  2669. log_warn(LD_APP,"No unused stream IDs. Failing.");
  2670. return 0;
  2671. }
  2672. if (test_stream_id == 0)
  2673. goto again;
  2674. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  2675. if (tmpconn->stream_id == test_stream_id)
  2676. goto again;
  2677. if (connection_half_edge_find_stream_id(circ->half_streams,
  2678. test_stream_id))
  2679. goto again;
  2680. return test_stream_id;
  2681. }
  2682. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  2683. * an exit that supports optimistic data. */
  2684. static int
  2685. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  2686. {
  2687. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2688. /* We can only send optimistic data if we're connected to an open
  2689. general circuit. */
  2690. if (edge_conn->on_circuit == NULL ||
  2691. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  2692. (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  2693. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
  2694. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
  2695. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
  2696. return 0;
  2697. return conn->may_use_optimistic_data;
  2698. }
  2699. /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
  2700. * RELAY_BEGIN cell for <b>ap_conn</b>. */
  2701. static uint32_t
  2702. connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
  2703. {
  2704. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2705. const node_t *exitnode = NULL;
  2706. const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
  2707. uint32_t flags = 0;
  2708. /* No flags for begindir */
  2709. if (ap_conn->use_begindir)
  2710. return 0;
  2711. /* No flags for hidden services. */
  2712. if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  2713. return 0;
  2714. /* If only IPv4 is supported, no flags */
  2715. if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
  2716. return 0;
  2717. if (! cpath_layer ||
  2718. ! cpath_layer->extend_info)
  2719. return 0;
  2720. if (!ap_conn->entry_cfg.ipv4_traffic)
  2721. flags |= BEGIN_FLAG_IPV4_NOT_OK;
  2722. exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
  2723. if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
  2724. tor_addr_t a;
  2725. tor_addr_make_null(&a, AF_INET6);
  2726. if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
  2727. exitnode)
  2728. != ADDR_POLICY_REJECTED) {
  2729. /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
  2730. * no point. */
  2731. flags |= BEGIN_FLAG_IPV6_OK;
  2732. }
  2733. }
  2734. if (flags == BEGIN_FLAG_IPV6_OK) {
  2735. /* When IPv4 and IPv6 are both allowed, consider whether to say we
  2736. * prefer IPv6. Otherwise there's no point in declaring a preference */
  2737. if (ap_conn->entry_cfg.prefer_ipv6)
  2738. flags |= BEGIN_FLAG_IPV6_PREFERRED;
  2739. }
  2740. if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
  2741. log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
  2742. "am telling it to fulfil with neither IPv4 nor IPv6. That's "
  2743. "not going to work. Did you perhaps ask for an IPv6 address "
  2744. "on an IPv4Only port, or vice versa?");
  2745. }
  2746. return flags;
  2747. }
  2748. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  2749. * socks_request field, and send it down circ.
  2750. *
  2751. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2752. */
  2753. MOCK_IMPL(int,
  2754. connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
  2755. {
  2756. char payload[CELL_PAYLOAD_SIZE];
  2757. int payload_len;
  2758. int begin_type;
  2759. const or_options_t *options = get_options();
  2760. origin_circuit_t *circ;
  2761. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2762. connection_t *base_conn = TO_CONN(edge_conn);
  2763. tor_assert(edge_conn->on_circuit);
  2764. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2765. tor_assert(base_conn->type == CONN_TYPE_AP);
  2766. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2767. tor_assert(ap_conn->socks_request);
  2768. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  2769. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2770. if (edge_conn->stream_id==0) {
  2771. /* XXXX+ Instead of closing this stream, we should make it get
  2772. * retried on another circuit. */
  2773. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2774. /* Mark this circuit "unusable for new streams". */
  2775. mark_circuit_unusable_for_new_conns(circ);
  2776. return -1;
  2777. }
  2778. /* Set up begin cell flags. */
  2779. edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
  2780. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  2781. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  2782. ap_conn->socks_request->address : "",
  2783. ap_conn->socks_request->port);
  2784. payload_len = (int)strlen(payload)+1;
  2785. if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  2786. set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  2787. payload_len += 4;
  2788. }
  2789. log_info(LD_APP,
  2790. "Sending relay cell %d on circ %u to begin stream %d.",
  2791. (int)ap_conn->use_begindir,
  2792. (unsigned)circ->base_.n_circ_id,
  2793. edge_conn->stream_id);
  2794. begin_type = ap_conn->use_begindir ?
  2795. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  2796. /* Check that circuits are anonymised, based on their type. */
  2797. if (begin_type == RELAY_COMMAND_BEGIN) {
  2798. /* This connection is a standard OR connection.
  2799. * Make sure its path length is anonymous, or that we're in a
  2800. * non-anonymous mode. */
  2801. assert_circ_anonymity_ok(circ, options);
  2802. } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
  2803. /* This connection is a begindir directory connection.
  2804. * Look at the linked directory connection to access the directory purpose.
  2805. * If a BEGINDIR connection is ever not linked, that's a bug. */
  2806. if (BUG(!base_conn->linked)) {
  2807. return -1;
  2808. }
  2809. connection_t *linked_dir_conn_base = base_conn->linked_conn;
  2810. /* If the linked connection has been unlinked by other code, we can't send
  2811. * a begin cell on it. */
  2812. if (!linked_dir_conn_base) {
  2813. return -1;
  2814. }
  2815. /* Sensitive directory connections must have an anonymous path length.
  2816. * Otherwise, directory connections are typically one-hop.
  2817. * This matches the earlier check for directory connection path anonymity
  2818. * in directory_initiate_request(). */
  2819. if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
  2820. TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
  2821. TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
  2822. assert_circ_anonymity_ok(circ, options);
  2823. }
  2824. } else {
  2825. /* This code was written for the two connection types BEGIN and BEGIN_DIR
  2826. */
  2827. tor_assert_unreached();
  2828. }
  2829. if (connection_edge_send_command(edge_conn, begin_type,
  2830. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  2831. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  2832. return -1; /* circuit is closed, don't continue */
  2833. edge_conn->package_window = STREAMWINDOW_START;
  2834. edge_conn->deliver_window = STREAMWINDOW_START;
  2835. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  2836. log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
  2837. ", n_circ_id %u",
  2838. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2839. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  2840. /* If there's queued-up data, send it now */
  2841. if ((connection_get_inbuf_len(base_conn) ||
  2842. ap_conn->sending_optimistic_data) &&
  2843. connection_ap_supports_optimistic_data(ap_conn)) {
  2844. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  2845. (long)connection_get_inbuf_len(base_conn),
  2846. ap_conn->sending_optimistic_data ?
  2847. (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
  2848. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  2849. connection_mark_for_close(base_conn);
  2850. }
  2851. }
  2852. return 0;
  2853. }
  2854. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  2855. * socks_request field, and send it down circ.
  2856. *
  2857. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2858. */
  2859. int
  2860. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  2861. {
  2862. int payload_len, command;
  2863. const char *string_addr;
  2864. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  2865. origin_circuit_t *circ;
  2866. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2867. connection_t *base_conn = TO_CONN(edge_conn);
  2868. tor_assert(edge_conn->on_circuit);
  2869. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2870. tor_assert(base_conn->type == CONN_TYPE_AP);
  2871. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2872. tor_assert(ap_conn->socks_request);
  2873. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  2874. command = ap_conn->socks_request->command;
  2875. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  2876. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2877. if (edge_conn->stream_id==0) {
  2878. /* XXXX+ Instead of closing this stream, we should make it get
  2879. * retried on another circuit. */
  2880. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2881. /* Mark this circuit "unusable for new streams". */
  2882. mark_circuit_unusable_for_new_conns(circ);
  2883. return -1;
  2884. }
  2885. if (command == SOCKS_COMMAND_RESOLVE) {
  2886. string_addr = ap_conn->socks_request->address;
  2887. payload_len = (int)strlen(string_addr)+1;
  2888. } else {
  2889. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  2890. const char *a = ap_conn->socks_request->address;
  2891. tor_addr_t addr;
  2892. int r;
  2893. /* We're doing a reverse lookup. The input could be an IP address, or
  2894. * could be an .in-addr.arpa or .ip6.arpa address */
  2895. r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
  2896. if (r <= 0) {
  2897. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  2898. safe_str_client(a));
  2899. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2900. return -1;
  2901. }
  2902. r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2903. if (r < 0) {
  2904. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2905. safe_str_client(a));
  2906. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2907. return -1;
  2908. }
  2909. string_addr = inaddr_buf;
  2910. payload_len = (int)strlen(inaddr_buf)+1;
  2911. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2912. }
  2913. log_debug(LD_APP,
  2914. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  2915. if (connection_edge_send_command(edge_conn,
  2916. RELAY_COMMAND_RESOLVE,
  2917. string_addr, payload_len) < 0)
  2918. return -1; /* circuit is closed, don't continue */
  2919. if (!base_conn->address) {
  2920. /* This might be unnecessary. XXXX */
  2921. base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
  2922. }
  2923. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  2924. log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
  2925. ", n_circ_id %u",
  2926. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2927. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2928. return 0;
  2929. }
  2930. /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
  2931. * new linked connection pair, and attach one side to the conn, connection_add
  2932. * it, initialize it to circuit_wait, and call
  2933. * connection_ap_handshake_attach_circuit(conn) on it.
  2934. *
  2935. * Return the newly created end of the linked connection pair, or -1 if error.
  2936. */
  2937. entry_connection_t *
  2938. connection_ap_make_link(connection_t *partner,
  2939. char *address, uint16_t port,
  2940. const char *digest,
  2941. int session_group, int isolation_flags,
  2942. int use_begindir, int want_onehop)
  2943. {
  2944. entry_connection_t *conn;
  2945. connection_t *base_conn;
  2946. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2947. want_onehop ? "direct" : "anonymized",
  2948. safe_str_client(address), port);
  2949. conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
  2950. base_conn = ENTRY_TO_CONN(conn);
  2951. base_conn->linked = 1; /* so that we can add it safely below. */
  2952. /* populate conn->socks_request */
  2953. /* leave version at zero, so the socks_reply is empty */
  2954. conn->socks_request->socks_version = 0;
  2955. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2956. strlcpy(conn->socks_request->address, address,
  2957. sizeof(conn->socks_request->address));
  2958. conn->socks_request->port = port;
  2959. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2960. conn->want_onehop = want_onehop;
  2961. conn->use_begindir = use_begindir;
  2962. if (use_begindir) {
  2963. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2964. conn->chosen_exit_name[0] = '$';
  2965. tor_assert(digest);
  2966. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2967. digest, DIGEST_LEN);
  2968. }
  2969. /* Populate isolation fields. */
  2970. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  2971. conn->original_dest_address = tor_strdup(address);
  2972. conn->entry_cfg.session_group = session_group;
  2973. conn->entry_cfg.isolation_flags = isolation_flags;
  2974. base_conn->address = tor_strdup("(Tor_internal)");
  2975. tor_addr_make_unspec(&base_conn->addr);
  2976. base_conn->port = 0;
  2977. connection_link_connections(partner, base_conn);
  2978. if (connection_add(base_conn) < 0) { /* no space, forget it */
  2979. connection_free(base_conn);
  2980. return NULL;
  2981. }
  2982. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2983. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2984. /* attaching to a dirty circuit is fine */
  2985. connection_ap_mark_as_pending_circuit(conn);
  2986. log_info(LD_APP,"... application connection created and linked.");
  2987. return conn;
  2988. }
  2989. /** Notify any interested controller connections about a new hostname resolve
  2990. * or resolve error. Takes the same arguments as does
  2991. * connection_ap_handshake_socks_resolved(). */
  2992. static void
  2993. tell_controller_about_resolved_result(entry_connection_t *conn,
  2994. int answer_type,
  2995. size_t answer_len,
  2996. const char *answer,
  2997. int ttl,
  2998. time_t expires)
  2999. {
  3000. expires = time(NULL) + ttl;
  3001. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  3002. char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
  3003. control_event_address_mapped(conn->socks_request->address,
  3004. cp, expires, NULL, 0);
  3005. tor_free(cp);
  3006. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3007. char *cp = tor_strndup(answer, answer_len);
  3008. control_event_address_mapped(conn->socks_request->address,
  3009. cp, expires, NULL, 0);
  3010. tor_free(cp);
  3011. } else {
  3012. control_event_address_mapped(conn->socks_request->address,
  3013. "<error>", time(NULL)+ttl,
  3014. "error=yes", 0);
  3015. }
  3016. }
  3017. /**
  3018. * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
  3019. * as the answer.
  3020. */
  3021. void
  3022. connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
  3023. const tor_addr_t *answer,
  3024. int ttl,
  3025. time_t expires)
  3026. {
  3027. if (tor_addr_family(answer) == AF_INET) {
  3028. uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
  3029. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  3030. (uint8_t*)&a,
  3031. ttl, expires);
  3032. } else if (tor_addr_family(answer) == AF_INET6) {
  3033. const uint8_t *a = tor_addr_to_in6_addr8(answer);
  3034. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
  3035. a,
  3036. ttl, expires);
  3037. } else {
  3038. log_warn(LD_BUG, "Got called with address of unexpected family %d",
  3039. tor_addr_family(answer));
  3040. connection_ap_handshake_socks_resolved(conn,
  3041. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  3042. }
  3043. }
  3044. /** Send an answer to an AP connection that has requested a DNS lookup via
  3045. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  3046. * for unreachable; the answer should be in the format specified in the socks
  3047. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  3048. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  3049. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  3050. **/
  3051. /* XXXX the use of the ttl and expires fields is nutty. Let's make this
  3052. * interface and those that use it less ugly. */
  3053. MOCK_IMPL(void,
  3054. connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
  3055. int answer_type,
  3056. size_t answer_len,
  3057. const uint8_t *answer,
  3058. int ttl,
  3059. time_t expires))
  3060. {
  3061. char buf[384];
  3062. size_t replylen;
  3063. if (ttl >= 0) {
  3064. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3065. tor_addr_t a;
  3066. tor_addr_from_ipv4n(&a, get_uint32(answer));
  3067. if (! tor_addr_is_null(&a)) {
  3068. client_dns_set_addressmap(conn,
  3069. conn->socks_request->address, &a,
  3070. conn->chosen_exit_name, ttl);
  3071. }
  3072. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  3073. tor_addr_t a;
  3074. tor_addr_from_ipv6_bytes(&a, (char*)answer);
  3075. if (! tor_addr_is_null(&a)) {
  3076. client_dns_set_addressmap(conn,
  3077. conn->socks_request->address, &a,
  3078. conn->chosen_exit_name, ttl);
  3079. }
  3080. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3081. char *cp = tor_strndup((char*)answer, answer_len);
  3082. client_dns_set_reverse_addressmap(conn,
  3083. conn->socks_request->address,
  3084. cp,
  3085. conn->chosen_exit_name, ttl);
  3086. tor_free(cp);
  3087. }
  3088. }
  3089. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  3090. if (conn->dns_server_request) {
  3091. /* We had a request on our DNS port: answer it. */
  3092. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  3093. conn->socks_request->has_finished = 1;
  3094. return;
  3095. } else {
  3096. /* This must be a request from the controller. Since answers to those
  3097. * requests are not cached, they do not generate an ADDRMAP event on
  3098. * their own. */
  3099. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  3100. (char*)answer, ttl, expires);
  3101. conn->socks_request->has_finished = 1;
  3102. return;
  3103. }
  3104. /* We shouldn't need to free conn here; it gets marked by the caller. */
  3105. }
  3106. if (conn->socks_request->socks_version == 4) {
  3107. buf[0] = 0x00; /* version */
  3108. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3109. buf[1] = SOCKS4_GRANTED;
  3110. set_uint16(buf+2, 0);
  3111. memcpy(buf+4, answer, 4); /* address */
  3112. replylen = SOCKS4_NETWORK_LEN;
  3113. } else { /* "error" */
  3114. buf[1] = SOCKS4_REJECT;
  3115. memset(buf+2, 0, 6);
  3116. replylen = SOCKS4_NETWORK_LEN;
  3117. }
  3118. } else if (conn->socks_request->socks_version == 5) {
  3119. /* SOCKS5 */
  3120. buf[0] = 0x05; /* version */
  3121. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3122. buf[1] = SOCKS5_SUCCEEDED;
  3123. buf[2] = 0; /* reserved */
  3124. buf[3] = 0x01; /* IPv4 address type */
  3125. memcpy(buf+4, answer, 4); /* address */
  3126. set_uint16(buf+8, 0); /* port == 0. */
  3127. replylen = 10;
  3128. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  3129. buf[1] = SOCKS5_SUCCEEDED;
  3130. buf[2] = 0; /* reserved */
  3131. buf[3] = 0x04; /* IPv6 address type */
  3132. memcpy(buf+4, answer, 16); /* address */
  3133. set_uint16(buf+20, 0); /* port == 0. */
  3134. replylen = 22;
  3135. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3136. buf[1] = SOCKS5_SUCCEEDED;
  3137. buf[2] = 0; /* reserved */
  3138. buf[3] = 0x03; /* Domainname address type */
  3139. buf[4] = (char)answer_len;
  3140. memcpy(buf+5, answer, answer_len); /* address */
  3141. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  3142. replylen = 5+answer_len+2;
  3143. } else {
  3144. buf[1] = SOCKS5_HOST_UNREACHABLE;
  3145. memset(buf+2, 0, 8);
  3146. replylen = 10;
  3147. }
  3148. } else {
  3149. /* no socks version info; don't send anything back */
  3150. return;
  3151. }
  3152. connection_ap_handshake_socks_reply(conn, buf, replylen,
  3153. (answer_type == RESOLVED_TYPE_IPV4 ||
  3154. answer_type == RESOLVED_TYPE_IPV6 ||
  3155. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  3156. 0 : END_STREAM_REASON_RESOLVEFAILED);
  3157. }
  3158. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  3159. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  3160. * handshaking.
  3161. *
  3162. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  3163. * and return, else reply based on <b>endreason</b> (one of
  3164. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  3165. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  3166. */
  3167. void
  3168. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  3169. size_t replylen, int endreason)
  3170. {
  3171. char buf[256];
  3172. socks5_reply_status_t status =
  3173. stream_end_reason_to_socks5_response(endreason);
  3174. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  3175. if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3176. control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
  3177. STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  3178. endreason);
  3179. }
  3180. /* Flag this stream's circuit as having completed a stream successfully
  3181. * (for path bias) */
  3182. if (status == SOCKS5_SUCCEEDED ||
  3183. endreason == END_STREAM_REASON_RESOLVEFAILED ||
  3184. endreason == END_STREAM_REASON_CONNECTREFUSED ||
  3185. endreason == END_STREAM_REASON_CONNRESET ||
  3186. endreason == END_STREAM_REASON_NOROUTE ||
  3187. endreason == END_STREAM_REASON_RESOURCELIMIT) {
  3188. if (!conn->edge_.on_circuit ||
  3189. !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
  3190. if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
  3191. log_info(LD_BUG,
  3192. "No origin circuit for successful SOCKS stream %"PRIu64
  3193. ". Reason: %d",
  3194. (ENTRY_TO_CONN(conn)->global_identifier),
  3195. endreason);
  3196. }
  3197. /*
  3198. * Else DNS remaps and failed hidden service lookups can send us
  3199. * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
  3200. *
  3201. * Perhaps we could make the test more precise; we can tell hidden
  3202. * services by conn->edge_.renddata != NULL; anything analogous for
  3203. * the DNS remap case?
  3204. */
  3205. } else {
  3206. // XXX: Hrmm. It looks like optimistic data can't go through this
  3207. // codepath, but someone should probably test it and make sure.
  3208. // We don't want to mark optimistically opened streams as successful.
  3209. pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
  3210. }
  3211. }
  3212. if (conn->socks_request->has_finished) {
  3213. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  3214. "connection_ap_handshake_socks_reply.");
  3215. return;
  3216. }
  3217. if (replylen) { /* we already have a reply in mind */
  3218. connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
  3219. conn->socks_request->has_finished = 1;
  3220. return;
  3221. }
  3222. if (conn->socks_request->listener_type ==
  3223. CONN_TYPE_AP_HTTP_CONNECT_LISTENER) {
  3224. const char *response = end_reason_to_http_connect_response_line(endreason);
  3225. if (!response) {
  3226. response = "HTTP/1.0 400 Bad Request\r\n\r\n";
  3227. }
  3228. connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
  3229. } else if (conn->socks_request->socks_version == 4) {
  3230. memset(buf,0,SOCKS4_NETWORK_LEN);
  3231. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  3232. /* leave version, destport, destip zero */
  3233. connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  3234. } else if (conn->socks_request->socks_version == 5) {
  3235. size_t buf_len;
  3236. memset(buf,0,sizeof(buf));
  3237. if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
  3238. buf[0] = 5; /* version 5 */
  3239. buf[1] = (char)status;
  3240. buf[2] = 0;
  3241. buf[3] = 1; /* ipv4 addr */
  3242. /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
  3243. buf_len = 10;
  3244. } else { /* AF_INET6. */
  3245. buf[0] = 5; /* version 5 */
  3246. buf[1] = (char)status;
  3247. buf[2] = 0;
  3248. buf[3] = 4; /* ipv6 addr */
  3249. /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
  3250. buf_len = 22;
  3251. }
  3252. connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
  3253. }
  3254. /* If socks_version isn't 4 or 5, don't send anything.
  3255. * This can happen in the case of AP bridges. */
  3256. conn->socks_request->has_finished = 1;
  3257. return;
  3258. }
  3259. /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
  3260. * place the result in <b>bcell</b>. On success return 0; on failure return
  3261. * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
  3262. * the client.
  3263. *
  3264. * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
  3265. * we don't.
  3266. **/
  3267. STATIC int
  3268. begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
  3269. uint8_t *end_reason_out)
  3270. {
  3271. relay_header_t rh;
  3272. const uint8_t *body, *nul;
  3273. memset(bcell, 0, sizeof(*bcell));
  3274. *end_reason_out = END_STREAM_REASON_MISC;
  3275. relay_header_unpack(&rh, cell->payload);
  3276. if (rh.length > RELAY_PAYLOAD_SIZE) {
  3277. return -2; /*XXXX why not TORPROTOCOL? */
  3278. }
  3279. bcell->stream_id = rh.stream_id;
  3280. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3281. bcell->is_begindir = 1;
  3282. return 0;
  3283. } else if (rh.command != RELAY_COMMAND_BEGIN) {
  3284. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  3285. *end_reason_out = END_STREAM_REASON_INTERNAL;
  3286. return -1;
  3287. }
  3288. body = cell->payload + RELAY_HEADER_SIZE;
  3289. nul = memchr(body, 0, rh.length);
  3290. if (! nul) {
  3291. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3292. "Relay begin cell has no \\0. Closing.");
  3293. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3294. return -1;
  3295. }
  3296. if (tor_addr_port_split(LOG_PROTOCOL_WARN,
  3297. (char*)(body),
  3298. &bcell->address,&bcell->port)<0) {
  3299. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3300. "Unable to parse addr:port in relay begin cell. Closing.");
  3301. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3302. return -1;
  3303. }
  3304. if (bcell->port == 0) {
  3305. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3306. "Missing port in relay begin cell. Closing.");
  3307. tor_free(bcell->address);
  3308. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3309. return -1;
  3310. }
  3311. if (body + rh.length >= nul + 4)
  3312. bcell->flags = ntohl(get_uint32(nul+1));
  3313. return 0;
  3314. }
  3315. /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
  3316. * connection, attach it to the circ and connect it. Return 0 on success
  3317. * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
  3318. * where the caller should close the circuit. */
  3319. static int
  3320. handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
  3321. {
  3322. int ret;
  3323. origin_circuit_t *origin_circ;
  3324. assert_circuit_ok(circ);
  3325. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3326. tor_assert(conn);
  3327. log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
  3328. "to the service destination.");
  3329. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3330. conn->base_.address = tor_strdup("(rendezvous)");
  3331. conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  3332. /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
  3333. * service. */
  3334. if (origin_circ->rend_data) {
  3335. conn->rend_data = rend_data_dup(origin_circ->rend_data);
  3336. tor_assert(connection_edge_is_rendezvous_stream(conn));
  3337. ret = rend_service_set_connection_addr_port(conn, origin_circ);
  3338. } else if (origin_circ->hs_ident) {
  3339. /* Setup the identifier to be the one for the circuit service. */
  3340. conn->hs_ident =
  3341. hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
  3342. tor_assert(connection_edge_is_rendezvous_stream(conn));
  3343. ret = hs_service_set_conn_addr_port(origin_circ, conn);
  3344. } else {
  3345. /* We should never get here if the circuit's purpose is rendezvous. */
  3346. tor_assert_nonfatal_unreached();
  3347. return -1;
  3348. }
  3349. if (ret < 0) {
  3350. log_info(LD_REND, "Didn't find rendezvous service (addr%s, port %d)",
  3351. fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
  3352. /* Send back reason DONE because we want to make hidden service port
  3353. * scanning harder thus instead of returning that the exit policy
  3354. * didn't match, which makes it obvious that the port is closed,
  3355. * return DONE and kill the circuit. That way, a user (malicious or
  3356. * not) needs one circuit per bad port unless it matches the policy of
  3357. * the hidden service. */
  3358. relay_send_end_cell_from_edge(conn->stream_id, circ,
  3359. END_STREAM_REASON_DONE,
  3360. origin_circ->cpath->prev);
  3361. connection_free_(TO_CONN(conn));
  3362. /* Drop the circuit here since it might be someone deliberately
  3363. * scanning the hidden service ports. Note that this mitigates port
  3364. * scanning by adding more work on the attacker side to successfully
  3365. * scan but does not fully solve it. */
  3366. if (ret < -1) {
  3367. return END_CIRC_AT_ORIGIN;
  3368. } else {
  3369. return 0;
  3370. }
  3371. }
  3372. /* Link the circuit and the connection crypt path. */
  3373. conn->cpath_layer = origin_circ->cpath->prev;
  3374. /* If this is the first stream on this circuit, tell circpad */
  3375. if (!origin_circ->p_streams)
  3376. circpad_machine_event_circ_has_streams(origin_circ);
  3377. /* Add it into the linked list of p_streams on this circuit */
  3378. conn->next_stream = origin_circ->p_streams;
  3379. origin_circ->p_streams = conn;
  3380. conn->on_circuit = circ;
  3381. assert_circuit_ok(circ);
  3382. hs_inc_rdv_stream_counter(origin_circ);
  3383. /* If it's an onion service connection, we might want to include the proxy
  3384. * protocol header: */
  3385. if (conn->hs_ident) {
  3386. hs_circuit_id_protocol_t circuit_id_protocol =
  3387. hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
  3388. export_hs_client_circuit_id(conn, circuit_id_protocol);
  3389. }
  3390. /* Connect tor to the hidden service destination. */
  3391. connection_exit_connect(conn);
  3392. /* For path bias: This circuit was used successfully */
  3393. pathbias_mark_use_success(origin_circ);
  3394. return 0;
  3395. }
  3396. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  3397. * an exit hop for the circuit, or we are the origin and it is a
  3398. * rendezvous begin.
  3399. *
  3400. * Launch a new exit connection and initialize things appropriately.
  3401. *
  3402. * If it's a rendezvous stream, call connection_exit_connect() on
  3403. * it.
  3404. *
  3405. * For general streams, call dns_resolve() on it first, and only call
  3406. * connection_exit_connect() if the dns answer is already known.
  3407. *
  3408. * Note that we don't call connection_add() on the new stream! We wait
  3409. * for connection_exit_connect() to do that.
  3410. *
  3411. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  3412. * Else return 0.
  3413. */
  3414. int
  3415. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  3416. {
  3417. edge_connection_t *n_stream;
  3418. relay_header_t rh;
  3419. char *address = NULL;
  3420. uint16_t port = 0;
  3421. or_circuit_t *or_circ = NULL;
  3422. origin_circuit_t *origin_circ = NULL;
  3423. crypt_path_t *layer_hint = NULL;
  3424. const or_options_t *options = get_options();
  3425. begin_cell_t bcell;
  3426. int rv;
  3427. uint8_t end_reason=0;
  3428. assert_circuit_ok(circ);
  3429. if (!CIRCUIT_IS_ORIGIN(circ)) {
  3430. or_circ = TO_OR_CIRCUIT(circ);
  3431. } else {
  3432. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3433. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3434. layer_hint = origin_circ->cpath->prev;
  3435. }
  3436. relay_header_unpack(&rh, cell->payload);
  3437. if (rh.length > RELAY_PAYLOAD_SIZE)
  3438. return -END_CIRC_REASON_TORPROTOCOL;
  3439. if (!server_mode(options) &&
  3440. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  3441. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3442. "Relay begin cell at non-server. Closing.");
  3443. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3444. END_STREAM_REASON_EXITPOLICY, NULL);
  3445. return 0;
  3446. }
  3447. rv = begin_cell_parse(cell, &bcell, &end_reason);
  3448. if (rv < -1) {
  3449. return -END_CIRC_REASON_TORPROTOCOL;
  3450. } else if (rv == -1) {
  3451. tor_free(bcell.address);
  3452. relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
  3453. return 0;
  3454. }
  3455. if (! bcell.is_begindir) {
  3456. /* Steal reference */
  3457. tor_assert(bcell.address);
  3458. address = bcell.address;
  3459. port = bcell.port;
  3460. if (or_circ && or_circ->p_chan) {
  3461. const int client_chan = channel_is_client(or_circ->p_chan);
  3462. if ((client_chan ||
  3463. (!connection_or_digest_is_known_relay(
  3464. or_circ->p_chan->identity_digest) &&
  3465. should_refuse_unknown_exits(options)))) {
  3466. /* Don't let clients use us as a single-hop proxy. It attracts
  3467. * attackers and users who'd be better off with, well, single-hop
  3468. * proxies. */
  3469. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3470. "Attempt by %s to open a stream %s. Closing.",
  3471. safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
  3472. client_chan ? "on first hop of circuit" :
  3473. "from unknown relay");
  3474. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3475. client_chan ?
  3476. END_STREAM_REASON_TORPROTOCOL :
  3477. END_STREAM_REASON_MISC,
  3478. NULL);
  3479. tor_free(address);
  3480. return 0;
  3481. }
  3482. }
  3483. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3484. if (!directory_permits_begindir_requests(options) ||
  3485. circ->purpose != CIRCUIT_PURPOSE_OR) {
  3486. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3487. END_STREAM_REASON_NOTDIRECTORY, layer_hint);
  3488. return 0;
  3489. }
  3490. /* Make sure to get the 'real' address of the previous hop: the
  3491. * caller might want to know whether the remote IP address has changed,
  3492. * and we might already have corrected base_.addr[ess] for the relay's
  3493. * canonical IP address. */
  3494. if (or_circ && or_circ->p_chan)
  3495. address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
  3496. else
  3497. address = tor_strdup("127.0.0.1");
  3498. port = 1; /* XXXX This value is never actually used anywhere, and there
  3499. * isn't "really" a connection here. But we
  3500. * need to set it to something nonzero. */
  3501. } else {
  3502. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  3503. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3504. END_STREAM_REASON_INTERNAL, layer_hint);
  3505. return 0;
  3506. }
  3507. if (! options->IPv6Exit) {
  3508. /* I don't care if you prefer IPv6; I can't give you any. */
  3509. bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
  3510. /* If you don't want IPv4, I can't help. */
  3511. if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
  3512. tor_free(address);
  3513. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3514. END_STREAM_REASON_EXITPOLICY, layer_hint);
  3515. return 0;
  3516. }
  3517. }
  3518. log_debug(LD_EXIT,"Creating new exit connection.");
  3519. /* The 'AF_INET' here is temporary; we might need to change it later in
  3520. * connection_exit_connect(). */
  3521. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  3522. /* Remember the tunneled request ID in the new edge connection, so that
  3523. * we can measure download times. */
  3524. n_stream->dirreq_id = circ->dirreq_id;
  3525. n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
  3526. n_stream->begincell_flags = bcell.flags;
  3527. n_stream->stream_id = rh.stream_id;
  3528. n_stream->base_.port = port;
  3529. /* leave n_stream->s at -1, because it's not yet valid */
  3530. n_stream->package_window = STREAMWINDOW_START;
  3531. n_stream->deliver_window = STREAMWINDOW_START;
  3532. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  3533. int ret;
  3534. tor_free(address);
  3535. /* We handle this circuit and stream in this function for all supported
  3536. * hidden service version. */
  3537. ret = handle_hs_exit_conn(circ, n_stream);
  3538. if (ret == 0) {
  3539. /* This was a valid cell. Count it as delivered + overhead. */
  3540. circuit_read_valid_data(origin_circ, rh.length);
  3541. }
  3542. return ret;
  3543. }
  3544. tor_strlower(address);
  3545. n_stream->base_.address = address;
  3546. n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  3547. /* default to failed, change in dns_resolve if it turns out not to fail */
  3548. /* If we're hibernating or shutting down, we refuse to open new streams. */
  3549. if (we_are_hibernating()) {
  3550. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3551. END_STREAM_REASON_HIBERNATING, NULL);
  3552. connection_free_(TO_CONN(n_stream));
  3553. return 0;
  3554. }
  3555. n_stream->on_circuit = circ;
  3556. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3557. tor_addr_t tmp_addr;
  3558. tor_assert(or_circ);
  3559. if (or_circ->p_chan &&
  3560. channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
  3561. tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
  3562. }
  3563. return connection_exit_connect_dir(n_stream);
  3564. }
  3565. log_debug(LD_EXIT,"about to start the dns_resolve().");
  3566. /* send it off to the gethostbyname farm */
  3567. switch (dns_resolve(n_stream)) {
  3568. case 1: /* resolve worked; now n_stream is attached to circ. */
  3569. assert_circuit_ok(circ);
  3570. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  3571. connection_exit_connect(n_stream);
  3572. return 0;
  3573. case -1: /* resolve failed */
  3574. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3575. END_STREAM_REASON_RESOLVEFAILED, NULL);
  3576. /* n_stream got freed. don't touch it. */
  3577. break;
  3578. case 0: /* resolve added to pending list */
  3579. assert_circuit_ok(circ);
  3580. break;
  3581. }
  3582. return 0;
  3583. }
  3584. /**
  3585. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  3586. * circuit <b>circ</b>;
  3587. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  3588. */
  3589. int
  3590. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  3591. {
  3592. edge_connection_t *dummy_conn;
  3593. relay_header_t rh;
  3594. assert_circuit_ok(TO_CIRCUIT(circ));
  3595. relay_header_unpack(&rh, cell->payload);
  3596. if (rh.length > RELAY_PAYLOAD_SIZE)
  3597. return -1;
  3598. /* This 'dummy_conn' only exists to remember the stream ID
  3599. * associated with the resolve request; and to make the
  3600. * implementation of dns.c more uniform. (We really only need to
  3601. * remember the circuit, the stream ID, and the hostname to be
  3602. * resolved; but if we didn't store them in a connection like this,
  3603. * the housekeeping in dns.c would get way more complicated.)
  3604. */
  3605. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  3606. dummy_conn->stream_id = rh.stream_id;
  3607. dummy_conn->base_.address = tor_strndup(
  3608. (char*)cell->payload+RELAY_HEADER_SIZE,
  3609. rh.length);
  3610. dummy_conn->base_.port = 0;
  3611. dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  3612. dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
  3613. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  3614. /* send it off to the gethostbyname farm */
  3615. switch (dns_resolve(dummy_conn)) {
  3616. case -1: /* Impossible to resolve; a resolved cell was sent. */
  3617. /* Connection freed; don't touch it. */
  3618. return 0;
  3619. case 1: /* The result was cached; a resolved cell was sent. */
  3620. if (!dummy_conn->base_.marked_for_close)
  3621. connection_free_(TO_CONN(dummy_conn));
  3622. return 0;
  3623. case 0: /* resolve added to pending list */
  3624. assert_circuit_ok(TO_CIRCUIT(circ));
  3625. break;
  3626. }
  3627. return 0;
  3628. }
  3629. /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
  3630. * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
  3631. */
  3632. static int
  3633. my_exit_policy_rejects(const tor_addr_t *addr,
  3634. uint16_t port,
  3635. const char **why_rejected)
  3636. {
  3637. if (router_compare_to_my_exit_policy(addr, port)) {
  3638. *why_rejected = "";
  3639. return 1;
  3640. } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
  3641. *why_rejected = " (IPv6 address without IPv6Exit configured)";
  3642. return 1;
  3643. }
  3644. return 0;
  3645. }
  3646. /** Connect to conn's specified addr and port. If it worked, conn
  3647. * has now been added to the connection_array.
  3648. *
  3649. * Send back a connected cell. Include the resolved IP of the destination
  3650. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  3651. * streams must not reveal what IP they connected to.)
  3652. */
  3653. void
  3654. connection_exit_connect(edge_connection_t *edge_conn)
  3655. {
  3656. const tor_addr_t *addr;
  3657. uint16_t port;
  3658. connection_t *conn = TO_CONN(edge_conn);
  3659. int socket_error = 0, result;
  3660. const char *why_failed_exit_policy = NULL;
  3661. /* Apply exit policy to non-rendezvous connections. */
  3662. if (! connection_edge_is_rendezvous_stream(edge_conn) &&
  3663. my_exit_policy_rejects(&edge_conn->base_.addr,
  3664. edge_conn->base_.port,
  3665. &why_failed_exit_policy)) {
  3666. if (BUG(!why_failed_exit_policy))
  3667. why_failed_exit_policy = "";
  3668. log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
  3669. escaped_safe_str_client(conn->address), conn->port,
  3670. why_failed_exit_policy);
  3671. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  3672. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3673. connection_free(conn);
  3674. return;
  3675. }
  3676. #ifdef HAVE_SYS_UN_H
  3677. if (conn->socket_family != AF_UNIX) {
  3678. #else
  3679. {
  3680. #endif /* defined(HAVE_SYS_UN_H) */
  3681. addr = &conn->addr;
  3682. port = conn->port;
  3683. if (tor_addr_family(addr) == AF_INET6)
  3684. conn->socket_family = AF_INET6;
  3685. log_debug(LD_EXIT, "about to try connecting");
  3686. result = connection_connect(conn, conn->address,
  3687. addr, port, &socket_error);
  3688. #ifdef HAVE_SYS_UN_H
  3689. } else {
  3690. /*
  3691. * In the AF_UNIX case, we expect to have already had conn->port = 1,
  3692. * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
  3693. * case in connection_handle_listener_read()), and conn->address should
  3694. * have the socket path to connect to.
  3695. */
  3696. tor_assert(conn->address && strlen(conn->address) > 0);
  3697. log_debug(LD_EXIT, "about to try connecting");
  3698. result = connection_connect_unix(conn, conn->address, &socket_error);
  3699. #endif /* defined(HAVE_SYS_UN_H) */
  3700. }
  3701. switch (result) {
  3702. case -1: {
  3703. int reason = errno_to_stream_end_reason(socket_error);
  3704. connection_edge_end(edge_conn, reason);
  3705. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3706. connection_free(conn);
  3707. return;
  3708. }
  3709. case 0:
  3710. conn->state = EXIT_CONN_STATE_CONNECTING;
  3711. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  3712. /* writable indicates finish;
  3713. * readable/error indicates broken link in windows-land. */
  3714. return;
  3715. /* case 1: fall through */
  3716. }
  3717. conn->state = EXIT_CONN_STATE_OPEN;
  3718. if (connection_get_outbuf_len(conn)) {
  3719. /* in case there are any queued data cells, from e.g. optimistic data */
  3720. connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
  3721. } else {
  3722. connection_watch_events(conn, READ_EVENT);
  3723. }
  3724. /* also, deliver a 'connected' cell back through the circuit. */
  3725. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  3726. /* don't send an address back! */
  3727. connection_edge_send_command(edge_conn,
  3728. RELAY_COMMAND_CONNECTED,
  3729. NULL, 0);
  3730. } else { /* normal stream */
  3731. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  3732. int connected_payload_len =
  3733. connected_cell_format_payload(connected_payload, &conn->addr,
  3734. edge_conn->address_ttl);
  3735. if (connected_payload_len < 0) {
  3736. connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
  3737. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3738. connection_free(conn);
  3739. return;
  3740. }
  3741. connection_edge_send_command(edge_conn,
  3742. RELAY_COMMAND_CONNECTED,
  3743. (char*)connected_payload,
  3744. connected_payload_len);
  3745. }
  3746. }
  3747. /** Given an exit conn that should attach to us as a directory server, open a
  3748. * bridge connection with a linked connection pair, create a new directory
  3749. * conn, and join them together. Return 0 on success (or if there was an
  3750. * error we could send back an end cell for). Return -(some circuit end
  3751. * reason) if the circuit needs to be torn down. Either connects
  3752. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  3753. */
  3754. static int
  3755. connection_exit_connect_dir(edge_connection_t *exitconn)
  3756. {
  3757. dir_connection_t *dirconn = NULL;
  3758. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  3759. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  3760. exitconn->base_.state = EXIT_CONN_STATE_OPEN;
  3761. dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
  3762. tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
  3763. dirconn->base_.port = 0;
  3764. dirconn->base_.address = tor_strdup(exitconn->base_.address);
  3765. dirconn->base_.type = CONN_TYPE_DIR;
  3766. dirconn->base_.purpose = DIR_PURPOSE_SERVER;
  3767. dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  3768. /* Note that the new dir conn belongs to the same tunneled request as
  3769. * the edge conn, so that we can measure download times. */
  3770. dirconn->dirreq_id = exitconn->dirreq_id;
  3771. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  3772. if (connection_add(TO_CONN(exitconn))<0) {
  3773. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3774. connection_free_(TO_CONN(exitconn));
  3775. connection_free_(TO_CONN(dirconn));
  3776. return 0;
  3777. }
  3778. /* link exitconn to circ, now that we know we can use it. */
  3779. exitconn->next_stream = circ->n_streams;
  3780. circ->n_streams = exitconn;
  3781. if (connection_add(TO_CONN(dirconn))<0) {
  3782. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3783. connection_close_immediate(TO_CONN(exitconn));
  3784. connection_mark_for_close(TO_CONN(exitconn));
  3785. connection_free_(TO_CONN(dirconn));
  3786. return 0;
  3787. }
  3788. connection_start_reading(TO_CONN(dirconn));
  3789. connection_start_reading(TO_CONN(exitconn));
  3790. if (connection_edge_send_command(exitconn,
  3791. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  3792. connection_mark_for_close(TO_CONN(exitconn));
  3793. connection_mark_for_close(TO_CONN(dirconn));
  3794. return 0;
  3795. }
  3796. return 0;
  3797. }
  3798. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  3799. * it is a general stream.
  3800. */
  3801. int
  3802. connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
  3803. {
  3804. tor_assert(conn);
  3805. /* It should not be possible to set both of these structs */
  3806. tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
  3807. if (conn->rend_data || conn->hs_ident) {
  3808. return 1;
  3809. }
  3810. return 0;
  3811. }
  3812. /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
  3813. * to exit from it, or 0 if it probably will not allow it.
  3814. * (We might be uncertain if conn's destination address has not yet been
  3815. * resolved.)
  3816. */
  3817. int
  3818. connection_ap_can_use_exit(const entry_connection_t *conn,
  3819. const node_t *exit_node)
  3820. {
  3821. const or_options_t *options = get_options();
  3822. tor_assert(conn);
  3823. tor_assert(conn->socks_request);
  3824. tor_assert(exit_node);
  3825. /* If a particular exit node has been requested for the new connection,
  3826. * make sure the exit node of the existing circuit matches exactly.
  3827. */
  3828. if (conn->chosen_exit_name) {
  3829. const node_t *chosen_exit =
  3830. node_get_by_nickname(conn->chosen_exit_name, 0);
  3831. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  3832. exit_node->identity, DIGEST_LEN)) {
  3833. /* doesn't match */
  3834. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  3835. // conn->chosen_exit_name, exit->nickname);
  3836. return 0;
  3837. }
  3838. }
  3839. if (conn->use_begindir) {
  3840. /* Internal directory fetches do not count as exiting. */
  3841. return 1;
  3842. }
  3843. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  3844. tor_addr_t addr, *addrp = NULL;
  3845. addr_policy_result_t r;
  3846. if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
  3847. addrp = &addr;
  3848. } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
  3849. tor_addr_make_null(&addr, AF_INET6);
  3850. addrp = &addr;
  3851. } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
  3852. tor_addr_make_null(&addr, AF_INET);
  3853. addrp = &addr;
  3854. }
  3855. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
  3856. exit_node);
  3857. if (r == ADDR_POLICY_REJECTED)
  3858. return 0; /* We know the address, and the exit policy rejects it. */
  3859. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  3860. return 0; /* We don't know the addr, but the exit policy rejects most
  3861. * addresses with this port. Since the user didn't ask for
  3862. * this node, err on the side of caution. */
  3863. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3864. /* Don't send DNS requests to non-exit servers by default. */
  3865. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
  3866. return 0;
  3867. }
  3868. if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
  3869. /* Not a suitable exit. Refuse it. */
  3870. return 0;
  3871. }
  3872. return 1;
  3873. }
  3874. /** If address is of the form "y.onion" with a well-formed handle y:
  3875. * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
  3876. * ONION_V3_HOSTNAME depending on the HS version.
  3877. *
  3878. * If address is of the form "x.y.onion" with a well-formed handle x:
  3879. * Drop "x.", put a NUL after y, lower-case it, and return
  3880. * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
  3881. *
  3882. * If address is of the form "y.onion" with a badly-formed handle y:
  3883. * Return BAD_HOSTNAME and log a message.
  3884. *
  3885. * If address is of the form "y.exit":
  3886. * Put a NUL after y and return EXIT_HOSTNAME.
  3887. *
  3888. * Otherwise:
  3889. * Return NORMAL_HOSTNAME and change nothing.
  3890. */
  3891. hostname_type_t
  3892. parse_extended_hostname(char *address)
  3893. {
  3894. char *s;
  3895. char *q;
  3896. char query[HS_SERVICE_ADDR_LEN_BASE32+1];
  3897. s = strrchr(address,'.');
  3898. if (!s)
  3899. return NORMAL_HOSTNAME; /* no dot, thus normal */
  3900. if (!strcmp(s+1,"exit")) {
  3901. *s = 0; /* NUL-terminate it */
  3902. return EXIT_HOSTNAME; /* .exit */
  3903. }
  3904. if (strcmp(s+1,"onion"))
  3905. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  3906. /* so it is .onion */
  3907. *s = 0; /* NUL-terminate it */
  3908. /* locate a 'sub-domain' component, in order to remove it */
  3909. q = strrchr(address, '.');
  3910. if (q == address) {
  3911. goto failed; /* reject sub-domain, as DNS does */
  3912. }
  3913. q = (NULL == q) ? address : q + 1;
  3914. if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
  3915. HS_SERVICE_ADDR_LEN_BASE32+1)
  3916. goto failed;
  3917. if (q != address) {
  3918. memmove(address, q, strlen(q) + 1 /* also get \0 */);
  3919. }
  3920. if (rend_valid_v2_service_id(query)) {
  3921. return ONION_V2_HOSTNAME; /* success */
  3922. }
  3923. if (hs_address_is_valid(query)) {
  3924. return ONION_V3_HOSTNAME;
  3925. }
  3926. failed:
  3927. /* otherwise, return to previous state and return 0 */
  3928. *s = '.';
  3929. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  3930. safe_str_client(address));
  3931. return BAD_HOSTNAME;
  3932. }
  3933. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  3934. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  3935. * at <b>b</b>. */
  3936. static int
  3937. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  3938. {
  3939. if (a == NULL) {
  3940. return (b == NULL);
  3941. } else if (b == NULL) {
  3942. return 0;
  3943. } else if (alen != blen) {
  3944. return 0;
  3945. } else {
  3946. return tor_memeq(a, b, alen);
  3947. }
  3948. }
  3949. /**
  3950. * Return true iff none of the isolation flags and fields in <b>conn</b>
  3951. * should prevent it from being attached to <b>circ</b>.
  3952. */
  3953. int
  3954. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  3955. const origin_circuit_t *circ)
  3956. {
  3957. const uint8_t iso = conn->entry_cfg.isolation_flags;
  3958. const socks_request_t *sr = conn->socks_request;
  3959. /* If circ has never been used for an isolated connection, we can
  3960. * totally use it for this one. */
  3961. if (!circ->isolation_values_set)
  3962. return 1;
  3963. /* If circ has been used for connections having more than one value
  3964. * for some field f, it will have the corresponding bit set in
  3965. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  3966. * in common with iso, then conn must be isolated from at least
  3967. * one stream that has been attached to circ. */
  3968. if ((iso & circ->isolation_flags_mixed) != 0) {
  3969. /* For at least one field where conn is isolated, the circuit
  3970. * already has mixed streams. */
  3971. return 0;
  3972. }
  3973. if (! conn->original_dest_address) {
  3974. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  3975. "having set conn->original_dest_address");
  3976. ((entry_connection_t*)conn)->original_dest_address =
  3977. tor_strdup(conn->socks_request->address);
  3978. }
  3979. if ((iso & ISO_STREAM) &&
  3980. (circ->associated_isolated_stream_global_id !=
  3981. ENTRY_TO_CONN(conn)->global_identifier))
  3982. return 0;
  3983. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  3984. return 0;
  3985. if ((iso & ISO_DESTADDR) &&
  3986. strcasecmp(conn->original_dest_address, circ->dest_address))
  3987. return 0;
  3988. if ((iso & ISO_SOCKSAUTH) &&
  3989. (! memeq_opt(sr->username, sr->usernamelen,
  3990. circ->socks_username, circ->socks_username_len) ||
  3991. ! memeq_opt(sr->password, sr->passwordlen,
  3992. circ->socks_password, circ->socks_password_len)))
  3993. return 0;
  3994. if ((iso & ISO_CLIENTPROTO) &&
  3995. (conn->socks_request->listener_type != circ->client_proto_type ||
  3996. conn->socks_request->socks_version != circ->client_proto_socksver))
  3997. return 0;
  3998. if ((iso & ISO_CLIENTADDR) &&
  3999. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  4000. return 0;
  4001. if ((iso & ISO_SESSIONGRP) &&
  4002. conn->entry_cfg.session_group != circ->session_group)
  4003. return 0;
  4004. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  4005. return 0;
  4006. return 1;
  4007. }
  4008. /**
  4009. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  4010. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  4011. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  4012. * a bitfield of isolation flags that we would have to set in
  4013. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  4014. * <b>circ</b> has had no streams attached to it.
  4015. */
  4016. int
  4017. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  4018. origin_circuit_t *circ,
  4019. int dry_run)
  4020. {
  4021. const socks_request_t *sr = conn->socks_request;
  4022. if (! conn->original_dest_address) {
  4023. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  4024. "having set conn->original_dest_address");
  4025. ((entry_connection_t*)conn)->original_dest_address =
  4026. tor_strdup(conn->socks_request->address);
  4027. }
  4028. if (!circ->isolation_values_set) {
  4029. if (dry_run)
  4030. return -1;
  4031. circ->associated_isolated_stream_global_id =
  4032. ENTRY_TO_CONN(conn)->global_identifier;
  4033. circ->dest_port = conn->socks_request->port;
  4034. circ->dest_address = tor_strdup(conn->original_dest_address);
  4035. circ->client_proto_type = conn->socks_request->listener_type;
  4036. circ->client_proto_socksver = conn->socks_request->socks_version;
  4037. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  4038. circ->session_group = conn->entry_cfg.session_group;
  4039. circ->nym_epoch = conn->nym_epoch;
  4040. circ->socks_username = sr->username ?
  4041. tor_memdup(sr->username, sr->usernamelen) : NULL;
  4042. circ->socks_password = sr->password ?
  4043. tor_memdup(sr->password, sr->passwordlen) : NULL;
  4044. circ->socks_username_len = sr->usernamelen;
  4045. circ->socks_password_len = sr->passwordlen;
  4046. circ->isolation_values_set = 1;
  4047. return 0;
  4048. } else {
  4049. uint8_t mixed = 0;
  4050. if (conn->socks_request->port != circ->dest_port)
  4051. mixed |= ISO_DESTPORT;
  4052. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  4053. mixed |= ISO_DESTADDR;
  4054. if (!memeq_opt(sr->username, sr->usernamelen,
  4055. circ->socks_username, circ->socks_username_len) ||
  4056. !memeq_opt(sr->password, sr->passwordlen,
  4057. circ->socks_password, circ->socks_password_len))
  4058. mixed |= ISO_SOCKSAUTH;
  4059. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  4060. conn->socks_request->socks_version != circ->client_proto_socksver))
  4061. mixed |= ISO_CLIENTPROTO;
  4062. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  4063. mixed |= ISO_CLIENTADDR;
  4064. if (conn->entry_cfg.session_group != circ->session_group)
  4065. mixed |= ISO_SESSIONGRP;
  4066. if (conn->nym_epoch != circ->nym_epoch)
  4067. mixed |= ISO_NYM_EPOCH;
  4068. if (dry_run)
  4069. return mixed;
  4070. if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
  4071. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  4072. "isolation flags.");
  4073. }
  4074. circ->isolation_flags_mixed |= mixed;
  4075. return 0;
  4076. }
  4077. }
  4078. /**
  4079. * Clear the isolation settings on <b>circ</b>.
  4080. *
  4081. * This only works on an open circuit that has never had a stream attached to
  4082. * it, and whose isolation settings are hypothetical. (We set hypothetical
  4083. * isolation settings on circuits as we're launching them, so that we
  4084. * know whether they can handle more streams or whether we need to launch
  4085. * even more circuits. Once the circuit is open, if it turns out that
  4086. * we no longer have any streams to attach to it, we clear the isolation flags
  4087. * and data so that other streams can have a chance.)
  4088. */
  4089. void
  4090. circuit_clear_isolation(origin_circuit_t *circ)
  4091. {
  4092. if (circ->isolation_any_streams_attached) {
  4093. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  4094. return;
  4095. }
  4096. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  4097. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  4098. "circuit");
  4099. return;
  4100. }
  4101. circ->isolation_values_set = 0;
  4102. circ->isolation_flags_mixed = 0;
  4103. circ->associated_isolated_stream_global_id = 0;
  4104. circ->client_proto_type = 0;
  4105. circ->client_proto_socksver = 0;
  4106. circ->dest_port = 0;
  4107. tor_addr_make_unspec(&circ->client_addr);
  4108. tor_free(circ->dest_address);
  4109. circ->session_group = -1;
  4110. circ->nym_epoch = 0;
  4111. if (circ->socks_username) {
  4112. memwipe(circ->socks_username, 0x11, circ->socks_username_len);
  4113. tor_free(circ->socks_username);
  4114. }
  4115. if (circ->socks_password) {
  4116. memwipe(circ->socks_password, 0x05, circ->socks_password_len);
  4117. tor_free(circ->socks_password);
  4118. }
  4119. circ->socks_username_len = circ->socks_password_len = 0;
  4120. }
  4121. /** Send an END and mark for close the given edge connection conn using the
  4122. * given reason that has to be a stream reason.
  4123. *
  4124. * Note: We don't unattached the AP connection (if applicable) because we
  4125. * don't want to flush the remaining data. This function aims at ending
  4126. * everything quickly regardless of the connection state.
  4127. *
  4128. * This function can't fail and does nothing if conn is NULL. */
  4129. void
  4130. connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
  4131. {
  4132. if (!conn) {
  4133. return;
  4134. }
  4135. connection_edge_end(conn, reason);
  4136. connection_mark_for_close(TO_CONN(conn));
  4137. }
  4138. /** Free all storage held in module-scoped variables for connection_edge.c */
  4139. void
  4140. connection_edge_free_all(void)
  4141. {
  4142. untried_pending_connections = 0;
  4143. smartlist_free(pending_entry_connections);
  4144. pending_entry_connections = NULL;
  4145. mainloop_event_free(attach_pending_entry_connections_ev);
  4146. }