connection_edge.c 164 KB

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