connection_edge.c 166 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603
  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. static ratelim_t exit_warning_limit = RATELIM_INIT(60*15);
  1447. log_fn_ratelim(&exit_warning_limit, LOG_WARN, LD_APP,
  1448. "The \".exit\" notation is disabled in Tor due to "
  1449. "security risks.");
  1450. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1451. escaped(socks->address));
  1452. out->end_reason = END_STREAM_REASON_TORPROTOCOL;
  1453. out->should_close = 1;
  1454. return;
  1455. }
  1456. /* Remember the original address so we can tell the user about what
  1457. * they actually said, not just what it turned into. */
  1458. /* XXX yes, this is the same as out->orig_address above. One is
  1459. * in the output, and one is in the connection. */
  1460. if (! conn->original_dest_address) {
  1461. /* Is the 'if' necessary here? XXXX */
  1462. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  1463. }
  1464. /* First, apply MapAddress and MAPADDRESS mappings. We need to do
  1465. * these only for non-reverse lookups, since they don't exist for those.
  1466. * We also need to do this before we consider automapping, since we might
  1467. * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
  1468. * we'd need to automap it. */
  1469. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1470. const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
  1471. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1472. rewrite_flags, &out->map_expires, &out->exit_source)) {
  1473. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1474. REMAP_STREAM_SOURCE_CACHE);
  1475. }
  1476. }
  1477. /* Now see if we need to create or return an existing Hostname->IP
  1478. * automapping. Automapping happens when we're asked to resolve a
  1479. * hostname, and AutomapHostsOnResolve is set, and the hostname has a
  1480. * suffix listed in AutomapHostsSuffixes. It's a handy feature
  1481. * that lets you have Tor assign e.g. IPv6 addresses for .onion
  1482. * names, and return them safely from DNSPort.
  1483. */
  1484. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  1485. tor_addr_parse(&addr_tmp, socks->address)<0 &&
  1486. options->AutomapHostsOnResolve) {
  1487. /* Check the suffix... */
  1488. out->automap = addressmap_address_should_automap(socks->address, options);
  1489. if (out->automap) {
  1490. /* If we get here, then we should apply an automapping for this. */
  1491. const char *new_addr;
  1492. /* We return an IPv4 address by default, or an IPv6 address if we
  1493. * are allowed to do so. */
  1494. int addr_type = RESOLVED_TYPE_IPV4;
  1495. if (conn->socks_request->socks_version != 4) {
  1496. if (!conn->entry_cfg.ipv4_traffic ||
  1497. (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
  1498. conn->entry_cfg.prefer_ipv6_virtaddr)
  1499. addr_type = RESOLVED_TYPE_IPV6;
  1500. }
  1501. /* Okay, register the target address as automapped, and find the new
  1502. * address we're supposed to give as a resolve answer. (Return a cached
  1503. * value if we've looked up this address before.
  1504. */
  1505. new_addr = addressmap_register_virtual_address(
  1506. addr_type, tor_strdup(socks->address));
  1507. if (! new_addr) {
  1508. log_warn(LD_APP, "Unable to automap address %s",
  1509. escaped_safe_str(socks->address));
  1510. out->end_reason = END_STREAM_REASON_INTERNAL;
  1511. out->should_close = 1;
  1512. return;
  1513. }
  1514. log_info(LD_APP, "Automapping %s to %s",
  1515. escaped_safe_str_client(socks->address),
  1516. safe_str_client(new_addr));
  1517. strlcpy(socks->address, new_addr, sizeof(socks->address));
  1518. }
  1519. }
  1520. /* Now handle reverse lookups, if they're in the cache. This doesn't
  1521. * happen too often, since client-side DNS caching is off by default,
  1522. * and very deprecated. */
  1523. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1524. unsigned rewrite_flags = 0;
  1525. if (conn->entry_cfg.use_cached_ipv4_answers)
  1526. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1527. if (conn->entry_cfg.use_cached_ipv6_answers)
  1528. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1529. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  1530. rewrite_flags, &out->map_expires)) {
  1531. char *result = tor_strdup(socks->address);
  1532. /* remember _what_ is supposed to have been resolved. */
  1533. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  1534. out->orig_address);
  1535. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1536. strlen(result), (uint8_t*)result,
  1537. -1,
  1538. out->map_expires);
  1539. tor_free(result);
  1540. out->end_reason = END_STREAM_REASON_DONE |
  1541. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1542. out->should_close = 1;
  1543. return;
  1544. }
  1545. /* Hang on, did we find an answer saying that this is a reverse lookup for
  1546. * an internal address? If so, we should reject it if we're configured to
  1547. * do so. */
  1548. if (options->ClientDNSRejectInternalAddresses) {
  1549. /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
  1550. tor_addr_t addr;
  1551. int ok;
  1552. ok = tor_addr_parse_PTR_name(
  1553. &addr, socks->address, AF_UNSPEC, 1);
  1554. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  1555. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  1556. 0, NULL, -1, TIME_MAX);
  1557. out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
  1558. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1559. out->should_close = 1;
  1560. return;
  1561. }
  1562. }
  1563. }
  1564. /* If we didn't automap it before, then this is still the address that
  1565. * came straight from the user, mapped according to any
  1566. * MapAddress/MAPADDRESS commands. Now apply other mappings,
  1567. * including previously registered Automap entries (IP back to
  1568. * hostname), TrackHostExits entries, and client-side DNS cache
  1569. * entries (if they're turned on).
  1570. */
  1571. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1572. !out->automap) {
  1573. unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
  1574. addressmap_entry_source_t exit_source2;
  1575. if (conn->entry_cfg.use_cached_ipv4_answers)
  1576. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1577. if (conn->entry_cfg.use_cached_ipv6_answers)
  1578. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1579. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1580. rewrite_flags, &out->map_expires, &exit_source2)) {
  1581. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1582. REMAP_STREAM_SOURCE_CACHE);
  1583. }
  1584. if (out->exit_source == ADDRMAPSRC_NONE) {
  1585. /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
  1586. * the original source of a .exit. */
  1587. out->exit_source = exit_source2;
  1588. }
  1589. }
  1590. /* Check to see whether we're about to use an address in the virtual
  1591. * range without actually having gotten it from an Automap. */
  1592. if (!out->automap && address_is_in_virtual_range(socks->address)) {
  1593. /* This address was probably handed out by
  1594. * client_dns_get_unmapped_address, but the mapping was discarded for some
  1595. * reason. Or the user typed in a virtual address range manually. We
  1596. * *don't* want to send the address through Tor; that's likely to fail,
  1597. * and may leak information.
  1598. */
  1599. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1600. safe_str_client(socks->address));
  1601. out->end_reason = END_STREAM_REASON_INTERNAL;
  1602. out->should_close = 1;
  1603. return;
  1604. }
  1605. }
  1606. /** We just received a SOCKS request in <b>conn</b> to an onion address of type
  1607. * <b>addresstype</b>. Start connecting to the onion service. */
  1608. static int
  1609. connection_ap_handle_onion(entry_connection_t *conn,
  1610. socks_request_t *socks,
  1611. origin_circuit_t *circ,
  1612. hostname_type_t addresstype)
  1613. {
  1614. time_t now = approx_time();
  1615. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1616. /* If .onion address requests are disabled, refuse the request */
  1617. if (!conn->entry_cfg.onion_traffic) {
  1618. log_warn(LD_APP, "Onion address %s requested from a port with .onion "
  1619. "disabled", safe_str_client(socks->address));
  1620. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1621. return -1;
  1622. }
  1623. /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
  1624. * for hidden service addresses. */
  1625. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1626. /* if it's a resolve request, fail it right now, rather than
  1627. * building all the circuits and then realizing it won't work. */
  1628. log_warn(LD_APP,
  1629. "Resolve requests to hidden services not allowed. Failing.");
  1630. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1631. 0,NULL,-1,TIME_MAX);
  1632. connection_mark_unattached_ap(conn,
  1633. END_STREAM_REASON_SOCKSPROTOCOL |
  1634. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1635. return -1;
  1636. }
  1637. /* If we were passed a circuit, then we need to fail. .onion addresses
  1638. * only work when we launch our own circuits for now. */
  1639. if (circ) {
  1640. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1641. "supported for .onion addresses currently. Failing.");
  1642. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1643. return -1;
  1644. }
  1645. /* Interface: Regardless of HS version after the block below we should have
  1646. set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
  1647. const char *onion_address = NULL;
  1648. int rend_cache_lookup_result = -ENOENT;
  1649. int descriptor_is_usable = 0;
  1650. if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
  1651. rend_cache_entry_t *entry = NULL;
  1652. /* Look up if we have client authorization configured for this hidden
  1653. * service. If we do, associate it with the rend_data. */
  1654. rend_service_authorization_t *client_auth =
  1655. rend_client_lookup_service_authorization(socks->address);
  1656. const uint8_t *cookie = NULL;
  1657. rend_auth_type_t auth_type = REND_NO_AUTH;
  1658. if (client_auth) {
  1659. log_info(LD_REND, "Using previously configured client authorization "
  1660. "for hidden service request.");
  1661. auth_type = client_auth->auth_type;
  1662. cookie = client_auth->descriptor_cookie;
  1663. }
  1664. /* Fill in the rend_data field so we can start doing a connection to
  1665. * a hidden service. */
  1666. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
  1667. rend_data_client_create(socks->address, NULL, (char *) cookie,
  1668. auth_type);
  1669. if (rend_data == NULL) {
  1670. return -1;
  1671. }
  1672. onion_address = rend_data_get_address(rend_data);
  1673. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1674. safe_str_client(onion_address));
  1675. rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
  1676. &entry);
  1677. if (!rend_cache_lookup_result && entry) {
  1678. descriptor_is_usable = rend_client_any_intro_points_usable(entry);
  1679. }
  1680. } else { /* it's a v3 hidden service */
  1681. tor_assert(addresstype == ONION_V3_HOSTNAME);
  1682. const hs_descriptor_t *cached_desc = NULL;
  1683. int retval;
  1684. /* Create HS conn identifier with HS pubkey */
  1685. hs_ident_edge_conn_t *hs_conn_ident =
  1686. tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
  1687. retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
  1688. NULL, NULL);
  1689. if (retval < 0) {
  1690. log_warn(LD_GENERAL, "failed to parse hs address");
  1691. tor_free(hs_conn_ident);
  1692. return -1;
  1693. }
  1694. ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
  1695. onion_address = socks->address;
  1696. /* Check the v3 desc cache */
  1697. cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
  1698. if (cached_desc) {
  1699. rend_cache_lookup_result = 0;
  1700. descriptor_is_usable =
  1701. hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
  1702. cached_desc);
  1703. log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
  1704. (descriptor_is_usable) ? "usable" : "unusable",
  1705. safe_str_client(onion_address),
  1706. (descriptor_is_usable) ? "Not fetching." : "Refecting.");
  1707. } else {
  1708. rend_cache_lookup_result = -ENOENT;
  1709. }
  1710. }
  1711. /* Lookup the given onion address. If invalid, stop right now.
  1712. * Otherwise, we might have it in the cache or not. */
  1713. unsigned int refetch_desc = 0;
  1714. if (rend_cache_lookup_result < 0) {
  1715. switch (-rend_cache_lookup_result) {
  1716. case EINVAL:
  1717. /* We should already have rejected this address! */
  1718. log_warn(LD_BUG,"Invalid service name '%s'",
  1719. safe_str_client(onion_address));
  1720. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1721. return -1;
  1722. case ENOENT:
  1723. /* We didn't have this; we should look it up. */
  1724. log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
  1725. safe_str_client(onion_address));
  1726. refetch_desc = 1;
  1727. break;
  1728. default:
  1729. log_warn(LD_BUG, "Unknown cache lookup error %d",
  1730. rend_cache_lookup_result);
  1731. return -1;
  1732. }
  1733. }
  1734. /* Help predict that we'll want to do hidden service circuits in the
  1735. * future. We're not sure if it will need a stable circuit yet, but
  1736. * we know we'll need *something*. */
  1737. rep_hist_note_used_internal(now, 0, 1);
  1738. /* Now we have a descriptor but is it usable or not? If not, refetch.
  1739. * Also, a fetch could have been requested if the onion address was not
  1740. * found in the cache previously. */
  1741. if (refetch_desc || !descriptor_is_usable) {
  1742. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  1743. connection_ap_mark_as_non_pending_circuit(conn);
  1744. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1745. if (addresstype == ONION_V2_HOSTNAME) {
  1746. tor_assert(edge_conn->rend_data);
  1747. rend_client_refetch_v2_renddesc(edge_conn->rend_data);
  1748. /* Whatever the result of the refetch, we don't go further. */
  1749. return 0;
  1750. } else {
  1751. tor_assert(addresstype == ONION_V3_HOSTNAME);
  1752. tor_assert(edge_conn->hs_ident);
  1753. /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
  1754. * went and act accordingly. */
  1755. int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
  1756. switch (ret) {
  1757. case HS_CLIENT_FETCH_MISSING_INFO:
  1758. /* Keeping the connection in descriptor wait state is fine because
  1759. * once we get enough dirinfo or a new live consensus, the HS client
  1760. * subsystem is notified and every connection in that state will
  1761. * trigger a fetch for the service key. */
  1762. case HS_CLIENT_FETCH_LAUNCHED:
  1763. case HS_CLIENT_FETCH_PENDING:
  1764. case HS_CLIENT_FETCH_HAVE_DESC:
  1765. return 0;
  1766. case HS_CLIENT_FETCH_ERROR:
  1767. case HS_CLIENT_FETCH_NO_HSDIRS:
  1768. case HS_CLIENT_FETCH_NOT_ALLOWED:
  1769. /* Can't proceed further and better close the SOCKS request. */
  1770. return -1;
  1771. }
  1772. }
  1773. }
  1774. /* We have the descriptor! So launch a connection to the HS. */
  1775. log_info(LD_REND, "Descriptor is here. Great.");
  1776. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1777. /* We'll try to attach it at the next event loop, or whenever
  1778. * we call connection_ap_attach_pending() */
  1779. connection_ap_mark_as_pending_circuit(conn);
  1780. return 0;
  1781. }
  1782. /** Connection <b>conn</b> just finished its socks handshake, or the
  1783. * controller asked us to take care of it. If <b>circ</b> is defined,
  1784. * then that's where we'll want to attach it. Otherwise we have to
  1785. * figure it out ourselves.
  1786. *
  1787. * First, parse whether it's a .exit address, remap it, and so on. Then
  1788. * if it's for a general circuit, try to attach it to a circuit (or launch
  1789. * one as needed), else if it's for a rendezvous circuit, fetch a
  1790. * rendezvous descriptor first (or attach/launch a circuit if the
  1791. * rendezvous descriptor is already here and fresh enough).
  1792. *
  1793. * The stream will exit from the hop
  1794. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1795. * <b>cpath</b> is NULL.
  1796. */
  1797. int
  1798. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  1799. origin_circuit_t *circ,
  1800. crypt_path_t *cpath)
  1801. {
  1802. socks_request_t *socks = conn->socks_request;
  1803. const or_options_t *options = get_options();
  1804. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1805. time_t now = time(NULL);
  1806. rewrite_result_t rr;
  1807. /* First we'll do the rewrite part. Let's see if we get a reasonable
  1808. * answer.
  1809. */
  1810. memset(&rr, 0, sizeof(rr));
  1811. connection_ap_handshake_rewrite(conn,&rr);
  1812. if (rr.should_close) {
  1813. /* connection_ap_handshake_rewrite told us to close the connection:
  1814. * either because it sent back an answer, or because it sent back an
  1815. * error */
  1816. connection_mark_unattached_ap(conn, rr.end_reason);
  1817. if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
  1818. return 0;
  1819. else
  1820. return -1;
  1821. }
  1822. const time_t map_expires = rr.map_expires;
  1823. const int automap = rr.automap;
  1824. const addressmap_entry_source_t exit_source = rr.exit_source;
  1825. /* Now, we parse the address to see if it's an .onion or .exit or
  1826. * other special address.
  1827. */
  1828. const hostname_type_t addresstype = parse_extended_hostname(socks->address);
  1829. /* Now see whether the hostname is bogus. This could happen because of an
  1830. * onion hostname whose format we don't recognize. */
  1831. if (addresstype == BAD_HOSTNAME) {
  1832. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1833. escaped(socks->address));
  1834. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1835. return -1;
  1836. }
  1837. /* If this is a .exit hostname, strip off the .name.exit part, and
  1838. * see whether we're willing to connect there, and and otherwise handle the
  1839. * .exit address.
  1840. *
  1841. * We'll set chosen_exit_name and/or close the connection as appropriate.
  1842. */
  1843. if (addresstype == EXIT_HOSTNAME) {
  1844. /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
  1845. * not ExcludeExitNodes. */
  1846. routerset_t *excludeset = options->StrictNodes ?
  1847. options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
  1848. const node_t *node = NULL;
  1849. /* If this .exit was added by an AUTOMAP, then it came straight from
  1850. * a user. That's not safe. */
  1851. if (exit_source == ADDRMAPSRC_AUTOMAP) {
  1852. /* Whoops; this one is stale. It must have gotten added earlier?
  1853. * (Probably this is not possible, since AllowDotExit no longer
  1854. * exists.) */
  1855. log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
  1856. safe_str_client(socks->address));
  1857. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1858. escaped(socks->address));
  1859. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1860. tor_assert_nonfatal_unreached();
  1861. return -1;
  1862. }
  1863. /* Double-check to make sure there are no .exits coming from
  1864. * impossible/weird sources. */
  1865. if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
  1866. /* It shouldn't be possible to get a .exit address from any of these
  1867. * sources. */
  1868. log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
  1869. ".exit part. Refusing.",
  1870. safe_str_client(socks->address));
  1871. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1872. escaped(socks->address));
  1873. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1874. return -1;
  1875. }
  1876. tor_assert(!automap);
  1877. /* Now, find the character before the .(name) part.
  1878. * (The ".exit" part got stripped off by "parse_extended_hostname").
  1879. *
  1880. * We're going to put the exit name into conn->chosen_exit_name, and
  1881. * look up a node correspondingly. */
  1882. char *s = strrchr(socks->address,'.');
  1883. if (s) {
  1884. /* The address was of the form "(stuff).(name).exit */
  1885. if (s[1] != '\0') {
  1886. /* Looks like a real .exit one. */
  1887. conn->chosen_exit_name = tor_strdup(s+1);
  1888. node = node_get_by_nickname(conn->chosen_exit_name, 0);
  1889. if (exit_source == ADDRMAPSRC_TRACKEXIT) {
  1890. /* We 5 tries before it expires the addressmap */
  1891. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1892. }
  1893. *s = 0;
  1894. } else {
  1895. /* Oops, the address was (stuff)..exit. That's not okay. */
  1896. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1897. safe_str_client(socks->address));
  1898. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1899. escaped(socks->address));
  1900. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1901. return -1;
  1902. }
  1903. } else {
  1904. /* It looks like they just asked for "foo.exit". That's a special
  1905. * form that means (foo's address).foo.exit. */
  1906. conn->chosen_exit_name = tor_strdup(socks->address);
  1907. node = node_get_by_nickname(conn->chosen_exit_name, 0);
  1908. if (node) {
  1909. *socks->address = 0;
  1910. node_get_address_string(node, socks->address, sizeof(socks->address));
  1911. }
  1912. }
  1913. /* Now make sure that the chosen exit exists... */
  1914. if (!node) {
  1915. log_warn(LD_APP,
  1916. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1917. safe_str_client(socks->address));
  1918. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1919. return -1;
  1920. }
  1921. /* ...and make sure that it isn't excluded. */
  1922. if (routerset_contains_node(excludeset, node)) {
  1923. log_warn(LD_APP,
  1924. "Excluded relay in exit address '%s.exit'. Refusing.",
  1925. safe_str_client(socks->address));
  1926. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1927. return -1;
  1928. }
  1929. /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1930. Bar is not listed in it? I say yes, but our revised manpage branch
  1931. implies no. */
  1932. }
  1933. /* Now, we handle everything that isn't a .onion address. */
  1934. if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
  1935. /* Not a hidden-service request. It's either a hostname or an IP,
  1936. * possibly with a .exit that we stripped off. We're going to check
  1937. * if we're allowed to connect/resolve there, and then launch the
  1938. * appropriate request. */
  1939. /* Check for funny characters in the address. */
  1940. if (address_is_invalid_destination(socks->address, 1)) {
  1941. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1942. escaped(socks->address));
  1943. log_warn(LD_APP,
  1944. "Destination '%s' seems to be an invalid hostname. Failing.",
  1945. safe_str_client(socks->address));
  1946. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1947. return -1;
  1948. }
  1949. /* socks->address is a non-onion hostname or IP address.
  1950. * If we can't do any non-onion requests, refuse the connection.
  1951. * If we have a hostname but can't do DNS, refuse the connection.
  1952. * If we have an IP address, but we can't use that address family,
  1953. * refuse the connection.
  1954. *
  1955. * If we can do DNS requests, and we can use at least one address family,
  1956. * then we have to resolve the address first. Then we'll know if it
  1957. * resolves to a usable address family. */
  1958. /* First, check if all non-onion traffic is disabled */
  1959. if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
  1960. && !conn->entry_cfg.ipv6_traffic) {
  1961. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
  1962. "or IP address %s because Port has OnionTrafficOnly set (or "
  1963. "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
  1964. safe_str_client(socks->address));
  1965. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1966. return -1;
  1967. }
  1968. /* Then check if we have a hostname or IP address, and whether DNS or
  1969. * the IP address family are permitted. Reject if not. */
  1970. tor_addr_t dummy_addr;
  1971. int socks_family = tor_addr_parse(&dummy_addr, socks->address);
  1972. /* family will be -1 for a non-onion hostname that's not an IP */
  1973. if (socks_family == -1) {
  1974. if (!conn->entry_cfg.dns_request) {
  1975. log_warn(LD_APP, "Refusing to connect to hostname %s "
  1976. "because Port has NoDNSRequest set.",
  1977. safe_str_client(socks->address));
  1978. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1979. return -1;
  1980. }
  1981. } else if (socks_family == AF_INET) {
  1982. if (!conn->entry_cfg.ipv4_traffic) {
  1983. log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
  1984. "Port has NoIPv4Traffic set.",
  1985. safe_str_client(socks->address));
  1986. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1987. return -1;
  1988. }
  1989. } else if (socks_family == AF_INET6) {
  1990. if (!conn->entry_cfg.ipv6_traffic) {
  1991. log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
  1992. "Port has NoIPv6Traffic set.",
  1993. safe_str_client(socks->address));
  1994. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1995. return -1;
  1996. }
  1997. } else {
  1998. tor_assert_nonfatal_unreached_once();
  1999. }
  2000. /* See if this is a hostname lookup that we can answer immediately.
  2001. * (For example, an attempt to look up the IP address for an IP address.)
  2002. */
  2003. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  2004. tor_addr_t answer;
  2005. /* Reply to resolves immediately if we can. */
  2006. if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
  2007. /* remember _what_ is supposed to have been resolved. */
  2008. strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
  2009. connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
  2010. map_expires);
  2011. connection_mark_unattached_ap(conn,
  2012. END_STREAM_REASON_DONE |
  2013. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2014. return 0;
  2015. }
  2016. tor_assert(!automap);
  2017. rep_hist_note_used_resolve(now); /* help predict this next time */
  2018. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  2019. /* Now see if this is a connect request that we can reject immediately */
  2020. tor_assert(!automap);
  2021. /* Don't allow connections to port 0. */
  2022. if (socks->port == 0) {
  2023. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  2024. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  2025. return -1;
  2026. }
  2027. /* You can't make connections to internal addresses, by default.
  2028. * Exceptions are begindir requests (where the address is meaningless),
  2029. * or cases where you've hand-configured a particular exit, thereby
  2030. * making the local address meaningful. */
  2031. if (options->ClientRejectInternalAddresses &&
  2032. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  2033. /* If we reach this point then we don't want to allow internal
  2034. * addresses. Check if we got one. */
  2035. tor_addr_t addr;
  2036. if (tor_addr_hostname_is_local(socks->address) ||
  2037. (tor_addr_parse(&addr, socks->address) >= 0 &&
  2038. tor_addr_is_internal(&addr, 0))) {
  2039. /* If this is an explicit private address with no chosen exit node,
  2040. * then we really don't want to try to connect to it. That's
  2041. * probably an error. */
  2042. if (conn->is_transparent_ap) {
  2043. #define WARN_INTRVL_LOOP 300
  2044. static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
  2045. char *m;
  2046. if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
  2047. log_warn(LD_NET,
  2048. "Rejecting request for anonymous connection to private "
  2049. "address %s on a TransPort or NATDPort. Possible loop "
  2050. "in your NAT rules?%s", safe_str_client(socks->address),
  2051. m);
  2052. tor_free(m);
  2053. }
  2054. } else {
  2055. #define WARN_INTRVL_PRIV 300
  2056. static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
  2057. char *m;
  2058. if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
  2059. log_warn(LD_NET,
  2060. "Rejecting SOCKS request for anonymous connection to "
  2061. "private address %s.%s",
  2062. safe_str_client(socks->address),m);
  2063. tor_free(m);
  2064. }
  2065. }
  2066. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  2067. return -1;
  2068. }
  2069. } /* end "if we should check for internal addresses" */
  2070. /* Okay. We're still doing a CONNECT, and it wasn't a private
  2071. * address. Here we do special handling for literal IP addresses,
  2072. * to see if we should reject this preemptively, and to set up
  2073. * fields in conn->entry_cfg to tell the exit what AF we want. */
  2074. {
  2075. tor_addr_t addr;
  2076. /* XXX Duplicate call to tor_addr_parse. */
  2077. if (tor_addr_parse(&addr, socks->address) >= 0) {
  2078. /* If we reach this point, it's an IPv4 or an IPv6 address. */
  2079. sa_family_t family = tor_addr_family(&addr);
  2080. if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
  2081. (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
  2082. /* You can't do an IPv4 address on a v6-only socks listener,
  2083. * or vice versa. */
  2084. log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
  2085. "family that this listener does not support.");
  2086. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2087. return -1;
  2088. } else if (family == AF_INET6 && socks->socks_version == 4) {
  2089. /* You can't make a socks4 request to an IPv6 address. Socks4
  2090. * doesn't support that. */
  2091. log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
  2092. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2093. return -1;
  2094. } else if (socks->socks_version == 4 &&
  2095. !conn->entry_cfg.ipv4_traffic) {
  2096. /* You can't do any kind of Socks4 request when IPv4 is forbidden.
  2097. *
  2098. * XXX raise this check outside the enclosing block? */
  2099. log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
  2100. "no IPv4 traffic supported.");
  2101. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  2102. return -1;
  2103. } else if (family == AF_INET6) {
  2104. /* Tell the exit: we won't accept any ipv4 connection to an IPv6
  2105. * address. */
  2106. conn->entry_cfg.ipv4_traffic = 0;
  2107. } else if (family == AF_INET) {
  2108. /* Tell the exit: we won't accept any ipv6 connection to an IPv4
  2109. * address. */
  2110. conn->entry_cfg.ipv6_traffic = 0;
  2111. }
  2112. }
  2113. }
  2114. /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
  2115. if (socks->socks_version == 4)
  2116. conn->entry_cfg.ipv6_traffic = 0;
  2117. /* Still handling CONNECT. Now, check for exit enclaves. (Which we
  2118. * don't do on BEGIN_DIR, or when there is a chosen exit.)
  2119. *
  2120. * TODO: Should we remove this? Exit enclaves are nutty and don't
  2121. * work very well
  2122. */
  2123. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  2124. /* see if we can find a suitable enclave exit */
  2125. const node_t *r =
  2126. router_find_exact_exit_enclave(socks->address, socks->port);
  2127. if (r) {
  2128. log_info(LD_APP,
  2129. "Redirecting address %s to exit at enclave router %s",
  2130. safe_str_client(socks->address), node_describe(r));
  2131. /* use the hex digest, not nickname, in case there are two
  2132. routers with this nickname */
  2133. conn->chosen_exit_name =
  2134. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  2135. conn->chosen_exit_optional = 1;
  2136. }
  2137. }
  2138. /* Still handling CONNECT: warn or reject if it's using a dangerous
  2139. * port. */
  2140. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  2141. if (consider_plaintext_ports(conn, socks->port) < 0)
  2142. return -1;
  2143. /* Remember the port so that we will predict that more requests
  2144. there will happen in the future. */
  2145. if (!conn->use_begindir) {
  2146. /* help predict this next time */
  2147. rep_hist_note_used_port(now, socks->port);
  2148. }
  2149. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  2150. rep_hist_note_used_resolve(now); /* help predict this next time */
  2151. /* no extra processing needed */
  2152. } else {
  2153. /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
  2154. tor_fragile_assert();
  2155. }
  2156. /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
  2157. * address, and decided not to reject it for any number of reasons. Now
  2158. * mark the connection as waiting for a circuit, and try to attach it!
  2159. */
  2160. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2161. /* If we were given a circuit to attach to, try to attach. Otherwise,
  2162. * try to find a good one and attach to that. */
  2163. int rv;
  2164. if (circ) {
  2165. rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
  2166. } else {
  2167. /* We'll try to attach it at the next event loop, or whenever
  2168. * we call connection_ap_attach_pending() */
  2169. connection_ap_mark_as_pending_circuit(conn);
  2170. rv = 0;
  2171. }
  2172. /* If the above function returned 0 then we're waiting for a circuit.
  2173. * if it returned 1, we're attached. Both are okay. But if it returned
  2174. * -1, there was an error, so make sure the connection is marked, and
  2175. * return -1. */
  2176. if (rv < 0) {
  2177. if (!base_conn->marked_for_close)
  2178. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  2179. return -1;
  2180. }
  2181. return 0;
  2182. } else {
  2183. /* If we get here, it's a request for a .onion address! */
  2184. tor_assert(addresstype == ONION_V2_HOSTNAME ||
  2185. addresstype == ONION_V3_HOSTNAME);
  2186. tor_assert(!automap);
  2187. return connection_ap_handle_onion(conn, socks, circ, addresstype);
  2188. }
  2189. return 0; /* unreached but keeps the compiler happy */
  2190. }
  2191. #ifdef TRANS_PF
  2192. static int pf_socket = -1;
  2193. int
  2194. get_pf_socket(void)
  2195. {
  2196. int pf;
  2197. /* This should be opened before dropping privileges. */
  2198. if (pf_socket >= 0)
  2199. return pf_socket;
  2200. #if defined(OpenBSD)
  2201. /* only works on OpenBSD */
  2202. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  2203. #else
  2204. /* works on NetBSD and FreeBSD */
  2205. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  2206. #endif /* defined(OpenBSD) */
  2207. if (pf < 0) {
  2208. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  2209. return -1;
  2210. }
  2211. pf_socket = pf;
  2212. return pf_socket;
  2213. }
  2214. #endif /* defined(TRANS_PF) */
  2215. #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
  2216. defined(TRANS_TPROXY)
  2217. /** Try fill in the address of <b>req</b> from the socket configured
  2218. * with <b>conn</b>. */
  2219. static int
  2220. destination_from_socket(entry_connection_t *conn, socks_request_t *req)
  2221. {
  2222. struct sockaddr_storage orig_dst;
  2223. socklen_t orig_dst_len = sizeof(orig_dst);
  2224. tor_addr_t addr;
  2225. #ifdef TRANS_TPROXY
  2226. if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
  2227. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  2228. &orig_dst_len) < 0) {
  2229. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2230. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  2231. return -1;
  2232. }
  2233. goto done;
  2234. }
  2235. #endif /* defined(TRANS_TPROXY) */
  2236. #ifdef TRANS_NETFILTER
  2237. int rv = -1;
  2238. switch (ENTRY_TO_CONN(conn)->socket_family) {
  2239. #ifdef TRANS_NETFILTER_IPV4
  2240. case AF_INET:
  2241. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  2242. (struct sockaddr*)&orig_dst, &orig_dst_len);
  2243. break;
  2244. #endif /* defined(TRANS_NETFILTER_IPV4) */
  2245. #ifdef TRANS_NETFILTER_IPV6
  2246. case AF_INET6:
  2247. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
  2248. (struct sockaddr*)&orig_dst, &orig_dst_len);
  2249. break;
  2250. #endif /* defined(TRANS_NETFILTER_IPV6) */
  2251. default:
  2252. log_warn(LD_BUG,
  2253. "Received transparent data from an unsuported socket family %d",
  2254. ENTRY_TO_CONN(conn)->socket_family);
  2255. return -1;
  2256. }
  2257. if (rv < 0) {
  2258. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2259. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  2260. return -1;
  2261. }
  2262. goto done;
  2263. #elif defined(TRANS_PF)
  2264. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  2265. &orig_dst_len) < 0) {
  2266. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2267. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  2268. return -1;
  2269. }
  2270. goto done;
  2271. #else
  2272. (void)conn;
  2273. (void)req;
  2274. log_warn(LD_BUG, "Unable to determine destination from socket.");
  2275. return -1;
  2276. #endif /* defined(TRANS_NETFILTER) || ... */
  2277. done:
  2278. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  2279. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  2280. return 0;
  2281. }
  2282. #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
  2283. #ifdef TRANS_PF
  2284. static int
  2285. destination_from_pf(entry_connection_t *conn, socks_request_t *req)
  2286. {
  2287. struct sockaddr_storage proxy_addr;
  2288. socklen_t proxy_addr_len = sizeof(proxy_addr);
  2289. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  2290. struct pfioc_natlook pnl;
  2291. tor_addr_t addr;
  2292. int pf = -1;
  2293. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  2294. &proxy_addr_len) < 0) {
  2295. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  2296. log_warn(LD_NET, "getsockname() to determine transocks destination "
  2297. "failed: %s", tor_socket_strerror(e));
  2298. return -1;
  2299. }
  2300. #ifdef __FreeBSD__
  2301. if (get_options()->TransProxyType_parsed == TPT_IPFW) {
  2302. /* ipfw(8) is used and in this case getsockname returned the original
  2303. destination */
  2304. if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
  2305. tor_fragile_assert();
  2306. return -1;
  2307. }
  2308. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  2309. return 0;
  2310. }
  2311. #endif /* defined(__FreeBSD__) */
  2312. memset(&pnl, 0, sizeof(pnl));
  2313. pnl.proto = IPPROTO_TCP;
  2314. pnl.direction = PF_OUT;
  2315. if (proxy_sa->sa_family == AF_INET) {
  2316. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  2317. pnl.af = AF_INET;
  2318. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  2319. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  2320. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  2321. pnl.dport = sin->sin_port;
  2322. } else if (proxy_sa->sa_family == AF_INET6) {
  2323. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  2324. pnl.af = AF_INET6;
  2325. const struct in6_addr *dest_in6 =
  2326. tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr);
  2327. if (BUG(!dest_in6))
  2328. return -1;
  2329. memcpy(&pnl.saddr.v6, dest_in6, sizeof(struct in6_addr));
  2330. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  2331. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  2332. pnl.dport = sin6->sin6_port;
  2333. } else {
  2334. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  2335. (int)proxy_sa->sa_family);
  2336. return -1;
  2337. }
  2338. pf = get_pf_socket();
  2339. if (pf<0)
  2340. return -1;
  2341. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  2342. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  2343. return -1;
  2344. }
  2345. if (pnl.af == AF_INET) {
  2346. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  2347. } else if (pnl.af == AF_INET6) {
  2348. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  2349. } else {
  2350. tor_fragile_assert();
  2351. return -1;
  2352. }
  2353. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  2354. req->port = ntohs(pnl.rdport);
  2355. return 0;
  2356. }
  2357. #endif /* defined(TRANS_PF) */
  2358. /** Fetch the original destination address and port from a
  2359. * system-specific interface and put them into a
  2360. * socks_request_t as if they came from a socks request.
  2361. *
  2362. * Return -1 if an error prevents fetching the destination,
  2363. * else return 0.
  2364. */
  2365. static int
  2366. connection_ap_get_original_destination(entry_connection_t *conn,
  2367. socks_request_t *req)
  2368. {
  2369. #ifdef TRANS_NETFILTER
  2370. return destination_from_socket(conn, req);
  2371. #elif defined(TRANS_PF)
  2372. const or_options_t *options = get_options();
  2373. if (options->TransProxyType_parsed == TPT_PF_DIVERT)
  2374. return destination_from_socket(conn, req);
  2375. if (options->TransProxyType_parsed == TPT_DEFAULT ||
  2376. options->TransProxyType_parsed == TPT_IPFW)
  2377. return destination_from_pf(conn, req);
  2378. (void)conn;
  2379. (void)req;
  2380. log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
  2381. options->TransProxyType);
  2382. return -1;
  2383. #else
  2384. (void)conn;
  2385. (void)req;
  2386. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  2387. "transparent proxy method was configured.");
  2388. return -1;
  2389. #endif /* defined(TRANS_NETFILTER) || ... */
  2390. }
  2391. /** connection_edge_process_inbuf() found a conn in state
  2392. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  2393. * the socks handshake.
  2394. *
  2395. * If the handshake is complete, send it to
  2396. * connection_ap_handshake_rewrite_and_attach().
  2397. *
  2398. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  2399. * else return 0.
  2400. */
  2401. static int
  2402. connection_ap_handshake_process_socks(entry_connection_t *conn)
  2403. {
  2404. socks_request_t *socks;
  2405. int sockshere;
  2406. const or_options_t *options = get_options();
  2407. int had_reply = 0;
  2408. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2409. tor_assert(conn);
  2410. tor_assert(base_conn->type == CONN_TYPE_AP);
  2411. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  2412. tor_assert(conn->socks_request);
  2413. socks = conn->socks_request;
  2414. log_debug(LD_APP,"entered.");
  2415. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  2416. options->TestSocks, options->SafeSocks);
  2417. if (socks->replylen) {
  2418. had_reply = 1;
  2419. connection_buf_add((const char*)socks->reply, socks->replylen,
  2420. base_conn);
  2421. socks->replylen = 0;
  2422. if (sockshere == -1) {
  2423. /* An invalid request just got a reply, no additional
  2424. * one is necessary. */
  2425. socks->has_finished = 1;
  2426. }
  2427. }
  2428. if (sockshere == 0) {
  2429. log_debug(LD_APP,"socks handshake not all here yet.");
  2430. return 0;
  2431. } else if (sockshere == -1) {
  2432. if (!had_reply) {
  2433. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  2434. connection_ap_handshake_socks_reply(conn, NULL, 0,
  2435. END_STREAM_REASON_SOCKSPROTOCOL);
  2436. }
  2437. connection_mark_unattached_ap(conn,
  2438. END_STREAM_REASON_SOCKSPROTOCOL |
  2439. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2440. return -1;
  2441. } /* else socks handshake is done, continue processing */
  2442. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  2443. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2444. else
  2445. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  2446. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2447. }
  2448. /** connection_init_accepted_conn() found a new trans AP conn.
  2449. * Get the original destination and send it to
  2450. * connection_ap_handshake_rewrite_and_attach().
  2451. *
  2452. * Return -1 if an unexpected error with conn (and it should be marked
  2453. * for close), else return 0.
  2454. */
  2455. int
  2456. connection_ap_process_transparent(entry_connection_t *conn)
  2457. {
  2458. socks_request_t *socks;
  2459. tor_assert(conn);
  2460. tor_assert(conn->socks_request);
  2461. socks = conn->socks_request;
  2462. /* pretend that a socks handshake completed so we don't try to
  2463. * send a socks reply down a transparent conn */
  2464. socks->command = SOCKS_COMMAND_CONNECT;
  2465. socks->has_finished = 1;
  2466. log_debug(LD_APP,"entered.");
  2467. if (connection_ap_get_original_destination(conn, socks) < 0) {
  2468. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  2469. connection_mark_unattached_ap(conn,
  2470. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  2471. return -1;
  2472. }
  2473. /* we have the original destination */
  2474. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2475. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2476. }
  2477. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  2478. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  2479. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  2480. * form of the original destination.
  2481. *
  2482. * If the original destination is complete, send it to
  2483. * connection_ap_handshake_rewrite_and_attach().
  2484. *
  2485. * Return -1 if an unexpected error with conn (and it should be marked
  2486. * for close), else return 0.
  2487. */
  2488. static int
  2489. connection_ap_process_natd(entry_connection_t *conn)
  2490. {
  2491. char tmp_buf[36], *tbuf, *daddr;
  2492. size_t tlen = 30;
  2493. int err, port_ok;
  2494. socks_request_t *socks;
  2495. tor_assert(conn);
  2496. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  2497. tor_assert(conn->socks_request);
  2498. socks = conn->socks_request;
  2499. log_debug(LD_APP,"entered.");
  2500. /* look for LF-terminated "[DEST ip_addr port]"
  2501. * where ip_addr is a dotted-quad and port is in string form */
  2502. err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  2503. if (err == 0)
  2504. return 0;
  2505. if (err < 0) {
  2506. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  2507. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2508. return -1;
  2509. }
  2510. if (strcmpstart(tmp_buf, "[DEST ")) {
  2511. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2512. "said: %s",
  2513. escaped(tmp_buf));
  2514. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2515. return -1;
  2516. }
  2517. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  2518. if (!(tbuf = strchr(tbuf, ' '))) {
  2519. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2520. "said: %s",
  2521. escaped(tmp_buf));
  2522. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2523. return -1;
  2524. }
  2525. *tbuf++ = '\0';
  2526. /* pretend that a socks handshake completed so we don't try to
  2527. * send a socks reply down a natd conn */
  2528. strlcpy(socks->address, daddr, sizeof(socks->address));
  2529. socks->port = (uint16_t)
  2530. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  2531. if (!port_ok) {
  2532. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  2533. "of range.", escaped(tbuf));
  2534. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2535. return -1;
  2536. }
  2537. socks->command = SOCKS_COMMAND_CONNECT;
  2538. socks->has_finished = 1;
  2539. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2540. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2541. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2542. }
  2543. static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
  2544. "HTTP/1.0 405 Method Not Allowed\r\n"
  2545. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  2546. "<html>\n"
  2547. "<head>\n"
  2548. "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
  2549. "</head>\n"
  2550. "<body>\n"
  2551. "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
  2552. "<p>\n"
  2553. "It appears you have configured your web browser to use this Tor port as\n"
  2554. "an HTTP proxy.\n"
  2555. "</p><p>\n"
  2556. "This is not correct: This port is configured as a CONNECT tunnel, not\n"
  2557. "an HTTP proxy. Please configure your client accordingly. You can also\n"
  2558. "use HTTPS; then the client should automatically use HTTP CONNECT."
  2559. "</p>\n"
  2560. "<p>\n"
  2561. "See <a href=\"https://www.torproject.org/documentation.html\">"
  2562. "https://www.torproject.org/documentation.html</a> for more "
  2563. "information.\n"
  2564. "</p>\n"
  2565. "</body>\n"
  2566. "</html>\n";
  2567. /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
  2568. * but we have not yet received a full HTTP CONNECT request. Try to parse an
  2569. * HTTP CONNECT request from the connection's inbuf. On success, set up the
  2570. * connection's socks_request field and try to attach the connection. On
  2571. * failure, send an HTTP reply, and mark the connection.
  2572. */
  2573. STATIC int
  2574. connection_ap_process_http_connect(entry_connection_t *conn)
  2575. {
  2576. if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
  2577. return -1;
  2578. char *headers = NULL, *body = NULL;
  2579. char *command = NULL, *addrport = NULL;
  2580. char *addr = NULL;
  2581. size_t bodylen = 0;
  2582. const char *errmsg = NULL;
  2583. int rv = 0;
  2584. const int http_status =
  2585. fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
  2586. &body, &bodylen, 1024, 0);
  2587. if (http_status < 0) {
  2588. /* Bad http status */
  2589. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2590. goto err;
  2591. } else if (http_status == 0) {
  2592. /* no HTTP request yet. */
  2593. goto done;
  2594. }
  2595. const int cmd_status = parse_http_command(headers, &command, &addrport);
  2596. if (cmd_status < 0) {
  2597. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2598. goto err;
  2599. }
  2600. tor_assert(command);
  2601. tor_assert(addrport);
  2602. if (strcasecmp(command, "connect")) {
  2603. errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
  2604. goto err;
  2605. }
  2606. tor_assert(conn->socks_request);
  2607. socks_request_t *socks = conn->socks_request;
  2608. uint16_t port;
  2609. if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
  2610. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2611. goto err;
  2612. }
  2613. if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
  2614. errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
  2615. goto err;
  2616. }
  2617. /* Abuse the 'username' and 'password' fields here. They are already an
  2618. * abuse. */
  2619. {
  2620. char *authorization = http_get_header(headers, "Proxy-Authorization: ");
  2621. if (authorization) {
  2622. socks->username = authorization; // steal reference
  2623. socks->usernamelen = strlen(authorization);
  2624. }
  2625. char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
  2626. if (isolation) {
  2627. socks->password = isolation; // steal reference
  2628. socks->passwordlen = strlen(isolation);
  2629. }
  2630. }
  2631. socks->command = SOCKS_COMMAND_CONNECT;
  2632. socks->listener_type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
  2633. strlcpy(socks->address, addr, sizeof(socks->address));
  2634. socks->port = port;
  2635. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2636. rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2637. // XXXX send a "100 Continue" message?
  2638. goto done;
  2639. err:
  2640. if (BUG(errmsg == NULL))
  2641. errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
  2642. log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
  2643. connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
  2644. /* Mark it as "has_finished" so that we don't try to send an extra socks
  2645. * reply. */
  2646. conn->socks_request->has_finished = 1;
  2647. connection_mark_unattached_ap(conn,
  2648. END_STREAM_REASON_HTTPPROTOCOL|
  2649. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2650. done:
  2651. tor_free(headers);
  2652. tor_free(body);
  2653. tor_free(command);
  2654. tor_free(addrport);
  2655. tor_free(addr);
  2656. return rv;
  2657. }
  2658. /** Iterate over the two bytes of stream_id until we get one that is not
  2659. * already in use; return it. Return 0 if can't get a unique stream_id.
  2660. */
  2661. streamid_t
  2662. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  2663. {
  2664. edge_connection_t *tmpconn;
  2665. streamid_t test_stream_id;
  2666. uint32_t attempts=0;
  2667. again:
  2668. test_stream_id = circ->next_stream_id++;
  2669. if (++attempts > 1<<16) {
  2670. /* Make sure we don't loop forever if all stream_id's are used. */
  2671. log_warn(LD_APP,"No unused stream IDs. Failing.");
  2672. return 0;
  2673. }
  2674. if (test_stream_id == 0)
  2675. goto again;
  2676. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  2677. if (tmpconn->stream_id == test_stream_id)
  2678. goto again;
  2679. if (connection_half_edge_find_stream_id(circ->half_streams,
  2680. test_stream_id))
  2681. goto again;
  2682. return test_stream_id;
  2683. }
  2684. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  2685. * an exit that supports optimistic data. */
  2686. static int
  2687. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  2688. {
  2689. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2690. /* We can only send optimistic data if we're connected to an open
  2691. general circuit. */
  2692. if (edge_conn->on_circuit == NULL ||
  2693. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  2694. (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  2695. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
  2696. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
  2697. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
  2698. return 0;
  2699. return conn->may_use_optimistic_data;
  2700. }
  2701. /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
  2702. * RELAY_BEGIN cell for <b>ap_conn</b>. */
  2703. static uint32_t
  2704. connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
  2705. {
  2706. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2707. const node_t *exitnode = NULL;
  2708. const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
  2709. uint32_t flags = 0;
  2710. /* No flags for begindir */
  2711. if (ap_conn->use_begindir)
  2712. return 0;
  2713. /* No flags for hidden services. */
  2714. if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  2715. return 0;
  2716. /* If only IPv4 is supported, no flags */
  2717. if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
  2718. return 0;
  2719. if (! cpath_layer ||
  2720. ! cpath_layer->extend_info)
  2721. return 0;
  2722. if (!ap_conn->entry_cfg.ipv4_traffic)
  2723. flags |= BEGIN_FLAG_IPV4_NOT_OK;
  2724. exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
  2725. if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
  2726. tor_addr_t a;
  2727. tor_addr_make_null(&a, AF_INET6);
  2728. if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
  2729. exitnode)
  2730. != ADDR_POLICY_REJECTED) {
  2731. /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
  2732. * no point. */
  2733. flags |= BEGIN_FLAG_IPV6_OK;
  2734. }
  2735. }
  2736. if (flags == BEGIN_FLAG_IPV6_OK) {
  2737. /* When IPv4 and IPv6 are both allowed, consider whether to say we
  2738. * prefer IPv6. Otherwise there's no point in declaring a preference */
  2739. if (ap_conn->entry_cfg.prefer_ipv6)
  2740. flags |= BEGIN_FLAG_IPV6_PREFERRED;
  2741. }
  2742. if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
  2743. log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
  2744. "am telling it to fulfil with neither IPv4 nor IPv6. That's "
  2745. "not going to work. Did you perhaps ask for an IPv6 address "
  2746. "on an IPv4Only port, or vice versa?");
  2747. }
  2748. return flags;
  2749. }
  2750. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  2751. * socks_request field, and send it down circ.
  2752. *
  2753. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2754. */
  2755. MOCK_IMPL(int,
  2756. connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
  2757. {
  2758. char payload[CELL_PAYLOAD_SIZE];
  2759. int payload_len;
  2760. int begin_type;
  2761. const or_options_t *options = get_options();
  2762. origin_circuit_t *circ;
  2763. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2764. connection_t *base_conn = TO_CONN(edge_conn);
  2765. tor_assert(edge_conn->on_circuit);
  2766. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2767. tor_assert(base_conn->type == CONN_TYPE_AP);
  2768. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2769. tor_assert(ap_conn->socks_request);
  2770. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  2771. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2772. if (edge_conn->stream_id==0) {
  2773. /* XXXX+ Instead of closing this stream, we should make it get
  2774. * retried on another circuit. */
  2775. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2776. /* Mark this circuit "unusable for new streams". */
  2777. mark_circuit_unusable_for_new_conns(circ);
  2778. return -1;
  2779. }
  2780. /* Set up begin cell flags. */
  2781. edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
  2782. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  2783. // (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  2784. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  2785. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) ?
  2786. ap_conn->socks_request->address : "",
  2787. ap_conn->socks_request->port);
  2788. payload_len = (int)strlen(payload)+1;
  2789. if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  2790. set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  2791. payload_len += 4;
  2792. }
  2793. log_info(LD_APP,
  2794. "Sending relay cell %d on circ %u to begin stream %d.",
  2795. (int)ap_conn->use_begindir,
  2796. (unsigned)circ->base_.n_circ_id,
  2797. edge_conn->stream_id);
  2798. begin_type = ap_conn->use_begindir ?
  2799. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  2800. /* Check that circuits are anonymised, based on their type. */
  2801. if (begin_type == RELAY_COMMAND_BEGIN) {
  2802. /* This connection is a standard OR connection.
  2803. * Make sure its path length is anonymous, or that we're in a
  2804. * non-anonymous mode. */
  2805. assert_circ_anonymity_ok(circ, options);
  2806. } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
  2807. /* This connection is a begindir directory connection.
  2808. * Look at the linked directory connection to access the directory purpose.
  2809. * If a BEGINDIR connection is ever not linked, that's a bug. */
  2810. if (BUG(!base_conn->linked)) {
  2811. return -1;
  2812. }
  2813. connection_t *linked_dir_conn_base = base_conn->linked_conn;
  2814. /* If the linked connection has been unlinked by other code, we can't send
  2815. * a begin cell on it. */
  2816. if (!linked_dir_conn_base) {
  2817. return -1;
  2818. }
  2819. /* Sensitive directory connections must have an anonymous path length.
  2820. * Otherwise, directory connections are typically one-hop.
  2821. * This matches the earlier check for directory connection path anonymity
  2822. * in directory_initiate_request(). */
  2823. if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
  2824. TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
  2825. TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
  2826. assert_circ_anonymity_ok(circ, options);
  2827. }
  2828. } else {
  2829. /* This code was written for the two connection types BEGIN and BEGIN_DIR
  2830. */
  2831. tor_assert_unreached();
  2832. }
  2833. if (connection_edge_send_command(edge_conn, begin_type,
  2834. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  2835. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  2836. return -1; /* circuit is closed, don't continue */
  2837. edge_conn->package_window = STREAMWINDOW_START;
  2838. edge_conn->deliver_window = STREAMWINDOW_START;
  2839. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  2840. log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
  2841. ", n_circ_id %u",
  2842. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2843. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  2844. /* If there's queued-up data, send it now */
  2845. if ((connection_get_inbuf_len(base_conn) ||
  2846. ap_conn->sending_optimistic_data) &&
  2847. connection_ap_supports_optimistic_data(ap_conn)) {
  2848. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  2849. (long)connection_get_inbuf_len(base_conn),
  2850. ap_conn->sending_optimistic_data ?
  2851. (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
  2852. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  2853. connection_mark_for_close(base_conn);
  2854. }
  2855. }
  2856. return 0;
  2857. }
  2858. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  2859. * socks_request field, and send it down circ.
  2860. *
  2861. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2862. */
  2863. int
  2864. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  2865. {
  2866. int payload_len, command;
  2867. const char *string_addr;
  2868. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  2869. origin_circuit_t *circ;
  2870. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2871. connection_t *base_conn = TO_CONN(edge_conn);
  2872. tor_assert(edge_conn->on_circuit);
  2873. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2874. tor_assert(base_conn->type == CONN_TYPE_AP);
  2875. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2876. tor_assert(ap_conn->socks_request);
  2877. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  2878. command = ap_conn->socks_request->command;
  2879. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  2880. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2881. if (edge_conn->stream_id==0) {
  2882. /* XXXX+ Instead of closing this stream, we should make it get
  2883. * retried on another circuit. */
  2884. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2885. /* Mark this circuit "unusable for new streams". */
  2886. mark_circuit_unusable_for_new_conns(circ);
  2887. return -1;
  2888. }
  2889. if (command == SOCKS_COMMAND_RESOLVE) {
  2890. string_addr = ap_conn->socks_request->address;
  2891. payload_len = (int)strlen(string_addr)+1;
  2892. } else {
  2893. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  2894. const char *a = ap_conn->socks_request->address;
  2895. tor_addr_t addr;
  2896. int r;
  2897. /* We're doing a reverse lookup. The input could be an IP address, or
  2898. * could be an .in-addr.arpa or .ip6.arpa address */
  2899. r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
  2900. if (r <= 0) {
  2901. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  2902. safe_str_client(a));
  2903. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2904. return -1;
  2905. }
  2906. r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2907. if (r < 0) {
  2908. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2909. safe_str_client(a));
  2910. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2911. return -1;
  2912. }
  2913. string_addr = inaddr_buf;
  2914. payload_len = (int)strlen(inaddr_buf)+1;
  2915. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2916. }
  2917. log_debug(LD_APP,
  2918. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  2919. if (connection_edge_send_command(edge_conn,
  2920. RELAY_COMMAND_RESOLVE,
  2921. string_addr, payload_len) < 0)
  2922. return -1; /* circuit is closed, don't continue */
  2923. if (!base_conn->address) {
  2924. /* This might be unnecessary. XXXX */
  2925. base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
  2926. }
  2927. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  2928. log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
  2929. ", n_circ_id %u",
  2930. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2931. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2932. return 0;
  2933. }
  2934. /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
  2935. * new linked connection pair, and attach one side to the conn, connection_add
  2936. * it, initialize it to circuit_wait, and call
  2937. * connection_ap_handshake_attach_circuit(conn) on it.
  2938. *
  2939. * Return the newly created end of the linked connection pair, or -1 if error.
  2940. */
  2941. entry_connection_t *
  2942. connection_ap_make_link(connection_t *partner,
  2943. char *address, uint16_t port,
  2944. const char *digest,
  2945. int session_group, int isolation_flags,
  2946. int use_begindir, int want_onehop)
  2947. {
  2948. entry_connection_t *conn;
  2949. connection_t *base_conn;
  2950. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2951. want_onehop ? "direct" : "anonymized",
  2952. safe_str_client(address), port);
  2953. conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
  2954. base_conn = ENTRY_TO_CONN(conn);
  2955. base_conn->linked = 1; /* so that we can add it safely below. */
  2956. /* populate conn->socks_request */
  2957. /* leave version at zero, so the socks_reply is empty */
  2958. conn->socks_request->socks_version = 0;
  2959. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2960. strlcpy(conn->socks_request->address, address,
  2961. sizeof(conn->socks_request->address));
  2962. conn->socks_request->port = port;
  2963. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2964. conn->want_onehop = want_onehop;
  2965. conn->use_begindir = use_begindir;
  2966. if (use_begindir) {
  2967. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2968. conn->chosen_exit_name[0] = '$';
  2969. tor_assert(digest);
  2970. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2971. digest, DIGEST_LEN);
  2972. }
  2973. /* Populate isolation fields. */
  2974. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  2975. conn->original_dest_address = tor_strdup(address);
  2976. conn->entry_cfg.session_group = session_group;
  2977. conn->entry_cfg.isolation_flags = isolation_flags;
  2978. base_conn->address = tor_strdup("(Tor_internal)");
  2979. tor_addr_make_unspec(&base_conn->addr);
  2980. base_conn->port = 0;
  2981. connection_link_connections(partner, base_conn);
  2982. if (connection_add(base_conn) < 0) { /* no space, forget it */
  2983. connection_free(base_conn);
  2984. return NULL;
  2985. }
  2986. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2987. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2988. /* attaching to a dirty circuit is fine */
  2989. connection_ap_mark_as_pending_circuit(conn);
  2990. log_info(LD_APP,"... application connection created and linked.");
  2991. return conn;
  2992. }
  2993. /** Notify any interested controller connections about a new hostname resolve
  2994. * or resolve error. Takes the same arguments as does
  2995. * connection_ap_handshake_socks_resolved(). */
  2996. static void
  2997. tell_controller_about_resolved_result(entry_connection_t *conn,
  2998. int answer_type,
  2999. size_t answer_len,
  3000. const char *answer,
  3001. int ttl,
  3002. time_t expires)
  3003. {
  3004. expires = time(NULL) + ttl;
  3005. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  3006. char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
  3007. control_event_address_mapped(conn->socks_request->address,
  3008. cp, expires, NULL, 0);
  3009. tor_free(cp);
  3010. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3011. char *cp = tor_strndup(answer, answer_len);
  3012. control_event_address_mapped(conn->socks_request->address,
  3013. cp, expires, NULL, 0);
  3014. tor_free(cp);
  3015. } else {
  3016. control_event_address_mapped(conn->socks_request->address,
  3017. "<error>", time(NULL)+ttl,
  3018. "error=yes", 0);
  3019. }
  3020. }
  3021. /**
  3022. * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
  3023. * as the answer.
  3024. */
  3025. void
  3026. connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
  3027. const tor_addr_t *answer,
  3028. int ttl,
  3029. time_t expires)
  3030. {
  3031. if (tor_addr_family(answer) == AF_INET) {
  3032. uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
  3033. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  3034. (uint8_t*)&a,
  3035. ttl, expires);
  3036. } else if (tor_addr_family(answer) == AF_INET6) {
  3037. const uint8_t *a = tor_addr_to_in6_addr8(answer);
  3038. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
  3039. a,
  3040. ttl, expires);
  3041. } else {
  3042. log_warn(LD_BUG, "Got called with address of unexpected family %d",
  3043. tor_addr_family(answer));
  3044. connection_ap_handshake_socks_resolved(conn,
  3045. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  3046. }
  3047. }
  3048. /** Send an answer to an AP connection that has requested a DNS lookup via
  3049. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  3050. * for unreachable; the answer should be in the format specified in the socks
  3051. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  3052. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  3053. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  3054. **/
  3055. /* XXXX the use of the ttl and expires fields is nutty. Let's make this
  3056. * interface and those that use it less ugly. */
  3057. MOCK_IMPL(void,
  3058. connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
  3059. int answer_type,
  3060. size_t answer_len,
  3061. const uint8_t *answer,
  3062. int ttl,
  3063. time_t expires))
  3064. {
  3065. char buf[384];
  3066. size_t replylen;
  3067. if (ttl >= 0) {
  3068. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3069. tor_addr_t a;
  3070. tor_addr_from_ipv4n(&a, get_uint32(answer));
  3071. if (! tor_addr_is_null(&a)) {
  3072. client_dns_set_addressmap(conn,
  3073. conn->socks_request->address, &a,
  3074. conn->chosen_exit_name, ttl);
  3075. }
  3076. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  3077. tor_addr_t a;
  3078. tor_addr_from_ipv6_bytes(&a, (char*)answer);
  3079. if (! tor_addr_is_null(&a)) {
  3080. client_dns_set_addressmap(conn,
  3081. conn->socks_request->address, &a,
  3082. conn->chosen_exit_name, ttl);
  3083. }
  3084. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3085. char *cp = tor_strndup((char*)answer, answer_len);
  3086. client_dns_set_reverse_addressmap(conn,
  3087. conn->socks_request->address,
  3088. cp,
  3089. conn->chosen_exit_name, ttl);
  3090. tor_free(cp);
  3091. }
  3092. }
  3093. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  3094. if (conn->dns_server_request) {
  3095. /* We had a request on our DNS port: answer it. */
  3096. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  3097. conn->socks_request->has_finished = 1;
  3098. return;
  3099. } else {
  3100. /* This must be a request from the controller. Since answers to those
  3101. * requests are not cached, they do not generate an ADDRMAP event on
  3102. * their own. */
  3103. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  3104. (char*)answer, ttl, expires);
  3105. conn->socks_request->has_finished = 1;
  3106. return;
  3107. }
  3108. /* We shouldn't need to free conn here; it gets marked by the caller. */
  3109. }
  3110. if (conn->socks_request->socks_version == 4) {
  3111. buf[0] = 0x00; /* version */
  3112. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3113. buf[1] = SOCKS4_GRANTED;
  3114. set_uint16(buf+2, 0);
  3115. memcpy(buf+4, answer, 4); /* address */
  3116. replylen = SOCKS4_NETWORK_LEN;
  3117. } else { /* "error" */
  3118. buf[1] = SOCKS4_REJECT;
  3119. memset(buf+2, 0, 6);
  3120. replylen = SOCKS4_NETWORK_LEN;
  3121. }
  3122. } else if (conn->socks_request->socks_version == 5) {
  3123. /* SOCKS5 */
  3124. buf[0] = 0x05; /* version */
  3125. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  3126. buf[1] = SOCKS5_SUCCEEDED;
  3127. buf[2] = 0; /* reserved */
  3128. buf[3] = 0x01; /* IPv4 address type */
  3129. memcpy(buf+4, answer, 4); /* address */
  3130. set_uint16(buf+8, 0); /* port == 0. */
  3131. replylen = 10;
  3132. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  3133. buf[1] = SOCKS5_SUCCEEDED;
  3134. buf[2] = 0; /* reserved */
  3135. buf[3] = 0x04; /* IPv6 address type */
  3136. memcpy(buf+4, answer, 16); /* address */
  3137. set_uint16(buf+20, 0); /* port == 0. */
  3138. replylen = 22;
  3139. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  3140. buf[1] = SOCKS5_SUCCEEDED;
  3141. buf[2] = 0; /* reserved */
  3142. buf[3] = 0x03; /* Domainname address type */
  3143. buf[4] = (char)answer_len;
  3144. memcpy(buf+5, answer, answer_len); /* address */
  3145. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  3146. replylen = 5+answer_len+2;
  3147. } else {
  3148. buf[1] = SOCKS5_HOST_UNREACHABLE;
  3149. memset(buf+2, 0, 8);
  3150. replylen = 10;
  3151. }
  3152. } else {
  3153. /* no socks version info; don't send anything back */
  3154. return;
  3155. }
  3156. connection_ap_handshake_socks_reply(conn, buf, replylen,
  3157. (answer_type == RESOLVED_TYPE_IPV4 ||
  3158. answer_type == RESOLVED_TYPE_IPV6 ||
  3159. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  3160. 0 : END_STREAM_REASON_RESOLVEFAILED);
  3161. }
  3162. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  3163. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  3164. * handshaking.
  3165. *
  3166. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  3167. * and return, else reply based on <b>endreason</b> (one of
  3168. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  3169. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  3170. */
  3171. void
  3172. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  3173. size_t replylen, int endreason)
  3174. {
  3175. char buf[256];
  3176. socks5_reply_status_t status =
  3177. stream_end_reason_to_socks5_response(endreason);
  3178. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  3179. if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3180. control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
  3181. STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  3182. endreason);
  3183. }
  3184. /* Flag this stream's circuit as having completed a stream successfully
  3185. * (for path bias) */
  3186. if (status == SOCKS5_SUCCEEDED ||
  3187. endreason == END_STREAM_REASON_RESOLVEFAILED ||
  3188. endreason == END_STREAM_REASON_CONNECTREFUSED ||
  3189. endreason == END_STREAM_REASON_CONNRESET ||
  3190. endreason == END_STREAM_REASON_NOROUTE ||
  3191. endreason == END_STREAM_REASON_RESOURCELIMIT) {
  3192. if (!conn->edge_.on_circuit ||
  3193. !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
  3194. if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
  3195. log_info(LD_BUG,
  3196. "No origin circuit for successful SOCKS stream %"PRIu64
  3197. ". Reason: %d",
  3198. (ENTRY_TO_CONN(conn)->global_identifier),
  3199. endreason);
  3200. }
  3201. /*
  3202. * Else DNS remaps and failed hidden service lookups can send us
  3203. * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
  3204. *
  3205. * Perhaps we could make the test more precise; we can tell hidden
  3206. * services by conn->edge_.renddata != NULL; anything analogous for
  3207. * the DNS remap case?
  3208. */
  3209. } else {
  3210. // XXX: Hrmm. It looks like optimistic data can't go through this
  3211. // codepath, but someone should probably test it and make sure.
  3212. // We don't want to mark optimistically opened streams as successful.
  3213. pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
  3214. }
  3215. }
  3216. if (conn->socks_request->has_finished) {
  3217. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  3218. "connection_ap_handshake_socks_reply.");
  3219. return;
  3220. }
  3221. if (replylen) { /* we already have a reply in mind */
  3222. connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
  3223. conn->socks_request->has_finished = 1;
  3224. return;
  3225. }
  3226. if (conn->socks_request->listener_type ==
  3227. CONN_TYPE_AP_HTTP_CONNECT_LISTENER) {
  3228. const char *response = end_reason_to_http_connect_response_line(endreason);
  3229. if (!response) {
  3230. response = "HTTP/1.0 400 Bad Request\r\n\r\n";
  3231. }
  3232. connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
  3233. } else if (conn->socks_request->socks_version == 4) {
  3234. memset(buf,0,SOCKS4_NETWORK_LEN);
  3235. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  3236. /* leave version, destport, destip zero */
  3237. connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  3238. } else if (conn->socks_request->socks_version == 5) {
  3239. size_t buf_len;
  3240. memset(buf,0,sizeof(buf));
  3241. if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
  3242. buf[0] = 5; /* version 5 */
  3243. buf[1] = (char)status;
  3244. buf[2] = 0;
  3245. buf[3] = 1; /* ipv4 addr */
  3246. /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
  3247. buf_len = 10;
  3248. } else { /* AF_INET6. */
  3249. buf[0] = 5; /* version 5 */
  3250. buf[1] = (char)status;
  3251. buf[2] = 0;
  3252. buf[3] = 4; /* ipv6 addr */
  3253. /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
  3254. buf_len = 22;
  3255. }
  3256. connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
  3257. }
  3258. /* If socks_version isn't 4 or 5, don't send anything.
  3259. * This can happen in the case of AP bridges. */
  3260. conn->socks_request->has_finished = 1;
  3261. return;
  3262. }
  3263. /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
  3264. * place the result in <b>bcell</b>. On success return 0; on failure return
  3265. * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
  3266. * the client.
  3267. *
  3268. * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
  3269. * we don't.
  3270. **/
  3271. STATIC int
  3272. begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
  3273. uint8_t *end_reason_out)
  3274. {
  3275. relay_header_t rh;
  3276. const uint8_t *body, *nul;
  3277. memset(bcell, 0, sizeof(*bcell));
  3278. *end_reason_out = END_STREAM_REASON_MISC;
  3279. relay_header_unpack(&rh, cell->payload);
  3280. if (rh.length > RELAY_PAYLOAD_SIZE) {
  3281. return -2; /*XXXX why not TORPROTOCOL? */
  3282. }
  3283. bcell->stream_id = rh.stream_id;
  3284. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3285. bcell->is_begindir = 1;
  3286. return 0;
  3287. } else if (rh.command != RELAY_COMMAND_BEGIN) {
  3288. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  3289. *end_reason_out = END_STREAM_REASON_INTERNAL;
  3290. return -1;
  3291. }
  3292. body = cell->payload + RELAY_HEADER_SIZE;
  3293. nul = memchr(body, 0, rh.length);
  3294. if (! nul) {
  3295. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3296. "Relay begin cell has no \\0. Closing.");
  3297. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3298. return -1;
  3299. }
  3300. if (tor_addr_port_split(LOG_PROTOCOL_WARN,
  3301. (char*)(body),
  3302. &bcell->address,&bcell->port)<0) {
  3303. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3304. "Unable to parse addr:port in relay begin cell. Closing.");
  3305. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3306. return -1;
  3307. }
  3308. if (bcell->port == 0) {
  3309. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3310. "Missing port in relay begin cell. Closing.");
  3311. tor_free(bcell->address);
  3312. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  3313. return -1;
  3314. }
  3315. if (body + rh.length >= nul + 4)
  3316. bcell->flags = ntohl(get_uint32(nul+1));
  3317. return 0;
  3318. }
  3319. /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
  3320. * connection, attach it to the circ and connect it. Return 0 on success
  3321. * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
  3322. * where the caller should close the circuit. */
  3323. static int
  3324. handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
  3325. {
  3326. int ret;
  3327. origin_circuit_t *origin_circ;
  3328. assert_circuit_ok(circ);
  3329. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3330. tor_assert(conn);
  3331. log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
  3332. "to the service destination.");
  3333. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3334. conn->base_.address = tor_strdup("(rendezvous)");
  3335. conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  3336. /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
  3337. * service. */
  3338. if (origin_circ->rend_data) {
  3339. conn->rend_data = rend_data_dup(origin_circ->rend_data);
  3340. tor_assert(connection_edge_is_rendezvous_stream(conn));
  3341. ret = rend_service_set_connection_addr_port(conn, origin_circ);
  3342. } else if (origin_circ->hs_ident) {
  3343. /* Setup the identifier to be the one for the circuit service. */
  3344. conn->hs_ident =
  3345. hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
  3346. tor_assert(connection_edge_is_rendezvous_stream(conn));
  3347. ret = hs_service_set_conn_addr_port(origin_circ, conn);
  3348. } else {
  3349. /* We should never get here if the circuit's purpose is rendezvous. */
  3350. tor_assert_nonfatal_unreached();
  3351. return -1;
  3352. }
  3353. if (ret < 0) {
  3354. log_info(LD_REND, "Didn't find rendezvous service (addr%s, port %d)",
  3355. fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
  3356. /* Send back reason DONE because we want to make hidden service port
  3357. * scanning harder thus instead of returning that the exit policy
  3358. * didn't match, which makes it obvious that the port is closed,
  3359. * return DONE and kill the circuit. That way, a user (malicious or
  3360. * not) needs one circuit per bad port unless it matches the policy of
  3361. * the hidden service. */
  3362. relay_send_end_cell_from_edge(conn->stream_id, circ,
  3363. END_STREAM_REASON_DONE,
  3364. origin_circ->cpath->prev);
  3365. connection_free_(TO_CONN(conn));
  3366. /* Drop the circuit here since it might be someone deliberately
  3367. * scanning the hidden service ports. Note that this mitigates port
  3368. * scanning by adding more work on the attacker side to successfully
  3369. * scan but does not fully solve it. */
  3370. if (ret < -1) {
  3371. return END_CIRC_AT_ORIGIN;
  3372. } else {
  3373. return 0;
  3374. }
  3375. }
  3376. /* Link the circuit and the connection crypt path. */
  3377. conn->cpath_layer = origin_circ->cpath->prev;
  3378. /* If this is the first stream on this circuit, tell circpad */
  3379. if (!origin_circ->p_streams)
  3380. circpad_machine_event_circ_has_streams(origin_circ);
  3381. /* Add it into the linked list of p_streams on this circuit */
  3382. conn->next_stream = origin_circ->p_streams;
  3383. origin_circ->p_streams = conn;
  3384. conn->on_circuit = circ;
  3385. assert_circuit_ok(circ);
  3386. hs_inc_rdv_stream_counter(origin_circ);
  3387. /* If it's an onion service connection, we might want to include the proxy
  3388. * protocol header: */
  3389. if (conn->hs_ident) {
  3390. hs_circuit_id_protocol_t circuit_id_protocol =
  3391. hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
  3392. export_hs_client_circuit_id(conn, circuit_id_protocol);
  3393. }
  3394. /* Connect tor to the hidden service destination. */
  3395. connection_exit_connect(conn);
  3396. /* For path bias: This circuit was used successfully */
  3397. pathbias_mark_use_success(origin_circ);
  3398. return 0;
  3399. }
  3400. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  3401. * an exit hop for the circuit, or we are the origin and it is a
  3402. * rendezvous begin.
  3403. *
  3404. * Launch a new exit connection and initialize things appropriately.
  3405. *
  3406. * If it's a rendezvous stream, call connection_exit_connect() on
  3407. * it.
  3408. *
  3409. * For general streams, call dns_resolve() on it first, and only call
  3410. * connection_exit_connect() if the dns answer is already known.
  3411. *
  3412. * Note that we don't call connection_add() on the new stream! We wait
  3413. * for connection_exit_connect() to do that.
  3414. *
  3415. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  3416. * Else return 0.
  3417. */
  3418. int
  3419. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  3420. {
  3421. edge_connection_t *n_stream;
  3422. relay_header_t rh;
  3423. char *address = NULL;
  3424. uint16_t port = 0;
  3425. or_circuit_t *or_circ = NULL;
  3426. origin_circuit_t *origin_circ = NULL;
  3427. crypt_path_t *layer_hint = NULL;
  3428. const or_options_t *options = get_options();
  3429. begin_cell_t bcell;
  3430. int rv;
  3431. uint8_t end_reason=0;
  3432. assert_circuit_ok(circ);
  3433. if (!CIRCUIT_IS_ORIGIN(circ)) {
  3434. or_circ = TO_OR_CIRCUIT(circ);
  3435. } else {
  3436. tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3437. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3438. layer_hint = origin_circ->cpath->prev;
  3439. }
  3440. relay_header_unpack(&rh, cell->payload);
  3441. if (rh.length > RELAY_PAYLOAD_SIZE)
  3442. return -END_CIRC_REASON_TORPROTOCOL;
  3443. if (!server_mode(options) &&
  3444. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  3445. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3446. "Relay begin cell at non-server. Closing.");
  3447. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3448. END_STREAM_REASON_EXITPOLICY, NULL);
  3449. return 0;
  3450. }
  3451. rv = begin_cell_parse(cell, &bcell, &end_reason);
  3452. if (rv < -1) {
  3453. return -END_CIRC_REASON_TORPROTOCOL;
  3454. } else if (rv == -1) {
  3455. tor_free(bcell.address);
  3456. relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
  3457. return 0;
  3458. }
  3459. if (! bcell.is_begindir) {
  3460. /* Steal reference */
  3461. tor_assert(bcell.address);
  3462. address = bcell.address;
  3463. port = bcell.port;
  3464. if (or_circ && or_circ->p_chan) {
  3465. const int client_chan = channel_is_client(or_circ->p_chan);
  3466. if ((client_chan ||
  3467. (!connection_or_digest_is_known_relay(
  3468. or_circ->p_chan->identity_digest) &&
  3469. should_refuse_unknown_exits(options)))) {
  3470. /* Don't let clients use us as a single-hop proxy. It attracts
  3471. * attackers and users who'd be better off with, well, single-hop
  3472. * proxies. */
  3473. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3474. "Attempt by %s to open a stream %s. Closing.",
  3475. safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
  3476. client_chan ? "on first hop of circuit" :
  3477. "from unknown relay");
  3478. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3479. client_chan ?
  3480. END_STREAM_REASON_TORPROTOCOL :
  3481. END_STREAM_REASON_MISC,
  3482. NULL);
  3483. tor_free(address);
  3484. return 0;
  3485. }
  3486. }
  3487. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3488. if (!directory_permits_begindir_requests(options) ||
  3489. circ->purpose != CIRCUIT_PURPOSE_OR) {
  3490. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3491. END_STREAM_REASON_NOTDIRECTORY, layer_hint);
  3492. return 0;
  3493. }
  3494. /* Make sure to get the 'real' address of the previous hop: the
  3495. * caller might want to know whether the remote IP address has changed,
  3496. * and we might already have corrected base_.addr[ess] for the relay's
  3497. * canonical IP address. */
  3498. if (or_circ && or_circ->p_chan)
  3499. address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
  3500. else
  3501. address = tor_strdup("127.0.0.1");
  3502. port = 1; /* XXXX This value is never actually used anywhere, and there
  3503. * isn't "really" a connection here. But we
  3504. * need to set it to something nonzero. */
  3505. } else {
  3506. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  3507. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3508. END_STREAM_REASON_INTERNAL, layer_hint);
  3509. return 0;
  3510. }
  3511. if (! options->IPv6Exit) {
  3512. /* I don't care if you prefer IPv6; I can't give you any. */
  3513. bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
  3514. /* If you don't want IPv4, I can't help. */
  3515. if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
  3516. tor_free(address);
  3517. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3518. END_STREAM_REASON_EXITPOLICY, layer_hint);
  3519. return 0;
  3520. }
  3521. }
  3522. log_debug(LD_EXIT,"Creating new exit connection.");
  3523. /* The 'AF_INET' here is temporary; we might need to change it later in
  3524. * connection_exit_connect(). */
  3525. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  3526. /* Remember the tunneled request ID in the new edge connection, so that
  3527. * we can measure download times. */
  3528. n_stream->dirreq_id = circ->dirreq_id;
  3529. n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
  3530. n_stream->begincell_flags = bcell.flags;
  3531. n_stream->stream_id = rh.stream_id;
  3532. n_stream->base_.port = port;
  3533. /* leave n_stream->s at -1, because it's not yet valid */
  3534. n_stream->package_window = STREAMWINDOW_START;
  3535. n_stream->deliver_window = STREAMWINDOW_START;
  3536. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  3537. int ret;
  3538. tor_free(address);
  3539. /* We handle this circuit and stream in this function for all supported
  3540. * hidden service version. */
  3541. ret = handle_hs_exit_conn(circ, n_stream);
  3542. if (ret == 0) {
  3543. /* This was a valid cell. Count it as delivered + overhead. */
  3544. circuit_read_valid_data(origin_circ, rh.length);
  3545. }
  3546. return ret;
  3547. }
  3548. tor_strlower(address);
  3549. n_stream->base_.address = address;
  3550. n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  3551. /* default to failed, change in dns_resolve if it turns out not to fail */
  3552. /* If we're hibernating or shutting down, we refuse to open new streams. */
  3553. if (we_are_hibernating()) {
  3554. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3555. END_STREAM_REASON_HIBERNATING, NULL);
  3556. connection_free_(TO_CONN(n_stream));
  3557. return 0;
  3558. }
  3559. n_stream->on_circuit = circ;
  3560. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  3561. tor_addr_t tmp_addr;
  3562. tor_assert(or_circ);
  3563. if (or_circ->p_chan &&
  3564. channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
  3565. tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
  3566. }
  3567. return connection_exit_connect_dir(n_stream);
  3568. }
  3569. log_debug(LD_EXIT,"about to start the dns_resolve().");
  3570. /* send it off to the gethostbyname farm */
  3571. switch (dns_resolve(n_stream)) {
  3572. case 1: /* resolve worked; now n_stream is attached to circ. */
  3573. assert_circuit_ok(circ);
  3574. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  3575. connection_exit_connect(n_stream);
  3576. return 0;
  3577. case -1: /* resolve failed */
  3578. relay_send_end_cell_from_edge(rh.stream_id, circ,
  3579. END_STREAM_REASON_RESOLVEFAILED, NULL);
  3580. /* n_stream got freed. don't touch it. */
  3581. break;
  3582. case 0: /* resolve added to pending list */
  3583. assert_circuit_ok(circ);
  3584. break;
  3585. }
  3586. return 0;
  3587. }
  3588. /**
  3589. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  3590. * circuit <b>circ</b>;
  3591. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  3592. */
  3593. int
  3594. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  3595. {
  3596. edge_connection_t *dummy_conn;
  3597. relay_header_t rh;
  3598. assert_circuit_ok(TO_CIRCUIT(circ));
  3599. relay_header_unpack(&rh, cell->payload);
  3600. if (rh.length > RELAY_PAYLOAD_SIZE)
  3601. return -1;
  3602. /* This 'dummy_conn' only exists to remember the stream ID
  3603. * associated with the resolve request; and to make the
  3604. * implementation of dns.c more uniform. (We really only need to
  3605. * remember the circuit, the stream ID, and the hostname to be
  3606. * resolved; but if we didn't store them in a connection like this,
  3607. * the housekeeping in dns.c would get way more complicated.)
  3608. */
  3609. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  3610. dummy_conn->stream_id = rh.stream_id;
  3611. dummy_conn->base_.address = tor_strndup(
  3612. (char*)cell->payload+RELAY_HEADER_SIZE,
  3613. rh.length);
  3614. dummy_conn->base_.port = 0;
  3615. dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  3616. dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
  3617. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  3618. /* send it off to the gethostbyname farm */
  3619. switch (dns_resolve(dummy_conn)) {
  3620. case -1: /* Impossible to resolve; a resolved cell was sent. */
  3621. /* Connection freed; don't touch it. */
  3622. return 0;
  3623. case 1: /* The result was cached; a resolved cell was sent. */
  3624. if (!dummy_conn->base_.marked_for_close)
  3625. connection_free_(TO_CONN(dummy_conn));
  3626. return 0;
  3627. case 0: /* resolve added to pending list */
  3628. assert_circuit_ok(TO_CIRCUIT(circ));
  3629. break;
  3630. }
  3631. return 0;
  3632. }
  3633. /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
  3634. * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
  3635. */
  3636. static int
  3637. my_exit_policy_rejects(const tor_addr_t *addr,
  3638. uint16_t port,
  3639. const char **why_rejected)
  3640. {
  3641. if (router_compare_to_my_exit_policy(addr, port)) {
  3642. *why_rejected = "";
  3643. return 1;
  3644. } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
  3645. *why_rejected = " (IPv6 address without IPv6Exit configured)";
  3646. return 1;
  3647. }
  3648. return 0;
  3649. }
  3650. /** Connect to conn's specified addr and port. If it worked, conn
  3651. * has now been added to the connection_array.
  3652. *
  3653. * Send back a connected cell. Include the resolved IP of the destination
  3654. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  3655. * streams must not reveal what IP they connected to.)
  3656. */
  3657. void
  3658. connection_exit_connect(edge_connection_t *edge_conn)
  3659. {
  3660. const tor_addr_t *addr;
  3661. uint16_t port;
  3662. connection_t *conn = TO_CONN(edge_conn);
  3663. int socket_error = 0, result;
  3664. const char *why_failed_exit_policy = NULL;
  3665. /* Apply exit policy to non-rendezvous connections. */
  3666. if (! connection_edge_is_rendezvous_stream(edge_conn) &&
  3667. my_exit_policy_rejects(&edge_conn->base_.addr,
  3668. edge_conn->base_.port,
  3669. &why_failed_exit_policy)) {
  3670. if (BUG(!why_failed_exit_policy))
  3671. why_failed_exit_policy = "";
  3672. log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
  3673. escaped_safe_str_client(conn->address), conn->port,
  3674. why_failed_exit_policy);
  3675. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  3676. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3677. connection_free(conn);
  3678. return;
  3679. }
  3680. #ifdef HAVE_SYS_UN_H
  3681. if (conn->socket_family != AF_UNIX) {
  3682. #else
  3683. {
  3684. #endif /* defined(HAVE_SYS_UN_H) */
  3685. addr = &conn->addr;
  3686. port = conn->port;
  3687. if (tor_addr_family(addr) == AF_INET6)
  3688. conn->socket_family = AF_INET6;
  3689. log_debug(LD_EXIT, "about to try connecting");
  3690. result = connection_connect(conn, conn->address,
  3691. addr, port, &socket_error);
  3692. #ifdef HAVE_SYS_UN_H
  3693. } else {
  3694. /*
  3695. * In the AF_UNIX case, we expect to have already had conn->port = 1,
  3696. * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
  3697. * case in connection_handle_listener_read()), and conn->address should
  3698. * have the socket path to connect to.
  3699. */
  3700. tor_assert(conn->address && strlen(conn->address) > 0);
  3701. log_debug(LD_EXIT, "about to try connecting");
  3702. result = connection_connect_unix(conn, conn->address, &socket_error);
  3703. #endif /* defined(HAVE_SYS_UN_H) */
  3704. }
  3705. switch (result) {
  3706. case -1: {
  3707. int reason = errno_to_stream_end_reason(socket_error);
  3708. connection_edge_end(edge_conn, reason);
  3709. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3710. connection_free(conn);
  3711. return;
  3712. }
  3713. case 0:
  3714. conn->state = EXIT_CONN_STATE_CONNECTING;
  3715. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  3716. /* writable indicates finish;
  3717. * readable/error indicates broken link in windows-land. */
  3718. return;
  3719. /* case 1: fall through */
  3720. }
  3721. conn->state = EXIT_CONN_STATE_OPEN;
  3722. if (connection_get_outbuf_len(conn)) {
  3723. /* in case there are any queued data cells, from e.g. optimistic data */
  3724. connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
  3725. } else {
  3726. connection_watch_events(conn, READ_EVENT);
  3727. }
  3728. /* also, deliver a 'connected' cell back through the circuit. */
  3729. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  3730. /* don't send an address back! */
  3731. connection_edge_send_command(edge_conn,
  3732. RELAY_COMMAND_CONNECTED,
  3733. NULL, 0);
  3734. } else { /* normal stream */
  3735. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  3736. int connected_payload_len =
  3737. connected_cell_format_payload(connected_payload, &conn->addr,
  3738. edge_conn->address_ttl);
  3739. if (connected_payload_len < 0) {
  3740. connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
  3741. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3742. connection_free(conn);
  3743. return;
  3744. }
  3745. connection_edge_send_command(edge_conn,
  3746. RELAY_COMMAND_CONNECTED,
  3747. (char*)connected_payload,
  3748. connected_payload_len);
  3749. }
  3750. }
  3751. /** Given an exit conn that should attach to us as a directory server, open a
  3752. * bridge connection with a linked connection pair, create a new directory
  3753. * conn, and join them together. Return 0 on success (or if there was an
  3754. * error we could send back an end cell for). Return -(some circuit end
  3755. * reason) if the circuit needs to be torn down. Either connects
  3756. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  3757. */
  3758. static int
  3759. connection_exit_connect_dir(edge_connection_t *exitconn)
  3760. {
  3761. dir_connection_t *dirconn = NULL;
  3762. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  3763. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  3764. exitconn->base_.state = EXIT_CONN_STATE_OPEN;
  3765. dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
  3766. tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
  3767. dirconn->base_.port = 0;
  3768. dirconn->base_.address = tor_strdup(exitconn->base_.address);
  3769. dirconn->base_.type = CONN_TYPE_DIR;
  3770. dirconn->base_.purpose = DIR_PURPOSE_SERVER;
  3771. dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  3772. /* Note that the new dir conn belongs to the same tunneled request as
  3773. * the edge conn, so that we can measure download times. */
  3774. dirconn->dirreq_id = exitconn->dirreq_id;
  3775. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  3776. if (connection_add(TO_CONN(exitconn))<0) {
  3777. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3778. connection_free_(TO_CONN(exitconn));
  3779. connection_free_(TO_CONN(dirconn));
  3780. return 0;
  3781. }
  3782. /* link exitconn to circ, now that we know we can use it. */
  3783. exitconn->next_stream = circ->n_streams;
  3784. circ->n_streams = exitconn;
  3785. if (connection_add(TO_CONN(dirconn))<0) {
  3786. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3787. connection_close_immediate(TO_CONN(exitconn));
  3788. connection_mark_for_close(TO_CONN(exitconn));
  3789. connection_free_(TO_CONN(dirconn));
  3790. return 0;
  3791. }
  3792. connection_start_reading(TO_CONN(dirconn));
  3793. connection_start_reading(TO_CONN(exitconn));
  3794. if (connection_edge_send_command(exitconn,
  3795. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  3796. connection_mark_for_close(TO_CONN(exitconn));
  3797. connection_mark_for_close(TO_CONN(dirconn));
  3798. return 0;
  3799. }
  3800. return 0;
  3801. }
  3802. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  3803. * it is a general stream.
  3804. */
  3805. int
  3806. connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
  3807. {
  3808. tor_assert(conn);
  3809. /* It should not be possible to set both of these structs */
  3810. tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
  3811. if (conn->rend_data || conn->hs_ident) {
  3812. return 1;
  3813. }
  3814. return 0;
  3815. }
  3816. /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
  3817. * to exit from it, or 0 if it probably will not allow it.
  3818. * (We might be uncertain if conn's destination address has not yet been
  3819. * resolved.)
  3820. */
  3821. int
  3822. connection_ap_can_use_exit(const entry_connection_t *conn,
  3823. const node_t *exit_node)
  3824. {
  3825. const or_options_t *options = get_options();
  3826. tor_assert(conn);
  3827. tor_assert(conn->socks_request);
  3828. tor_assert(exit_node);
  3829. /* If a particular exit node has been requested for the new connection,
  3830. * make sure the exit node of the existing circuit matches exactly.
  3831. */
  3832. if (conn->chosen_exit_name) {
  3833. const node_t *chosen_exit =
  3834. node_get_by_nickname(conn->chosen_exit_name, 0);
  3835. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  3836. exit_node->identity, DIGEST_LEN)) {
  3837. /* doesn't match */
  3838. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  3839. // conn->chosen_exit_name, exit->nickname);
  3840. return 0;
  3841. }
  3842. }
  3843. if (conn->use_begindir) {
  3844. /* Internal directory fetches do not count as exiting. */
  3845. return 1;
  3846. }
  3847. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  3848. tor_addr_t addr, *addrp = NULL;
  3849. addr_policy_result_t r;
  3850. if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
  3851. addrp = &addr;
  3852. } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
  3853. tor_addr_make_null(&addr, AF_INET6);
  3854. addrp = &addr;
  3855. } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
  3856. tor_addr_make_null(&addr, AF_INET);
  3857. addrp = &addr;
  3858. }
  3859. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
  3860. exit_node);
  3861. if (r == ADDR_POLICY_REJECTED)
  3862. return 0; /* We know the address, and the exit policy rejects it. */
  3863. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  3864. return 0; /* We don't know the addr, but the exit policy rejects most
  3865. * addresses with this port. Since the user didn't ask for
  3866. * this node, err on the side of caution. */
  3867. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3868. /* Don't send DNS requests to non-exit servers by default. */
  3869. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
  3870. return 0;
  3871. }
  3872. if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
  3873. /* Not a suitable exit. Refuse it. */
  3874. return 0;
  3875. }
  3876. return 1;
  3877. }
  3878. /** If address is of the form "y.onion" with a well-formed handle y:
  3879. * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
  3880. * ONION_V3_HOSTNAME depending on the HS version.
  3881. *
  3882. * If address is of the form "x.y.onion" with a well-formed handle x:
  3883. * Drop "x.", put a NUL after y, lower-case it, and return
  3884. * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
  3885. *
  3886. * If address is of the form "y.onion" with a badly-formed handle y:
  3887. * Return BAD_HOSTNAME and log a message.
  3888. *
  3889. * If address is of the form "y.exit":
  3890. * Put a NUL after y and return EXIT_HOSTNAME.
  3891. *
  3892. * Otherwise:
  3893. * Return NORMAL_HOSTNAME and change nothing.
  3894. */
  3895. hostname_type_t
  3896. parse_extended_hostname(char *address)
  3897. {
  3898. char *s;
  3899. char *q;
  3900. char query[HS_SERVICE_ADDR_LEN_BASE32+1];
  3901. s = strrchr(address,'.');
  3902. if (!s)
  3903. return NORMAL_HOSTNAME; /* no dot, thus normal */
  3904. if (!strcmp(s+1,"exit")) {
  3905. *s = 0; /* NUL-terminate it */
  3906. return EXIT_HOSTNAME; /* .exit */
  3907. }
  3908. if (strcmp(s+1,"onion"))
  3909. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  3910. /* so it is .onion */
  3911. *s = 0; /* NUL-terminate it */
  3912. /* locate a 'sub-domain' component, in order to remove it */
  3913. q = strrchr(address, '.');
  3914. if (q == address) {
  3915. goto failed; /* reject sub-domain, as DNS does */
  3916. }
  3917. q = (NULL == q) ? address : q + 1;
  3918. if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
  3919. HS_SERVICE_ADDR_LEN_BASE32+1)
  3920. goto failed;
  3921. if (q != address) {
  3922. memmove(address, q, strlen(q) + 1 /* also get \0 */);
  3923. }
  3924. if (rend_valid_v2_service_id(query)) {
  3925. return ONION_V2_HOSTNAME; /* success */
  3926. }
  3927. if (hs_address_is_valid(query)) {
  3928. return ONION_V3_HOSTNAME;
  3929. }
  3930. failed:
  3931. /* otherwise, return to previous state and return 0 */
  3932. *s = '.';
  3933. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  3934. safe_str_client(address));
  3935. return BAD_HOSTNAME;
  3936. }
  3937. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  3938. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  3939. * at <b>b</b>. */
  3940. static int
  3941. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  3942. {
  3943. if (a == NULL) {
  3944. return (b == NULL);
  3945. } else if (b == NULL) {
  3946. return 0;
  3947. } else if (alen != blen) {
  3948. return 0;
  3949. } else {
  3950. return tor_memeq(a, b, alen);
  3951. }
  3952. }
  3953. /**
  3954. * Return true iff none of the isolation flags and fields in <b>conn</b>
  3955. * should prevent it from being attached to <b>circ</b>.
  3956. */
  3957. int
  3958. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  3959. const origin_circuit_t *circ)
  3960. {
  3961. const uint8_t iso = conn->entry_cfg.isolation_flags;
  3962. const socks_request_t *sr = conn->socks_request;
  3963. /* If circ has never been used for an isolated connection, we can
  3964. * totally use it for this one. */
  3965. if (!circ->isolation_values_set)
  3966. return 1;
  3967. /* If circ has been used for connections having more than one value
  3968. * for some field f, it will have the corresponding bit set in
  3969. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  3970. * in common with iso, then conn must be isolated from at least
  3971. * one stream that has been attached to circ. */
  3972. if ((iso & circ->isolation_flags_mixed) != 0) {
  3973. /* For at least one field where conn is isolated, the circuit
  3974. * already has mixed streams. */
  3975. return 0;
  3976. }
  3977. if (! conn->original_dest_address) {
  3978. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  3979. "having set conn->original_dest_address");
  3980. ((entry_connection_t*)conn)->original_dest_address =
  3981. tor_strdup(conn->socks_request->address);
  3982. }
  3983. if ((iso & ISO_STREAM) &&
  3984. (circ->associated_isolated_stream_global_id !=
  3985. ENTRY_TO_CONN(conn)->global_identifier))
  3986. return 0;
  3987. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  3988. return 0;
  3989. if ((iso & ISO_DESTADDR) &&
  3990. strcasecmp(conn->original_dest_address, circ->dest_address))
  3991. return 0;
  3992. if ((iso & ISO_SOCKSAUTH) &&
  3993. (! memeq_opt(sr->username, sr->usernamelen,
  3994. circ->socks_username, circ->socks_username_len) ||
  3995. ! memeq_opt(sr->password, sr->passwordlen,
  3996. circ->socks_password, circ->socks_password_len)))
  3997. return 0;
  3998. if ((iso & ISO_CLIENTPROTO) &&
  3999. (conn->socks_request->listener_type != circ->client_proto_type ||
  4000. conn->socks_request->socks_version != circ->client_proto_socksver))
  4001. return 0;
  4002. if ((iso & ISO_CLIENTADDR) &&
  4003. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  4004. return 0;
  4005. if ((iso & ISO_SESSIONGRP) &&
  4006. conn->entry_cfg.session_group != circ->session_group)
  4007. return 0;
  4008. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  4009. return 0;
  4010. return 1;
  4011. }
  4012. /**
  4013. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  4014. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  4015. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  4016. * a bitfield of isolation flags that we would have to set in
  4017. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  4018. * <b>circ</b> has had no streams attached to it.
  4019. */
  4020. int
  4021. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  4022. origin_circuit_t *circ,
  4023. int dry_run)
  4024. {
  4025. const socks_request_t *sr = conn->socks_request;
  4026. if (! conn->original_dest_address) {
  4027. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  4028. "having set conn->original_dest_address");
  4029. ((entry_connection_t*)conn)->original_dest_address =
  4030. tor_strdup(conn->socks_request->address);
  4031. }
  4032. if (!circ->isolation_values_set) {
  4033. if (dry_run)
  4034. return -1;
  4035. circ->associated_isolated_stream_global_id =
  4036. ENTRY_TO_CONN(conn)->global_identifier;
  4037. circ->dest_port = conn->socks_request->port;
  4038. circ->dest_address = tor_strdup(conn->original_dest_address);
  4039. circ->client_proto_type = conn->socks_request->listener_type;
  4040. circ->client_proto_socksver = conn->socks_request->socks_version;
  4041. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  4042. circ->session_group = conn->entry_cfg.session_group;
  4043. circ->nym_epoch = conn->nym_epoch;
  4044. circ->socks_username = sr->username ?
  4045. tor_memdup(sr->username, sr->usernamelen) : NULL;
  4046. circ->socks_password = sr->password ?
  4047. tor_memdup(sr->password, sr->passwordlen) : NULL;
  4048. circ->socks_username_len = sr->usernamelen;
  4049. circ->socks_password_len = sr->passwordlen;
  4050. circ->isolation_values_set = 1;
  4051. return 0;
  4052. } else {
  4053. uint8_t mixed = 0;
  4054. if (conn->socks_request->port != circ->dest_port)
  4055. mixed |= ISO_DESTPORT;
  4056. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  4057. mixed |= ISO_DESTADDR;
  4058. if (!memeq_opt(sr->username, sr->usernamelen,
  4059. circ->socks_username, circ->socks_username_len) ||
  4060. !memeq_opt(sr->password, sr->passwordlen,
  4061. circ->socks_password, circ->socks_password_len))
  4062. mixed |= ISO_SOCKSAUTH;
  4063. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  4064. conn->socks_request->socks_version != circ->client_proto_socksver))
  4065. mixed |= ISO_CLIENTPROTO;
  4066. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  4067. mixed |= ISO_CLIENTADDR;
  4068. if (conn->entry_cfg.session_group != circ->session_group)
  4069. mixed |= ISO_SESSIONGRP;
  4070. if (conn->nym_epoch != circ->nym_epoch)
  4071. mixed |= ISO_NYM_EPOCH;
  4072. if (dry_run)
  4073. return mixed;
  4074. if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
  4075. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  4076. "isolation flags.");
  4077. }
  4078. circ->isolation_flags_mixed |= mixed;
  4079. return 0;
  4080. }
  4081. }
  4082. /**
  4083. * Clear the isolation settings on <b>circ</b>.
  4084. *
  4085. * This only works on an open circuit that has never had a stream attached to
  4086. * it, and whose isolation settings are hypothetical. (We set hypothetical
  4087. * isolation settings on circuits as we're launching them, so that we
  4088. * know whether they can handle more streams or whether we need to launch
  4089. * even more circuits. Once the circuit is open, if it turns out that
  4090. * we no longer have any streams to attach to it, we clear the isolation flags
  4091. * and data so that other streams can have a chance.)
  4092. */
  4093. void
  4094. circuit_clear_isolation(origin_circuit_t *circ)
  4095. {
  4096. if (circ->isolation_any_streams_attached) {
  4097. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  4098. return;
  4099. }
  4100. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  4101. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  4102. "circuit");
  4103. return;
  4104. }
  4105. circ->isolation_values_set = 0;
  4106. circ->isolation_flags_mixed = 0;
  4107. circ->associated_isolated_stream_global_id = 0;
  4108. circ->client_proto_type = 0;
  4109. circ->client_proto_socksver = 0;
  4110. circ->dest_port = 0;
  4111. tor_addr_make_unspec(&circ->client_addr);
  4112. tor_free(circ->dest_address);
  4113. circ->session_group = -1;
  4114. circ->nym_epoch = 0;
  4115. if (circ->socks_username) {
  4116. memwipe(circ->socks_username, 0x11, circ->socks_username_len);
  4117. tor_free(circ->socks_username);
  4118. }
  4119. if (circ->socks_password) {
  4120. memwipe(circ->socks_password, 0x05, circ->socks_password_len);
  4121. tor_free(circ->socks_password);
  4122. }
  4123. circ->socks_username_len = circ->socks_password_len = 0;
  4124. }
  4125. /** Send an END and mark for close the given edge connection conn using the
  4126. * given reason that has to be a stream reason.
  4127. *
  4128. * Note: We don't unattached the AP connection (if applicable) because we
  4129. * don't want to flush the remaining data. This function aims at ending
  4130. * everything quickly regardless of the connection state.
  4131. *
  4132. * This function can't fail and does nothing if conn is NULL. */
  4133. void
  4134. connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
  4135. {
  4136. if (!conn) {
  4137. return;
  4138. }
  4139. connection_edge_end(conn, reason);
  4140. connection_mark_for_close(TO_CONN(conn));
  4141. }
  4142. /** Free all storage held in module-scoped variables for connection_edge.c */
  4143. void
  4144. connection_edge_free_all(void)
  4145. {
  4146. untried_pending_connections = 0;
  4147. smartlist_free(pending_entry_connections);
  4148. pending_entry_connections = NULL;
  4149. mainloop_event_free(attach_pending_entry_connections_ev);
  4150. }