connection.c 195 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809
  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.c
  8. * \brief General high-level functions to handle reading and writing
  9. * on connections.
  10. *
  11. * Each connection (ideally) represents a TLS connection, a TCP socket, a unix
  12. * socket, or a UDP socket on which reads and writes can occur. (But see
  13. * connection_edge.c for cases where connections can also represent streams
  14. * that do not have a corresponding socket.)
  15. *
  16. * The module implements the abstract type, connection_t. The subtypes are:
  17. * <ul>
  18. * <li>listener_connection_t, implemented here in connection.c
  19. * <li>dir_connection_t, implemented in directory.c
  20. * <li>or_connection_t, implemented in connection_or.c
  21. * <li>edge_connection_t, implemented in connection_edge.c, along with
  22. * its subtype(s):
  23. * <ul><li>entry_connection_t, also implemented in connection_edge.c
  24. * </ul>
  25. * <li>control_connection_t, implemented in control.c
  26. * </ul>
  27. *
  28. * The base type implemented in this module is responsible for basic
  29. * rate limiting, flow control, and marshalling bytes onto and off of the
  30. * network (either directly or via TLS).
  31. *
  32. * Connections are registered with the main loop with connection_add(). As
  33. * they become able to read or write register the fact with the event main
  34. * loop by calling connection_watch_events(), connection_start_reading(), or
  35. * connection_start_writing(). When they no longer want to read or write,
  36. * they call connection_stop_reading() or connection_stop_writing().
  37. *
  38. * To queue data to be written on a connection, call
  39. * connection_buf_add(). When data arrives, the
  40. * connection_process_inbuf() callback is invoked, which dispatches to a
  41. * type-specific function (such as connection_edge_process_inbuf() for
  42. * example). Connection types that need notice of when data has been written
  43. * receive notification via connection_flushed_some() and
  44. * connection_finished_flushing(). These functions all delegate to
  45. * type-specific implementations.
  46. *
  47. * Additionally, beyond the core of connection_t, this module also implements:
  48. * <ul>
  49. * <li>Listeners, which wait for incoming sockets and launch connections
  50. * <li>Outgoing SOCKS proxy support
  51. * <li>Outgoing HTTP proxy support
  52. * <li>An out-of-sockets handler for dealing with socket exhaustion
  53. * </ul>
  54. **/
  55. #define CONNECTION_PRIVATE
  56. #include "core/or/or.h"
  57. #include "feature/client/bridges.h"
  58. #include "lib/buf/buffers.h"
  59. #include "lib/tls/buffers_tls.h"
  60. #include "lib/err/backtrace.h"
  61. /*
  62. * Define this so we get channel internal functions, since we're implementing
  63. * part of a subclass (channel_tls_t).
  64. */
  65. #define TOR_CHANNEL_INTERNAL_
  66. #define CONNECTION_PRIVATE
  67. #include "app/config/config.h"
  68. #include "core/mainloop/connection.h"
  69. #include "core/mainloop/mainloop.h"
  70. #include "core/mainloop/netstatus.h"
  71. #include "core/or/channel.h"
  72. #include "core/or/channeltls.h"
  73. #include "core/or/circuitbuild.h"
  74. #include "core/or/circuitlist.h"
  75. #include "core/or/circuituse.h"
  76. #include "core/or/connection_edge.h"
  77. #include "core/or/connection_or.h"
  78. #include "core/or/dos.h"
  79. #include "core/or/policies.h"
  80. #include "core/or/reasons.h"
  81. #include "core/or/relay.h"
  82. #include "core/or/crypt_path.h"
  83. #include "core/proto/proto_http.h"
  84. #include "core/proto/proto_socks.h"
  85. #include "feature/client/dnsserv.h"
  86. #include "feature/client/entrynodes.h"
  87. #include "feature/client/transports.h"
  88. #include "feature/control/control.h"
  89. #include "feature/control/control_events.h"
  90. #include "feature/dirauth/authmode.h"
  91. #include "feature/dircache/dirserv.h"
  92. #include "feature/dircommon/directory.h"
  93. #include "feature/hibernate/hibernate.h"
  94. #include "feature/hs/hs_common.h"
  95. #include "feature/hs/hs_ident.h"
  96. #include "feature/nodelist/nodelist.h"
  97. #include "feature/nodelist/routerlist.h"
  98. #include "feature/relay/dns.h"
  99. #include "feature/relay/ext_orport.h"
  100. #include "feature/relay/routermode.h"
  101. #include "feature/rend/rendclient.h"
  102. #include "feature/rend/rendcommon.h"
  103. #include "feature/stats/rephist.h"
  104. #include "lib/crypt_ops/crypto_util.h"
  105. #include "lib/geoip/geoip.h"
  106. #include "lib/sandbox/sandbox.h"
  107. #include "lib/net/buffers_net.h"
  108. #include "lib/tls/tortls.h"
  109. #include "lib/evloop/compat_libevent.h"
  110. #include "lib/compress/compress.h"
  111. #ifdef HAVE_PWD_H
  112. #include <pwd.h>
  113. #endif
  114. #ifdef HAVE_UNISTD_H
  115. #include <unistd.h>
  116. #endif
  117. #ifdef HAVE_SYS_STAT_H
  118. #include <sys/stat.h>
  119. #endif
  120. #ifdef HAVE_SYS_UN_H
  121. #include <sys/socket.h>
  122. #include <sys/un.h>
  123. #endif
  124. #include "feature/dircommon/dir_connection_st.h"
  125. #include "feature/control/control_connection_st.h"
  126. #include "core/or/entry_connection_st.h"
  127. #include "core/or/listener_connection_st.h"
  128. #include "core/or/safe_connection.h"
  129. #include "core/or/or_connection_st.h"
  130. #include "core/or/port_cfg_st.h"
  131. #include "feature/nodelist/routerinfo_st.h"
  132. #include "core/or/socks_request_st.h"
  133. /**
  134. * On Windows and Linux we cannot reliably bind() a socket to an
  135. * address and port if: 1) There's already a socket bound to wildcard
  136. * address (0.0.0.0 or ::) with the same port; 2) We try to bind()
  137. * to wildcard address and there's another socket bound to a
  138. * specific address and the same port.
  139. *
  140. * To address this problem on these two platforms we implement a
  141. * routine that:
  142. * 1) Checks if first attempt to bind() a new socket failed with
  143. * EADDRINUSE.
  144. * 2) If so, it will close the appropriate old listener connection and
  145. * 3) Attempts bind()'ing the new listener socket again.
  146. *
  147. * Just to be safe, we are enabling listener rebind code on all platforms,
  148. * to account for unexpected cases where it may be needed.
  149. */
  150. #define ENABLE_LISTENER_REBIND
  151. static connection_t *connection_listener_new(
  152. const struct sockaddr *listensockaddr,
  153. socklen_t listensocklen, int type,
  154. const char *address,
  155. const port_cfg_t *portcfg,
  156. int *addr_in_use);
  157. static connection_t *connection_listener_new_for_port(
  158. const port_cfg_t *port,
  159. int *defer, int *addr_in_use);
  160. static void connection_init(time_t now, connection_t *conn, int type,
  161. int socket_family);
  162. static int connection_handle_listener_read(connection_t *conn, int new_type);
  163. static int connection_finished_flushing(connection_t *conn);
  164. static int connection_flushed_some(connection_t *conn);
  165. static int connection_finished_connecting(connection_t *conn);
  166. static int connection_reached_eof(connection_t *conn);
  167. static int connection_buf_read_from_socket(connection_t *conn,
  168. ssize_t *max_to_read,
  169. int *socket_error);
  170. static int connection_process_inbuf(connection_t *conn, int package_partial);
  171. static void client_check_address_changed(tor_socket_t sock);
  172. static void set_constrained_socket_buffers(tor_socket_t sock, int size);
  173. static const char *connection_proxy_state_to_string(int state);
  174. static int connection_read_https_proxy_response(connection_t *conn);
  175. static void connection_send_socks5_connect(connection_t *conn);
  176. static const char *proxy_type_to_string(int proxy_type);
  177. static int conn_get_proxy_type(const connection_t *conn);
  178. const tor_addr_t *conn_get_outbound_address(sa_family_t family,
  179. const or_options_t *options, unsigned int conn_type);
  180. static void reenable_blocked_connection_init(const or_options_t *options);
  181. static void reenable_blocked_connection_schedule(void);
  182. /** The last addresses that our network interface seemed to have been
  183. * binding to. We use this as one way to detect when our IP changes.
  184. *
  185. * XXXX+ We should really use the entire list of interfaces here.
  186. **/
  187. static tor_addr_t *last_interface_ipv4 = NULL;
  188. /* DOCDOC last_interface_ipv6 */
  189. static tor_addr_t *last_interface_ipv6 = NULL;
  190. /** A list of tor_addr_t for addresses we've used in outgoing connections.
  191. * Used to detect IP address changes. */
  192. static smartlist_t *outgoing_addrs = NULL;
  193. #define CASE_ANY_LISTENER_TYPE \
  194. case CONN_TYPE_OR_LISTENER: \
  195. case CONN_TYPE_EXT_OR_LISTENER: \
  196. case CONN_TYPE_AP_LISTENER: \
  197. case CONN_TYPE_DIR_LISTENER: \
  198. case CONN_TYPE_CONTROL_LISTENER: \
  199. case CONN_TYPE_AP_TRANS_LISTENER: \
  200. case CONN_TYPE_AP_NATD_LISTENER: \
  201. case CONN_TYPE_AP_DNS_LISTENER: \
  202. case CONN_TYPE_AP_HTTP_CONNECT_LISTENER
  203. /**************************************************************/
  204. /** Convert a connection_t* to an listener_connection_t*; assert if the cast
  205. * is invalid. */
  206. listener_connection_t *
  207. TO_LISTENER_CONN(connection_t *c)
  208. {
  209. tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
  210. return DOWNCAST(listener_connection_t, c);
  211. }
  212. size_t
  213. connection_get_inbuf_len(connection_t *conn)
  214. {
  215. tor_assert(conn->safe_conn == NULL);
  216. return conn->inbuf ? buf_datalen(conn->inbuf) : 0;
  217. }
  218. size_t
  219. connection_get_outbuf_len(connection_t *conn)
  220. {
  221. tor_assert(conn->safe_conn == NULL);
  222. return conn->outbuf ? buf_datalen(conn->outbuf) : 0;
  223. }
  224. /**
  225. * Return the human-readable name for the connection type <b>type</b>
  226. */
  227. const char *
  228. conn_type_to_string(int type)
  229. {
  230. static char buf[64];
  231. switch (type) {
  232. case CONN_TYPE_OR_LISTENER: return "OR listener";
  233. case CONN_TYPE_OR: return "OR";
  234. case CONN_TYPE_EXIT: return "Exit";
  235. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  236. case CONN_TYPE_AP_TRANS_LISTENER:
  237. return "Transparent pf/netfilter listener";
  238. case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
  239. case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
  240. case CONN_TYPE_AP: return "Socks";
  241. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  242. case CONN_TYPE_DIR: return "Directory";
  243. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  244. case CONN_TYPE_CONTROL: return "Control";
  245. case CONN_TYPE_EXT_OR: return "Extended OR";
  246. case CONN_TYPE_EXT_OR_LISTENER: return "Extended OR listener";
  247. case CONN_TYPE_AP_HTTP_CONNECT_LISTENER: return "HTTP tunnel listener";
  248. default:
  249. log_warn(LD_BUG, "unknown connection type %d", type);
  250. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  251. return buf;
  252. }
  253. }
  254. /**
  255. * Return the human-readable name for the connection state <b>state</b>
  256. * for the connection type <b>type</b>
  257. */
  258. const char *
  259. conn_state_to_string(int type, int state)
  260. {
  261. static char buf[96];
  262. switch (type) {
  263. CASE_ANY_LISTENER_TYPE:
  264. if (state == LISTENER_STATE_READY)
  265. return "ready";
  266. break;
  267. case CONN_TYPE_OR:
  268. switch (state) {
  269. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  270. case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
  271. case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
  272. case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
  273. return "renegotiating (TLS, v2 handshake)";
  274. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  275. return "waiting for renegotiation or V3 handshake";
  276. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  277. return "handshaking (Tor, v2 handshake)";
  278. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  279. return "handshaking (Tor, v3 handshake)";
  280. case OR_CONN_STATE_OPEN: return "open";
  281. }
  282. break;
  283. case CONN_TYPE_EXT_OR:
  284. switch (state) {
  285. case EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE:
  286. return "waiting for authentication type";
  287. case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE:
  288. return "waiting for client nonce";
  289. case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH:
  290. return "waiting for client hash";
  291. case EXT_OR_CONN_STATE_OPEN: return "open";
  292. case EXT_OR_CONN_STATE_FLUSHING: return "flushing final OKAY";
  293. }
  294. break;
  295. case CONN_TYPE_EXIT:
  296. switch (state) {
  297. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  298. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  299. case EXIT_CONN_STATE_OPEN: return "open";
  300. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  301. }
  302. break;
  303. case CONN_TYPE_AP:
  304. switch (state) {
  305. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
  306. case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
  307. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  308. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  309. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
  310. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
  311. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
  312. case AP_CONN_STATE_OPEN: return "open";
  313. }
  314. break;
  315. case CONN_TYPE_DIR:
  316. switch (state) {
  317. case DIR_CONN_STATE_CONNECTING: return "connecting";
  318. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  319. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  320. case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
  321. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  322. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  323. }
  324. break;
  325. case CONN_TYPE_CONTROL:
  326. switch (state) {
  327. case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
  328. case CONTROL_CONN_STATE_NEEDAUTH:
  329. return "waiting for authentication (protocol v1)";
  330. }
  331. break;
  332. }
  333. log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
  334. tor_snprintf(buf, sizeof(buf),
  335. "unknown state [%d] on unknown [%s] connection",
  336. state, conn_type_to_string(type));
  337. return buf;
  338. }
  339. /** Allocate and return a new dir_connection_t, initialized as by
  340. * connection_init(). */
  341. dir_connection_t *
  342. dir_connection_new(int socket_family)
  343. {
  344. dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
  345. connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
  346. return dir_conn;
  347. }
  348. /** Allocate and return a new or_connection_t, initialized as by
  349. * connection_init().
  350. *
  351. * Initialize active_circuit_pqueue.
  352. *
  353. * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
  354. */
  355. or_connection_t *
  356. or_connection_new(int type, int socket_family)
  357. {
  358. or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  359. time_t now = time(NULL);
  360. tor_assert(type == CONN_TYPE_OR || type == CONN_TYPE_EXT_OR);
  361. connection_init(now, TO_CONN(or_conn), type, socket_family);
  362. tor_assert(safe_or_conn_tcp_connecting_ev != EVENT_LABEL_UNSET);
  363. tor_assert(safe_or_conn_tls_handshaking_ev != EVENT_LABEL_UNSET);
  364. tor_assert(safe_or_conn_link_handshaking_ev != EVENT_LABEL_UNSET);
  365. tor_assert(safe_or_conn_open_ev != EVENT_LABEL_UNSET);
  366. tor_assert(safe_or_conn_closed_ev != EVENT_LABEL_UNSET);
  367. tor_assert(safe_or_conn_fixed_cell_ev != EVENT_LABEL_UNSET);
  368. tor_assert(safe_or_conn_var_cell_ev != EVENT_LABEL_UNSET);
  369. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  370. safe_or_conn_tcp_connecting_ev,
  371. NULL, connection_or_process_event);
  372. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  373. safe_or_conn_tls_handshaking_ev,
  374. NULL, connection_or_process_event);
  375. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  376. safe_or_conn_link_handshaking_ev,
  377. NULL, connection_or_process_event);
  378. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  379. safe_or_conn_open_ev,
  380. NULL, connection_or_process_event);
  381. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  382. safe_or_conn_closed_ev,
  383. NULL, connection_or_process_event);
  384. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  385. safe_or_conn_fixed_cell_ev,
  386. NULL, connection_or_process_event);
  387. event_listener_set_callback(TO_CONN(or_conn)->event_listener,
  388. safe_or_conn_var_cell_ev,
  389. NULL, connection_or_process_event);
  390. connection_or_set_canonical(or_conn, 0);
  391. if (type == CONN_TYPE_EXT_OR)
  392. connection_or_set_ext_or_identifier(or_conn);
  393. return or_conn;
  394. }
  395. /** Allocate and return a new entry_connection_t, initialized as by
  396. * connection_init().
  397. *
  398. * Allocate space to store the socks_request.
  399. */
  400. entry_connection_t *
  401. entry_connection_new(int type, int socket_family)
  402. {
  403. entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
  404. tor_assert(type == CONN_TYPE_AP);
  405. connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
  406. entry_conn->socks_request = socks_request_new();
  407. /* If this is coming from a listener, we'll set it up based on the listener
  408. * in a little while. Otherwise, we're doing this as a linked connection
  409. * of some kind, and we should set it up here based on the socket family */
  410. if (socket_family == AF_INET)
  411. entry_conn->entry_cfg.ipv4_traffic = 1;
  412. else if (socket_family == AF_INET6)
  413. entry_conn->entry_cfg.ipv6_traffic = 1;
  414. return entry_conn;
  415. }
  416. /** Allocate and return a new edge_connection_t, initialized as by
  417. * connection_init(). */
  418. edge_connection_t *
  419. edge_connection_new(int type, int socket_family)
  420. {
  421. edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
  422. tor_assert(type == CONN_TYPE_EXIT);
  423. connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  424. return edge_conn;
  425. }
  426. /** Allocate and return a new control_connection_t, initialized as by
  427. * connection_init(). */
  428. control_connection_t *
  429. control_connection_new(int socket_family)
  430. {
  431. control_connection_t *control_conn =
  432. tor_malloc_zero(sizeof(control_connection_t));
  433. connection_init(time(NULL),
  434. TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
  435. return control_conn;
  436. }
  437. /** Allocate and return a new listener_connection_t, initialized as by
  438. * connection_init(). */
  439. listener_connection_t *
  440. listener_connection_new(int type, int socket_family)
  441. {
  442. listener_connection_t *listener_conn =
  443. tor_malloc_zero(sizeof(listener_connection_t));
  444. connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
  445. return listener_conn;
  446. }
  447. /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
  448. * to make or receive connections of address family <b>socket_family</b>. The
  449. * type should be one of the CONN_TYPE_* constants. */
  450. connection_t *
  451. connection_new(int type, int socket_family)
  452. {
  453. switch (type) {
  454. case CONN_TYPE_OR:
  455. case CONN_TYPE_EXT_OR:
  456. return TO_CONN(or_connection_new(type, socket_family));
  457. case CONN_TYPE_EXIT:
  458. return TO_CONN(edge_connection_new(type, socket_family));
  459. case CONN_TYPE_AP:
  460. return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
  461. case CONN_TYPE_DIR:
  462. return TO_CONN(dir_connection_new(socket_family));
  463. case CONN_TYPE_CONTROL:
  464. return TO_CONN(control_connection_new(socket_family));
  465. CASE_ANY_LISTENER_TYPE:
  466. return TO_CONN(listener_connection_new(type, socket_family));
  467. default: {
  468. connection_t *conn = tor_malloc_zero(sizeof(connection_t));
  469. connection_init(time(NULL), conn, type, socket_family);
  470. return conn;
  471. }
  472. }
  473. }
  474. static bool
  475. connection_uses_safe_conn(int type)
  476. {
  477. switch (type) {
  478. case CONN_TYPE_OR:
  479. case CONN_TYPE_EXT_OR:
  480. return true;
  481. default:
  482. return false;
  483. }
  484. }
  485. /** Initializes conn. (you must call connection_add() to link it into the main
  486. * array).
  487. *
  488. * Set conn-\>magic to the correct value.
  489. *
  490. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  491. * -1 to signify they are not yet assigned.
  492. *
  493. * Initialize conn's timestamps to now.
  494. */
  495. static void
  496. connection_init(time_t now, connection_t *conn, int type, int socket_family)
  497. {
  498. static uint64_t n_connections_allocated = 1;
  499. switch (type) {
  500. case CONN_TYPE_OR:
  501. case CONN_TYPE_EXT_OR:
  502. conn->magic = OR_CONNECTION_MAGIC;
  503. break;
  504. case CONN_TYPE_EXIT:
  505. conn->magic = EDGE_CONNECTION_MAGIC;
  506. break;
  507. case CONN_TYPE_AP:
  508. conn->magic = ENTRY_CONNECTION_MAGIC;
  509. break;
  510. case CONN_TYPE_DIR:
  511. conn->magic = DIR_CONNECTION_MAGIC;
  512. break;
  513. case CONN_TYPE_CONTROL:
  514. conn->magic = CONTROL_CONNECTION_MAGIC;
  515. break;
  516. CASE_ANY_LISTENER_TYPE:
  517. conn->magic = LISTENER_CONNECTION_MAGIC;
  518. break;
  519. default:
  520. conn->magic = BASE_CONNECTION_MAGIC;
  521. break;
  522. }
  523. conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
  524. conn->conn_array_index = -1; /* also default to 'not used' */
  525. conn->global_identifier = n_connections_allocated++;
  526. conn->event_listener = event_listener_new(conn);
  527. conn->type = type;
  528. conn->socket_family = socket_family;
  529. if (!connection_is_listener(conn) && !connection_uses_safe_conn(type)) {
  530. /* listeners never use their buf */
  531. conn->inbuf = buf_new();
  532. conn->outbuf = buf_new();
  533. }
  534. conn->timestamp_created = now;
  535. conn->timestamp_last_read_allowed = now;
  536. conn->timestamp_last_write_allowed = now;
  537. }
  538. /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
  539. void
  540. connection_link_connections(connection_t *conn_a, connection_t *conn_b)
  541. {
  542. tor_assert(! SOCKET_OK(conn_a->s));
  543. tor_assert(! SOCKET_OK(conn_b->s));
  544. conn_a->linked = 1;
  545. conn_b->linked = 1;
  546. conn_a->linked_conn = conn_b;
  547. conn_b->linked_conn = conn_a;
  548. }
  549. /** Return true iff the provided connection listener type supports AF_UNIX
  550. * sockets. */
  551. int
  552. conn_listener_type_supports_af_unix(int type)
  553. {
  554. /* For now only control ports or SOCKS ports can be Unix domain sockets
  555. * and listeners at the same time */
  556. switch (type) {
  557. case CONN_TYPE_CONTROL_LISTENER:
  558. case CONN_TYPE_AP_LISTENER:
  559. return 1;
  560. default:
  561. return 0;
  562. }
  563. }
  564. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  565. * necessary, close its socket if necessary, and mark the directory as dirty
  566. * if <b>conn</b> is an OR or OP connection.
  567. */
  568. STATIC void
  569. connection_free_minimal(connection_t *conn)
  570. {
  571. void *mem;
  572. size_t memlen;
  573. if (!conn)
  574. return;
  575. switch (conn->type) {
  576. case CONN_TYPE_OR:
  577. case CONN_TYPE_EXT_OR:
  578. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  579. mem = TO_OR_CONN(conn);
  580. memlen = sizeof(or_connection_t);
  581. break;
  582. case CONN_TYPE_AP:
  583. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  584. mem = TO_ENTRY_CONN(conn);
  585. memlen = sizeof(entry_connection_t);
  586. break;
  587. case CONN_TYPE_EXIT:
  588. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  589. mem = TO_EDGE_CONN(conn);
  590. memlen = sizeof(edge_connection_t);
  591. break;
  592. case CONN_TYPE_DIR:
  593. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  594. mem = TO_DIR_CONN(conn);
  595. memlen = sizeof(dir_connection_t);
  596. break;
  597. case CONN_TYPE_CONTROL:
  598. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  599. mem = TO_CONTROL_CONN(conn);
  600. memlen = sizeof(control_connection_t);
  601. break;
  602. CASE_ANY_LISTENER_TYPE:
  603. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  604. mem = TO_LISTENER_CONN(conn);
  605. memlen = sizeof(listener_connection_t);
  606. break;
  607. default:
  608. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  609. mem = conn;
  610. memlen = sizeof(connection_t);
  611. break;
  612. }
  613. if (conn->linked) {
  614. log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
  615. "bytes on inbuf, %d on outbuf.",
  616. conn_type_to_string(conn->type),
  617. conn_state_to_string(conn->type, conn->state),
  618. (int)connection_get_inbuf_len(conn),
  619. (int)connection_get_outbuf_len(conn));
  620. }
  621. if (!connection_is_listener(conn) && !connection_uses_safe_conn(conn->type)) {
  622. buf_free(conn->inbuf);
  623. buf_free(conn->outbuf);
  624. }
  625. event_listener_free(conn->event_listener);
  626. if (connection_is_listener(conn)) {
  627. if (conn->socket_family == AF_UNIX) {
  628. /* For now only control and SOCKS ports can be Unix domain sockets
  629. * and listeners at the same time */
  630. tor_assert(conn_listener_type_supports_af_unix(conn->type));
  631. if (unlink(conn->address) < 0 && errno != ENOENT) {
  632. log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
  633. strerror(errno));
  634. }
  635. }
  636. }
  637. tor_free(conn->address);
  638. if (connection_speaks_cells(conn)) {
  639. or_connection_t *or_conn = TO_OR_CONN(conn);
  640. //if (or_conn->tls) {
  641. // if (! SOCKET_OK(conn->s)) {
  642. // /* The socket has been closed by somebody else; we must tell the
  643. // * TLS object not to close it. */
  644. // tor_tls_release_socket(or_conn->tls);
  645. // } else {
  646. // /* The tor_tls_free() call below will close the socket; we must tell
  647. // * the code below not to close it a second time. */
  648. // tor_release_socket_ownership(conn->s);
  649. // conn->s = TOR_INVALID_SOCKET;
  650. // }
  651. // tor_tls_free(or_conn->tls);
  652. // or_conn->tls = NULL;
  653. //}
  654. if (or_conn->tls_own_cert != NULL) {
  655. tor_x509_cert_free(or_conn->tls_own_cert);
  656. or_conn->tls_own_cert = NULL;
  657. }
  658. if (or_conn->tls_peer_cert != NULL) {
  659. tor_x509_cert_free(or_conn->tls_peer_cert);
  660. or_conn->tls_peer_cert = NULL;
  661. }
  662. or_handshake_state_free(or_conn->handshake_state);
  663. or_conn->handshake_state = NULL;
  664. tor_free(or_conn->nickname);
  665. if (or_conn->chan) {
  666. /* Owww, this shouldn't happen, but... */
  667. channel_t *base_chan = TLS_CHAN_TO_BASE(or_conn->chan);
  668. tor_assert(base_chan);
  669. log_info(LD_CHANNEL,
  670. "Freeing orconn at %p, saw channel %p with ID "
  671. "%"PRIu64 " left un-NULLed",
  672. or_conn, base_chan,
  673. base_chan->global_identifier);
  674. if (!CHANNEL_FINISHED(base_chan)) {
  675. channel_close_for_error(base_chan);
  676. }
  677. or_conn->chan->conn = NULL;
  678. or_conn->chan = NULL;
  679. }
  680. }
  681. if (conn->type == CONN_TYPE_AP) {
  682. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  683. tor_free(entry_conn->chosen_exit_name);
  684. tor_free(entry_conn->original_dest_address);
  685. if (entry_conn->socks_request)
  686. socks_request_free(entry_conn->socks_request);
  687. if (entry_conn->pending_optimistic_data) {
  688. buf_free(entry_conn->pending_optimistic_data);
  689. }
  690. if (entry_conn->sending_optimistic_data) {
  691. buf_free(entry_conn->sending_optimistic_data);
  692. }
  693. }
  694. if (CONN_IS_EDGE(conn)) {
  695. rend_data_free(TO_EDGE_CONN(conn)->rend_data);
  696. hs_ident_edge_conn_free(TO_EDGE_CONN(conn)->hs_ident);
  697. }
  698. if (conn->type == CONN_TYPE_CONTROL) {
  699. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  700. tor_free(control_conn->safecookie_client_hash);
  701. tor_free(control_conn->incoming_cmd);
  702. tor_free(control_conn->current_cmd);
  703. if (control_conn->ephemeral_onion_services) {
  704. SMARTLIST_FOREACH(control_conn->ephemeral_onion_services, char *, cp, {
  705. memwipe(cp, 0, strlen(cp));
  706. tor_free(cp);
  707. });
  708. smartlist_free(control_conn->ephemeral_onion_services);
  709. }
  710. }
  711. /* Probably already freed by connection_free. */
  712. tor_event_free(conn->read_event);
  713. tor_event_free(conn->write_event);
  714. conn->read_event = conn->write_event = NULL;
  715. if (conn->type == CONN_TYPE_DIR) {
  716. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  717. tor_free(dir_conn->requested_resource);
  718. tor_compress_free(dir_conn->compress_state);
  719. if (dir_conn->spool) {
  720. SMARTLIST_FOREACH(dir_conn->spool, spooled_resource_t *, spooled,
  721. spooled_resource_free(spooled));
  722. smartlist_free(dir_conn->spool);
  723. }
  724. rend_data_free(dir_conn->rend_data);
  725. hs_ident_dir_conn_free(dir_conn->hs_ident);
  726. if (dir_conn->guard_state) {
  727. /* Cancel before freeing, if it's still there. */
  728. entry_guard_cancel(&dir_conn->guard_state);
  729. }
  730. circuit_guard_state_free(dir_conn->guard_state);
  731. }
  732. if (SOCKET_OK(conn->s)) {
  733. log_debug(LD_NET,"closing fd %d.",(int)conn->s);
  734. tor_close_socket(conn->s);
  735. conn->s = TOR_INVALID_SOCKET;
  736. }
  737. if (conn->type == CONN_TYPE_OR &&
  738. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  739. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  740. connection_or_clear_identity(TO_OR_CONN(conn));
  741. }
  742. if (conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR) {
  743. connection_or_remove_from_ext_or_id_map(TO_OR_CONN(conn));
  744. tor_free(TO_OR_CONN(conn)->ext_or_conn_id);
  745. tor_free(TO_OR_CONN(conn)->ext_or_auth_correct_client_hash);
  746. tor_free(TO_OR_CONN(conn)->ext_or_transport);
  747. }
  748. memwipe(mem, 0xCC, memlen); /* poison memory */
  749. tor_free(mem);
  750. }
  751. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  752. */
  753. MOCK_IMPL(void,
  754. connection_free_,(connection_t *conn))
  755. {
  756. if (!conn)
  757. return;
  758. tor_assert(!connection_is_on_closeable_list(conn));
  759. tor_assert(!connection_in_array(conn));
  760. if (BUG(conn->linked_conn)) {
  761. conn->linked_conn->linked_conn = NULL;
  762. if (! conn->linked_conn->marked_for_close &&
  763. conn->linked_conn->reading_from_linked_conn)
  764. connection_start_reading(conn->linked_conn);
  765. conn->linked_conn = NULL;
  766. }
  767. if (connection_speaks_cells(conn)) {
  768. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  769. connection_or_clear_identity(TO_OR_CONN(conn));
  770. }
  771. }
  772. if (conn->type == CONN_TYPE_CONTROL) {
  773. connection_control_closed(TO_CONTROL_CONN(conn));
  774. }
  775. #if 1
  776. /* DEBUGGING */
  777. if (conn->type == CONN_TYPE_AP) {
  778. connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn),
  779. "connection_free");
  780. }
  781. #endif /* 1 */
  782. /* Notify the circuit creation DoS mitigation subsystem that an OR client
  783. * connection has been closed. And only do that if we track it. */
  784. if (conn->type == CONN_TYPE_OR) {
  785. dos_close_client_conn(TO_OR_CONN(conn));
  786. }
  787. connection_unregister_events(conn);
  788. connection_free_minimal(conn);
  789. }
  790. /**
  791. * Called when we're about to finally unlink and free a connection:
  792. * perform necessary accounting and cleanup
  793. * - Directory conns that failed to fetch a rendezvous descriptor
  794. * need to inform pending rendezvous streams.
  795. * - OR conns need to call rep_hist_note_*() to record status.
  796. * - AP conns need to send a socks reject if necessary.
  797. * - Exit conns need to call connection_dns_remove() if necessary.
  798. * - AP and Exit conns need to send an end cell if they can.
  799. * - DNS conns need to fail any resolves that are pending on them.
  800. * - OR and edge connections need to be unlinked from circuits.
  801. */
  802. void
  803. connection_about_to_close_connection(connection_t *conn)
  804. {
  805. tor_assert(conn->marked_for_close);
  806. switch (conn->type) {
  807. case CONN_TYPE_DIR:
  808. connection_dir_about_to_close(TO_DIR_CONN(conn));
  809. break;
  810. case CONN_TYPE_OR:
  811. case CONN_TYPE_EXT_OR:
  812. connection_or_about_to_close(TO_OR_CONN(conn));
  813. break;
  814. case CONN_TYPE_AP:
  815. connection_ap_about_to_close(TO_ENTRY_CONN(conn));
  816. break;
  817. case CONN_TYPE_EXIT:
  818. connection_exit_about_to_close(TO_EDGE_CONN(conn));
  819. break;
  820. }
  821. }
  822. /** Return true iff connection_close_immediate() has been called on this
  823. * connection. */
  824. #define CONN_IS_CLOSED(c) \
  825. ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
  826. /** Close the underlying socket for <b>conn</b>, so we don't try to
  827. * flush it. Must be used in conjunction with (right before)
  828. * connection_mark_for_close().
  829. */
  830. void
  831. connection_close_immediate(connection_t *conn)
  832. {
  833. assert_connection_ok(conn,0);
  834. if (!connection_uses_safe_conn(conn->type) && CONN_IS_CLOSED(conn)) {
  835. log_err(LD_BUG,"Attempt to close already-closed connection.");
  836. tor_fragile_assert();
  837. return;
  838. }
  839. if (conn->outbuf_flushlen) {
  840. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  841. (int)conn->s, conn_type_to_string(conn->type),
  842. conn_state_to_string(conn->type, conn->state),
  843. (int)conn->outbuf_flushlen);
  844. }
  845. connection_unregister_events(conn);
  846. /* Prevent the event from getting unblocked. */
  847. conn->read_blocked_on_bw = 0;
  848. conn->write_blocked_on_bw = 0;
  849. if (SOCKET_OK(conn->s))
  850. tor_close_socket(conn->s);
  851. conn->s = TOR_INVALID_SOCKET;
  852. if (conn->linked)
  853. conn->linked_conn_is_closed = 1;
  854. if (conn->outbuf)
  855. buf_clear(conn->outbuf);
  856. conn->outbuf_flushlen = 0;
  857. }
  858. /** Mark <b>conn</b> to be closed next time we loop through
  859. * conn_close_if_marked() in main.c. */
  860. void
  861. connection_mark_for_close_(connection_t *conn, int line, const char *file)
  862. {
  863. assert_connection_ok(conn,0);
  864. tor_assert(line);
  865. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  866. tor_assert(file);
  867. if (conn->type == CONN_TYPE_OR) {
  868. /*
  869. * An or_connection should have been closed through one of the channel-
  870. * aware functions in connection_or.c. We'll assume this is an error
  871. * close and do that, and log a bug warning.
  872. */
  873. log_warn(LD_CHANNEL | LD_BUG,
  874. "Something tried to close an or_connection_t without going "
  875. "through channels at %s:%d",
  876. file, line);
  877. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  878. } else {
  879. /* Pass it down to the real function */
  880. connection_mark_for_close_internal_(conn, line, file);
  881. }
  882. }
  883. /** Mark <b>conn</b> to be closed next time we loop through
  884. * conn_close_if_marked() in main.c.
  885. *
  886. * This _internal version bypasses the CONN_TYPE_OR checks; this should be
  887. * called when you either are sure that if this is an or_connection_t the
  888. * controlling channel has been notified (e.g. with
  889. * connection_or_notify_error()), or you actually are the
  890. * connection_or_close_for_error() or connection_or_close_normally() function.
  891. * For all other cases, use connection_mark_and_flush() which checks for
  892. * or_connection_t properly, instead. See below.
  893. *
  894. * We want to keep this function simple and quick, since it can be called from
  895. * quite deep in the call chain, and hence it should avoid having side-effects
  896. * that interfere with its callers view of the connection.
  897. */
  898. MOCK_IMPL(void,
  899. connection_mark_for_close_internal_, (connection_t *conn,
  900. int line, const char *file))
  901. {
  902. assert_connection_ok(conn,0);
  903. tor_assert(line);
  904. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  905. tor_assert(file);
  906. if (conn->marked_for_close) {
  907. log_warn(LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  908. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  909. conn->marked_for_close);
  910. tor_fragile_assert();
  911. return;
  912. }
  913. if (conn->type == CONN_TYPE_OR) {
  914. /*
  915. * Bad news if this happens without telling the controlling channel; do
  916. * this so we can find things that call this wrongly when the asserts hit.
  917. */
  918. log_debug(LD_CHANNEL,
  919. "Calling connection_mark_for_close_internal_() on an OR conn "
  920. "at %s:%d",
  921. file, line);
  922. }
  923. conn->marked_for_close = line;
  924. conn->marked_for_close_file = file;
  925. add_connection_to_closeable_list(conn);
  926. /* in case we're going to be held-open-til-flushed, reset
  927. * the number of seconds since last successful write, so
  928. * we get our whole 15 seconds */
  929. conn->timestamp_last_write_allowed = time(NULL);
  930. }
  931. /** Find each connection that has hold_open_until_flushed set to
  932. * 1 but hasn't written in the past 15 seconds, and set
  933. * hold_open_until_flushed to 0. This means it will get cleaned
  934. * up in the next loop through close_if_marked() in main.c.
  935. */
  936. void
  937. connection_expire_held_open(void)
  938. {
  939. time_t now;
  940. smartlist_t *conns = get_connection_array();
  941. now = time(NULL);
  942. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  943. /* If we've been holding the connection open, but we haven't written
  944. * for 15 seconds...
  945. */
  946. if (conn->hold_open_until_flushed) {
  947. tor_assert(conn->marked_for_close);
  948. if (now - conn->timestamp_last_write_allowed >= 15) {
  949. int severity;
  950. if (conn->type == CONN_TYPE_EXIT ||
  951. (conn->type == CONN_TYPE_DIR &&
  952. conn->purpose == DIR_PURPOSE_SERVER))
  953. severity = LOG_INFO;
  954. else
  955. severity = LOG_NOTICE;
  956. log_fn(severity, LD_NET,
  957. "Giving up on marked_for_close conn that's been flushing "
  958. "for 15s (fd %d, type %s, state %s).",
  959. (int)conn->s, conn_type_to_string(conn->type),
  960. conn_state_to_string(conn->type, conn->state));
  961. conn->hold_open_until_flushed = 0;
  962. }
  963. }
  964. } SMARTLIST_FOREACH_END(conn);
  965. }
  966. #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
  967. /** Create an AF_UNIX listenaddr struct.
  968. * <b>listenaddress</b> provides the path to the Unix socket.
  969. *
  970. * Eventually <b>listenaddress</b> will also optionally contain user, group,
  971. * and file permissions for the new socket. But not yet. XXX
  972. * Also, since we do not create the socket here the information doesn't help
  973. * here.
  974. *
  975. * If not NULL <b>readable_address</b> will contain a copy of the path part of
  976. * <b>listenaddress</b>.
  977. *
  978. * The listenaddr struct has to be freed by the caller.
  979. */
  980. static struct sockaddr_un *
  981. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  982. socklen_t *len_out)
  983. {
  984. struct sockaddr_un *sockaddr = NULL;
  985. sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
  986. sockaddr->sun_family = AF_UNIX;
  987. if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
  988. >= sizeof(sockaddr->sun_path)) {
  989. log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
  990. escaped(listenaddress));
  991. tor_free(sockaddr);
  992. return NULL;
  993. }
  994. if (readable_address)
  995. *readable_address = tor_strdup(listenaddress);
  996. *len_out = sizeof(struct sockaddr_un);
  997. return sockaddr;
  998. }
  999. #else /* !(defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)) */
  1000. static struct sockaddr *
  1001. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  1002. socklen_t *len_out)
  1003. {
  1004. (void)listenaddress;
  1005. (void)readable_address;
  1006. log_fn(LOG_ERR, LD_BUG,
  1007. "Unix domain sockets not supported, yet we tried to create one.");
  1008. *len_out = 0;
  1009. tor_fragile_assert();
  1010. return NULL;
  1011. }
  1012. #endif /* defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN) */
  1013. /** Warn that an accept or a connect has failed because we're running out of
  1014. * TCP sockets we can use on current system. Rate-limit these warnings so
  1015. * that we don't spam the log. */
  1016. static void
  1017. warn_too_many_conns(void)
  1018. {
  1019. #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
  1020. static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
  1021. char *m;
  1022. if ((m = rate_limit_log(&last_warned, approx_time()))) {
  1023. int n_conns = get_n_open_sockets();
  1024. log_warn(LD_NET,"Failing because we have %d connections already. Please "
  1025. "read doc/TUNING for guidance.%s", n_conns, m);
  1026. tor_free(m);
  1027. control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
  1028. n_conns);
  1029. }
  1030. }
  1031. #ifdef HAVE_SYS_UN_H
  1032. #define UNIX_SOCKET_PURPOSE_CONTROL_SOCKET 0
  1033. #define UNIX_SOCKET_PURPOSE_SOCKS_SOCKET 1
  1034. /** Check if the purpose isn't one of the ones we know what to do with */
  1035. static int
  1036. is_valid_unix_socket_purpose(int purpose)
  1037. {
  1038. int valid = 0;
  1039. switch (purpose) {
  1040. case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
  1041. case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
  1042. valid = 1;
  1043. break;
  1044. }
  1045. return valid;
  1046. }
  1047. /** Return a string description of a unix socket purpose */
  1048. static const char *
  1049. unix_socket_purpose_to_string(int purpose)
  1050. {
  1051. const char *s = "unknown-purpose socket";
  1052. switch (purpose) {
  1053. case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
  1054. s = "control socket";
  1055. break;
  1056. case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
  1057. s = "SOCKS socket";
  1058. break;
  1059. }
  1060. return s;
  1061. }
  1062. /** Check whether we should be willing to open an AF_UNIX socket in
  1063. * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
  1064. static int
  1065. check_location_for_unix_socket(const or_options_t *options, const char *path,
  1066. int purpose, const port_cfg_t *port)
  1067. {
  1068. int r = -1;
  1069. char *p = NULL;
  1070. tor_assert(is_valid_unix_socket_purpose(purpose));
  1071. p = tor_strdup(path);
  1072. cpd_check_t flags = CPD_CHECK_MODE_ONLY;
  1073. if (get_parent_directory(p)<0 || p[0] != '/') {
  1074. log_warn(LD_GENERAL, "Bad unix socket address '%s'. Tor does not support "
  1075. "relative paths for unix sockets.", path);
  1076. goto done;
  1077. }
  1078. if (port->is_world_writable) {
  1079. /* World-writable sockets can go anywhere. */
  1080. r = 0;
  1081. goto done;
  1082. }
  1083. if (port->is_group_writable) {
  1084. flags |= CPD_GROUP_OK;
  1085. }
  1086. if (port->relax_dirmode_check) {
  1087. flags |= CPD_RELAX_DIRMODE_CHECK;
  1088. }
  1089. if (check_private_dir(p, flags, options->User) < 0) {
  1090. char *escpath, *escdir;
  1091. escpath = esc_for_log(path);
  1092. escdir = esc_for_log(p);
  1093. log_warn(LD_GENERAL, "Before Tor can create a %s in %s, the directory "
  1094. "%s needs to exist, and to be accessible only by the user%s "
  1095. "account that is running Tor. (On some Unix systems, anybody "
  1096. "who can list a socket can connect to it, so Tor is being "
  1097. "careful.)",
  1098. unix_socket_purpose_to_string(purpose), escpath, escdir,
  1099. port->is_group_writable ? " and group" : "");
  1100. tor_free(escpath);
  1101. tor_free(escdir);
  1102. goto done;
  1103. }
  1104. r = 0;
  1105. done:
  1106. tor_free(p);
  1107. return r;
  1108. }
  1109. #endif /* defined(HAVE_SYS_UN_H) */
  1110. /** Tell the TCP stack that it shouldn't wait for a long time after
  1111. * <b>sock</b> has closed before reusing its port. Return 0 on success,
  1112. * -1 on failure. */
  1113. static int
  1114. make_socket_reuseable(tor_socket_t sock)
  1115. {
  1116. #ifdef _WIN32
  1117. (void) sock;
  1118. return 0;
  1119. #else
  1120. int one=1;
  1121. /* REUSEADDR on normal places means you can rebind to the port
  1122. * right after somebody else has let it go. But REUSEADDR on win32
  1123. * means you can bind to the port _even when somebody else
  1124. * already has it bound_. So, don't do that on Win32. */
  1125. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
  1126. (socklen_t)sizeof(one)) == -1) {
  1127. return -1;
  1128. }
  1129. return 0;
  1130. #endif /* defined(_WIN32) */
  1131. }
  1132. #ifdef _WIN32
  1133. /** Tell the Windows TCP stack to prevent other applications from receiving
  1134. * traffic from tor's open ports. Return 0 on success, -1 on failure. */
  1135. static int
  1136. make_win32_socket_exclusive(tor_socket_t sock)
  1137. {
  1138. #ifdef SO_EXCLUSIVEADDRUSE
  1139. int one=1;
  1140. /* Any socket that sets REUSEADDR on win32 can bind to a port _even when
  1141. * somebody else already has it bound_, and _even if the original socket
  1142. * didn't set REUSEADDR_. Use EXCLUSIVEADDRUSE to prevent this port-stealing
  1143. * on win32. */
  1144. if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void*) &one,
  1145. (socklen_t)sizeof(one))) {
  1146. return -1;
  1147. }
  1148. return 0;
  1149. #else /* !defined(SO_EXCLUSIVEADDRUSE) */
  1150. (void) sock;
  1151. return 0;
  1152. #endif /* defined(SO_EXCLUSIVEADDRUSE) */
  1153. }
  1154. #endif /* defined(_WIN32) */
  1155. /** Max backlog to pass to listen. We start at */
  1156. static int listen_limit = INT_MAX;
  1157. /* Listen on <b>fd</b> with appropriate backlog. Return as for listen. */
  1158. static int
  1159. tor_listen(tor_socket_t fd)
  1160. {
  1161. int r;
  1162. if ((r = listen(fd, listen_limit)) < 0) {
  1163. if (listen_limit == SOMAXCONN)
  1164. return r;
  1165. if ((r = listen(fd, SOMAXCONN)) == 0) {
  1166. listen_limit = SOMAXCONN;
  1167. log_warn(LD_NET, "Setting listen backlog to INT_MAX connections "
  1168. "didn't work, but SOMAXCONN did. Lowering backlog limit.");
  1169. }
  1170. }
  1171. return r;
  1172. }
  1173. /** Bind a new non-blocking socket listening to the socket described
  1174. * by <b>listensockaddr</b>.
  1175. *
  1176. * <b>address</b> is only used for logging purposes and to add the information
  1177. * to the conn.
  1178. *
  1179. * Set <b>addr_in_use</b> to true in case socket binding fails with
  1180. * EADDRINUSE.
  1181. */
  1182. static connection_t *
  1183. connection_listener_new(const struct sockaddr *listensockaddr,
  1184. socklen_t socklen,
  1185. int type, const char *address,
  1186. const port_cfg_t *port_cfg,
  1187. int *addr_in_use)
  1188. {
  1189. listener_connection_t *lis_conn;
  1190. connection_t *conn = NULL;
  1191. tor_socket_t s = TOR_INVALID_SOCKET; /* the socket we're going to make */
  1192. or_options_t const *options = get_options();
  1193. (void) options; /* Windows doesn't use this. */
  1194. #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
  1195. const struct passwd *pw = NULL;
  1196. #endif
  1197. uint16_t usePort = 0, gotPort = 0;
  1198. int start_reading = 0;
  1199. static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
  1200. tor_addr_t addr;
  1201. int exhaustion = 0;
  1202. if (addr_in_use)
  1203. *addr_in_use = 0;
  1204. if (listensockaddr->sa_family == AF_INET ||
  1205. listensockaddr->sa_family == AF_INET6) {
  1206. int is_stream = (type != CONN_TYPE_AP_DNS_LISTENER);
  1207. if (is_stream)
  1208. start_reading = 1;
  1209. tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
  1210. log_notice(LD_NET, "Opening %s on %s",
  1211. conn_type_to_string(type), fmt_addrport(&addr, usePort));
  1212. s = tor_open_socket_nonblocking(tor_addr_family(&addr),
  1213. is_stream ? SOCK_STREAM : SOCK_DGRAM,
  1214. is_stream ? IPPROTO_TCP: IPPROTO_UDP);
  1215. if (!SOCKET_OK(s)) {
  1216. int e = tor_socket_errno(s);
  1217. if (ERRNO_IS_RESOURCE_LIMIT(e)) {
  1218. warn_too_many_conns();
  1219. /*
  1220. * We'll call the OOS handler at the error exit, so set the
  1221. * exhaustion flag for it.
  1222. */
  1223. exhaustion = 1;
  1224. } else {
  1225. log_warn(LD_NET, "Socket creation failed: %s",
  1226. tor_socket_strerror(e));
  1227. }
  1228. goto err;
  1229. }
  1230. if (make_socket_reuseable(s) < 0) {
  1231. log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
  1232. conn_type_to_string(type),
  1233. tor_socket_strerror(errno));
  1234. }
  1235. #ifdef _WIN32
  1236. if (make_win32_socket_exclusive(s) < 0) {
  1237. log_warn(LD_NET, "Error setting SO_EXCLUSIVEADDRUSE flag on %s: %s",
  1238. conn_type_to_string(type),
  1239. tor_socket_strerror(errno));
  1240. }
  1241. #endif /* defined(_WIN32) */
  1242. #if defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT)
  1243. if (options->TransProxyType_parsed == TPT_TPROXY &&
  1244. type == CONN_TYPE_AP_TRANS_LISTENER) {
  1245. int one = 1;
  1246. if (setsockopt(s, SOL_IP, IP_TRANSPARENT, (void*)&one,
  1247. (socklen_t)sizeof(one)) < 0) {
  1248. const char *extra = "";
  1249. int e = tor_socket_errno(s);
  1250. if (e == EPERM)
  1251. extra = "TransTPROXY requires root privileges or similar"
  1252. " capabilities.";
  1253. log_warn(LD_NET, "Error setting IP_TRANSPARENT flag: %s.%s",
  1254. tor_socket_strerror(e), extra);
  1255. }
  1256. }
  1257. #endif /* defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT) */
  1258. #ifdef IPV6_V6ONLY
  1259. if (listensockaddr->sa_family == AF_INET6) {
  1260. int one = 1;
  1261. /* We need to set IPV6_V6ONLY so that this socket can't get used for
  1262. * IPv4 connections. */
  1263. if (setsockopt(s,IPPROTO_IPV6, IPV6_V6ONLY,
  1264. (void*)&one, (socklen_t)sizeof(one)) < 0) {
  1265. int e = tor_socket_errno(s);
  1266. log_warn(LD_NET, "Error setting IPV6_V6ONLY flag: %s",
  1267. tor_socket_strerror(e));
  1268. /* Keep going; probably not harmful. */
  1269. }
  1270. }
  1271. #endif /* defined(IPV6_V6ONLY) */
  1272. if (bind(s,listensockaddr,socklen) < 0) {
  1273. const char *helpfulhint = "";
  1274. int e = tor_socket_errno(s);
  1275. if (ERRNO_IS_EADDRINUSE(e)) {
  1276. helpfulhint = ". Is Tor already running?";
  1277. if (addr_in_use)
  1278. *addr_in_use = 1;
  1279. }
  1280. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  1281. tor_socket_strerror(e), helpfulhint);
  1282. goto err;
  1283. }
  1284. if (is_stream) {
  1285. if (tor_listen(s) < 0) {
  1286. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  1287. tor_socket_strerror(tor_socket_errno(s)));
  1288. goto err;
  1289. }
  1290. }
  1291. if (usePort != 0) {
  1292. gotPort = usePort;
  1293. } else {
  1294. tor_addr_t addr2;
  1295. struct sockaddr_storage ss;
  1296. socklen_t ss_len=sizeof(ss);
  1297. if (getsockname(s, (struct sockaddr*)&ss, &ss_len)<0) {
  1298. log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
  1299. conn_type_to_string(type),
  1300. tor_socket_strerror(tor_socket_errno(s)));
  1301. gotPort = 0;
  1302. }
  1303. tor_addr_from_sockaddr(&addr2, (struct sockaddr*)&ss, &gotPort);
  1304. }
  1305. #ifdef HAVE_SYS_UN_H
  1306. /*
  1307. * AF_UNIX generic setup stuff
  1308. */
  1309. } else if (listensockaddr->sa_family == AF_UNIX) {
  1310. /* We want to start reading for both AF_UNIX cases */
  1311. start_reading = 1;
  1312. tor_assert(conn_listener_type_supports_af_unix(type));
  1313. if (check_location_for_unix_socket(options, address,
  1314. (type == CONN_TYPE_CONTROL_LISTENER) ?
  1315. UNIX_SOCKET_PURPOSE_CONTROL_SOCKET :
  1316. UNIX_SOCKET_PURPOSE_SOCKS_SOCKET, port_cfg) < 0) {
  1317. goto err;
  1318. }
  1319. log_notice(LD_NET, "Opening %s on %s",
  1320. conn_type_to_string(type), address);
  1321. tor_addr_make_unspec(&addr);
  1322. if (unlink(address) < 0 && errno != ENOENT) {
  1323. log_warn(LD_NET, "Could not unlink %s: %s", address,
  1324. strerror(errno));
  1325. goto err;
  1326. }
  1327. s = tor_open_socket_nonblocking(AF_UNIX, SOCK_STREAM, 0);
  1328. if (! SOCKET_OK(s)) {
  1329. int e = tor_socket_errno(s);
  1330. if (ERRNO_IS_RESOURCE_LIMIT(e)) {
  1331. warn_too_many_conns();
  1332. /*
  1333. * We'll call the OOS handler at the error exit, so set the
  1334. * exhaustion flag for it.
  1335. */
  1336. exhaustion = 1;
  1337. } else {
  1338. log_warn(LD_NET,"Socket creation failed: %s.", strerror(e));
  1339. }
  1340. goto err;
  1341. }
  1342. if (bind(s, listensockaddr,
  1343. (socklen_t)sizeof(struct sockaddr_un)) == -1) {
  1344. log_warn(LD_NET,"Bind to %s failed: %s.", address,
  1345. tor_socket_strerror(tor_socket_errno(s)));
  1346. goto err;
  1347. }
  1348. #ifdef HAVE_PWD_H
  1349. if (options->User) {
  1350. pw = tor_getpwnam(options->User);
  1351. struct stat st;
  1352. if (pw == NULL) {
  1353. log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
  1354. address, options->User);
  1355. goto err;
  1356. } else if (fstat(s, &st) == 0 &&
  1357. st.st_uid == pw->pw_uid && st.st_gid == pw->pw_gid) {
  1358. /* No change needed */
  1359. } else if (chown(sandbox_intern_string(address),
  1360. pw->pw_uid, pw->pw_gid) < 0) {
  1361. log_warn(LD_NET,"Unable to chown() %s socket: %s.",
  1362. address, strerror(errno));
  1363. goto err;
  1364. }
  1365. }
  1366. #endif /* defined(HAVE_PWD_H) */
  1367. {
  1368. unsigned mode;
  1369. const char *status;
  1370. struct stat st;
  1371. if (port_cfg->is_world_writable) {
  1372. mode = 0666;
  1373. status = "world-writable";
  1374. } else if (port_cfg->is_group_writable) {
  1375. mode = 0660;
  1376. status = "group-writable";
  1377. } else {
  1378. mode = 0600;
  1379. status = "private";
  1380. }
  1381. /* We need to use chmod; fchmod doesn't work on sockets on all
  1382. * platforms. */
  1383. if (fstat(s, &st) == 0 && (st.st_mode & 0777) == mode) {
  1384. /* no change needed */
  1385. } else if (chmod(sandbox_intern_string(address), mode) < 0) {
  1386. log_warn(LD_FS,"Unable to make %s %s.", address, status);
  1387. goto err;
  1388. }
  1389. }
  1390. if (listen(s, SOMAXCONN) < 0) {
  1391. log_warn(LD_NET, "Could not listen on %s: %s", address,
  1392. tor_socket_strerror(tor_socket_errno(s)));
  1393. goto err;
  1394. }
  1395. #ifndef __APPLE__
  1396. /* This code was introduced to help debug #28229. */
  1397. int value;
  1398. socklen_t len = sizeof(value);
  1399. if (!getsockopt(s, SOL_SOCKET, SO_ACCEPTCONN, &value, &len)) {
  1400. if (value == 0) {
  1401. log_err(LD_NET, "Could not listen on %s - "
  1402. "getsockopt(.,SO_ACCEPTCONN,.) yields 0.", address);
  1403. goto err;
  1404. }
  1405. }
  1406. #endif /* !defined(__APPLE__) */
  1407. #endif /* defined(HAVE_SYS_UN_H) */
  1408. } else {
  1409. log_err(LD_BUG, "Got unexpected address family %d.",
  1410. listensockaddr->sa_family);
  1411. tor_assert(0);
  1412. }
  1413. lis_conn = listener_connection_new(type, listensockaddr->sa_family);
  1414. conn = TO_CONN(lis_conn);
  1415. conn->socket_family = listensockaddr->sa_family;
  1416. conn->s = s;
  1417. s = TOR_INVALID_SOCKET; /* Prevent double-close */
  1418. conn->address = tor_strdup(address);
  1419. conn->port = gotPort;
  1420. tor_addr_copy(&conn->addr, &addr);
  1421. memcpy(&lis_conn->entry_cfg, &port_cfg->entry_cfg, sizeof(entry_port_cfg_t));
  1422. if (port_cfg->entry_cfg.isolation_flags) {
  1423. lis_conn->entry_cfg.isolation_flags = port_cfg->entry_cfg.isolation_flags;
  1424. if (port_cfg->entry_cfg.session_group >= 0) {
  1425. lis_conn->entry_cfg.session_group = port_cfg->entry_cfg.session_group;
  1426. } else {
  1427. /* This can wrap after around INT_MAX listeners are opened. But I don't
  1428. * believe that matters, since you would need to open a ridiculous
  1429. * number of listeners while keeping the early ones open before you ever
  1430. * hit this. An OR with a dozen ports open, for example, would have to
  1431. * close and re-open its listeners every second for 4 years nonstop.
  1432. */
  1433. lis_conn->entry_cfg.session_group = global_next_session_group--;
  1434. }
  1435. }
  1436. if (type != CONN_TYPE_AP_LISTENER) {
  1437. lis_conn->entry_cfg.ipv4_traffic = 1;
  1438. lis_conn->entry_cfg.ipv6_traffic = 1;
  1439. lis_conn->entry_cfg.prefer_ipv6 = 0;
  1440. }
  1441. if (connection_add(conn) < 0) { /* no space, forget it */
  1442. log_warn(LD_NET,"connection_add for listener failed. Giving up.");
  1443. goto err;
  1444. }
  1445. log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
  1446. "%s listening on port %u.",
  1447. conn_type_to_string(type), gotPort);
  1448. conn->state = LISTENER_STATE_READY;
  1449. if (start_reading) {
  1450. connection_start_reading(conn);
  1451. } else {
  1452. tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
  1453. dnsserv_configure_listener(conn);
  1454. }
  1455. /*
  1456. * Normal exit; call the OOS handler since connection count just changed;
  1457. * the exhaustion flag will always be zero here though.
  1458. */
  1459. connection_check_oos(get_n_open_sockets(), 0);
  1460. if (conn->socket_family == AF_UNIX) {
  1461. log_notice(LD_NET, "Opened %s on %s",
  1462. conn_type_to_string(type), conn->address);
  1463. } else {
  1464. log_notice(LD_NET, "Opened %s on %s",
  1465. conn_type_to_string(type), fmt_addrport(&addr, gotPort));
  1466. }
  1467. return conn;
  1468. err:
  1469. if (SOCKET_OK(s))
  1470. tor_close_socket(s);
  1471. if (conn)
  1472. connection_free(conn);
  1473. /* Call the OOS handler, indicate if we saw an exhaustion-related error */
  1474. connection_check_oos(get_n_open_sockets(), exhaustion);
  1475. return NULL;
  1476. }
  1477. /**
  1478. * Create a new listener connection for a given <b>port</b>. In case we
  1479. * for a reason that is not an error condition, set <b>defer</b>
  1480. * to true. If we cannot bind listening socket because address is already
  1481. * in use, set <b>addr_in_use</b> to true.
  1482. */
  1483. static connection_t *
  1484. connection_listener_new_for_port(const port_cfg_t *port,
  1485. int *defer, int *addr_in_use)
  1486. {
  1487. connection_t *conn;
  1488. struct sockaddr *listensockaddr;
  1489. socklen_t listensocklen = 0;
  1490. char *address=NULL;
  1491. int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
  1492. tor_assert(real_port <= UINT16_MAX);
  1493. if (defer)
  1494. *defer = 0;
  1495. if (port->server_cfg.no_listen) {
  1496. if (defer)
  1497. *defer = 1;
  1498. return NULL;
  1499. }
  1500. #ifndef _WIN32
  1501. /* We don't need to be root to create a UNIX socket, so defer until after
  1502. * setuid. */
  1503. const or_options_t *options = get_options();
  1504. if (port->is_unix_addr && !geteuid() && (options->User) &&
  1505. strcmp(options->User, "root")) {
  1506. if (defer)
  1507. *defer = 1;
  1508. return NULL;
  1509. }
  1510. #endif /* !defined(_WIN32) */
  1511. if (port->is_unix_addr) {
  1512. listensockaddr = (struct sockaddr *)
  1513. create_unix_sockaddr(port->unix_addr,
  1514. &address, &listensocklen);
  1515. } else {
  1516. listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
  1517. listensocklen = tor_addr_to_sockaddr(&port->addr,
  1518. real_port,
  1519. listensockaddr,
  1520. sizeof(struct sockaddr_storage));
  1521. address = tor_addr_to_str_dup(&port->addr);
  1522. }
  1523. if (listensockaddr) {
  1524. conn = connection_listener_new(listensockaddr, listensocklen,
  1525. port->type, address, port,
  1526. addr_in_use);
  1527. tor_free(listensockaddr);
  1528. tor_free(address);
  1529. } else {
  1530. conn = NULL;
  1531. }
  1532. return conn;
  1533. }
  1534. /** Do basic sanity checking on a newly received socket. Return 0
  1535. * if it looks ok, else return -1.
  1536. *
  1537. * Notably, some TCP stacks can erroneously have accept() return successfully
  1538. * with socklen 0, when the client sends an RST before the accept call (as
  1539. * nmap does). We want to detect that, and not go on with the connection.
  1540. */
  1541. static int
  1542. check_sockaddr(const struct sockaddr *sa, int len, int level)
  1543. {
  1544. int ok = 1;
  1545. if (sa->sa_family == AF_INET) {
  1546. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  1547. if (len != sizeof(struct sockaddr_in)) {
  1548. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1549. len,(int)sizeof(struct sockaddr_in));
  1550. ok = 0;
  1551. }
  1552. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  1553. log_fn(level, LD_NET,
  1554. "Address for new connection has address/port equal to zero.");
  1555. ok = 0;
  1556. }
  1557. } else if (sa->sa_family == AF_INET6) {
  1558. struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
  1559. if (len != sizeof(struct sockaddr_in6)) {
  1560. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1561. len,(int)sizeof(struct sockaddr_in6));
  1562. ok = 0;
  1563. }
  1564. if (fast_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
  1565. sin6->sin6_port == 0) {
  1566. log_fn(level, LD_NET,
  1567. "Address for new connection has address/port equal to zero.");
  1568. ok = 0;
  1569. }
  1570. } else if (sa->sa_family == AF_UNIX) {
  1571. ok = 1;
  1572. } else {
  1573. ok = 0;
  1574. }
  1575. return ok ? 0 : -1;
  1576. }
  1577. /** Check whether the socket family from an accepted socket <b>got</b> is the
  1578. * same as the one that <b>listener</b> is waiting for. If it isn't, log
  1579. * a useful message and return -1. Else return 0.
  1580. *
  1581. * This is annoying, but can apparently happen on some Darwins. */
  1582. static int
  1583. check_sockaddr_family_match(sa_family_t got, connection_t *listener)
  1584. {
  1585. if (got != listener->socket_family) {
  1586. log_info(LD_BUG, "A listener connection returned a socket with a "
  1587. "mismatched family. %s for addr_family %d gave us a socket "
  1588. "with address family %d. Dropping.",
  1589. conn_type_to_string(listener->type),
  1590. (int)listener->socket_family,
  1591. (int)got);
  1592. return -1;
  1593. }
  1594. return 0;
  1595. }
  1596. /** The listener connection <b>conn</b> told poll() it wanted to read.
  1597. * Call accept() on conn-\>s, and add the new connection if necessary.
  1598. */
  1599. static int
  1600. connection_handle_listener_read(connection_t *conn, int new_type)
  1601. {
  1602. tor_socket_t news; /* the new socket */
  1603. connection_t *newconn = 0;
  1604. /* information about the remote peer when connecting to other routers */
  1605. struct sockaddr_storage addrbuf;
  1606. struct sockaddr *remote = (struct sockaddr*)&addrbuf;
  1607. /* length of the remote address. Must be whatever accept() needs. */
  1608. socklen_t remotelen = (socklen_t)sizeof(addrbuf);
  1609. const or_options_t *options = get_options();
  1610. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  1611. memset(&addrbuf, 0, sizeof(addrbuf));
  1612. news = tor_accept_socket_nonblocking(conn->s,remote,&remotelen);
  1613. if (!SOCKET_OK(news)) { /* accept() error */
  1614. int e = tor_socket_errno(conn->s);
  1615. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  1616. /*
  1617. * they hung up before we could accept(). that's fine.
  1618. *
  1619. * give the OOS handler a chance to run though
  1620. */
  1621. connection_check_oos(get_n_open_sockets(), 0);
  1622. return 0;
  1623. } else if (ERRNO_IS_RESOURCE_LIMIT(e)) {
  1624. warn_too_many_conns();
  1625. /* Exhaustion; tell the OOS handler */
  1626. connection_check_oos(get_n_open_sockets(), 1);
  1627. return 0;
  1628. }
  1629. /* else there was a real error. */
  1630. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  1631. tor_socket_strerror(e));
  1632. connection_mark_for_close(conn);
  1633. /* Tell the OOS handler about this too */
  1634. connection_check_oos(get_n_open_sockets(), 0);
  1635. return -1;
  1636. }
  1637. log_debug(LD_NET,
  1638. "Connection accepted on socket %d (child of fd %d).",
  1639. (int)news,(int)conn->s);
  1640. /* We accepted a new conn; run OOS handler */
  1641. connection_check_oos(get_n_open_sockets(), 0);
  1642. if (make_socket_reuseable(news) < 0) {
  1643. if (tor_socket_errno(news) == EINVAL) {
  1644. /* This can happen on OSX if we get a badly timed shutdown. */
  1645. log_debug(LD_NET, "make_socket_reuseable returned EINVAL");
  1646. } else {
  1647. log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
  1648. conn_type_to_string(new_type),
  1649. tor_socket_strerror(errno));
  1650. }
  1651. tor_close_socket(news);
  1652. return 0;
  1653. }
  1654. if (options->ConstrainedSockets)
  1655. set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
  1656. if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
  1657. tor_close_socket(news);
  1658. return 0;
  1659. }
  1660. if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6 ||
  1661. (conn->socket_family == AF_UNIX && new_type == CONN_TYPE_AP)) {
  1662. tor_addr_t addr;
  1663. uint16_t port;
  1664. if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
  1665. log_info(LD_NET,
  1666. "accept() returned a strange address; closing connection.");
  1667. tor_close_socket(news);
  1668. return 0;
  1669. }
  1670. tor_addr_from_sockaddr(&addr, remote, &port);
  1671. /* process entrance policies here, before we even create the connection */
  1672. if (new_type == CONN_TYPE_AP) {
  1673. /* check sockspolicy to see if we should accept it */
  1674. if (socks_policy_permits_address(&addr) == 0) {
  1675. log_notice(LD_APP,
  1676. "Denying socks connection from untrusted address %s.",
  1677. fmt_and_decorate_addr(&addr));
  1678. tor_close_socket(news);
  1679. return 0;
  1680. }
  1681. }
  1682. if (new_type == CONN_TYPE_DIR) {
  1683. /* check dirpolicy to see if we should accept it */
  1684. if (dir_policy_permits_address(&addr) == 0) {
  1685. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  1686. fmt_and_decorate_addr(&addr));
  1687. tor_close_socket(news);
  1688. return 0;
  1689. }
  1690. }
  1691. if (new_type == CONN_TYPE_OR) {
  1692. /* Assess with the connection DoS mitigation subsystem if this address
  1693. * can open a new connection. */
  1694. if (dos_conn_addr_get_defense_type(&addr) == DOS_CONN_DEFENSE_CLOSE) {
  1695. tor_close_socket(news);
  1696. return 0;
  1697. }
  1698. }
  1699. newconn = connection_new(new_type, conn->socket_family);
  1700. /* remember the remote address */
  1701. tor_addr_copy(&newconn->addr, &addr);
  1702. if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  1703. newconn->port = 0;
  1704. newconn->address = tor_strdup(conn->address);
  1705. } else {
  1706. newconn->port = port;
  1707. newconn->address = tor_addr_to_str_dup(&addr);
  1708. }
  1709. if (!connection_uses_safe_conn(newconn->type)) {
  1710. newconn->s = news;
  1711. } else {
  1712. safe_connection_t *safe_conn = NULL;
  1713. if (new_type == CONN_TYPE_OR) {
  1714. safe_or_connection_t *safe_or_conn;
  1715. safe_or_conn = safe_or_connection_new(true, false, newconn->address);
  1716. safe_conn = TO_SAFE_CONN(safe_or_conn);
  1717. } else {
  1718. log_warn(LD_NET, "Safe conn not yet implemented for type %d", new_type);
  1719. tor_assert(0);
  1720. }
  1721. newconn->safe_conn = safe_conn;
  1722. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1723. safe_or_conn_tcp_connecting_ev);
  1724. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1725. safe_or_conn_tls_handshaking_ev);
  1726. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1727. safe_or_conn_link_handshaking_ev);
  1728. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1729. safe_or_conn_open_ev);
  1730. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1731. safe_or_conn_closed_ev);
  1732. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1733. safe_or_conn_fixed_cell_ev);
  1734. safe_connection_subscribe(newconn->safe_conn, newconn->event_listener,
  1735. safe_or_conn_var_cell_ev);
  1736. safe_connection_set_socket(newconn->safe_conn, news);
  1737. }
  1738. if (new_type == CONN_TYPE_AP && conn->socket_family != AF_UNIX) {
  1739. log_info(LD_NET, "New SOCKS connection opened from %s.",
  1740. fmt_and_decorate_addr(&addr));
  1741. }
  1742. if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  1743. log_info(LD_NET, "New SOCKS AF_UNIX connection opened");
  1744. }
  1745. if (new_type == CONN_TYPE_CONTROL) {
  1746. log_notice(LD_CONTROL, "New control connection opened from %s.",
  1747. fmt_and_decorate_addr(&addr));
  1748. }
  1749. } else if (conn->socket_family == AF_UNIX && conn->type != CONN_TYPE_AP) {
  1750. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  1751. tor_assert(new_type == CONN_TYPE_CONTROL);
  1752. log_notice(LD_CONTROL, "New control connection opened.");
  1753. newconn = connection_new(new_type, conn->socket_family);
  1754. newconn->s = news;
  1755. /* remember the remote address -- do we have anything sane to put here? */
  1756. tor_addr_make_unspec(&newconn->addr);
  1757. newconn->port = 1;
  1758. newconn->address = tor_strdup(conn->address);
  1759. } else {
  1760. tor_assert(0);
  1761. };
  1762. channel_t *chan = NULL;
  1763. if (new_type == CONN_TYPE_OR) {
  1764. /* Incoming connections will need a new channel passed to the
  1765. * channel_tls_listener */
  1766. tor_assert(TO_OR_CONN(newconn)->chan == NULL);
  1767. chan = channel_tls_handle_incoming(TO_OR_CONN(newconn));
  1768. channel_listener_queue_incoming(channel_tls_get_listener(), chan);
  1769. }
  1770. if (connection_add(newconn) < 0) { /* no space, forget it */
  1771. channel_close_for_error(chan);
  1772. connection_free(newconn);
  1773. return 0; /* no need to tear down the parent */
  1774. }
  1775. if (connection_init_accepted_conn(newconn, TO_LISTENER_CONN(conn)) < 0) {
  1776. channel_close_for_error(chan);
  1777. if (! newconn->marked_for_close)
  1778. connection_mark_for_close(newconn);
  1779. return 0;
  1780. }
  1781. return 0;
  1782. }
  1783. /** Initialize states for newly accepted connection <b>conn</b>.
  1784. *
  1785. * If conn is an OR, start the TLS handshake.
  1786. *
  1787. * If conn is a transparent AP, get its original destination
  1788. * and place it in circuit_wait.
  1789. *
  1790. * The <b>listener</b> parameter is only used for AP connections.
  1791. */
  1792. int
  1793. connection_init_accepted_conn(connection_t *conn,
  1794. const listener_connection_t *listener)
  1795. {
  1796. int rv;
  1797. if (conn->type != CONN_TYPE_OR) {
  1798. connection_start_reading(conn);
  1799. }
  1800. switch (conn->type) {
  1801. case CONN_TYPE_EXT_OR:
  1802. /* Initiate Extended ORPort authentication. */
  1803. return connection_ext_or_start_auth(TO_OR_CONN(conn));
  1804. case CONN_TYPE_OR:
  1805. connection_or_event_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
  1806. //rv = connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  1807. //if (rv < 0) {
  1808. // connection_or_close_for_error(TO_OR_CONN(conn), 0);
  1809. //}
  1810. //return rv;
  1811. return 0;
  1812. break;
  1813. case CONN_TYPE_AP:
  1814. memcpy(&TO_ENTRY_CONN(conn)->entry_cfg, &listener->entry_cfg,
  1815. sizeof(entry_port_cfg_t));
  1816. TO_ENTRY_CONN(conn)->nym_epoch = get_signewnym_epoch();
  1817. TO_ENTRY_CONN(conn)->socks_request->listener_type = listener->base_.type;
  1818. /* Any incoming connection on an entry port counts as user activity. */
  1819. note_user_activity(approx_time());
  1820. switch (TO_CONN(listener)->type) {
  1821. case CONN_TYPE_AP_LISTENER:
  1822. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  1823. TO_ENTRY_CONN(conn)->socks_request->socks_prefer_no_auth =
  1824. listener->entry_cfg.socks_prefer_no_auth;
  1825. break;
  1826. case CONN_TYPE_AP_TRANS_LISTENER:
  1827. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1828. /* XXXX028 -- is this correct still, with the addition of
  1829. * pending_entry_connections ? */
  1830. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1831. return connection_ap_process_transparent(TO_ENTRY_CONN(conn));
  1832. case CONN_TYPE_AP_NATD_LISTENER:
  1833. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1834. conn->state = AP_CONN_STATE_NATD_WAIT;
  1835. break;
  1836. case CONN_TYPE_AP_HTTP_CONNECT_LISTENER:
  1837. conn->state = AP_CONN_STATE_HTTP_CONNECT_WAIT;
  1838. }
  1839. break;
  1840. case CONN_TYPE_DIR:
  1841. conn->purpose = DIR_PURPOSE_SERVER;
  1842. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  1843. break;
  1844. case CONN_TYPE_CONTROL:
  1845. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  1846. break;
  1847. }
  1848. return 0;
  1849. }
  1850. /** Take conn, make a nonblocking socket; try to connect to
  1851. * sa, binding to bindaddr if sa is not localhost. If fail, return -1 and if
  1852. * applicable put your best guess about errno into *<b>socket_error</b>.
  1853. * If connected return 1, if EAGAIN return 0.
  1854. */
  1855. MOCK_IMPL(STATIC int,
  1856. connection_connect_sockaddr,(connection_t *conn,
  1857. const struct sockaddr *sa,
  1858. socklen_t sa_len,
  1859. const struct sockaddr *bindaddr,
  1860. socklen_t bindaddr_len,
  1861. int *socket_error))
  1862. {
  1863. tor_socket_t s;
  1864. int inprogress = 0;
  1865. const or_options_t *options = get_options();
  1866. tor_assert(conn);
  1867. tor_assert(sa);
  1868. tor_assert(socket_error);
  1869. if (net_is_completely_disabled()) {
  1870. /* We should never even try to connect anyplace if the network is
  1871. * completely shut off.
  1872. *
  1873. * (We don't check net_is_disabled() here, since we still sometimes
  1874. * want to open connections when we're in soft hibernation.)
  1875. */
  1876. static ratelim_t disablenet_violated = RATELIM_INIT(30*60);
  1877. *socket_error = SOCK_ERRNO(ENETUNREACH);
  1878. log_fn_ratelim(&disablenet_violated, LOG_WARN, LD_BUG,
  1879. "Tried to open a socket with DisableNetwork set.");
  1880. tor_fragile_assert();
  1881. return -1;
  1882. }
  1883. const int protocol_family = sa->sa_family;
  1884. const int proto = (sa->sa_family == AF_INET6 ||
  1885. sa->sa_family == AF_INET) ? IPPROTO_TCP : 0;
  1886. s = tor_open_socket_nonblocking(protocol_family, SOCK_STREAM, proto);
  1887. if (! SOCKET_OK(s)) {
  1888. /*
  1889. * Early OOS handler calls; it matters if it's an exhaustion-related
  1890. * error or not.
  1891. */
  1892. *socket_error = tor_socket_errno(s);
  1893. if (ERRNO_IS_RESOURCE_LIMIT(*socket_error)) {
  1894. warn_too_many_conns();
  1895. connection_check_oos(get_n_open_sockets(), 1);
  1896. } else {
  1897. log_warn(LD_NET,"Error creating network socket: %s",
  1898. tor_socket_strerror(*socket_error));
  1899. connection_check_oos(get_n_open_sockets(), 0);
  1900. }
  1901. return -1;
  1902. }
  1903. if (make_socket_reuseable(s) < 0) {
  1904. log_warn(LD_NET, "Error setting SO_REUSEADDR flag on new connection: %s",
  1905. tor_socket_strerror(errno));
  1906. }
  1907. /*
  1908. * We've got the socket open; give the OOS handler a chance to check
  1909. * against configured maximum socket number, but tell it no exhaustion
  1910. * failure.
  1911. */
  1912. connection_check_oos(get_n_open_sockets(), 0);
  1913. if (bindaddr && bind(s, bindaddr, bindaddr_len) < 0) {
  1914. *socket_error = tor_socket_errno(s);
  1915. log_warn(LD_NET,"Error binding network socket: %s",
  1916. tor_socket_strerror(*socket_error));
  1917. tor_close_socket(s);
  1918. return -1;
  1919. }
  1920. tor_assert(options);
  1921. if (options->ConstrainedSockets)
  1922. set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
  1923. if (connect(s, sa, sa_len) < 0) {
  1924. int e = tor_socket_errno(s);
  1925. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1926. /* yuck. kill it. */
  1927. *socket_error = e;
  1928. log_info(LD_NET,
  1929. "connect() to socket failed: %s",
  1930. tor_socket_strerror(e));
  1931. tor_close_socket(s);
  1932. return -1;
  1933. } else {
  1934. inprogress = 1;
  1935. }
  1936. }
  1937. /* it succeeded. we're connected. */
  1938. log_fn(inprogress ? LOG_DEBUG : LOG_INFO, LD_NET,
  1939. "Connection to socket %s (sock "TOR_SOCKET_T_FORMAT").",
  1940. inprogress ? "in progress" : "established", s);
  1941. conn->s = s;
  1942. if (!connection_uses_safe_conn(conn->type)) {
  1943. conn->s = s;
  1944. } else {
  1945. tor_assert(conn->safe_conn != NULL);
  1946. safe_connection_set_socket(conn->safe_conn, s);
  1947. }
  1948. if (connection_add_connecting(conn) < 0) {
  1949. /* no space, forget it */
  1950. *socket_error = SOCK_ERRNO(ENOBUFS);
  1951. return -1;
  1952. }
  1953. return inprogress ? 0 : 1;
  1954. }
  1955. /* Log a message if connection attempt is made when IPv4 or IPv6 is disabled.
  1956. * Log a less severe message if we couldn't conform to ClientPreferIPv6ORPort
  1957. * or ClientPreferIPv6ORPort. */
  1958. static void
  1959. connection_connect_log_client_use_ip_version(const connection_t *conn)
  1960. {
  1961. const or_options_t *options = get_options();
  1962. /* Only clients care about ClientUseIPv4/6, bail out early on servers, and
  1963. * on connections we don't care about */
  1964. if (server_mode(options) || !conn || conn->type == CONN_TYPE_EXIT) {
  1965. return;
  1966. }
  1967. /* We're only prepared to log OR and DIR connections here */
  1968. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR) {
  1969. return;
  1970. }
  1971. const int must_ipv4 = !fascist_firewall_use_ipv6(options);
  1972. const int must_ipv6 = (options->ClientUseIPv4 == 0);
  1973. const int pref_ipv6 = (conn->type == CONN_TYPE_OR
  1974. ? fascist_firewall_prefer_ipv6_orport(options)
  1975. : fascist_firewall_prefer_ipv6_dirport(options));
  1976. tor_addr_t real_addr;
  1977. tor_addr_make_null(&real_addr, AF_UNSPEC);
  1978. /* OR conns keep the original address in real_addr, as addr gets overwritten
  1979. * with the descriptor address */
  1980. if (conn->type == CONN_TYPE_OR) {
  1981. const or_connection_t *or_conn = TO_OR_CONN((connection_t *)conn);
  1982. tor_addr_copy(&real_addr, &or_conn->real_addr);
  1983. } else if (conn->type == CONN_TYPE_DIR) {
  1984. tor_addr_copy(&real_addr, &conn->addr);
  1985. }
  1986. /* Check if we broke a mandatory address family restriction */
  1987. if ((must_ipv4 && tor_addr_family(&real_addr) == AF_INET6)
  1988. || (must_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
  1989. static int logged_backtrace = 0;
  1990. log_info(LD_BUG, "Outgoing %s connection to %s violated ClientUseIPv%s 0.",
  1991. conn->type == CONN_TYPE_OR ? "OR" : "Dir",
  1992. fmt_addr(&real_addr),
  1993. options->ClientUseIPv4 == 0 ? "4" : "6");
  1994. if (!logged_backtrace) {
  1995. log_backtrace(LOG_INFO, LD_BUG, "Address came from");
  1996. logged_backtrace = 1;
  1997. }
  1998. }
  1999. /* Bridges are allowed to break IPv4/IPv6 ORPort preferences to connect to
  2000. * the node's configured address when ClientPreferIPv6ORPort is auto */
  2001. if (options->UseBridges && conn->type == CONN_TYPE_OR
  2002. && options->ClientPreferIPv6ORPort == -1) {
  2003. return;
  2004. }
  2005. if (fascist_firewall_use_ipv6(options)) {
  2006. log_info(LD_NET, "Our outgoing connection is using IPv%d.",
  2007. tor_addr_family(&real_addr) == AF_INET6 ? 6 : 4);
  2008. }
  2009. /* Check if we couldn't satisfy an address family preference */
  2010. if ((!pref_ipv6 && tor_addr_family(&real_addr) == AF_INET6)
  2011. || (pref_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
  2012. log_info(LD_NET, "Outgoing connection to %s doesn't satisfy "
  2013. "ClientPreferIPv6%sPort %d, with ClientUseIPv4 %d, and "
  2014. "fascist_firewall_use_ipv6 %d (ClientUseIPv6 %d and UseBridges "
  2015. "%d).",
  2016. fmt_addr(&real_addr),
  2017. conn->type == CONN_TYPE_OR ? "OR" : "Dir",
  2018. conn->type == CONN_TYPE_OR ? options->ClientPreferIPv6ORPort
  2019. : options->ClientPreferIPv6DirPort,
  2020. options->ClientUseIPv4, fascist_firewall_use_ipv6(options),
  2021. options->ClientUseIPv6, options->UseBridges);
  2022. }
  2023. }
  2024. /** Retrieve the outbound address depending on the protocol (IPv4 or IPv6)
  2025. * and the connection type (relay, exit, ...)
  2026. * Return a socket address or NULL in case nothing is configured.
  2027. **/
  2028. const tor_addr_t *
  2029. conn_get_outbound_address(sa_family_t family,
  2030. const or_options_t *options, unsigned int conn_type)
  2031. {
  2032. const tor_addr_t *ext_addr = NULL;
  2033. int fam_index;
  2034. switch (family) {
  2035. case AF_INET:
  2036. fam_index = 0;
  2037. break;
  2038. case AF_INET6:
  2039. fam_index = 1;
  2040. break;
  2041. default:
  2042. return NULL;
  2043. }
  2044. // If an exit connection, use the exit address (if present)
  2045. if (conn_type == CONN_TYPE_EXIT) {
  2046. if (!tor_addr_is_null(
  2047. &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT][fam_index])) {
  2048. ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT]
  2049. [fam_index];
  2050. } else if (!tor_addr_is_null(
  2051. &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
  2052. [fam_index])) {
  2053. ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
  2054. [fam_index];
  2055. }
  2056. } else { // All non-exit connections
  2057. if (!tor_addr_is_null(
  2058. &options->OutboundBindAddresses[OUTBOUND_ADDR_OR][fam_index])) {
  2059. ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_OR]
  2060. [fam_index];
  2061. } else if (!tor_addr_is_null(
  2062. &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
  2063. [fam_index])) {
  2064. ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
  2065. [fam_index];
  2066. }
  2067. }
  2068. return ext_addr;
  2069. }
  2070. /** Take conn, make a nonblocking socket; try to connect to
  2071. * addr:port (port arrives in *host order*). If fail, return -1 and if
  2072. * applicable put your best guess about errno into *<b>socket_error</b>.
  2073. * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  2074. *
  2075. * addr:port can be different to conn->addr:conn->port if connecting through
  2076. * a proxy.
  2077. *
  2078. * address is used to make the logs useful.
  2079. *
  2080. * On success, add conn to the list of polled connections.
  2081. */
  2082. int
  2083. connection_connect(connection_t *conn, const char *address,
  2084. const tor_addr_t *addr, uint16_t port, int *socket_error)
  2085. {
  2086. struct sockaddr_storage addrbuf;
  2087. struct sockaddr_storage bind_addr_ss;
  2088. struct sockaddr *bind_addr = NULL;
  2089. struct sockaddr *dest_addr;
  2090. int dest_addr_len, bind_addr_len = 0;
  2091. /* Log if we didn't stick to ClientUseIPv4/6 or ClientPreferIPv6OR/DirPort
  2092. */
  2093. connection_connect_log_client_use_ip_version(conn);
  2094. if (!tor_addr_is_loopback(addr)) {
  2095. const tor_addr_t *ext_addr = NULL;
  2096. ext_addr = conn_get_outbound_address(tor_addr_family(addr), get_options(),
  2097. conn->type);
  2098. if (ext_addr) {
  2099. memset(&bind_addr_ss, 0, sizeof(bind_addr_ss));
  2100. bind_addr_len = tor_addr_to_sockaddr(ext_addr, 0,
  2101. (struct sockaddr *) &bind_addr_ss,
  2102. sizeof(bind_addr_ss));
  2103. if (bind_addr_len == 0) {
  2104. log_warn(LD_NET,
  2105. "Error converting OutboundBindAddress %s into sockaddr. "
  2106. "Ignoring.", fmt_and_decorate_addr(ext_addr));
  2107. } else {
  2108. bind_addr = (struct sockaddr *)&bind_addr_ss;
  2109. }
  2110. }
  2111. }
  2112. memset(&addrbuf,0,sizeof(addrbuf));
  2113. dest_addr = (struct sockaddr*) &addrbuf;
  2114. dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
  2115. tor_assert(dest_addr_len > 0);
  2116. log_debug(LD_NET, "Connecting to %s:%u.",
  2117. escaped_safe_str_client(address), port);
  2118. return connection_connect_sockaddr(conn, dest_addr, dest_addr_len,
  2119. bind_addr, bind_addr_len, socket_error);
  2120. }
  2121. #ifdef HAVE_SYS_UN_H
  2122. /** Take conn, make a nonblocking socket; try to connect to
  2123. * an AF_UNIX socket at socket_path. If fail, return -1 and if applicable
  2124. * put your best guess about errno into *<b>socket_error</b>. Else assign s
  2125. * to conn-\>s: if connected return 1, if EAGAIN return 0.
  2126. *
  2127. * On success, add conn to the list of polled connections.
  2128. */
  2129. int
  2130. connection_connect_unix(connection_t *conn, const char *socket_path,
  2131. int *socket_error)
  2132. {
  2133. struct sockaddr_un dest_addr;
  2134. tor_assert(socket_path);
  2135. /* Check that we'll be able to fit it into dest_addr later */
  2136. if (strlen(socket_path) + 1 > sizeof(dest_addr.sun_path)) {
  2137. log_warn(LD_NET,
  2138. "Path %s is too long for an AF_UNIX socket\n",
  2139. escaped_safe_str_client(socket_path));
  2140. *socket_error = SOCK_ERRNO(ENAMETOOLONG);
  2141. return -1;
  2142. }
  2143. memset(&dest_addr, 0, sizeof(dest_addr));
  2144. dest_addr.sun_family = AF_UNIX;
  2145. strlcpy(dest_addr.sun_path, socket_path, sizeof(dest_addr.sun_path));
  2146. log_debug(LD_NET,
  2147. "Connecting to AF_UNIX socket at %s.",
  2148. escaped_safe_str_client(socket_path));
  2149. return connection_connect_sockaddr(conn,
  2150. (struct sockaddr *)&dest_addr, sizeof(dest_addr),
  2151. NULL, 0, socket_error);
  2152. }
  2153. #endif /* defined(HAVE_SYS_UN_H) */
  2154. /** Convert state number to string representation for logging purposes.
  2155. */
  2156. static const char *
  2157. connection_proxy_state_to_string(int state)
  2158. {
  2159. static const char *unknown = "???";
  2160. static const char *states[] = {
  2161. "PROXY_NONE",
  2162. "PROXY_INFANT",
  2163. "PROXY_HTTPS_WANT_CONNECT_OK",
  2164. "PROXY_SOCKS4_WANT_CONNECT_OK",
  2165. "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
  2166. "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
  2167. "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
  2168. "PROXY_SOCKS5_WANT_CONNECT_OK",
  2169. "PROXY_CONNECTED",
  2170. };
  2171. if (state < PROXY_NONE || state > PROXY_CONNECTED)
  2172. return unknown;
  2173. return states[state];
  2174. }
  2175. /** Returns the proxy type used by tor for a single connection, for
  2176. * logging or high-level purposes. Don't use it to fill the
  2177. * <b>proxy_type</b> field of or_connection_t; use the actual proxy
  2178. * protocol instead.*/
  2179. static int
  2180. conn_get_proxy_type(const connection_t *conn)
  2181. {
  2182. const or_options_t *options = get_options();
  2183. if (options->ClientTransportPlugin) {
  2184. /* If we have plugins configured *and* this addr/port is a known bridge
  2185. * with a transport, then we should be PROXY_PLUGGABLE. */
  2186. const transport_t *transport = NULL;
  2187. int r;
  2188. r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
  2189. if (r == 0 && transport)
  2190. return PROXY_PLUGGABLE;
  2191. }
  2192. /* In all other cases, we're using a global proxy. */
  2193. if (options->HTTPSProxy)
  2194. return PROXY_CONNECT;
  2195. else if (options->Socks4Proxy)
  2196. return PROXY_SOCKS4;
  2197. else if (options->Socks5Proxy)
  2198. return PROXY_SOCKS5;
  2199. else
  2200. return PROXY_NONE;
  2201. }
  2202. /* One byte for the version, one for the command, two for the
  2203. port, and four for the addr... and, one more for the
  2204. username NUL: */
  2205. #define SOCKS4_STANDARD_BUFFER_SIZE (1 + 1 + 2 + 4 + 1)
  2206. /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
  2207. * for conn->addr:conn->port, authenticating with the auth details given
  2208. * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
  2209. * support authentication.
  2210. *
  2211. * Returns -1 if conn->addr is incompatible with the proxy protocol, and
  2212. * 0 otherwise.
  2213. *
  2214. * Use connection_read_proxy_handshake() to complete the handshake.
  2215. */
  2216. int
  2217. connection_proxy_connect(connection_t *conn, int type)
  2218. {
  2219. const or_options_t *options;
  2220. tor_assert(conn);
  2221. options = get_options();
  2222. switch (type) {
  2223. case PROXY_CONNECT: {
  2224. char buf[1024];
  2225. char *base64_authenticator=NULL;
  2226. const char *authenticator = options->HTTPSProxyAuthenticator;
  2227. /* Send HTTP CONNECT and authentication (if available) in
  2228. * one request */
  2229. if (authenticator) {
  2230. base64_authenticator = alloc_http_authenticator(authenticator);
  2231. if (!base64_authenticator)
  2232. log_warn(LD_OR, "Encoding https authenticator failed");
  2233. }
  2234. if (base64_authenticator) {
  2235. const char *addrport = fmt_addrport(&conn->addr, conn->port);
  2236. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.1\r\n"
  2237. "Host: %s\r\n"
  2238. "Proxy-Authorization: Basic %s\r\n\r\n",
  2239. addrport,
  2240. addrport,
  2241. base64_authenticator);
  2242. tor_free(base64_authenticator);
  2243. } else {
  2244. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.0\r\n\r\n",
  2245. fmt_addrport(&conn->addr, conn->port));
  2246. }
  2247. connection_buf_add(buf, strlen(buf), conn);
  2248. conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
  2249. break;
  2250. }
  2251. case PROXY_SOCKS4: {
  2252. unsigned char *buf;
  2253. uint16_t portn;
  2254. uint32_t ip4addr;
  2255. size_t buf_size = 0;
  2256. char *socks_args_string = NULL;
  2257. /* Send a SOCKS4 connect request */
  2258. if (tor_addr_family(&conn->addr) != AF_INET) {
  2259. log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
  2260. return -1;
  2261. }
  2262. { /* If we are here because we are trying to connect to a
  2263. pluggable transport proxy, check if we have any SOCKS
  2264. arguments to transmit. If we do, compress all arguments to
  2265. a single string in 'socks_args_string': */
  2266. if (conn_get_proxy_type(conn) == PROXY_PLUGGABLE) {
  2267. socks_args_string =
  2268. pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
  2269. if (socks_args_string)
  2270. log_debug(LD_NET, "Sending out '%s' as our SOCKS argument string.",
  2271. socks_args_string);
  2272. }
  2273. }
  2274. { /* Figure out the buffer size we need for the SOCKS message: */
  2275. buf_size = SOCKS4_STANDARD_BUFFER_SIZE;
  2276. /* If we have a SOCKS argument string, consider its size when
  2277. calculating the buffer size: */
  2278. if (socks_args_string)
  2279. buf_size += strlen(socks_args_string);
  2280. }
  2281. buf = tor_malloc_zero(buf_size);
  2282. ip4addr = tor_addr_to_ipv4n(&conn->addr);
  2283. portn = htons(conn->port);
  2284. buf[0] = 4; /* version */
  2285. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  2286. memcpy(buf + 2, &portn, 2); /* port */
  2287. memcpy(buf + 4, &ip4addr, 4); /* addr */
  2288. /* Next packet field is the userid. If we have pluggable
  2289. transport SOCKS arguments, we have to embed them
  2290. there. Otherwise, we use an empty userid. */
  2291. if (socks_args_string) { /* place the SOCKS args string: */
  2292. tor_assert(strlen(socks_args_string) > 0);
  2293. tor_assert(buf_size >=
  2294. SOCKS4_STANDARD_BUFFER_SIZE + strlen(socks_args_string));
  2295. strlcpy((char *)buf + 8, socks_args_string, buf_size - 8);
  2296. tor_free(socks_args_string);
  2297. } else {
  2298. buf[8] = 0; /* no userid */
  2299. }
  2300. connection_buf_add((char *)buf, buf_size, conn);
  2301. tor_free(buf);
  2302. conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
  2303. break;
  2304. }
  2305. case PROXY_SOCKS5: {
  2306. unsigned char buf[4]; /* fields: vers, num methods, method list */
  2307. /* Send a SOCKS5 greeting (connect request must wait) */
  2308. buf[0] = 5; /* version */
  2309. /* We have to use SOCKS5 authentication, if we have a
  2310. Socks5ProxyUsername or if we want to pass arguments to our
  2311. pluggable transport proxy: */
  2312. if ((options->Socks5ProxyUsername) ||
  2313. (conn_get_proxy_type(conn) == PROXY_PLUGGABLE &&
  2314. (get_socks_args_by_bridge_addrport(&conn->addr, conn->port)))) {
  2315. /* number of auth methods */
  2316. buf[1] = 2;
  2317. buf[2] = 0x00; /* no authentication */
  2318. buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
  2319. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
  2320. } else {
  2321. buf[1] = 1;
  2322. buf[2] = 0x00; /* no authentication */
  2323. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
  2324. }
  2325. connection_buf_add((char *)buf, 2 + buf[1], conn);
  2326. break;
  2327. }
  2328. default:
  2329. log_err(LD_BUG, "Invalid proxy protocol, %d", type);
  2330. tor_fragile_assert();
  2331. return -1;
  2332. }
  2333. log_debug(LD_NET, "set state %s",
  2334. connection_proxy_state_to_string(conn->proxy_state));
  2335. return 0;
  2336. }
  2337. /** Read conn's inbuf. If the http response from the proxy is all
  2338. * here, make sure it's good news, then return 1. If it's bad news,
  2339. * return -1. Else return 0 and hope for better luck next time.
  2340. */
  2341. static int
  2342. connection_read_https_proxy_response(connection_t *conn)
  2343. {
  2344. char *headers;
  2345. char *reason=NULL;
  2346. int status_code;
  2347. time_t date_header;
  2348. switch (fetch_from_buf_http(conn->inbuf,
  2349. &headers, MAX_HEADERS_SIZE,
  2350. NULL, NULL, 10000, 0)) {
  2351. case -1: /* overflow */
  2352. log_warn(LD_PROTOCOL,
  2353. "Your https proxy sent back an oversized response. Closing.");
  2354. return -1;
  2355. case 0:
  2356. log_info(LD_NET,"https proxy response not all here yet. Waiting.");
  2357. return 0;
  2358. /* case 1, fall through */
  2359. }
  2360. if (parse_http_response(headers, &status_code, &date_header,
  2361. NULL, &reason) < 0) {
  2362. log_warn(LD_NET,
  2363. "Unparseable headers from proxy (connecting to '%s'). Closing.",
  2364. conn->address);
  2365. tor_free(headers);
  2366. return -1;
  2367. }
  2368. tor_free(headers);
  2369. if (!reason) reason = tor_strdup("[no reason given]");
  2370. if (status_code == 200) {
  2371. log_info(LD_NET,
  2372. "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
  2373. conn->address, escaped(reason));
  2374. tor_free(reason);
  2375. return 1;
  2376. }
  2377. /* else, bad news on the status code */
  2378. switch (status_code) {
  2379. case 403:
  2380. log_warn(LD_NET,
  2381. "The https proxy refused to allow connection to %s "
  2382. "(status code %d, %s). Closing.",
  2383. conn->address, status_code, escaped(reason));
  2384. break;
  2385. default:
  2386. log_warn(LD_NET,
  2387. "The https proxy sent back an unexpected status code %d (%s). "
  2388. "Closing.",
  2389. status_code, escaped(reason));
  2390. break;
  2391. }
  2392. tor_free(reason);
  2393. return -1;
  2394. }
  2395. /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
  2396. * and <b>conn->port</b> into the request.
  2397. */
  2398. static void
  2399. connection_send_socks5_connect(connection_t *conn)
  2400. {
  2401. unsigned char buf[1024];
  2402. size_t reqsize = 6;
  2403. uint16_t port = htons(conn->port);
  2404. buf[0] = 5; /* version */
  2405. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  2406. buf[2] = 0; /* reserved */
  2407. if (tor_addr_family(&conn->addr) == AF_INET) {
  2408. uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
  2409. buf[3] = 1;
  2410. reqsize += 4;
  2411. memcpy(buf + 4, &addr, 4);
  2412. memcpy(buf + 8, &port, 2);
  2413. } else { /* AF_INET6 */
  2414. buf[3] = 4;
  2415. reqsize += 16;
  2416. memcpy(buf + 4, tor_addr_to_in6_addr8(&conn->addr), 16);
  2417. memcpy(buf + 20, &port, 2);
  2418. }
  2419. connection_buf_add((char *)buf, reqsize, conn);
  2420. conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
  2421. }
  2422. /** Wrapper around fetch_from_buf_socks_client: see that functions
  2423. * for documentation of its behavior. */
  2424. static int
  2425. connection_fetch_from_buf_socks_client(connection_t *conn,
  2426. int state, char **reason)
  2427. {
  2428. return fetch_from_buf_socks_client(conn->inbuf, state, reason);
  2429. }
  2430. /** Call this from connection_*_process_inbuf() to advance the proxy
  2431. * handshake.
  2432. *
  2433. * No matter what proxy protocol is used, if this function returns 1, the
  2434. * handshake is complete, and the data remaining on inbuf may contain the
  2435. * start of the communication with the requested server.
  2436. *
  2437. * Returns 0 if the current buffer contains an incomplete response, and -1
  2438. * on error.
  2439. */
  2440. int
  2441. connection_read_proxy_handshake(connection_t *conn)
  2442. {
  2443. int ret = 0;
  2444. char *reason = NULL;
  2445. log_debug(LD_NET, "enter state %s",
  2446. connection_proxy_state_to_string(conn->proxy_state));
  2447. switch (conn->proxy_state) {
  2448. case PROXY_HTTPS_WANT_CONNECT_OK:
  2449. ret = connection_read_https_proxy_response(conn);
  2450. if (ret == 1)
  2451. conn->proxy_state = PROXY_CONNECTED;
  2452. break;
  2453. case PROXY_SOCKS4_WANT_CONNECT_OK:
  2454. ret = connection_fetch_from_buf_socks_client(conn,
  2455. conn->proxy_state,
  2456. &reason);
  2457. if (ret == 1)
  2458. conn->proxy_state = PROXY_CONNECTED;
  2459. break;
  2460. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  2461. ret = connection_fetch_from_buf_socks_client(conn,
  2462. conn->proxy_state,
  2463. &reason);
  2464. /* no auth needed, do connect */
  2465. if (ret == 1) {
  2466. connection_send_socks5_connect(conn);
  2467. ret = 0;
  2468. }
  2469. break;
  2470. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  2471. ret = connection_fetch_from_buf_socks_client(conn,
  2472. conn->proxy_state,
  2473. &reason);
  2474. /* send auth if needed, otherwise do connect */
  2475. if (ret == 1) {
  2476. connection_send_socks5_connect(conn);
  2477. ret = 0;
  2478. } else if (ret == 2) {
  2479. unsigned char buf[1024];
  2480. size_t reqsize, usize, psize;
  2481. const char *user, *pass;
  2482. char *socks_args_string = NULL;
  2483. if (conn_get_proxy_type(conn) == PROXY_PLUGGABLE) {
  2484. socks_args_string =
  2485. pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
  2486. if (!socks_args_string) {
  2487. log_warn(LD_NET, "Could not create SOCKS args string for PT.");
  2488. ret = -1;
  2489. break;
  2490. }
  2491. log_debug(LD_NET, "PT SOCKS5 arguments: %s", socks_args_string);
  2492. tor_assert(strlen(socks_args_string) > 0);
  2493. tor_assert(strlen(socks_args_string) <= MAX_SOCKS5_AUTH_SIZE_TOTAL);
  2494. if (strlen(socks_args_string) > MAX_SOCKS5_AUTH_FIELD_SIZE) {
  2495. user = socks_args_string;
  2496. usize = MAX_SOCKS5_AUTH_FIELD_SIZE;
  2497. pass = socks_args_string + MAX_SOCKS5_AUTH_FIELD_SIZE;
  2498. psize = strlen(socks_args_string) - MAX_SOCKS5_AUTH_FIELD_SIZE;
  2499. } else {
  2500. user = socks_args_string;
  2501. usize = strlen(socks_args_string);
  2502. pass = "\0";
  2503. psize = 1;
  2504. }
  2505. } else if (get_options()->Socks5ProxyUsername) {
  2506. user = get_options()->Socks5ProxyUsername;
  2507. pass = get_options()->Socks5ProxyPassword;
  2508. tor_assert(user && pass);
  2509. usize = strlen(user);
  2510. psize = strlen(pass);
  2511. } else {
  2512. log_err(LD_BUG, "We entered %s for no reason!", __func__);
  2513. tor_fragile_assert();
  2514. ret = -1;
  2515. break;
  2516. }
  2517. /* Username and password lengths should have been checked
  2518. above and during torrc parsing. */
  2519. tor_assert(usize <= MAX_SOCKS5_AUTH_FIELD_SIZE &&
  2520. psize <= MAX_SOCKS5_AUTH_FIELD_SIZE);
  2521. reqsize = 3 + usize + psize;
  2522. buf[0] = 1; /* negotiation version */
  2523. buf[1] = usize;
  2524. memcpy(buf + 2, user, usize);
  2525. buf[2 + usize] = psize;
  2526. memcpy(buf + 3 + usize, pass, psize);
  2527. if (socks_args_string)
  2528. tor_free(socks_args_string);
  2529. connection_buf_add((char *)buf, reqsize, conn);
  2530. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
  2531. ret = 0;
  2532. }
  2533. break;
  2534. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  2535. ret = connection_fetch_from_buf_socks_client(conn,
  2536. conn->proxy_state,
  2537. &reason);
  2538. /* send the connect request */
  2539. if (ret == 1) {
  2540. connection_send_socks5_connect(conn);
  2541. ret = 0;
  2542. }
  2543. break;
  2544. case PROXY_SOCKS5_WANT_CONNECT_OK:
  2545. ret = connection_fetch_from_buf_socks_client(conn,
  2546. conn->proxy_state,
  2547. &reason);
  2548. if (ret == 1)
  2549. conn->proxy_state = PROXY_CONNECTED;
  2550. break;
  2551. default:
  2552. log_err(LD_BUG, "Invalid proxy_state for reading, %d",
  2553. conn->proxy_state);
  2554. tor_fragile_assert();
  2555. ret = -1;
  2556. break;
  2557. }
  2558. log_debug(LD_NET, "leaving state %s",
  2559. connection_proxy_state_to_string(conn->proxy_state));
  2560. if (ret < 0) {
  2561. if (reason) {
  2562. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
  2563. conn->address, conn->port, escaped(reason));
  2564. tor_free(reason);
  2565. } else {
  2566. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
  2567. conn->address, conn->port);
  2568. }
  2569. } else if (ret == 1) {
  2570. log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
  2571. conn->address, conn->port);
  2572. }
  2573. return ret;
  2574. }
  2575. /** Given a list of listener connections in <b>old_conns</b>, and list of
  2576. * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
  2577. * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
  2578. *
  2579. * Remove from <b>old_conns</b> every connection that has a corresponding
  2580. * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
  2581. * launch. If we may need to perform socket rebind when creating new
  2582. * listener that replaces old one, create a <b>listener_replacement_t</b>
  2583. * struct for affected pair and add it to <b>replacements</b>.
  2584. *
  2585. * If <b>control_listeners_only</b> is true, then we only open control
  2586. * listeners, and we do not remove any noncontrol listeners from
  2587. * old_conns.
  2588. *
  2589. * Return 0 on success, -1 on failure.
  2590. **/
  2591. static int
  2592. retry_listener_ports(smartlist_t *old_conns,
  2593. const smartlist_t *ports,
  2594. smartlist_t *new_conns,
  2595. smartlist_t *replacements,
  2596. int control_listeners_only)
  2597. {
  2598. #ifndef ENABLE_LISTENER_REBIND
  2599. (void)replacements;
  2600. #endif
  2601. smartlist_t *launch = smartlist_new();
  2602. int r = 0;
  2603. if (control_listeners_only) {
  2604. SMARTLIST_FOREACH(ports, port_cfg_t *, p, {
  2605. if (p->type == CONN_TYPE_CONTROL_LISTENER)
  2606. smartlist_add(launch, p);
  2607. });
  2608. } else {
  2609. smartlist_add_all(launch, ports);
  2610. }
  2611. /* Iterate through old_conns, comparing it to launch: remove from both lists
  2612. * each pair of elements that corresponds to the same port. */
  2613. SMARTLIST_FOREACH_BEGIN(old_conns, connection_t *, conn) {
  2614. const port_cfg_t *found_port = NULL;
  2615. /* Okay, so this is a listener. Is it configured? */
  2616. /* That is, is it either: 1) exact match - address and port
  2617. * pair match exactly between old listener and new port; or 2)
  2618. * wildcard match - port matches exactly, but *one* of the
  2619. * addresses is wildcard (0.0.0.0 or ::)?
  2620. */
  2621. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, wanted) {
  2622. if (conn->type != wanted->type)
  2623. continue;
  2624. if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
  2625. (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
  2626. continue;
  2627. if (wanted->server_cfg.no_listen)
  2628. continue; /* We don't want to open a listener for this one */
  2629. if (wanted->is_unix_addr) {
  2630. if (conn->socket_family == AF_UNIX &&
  2631. !strcmp(wanted->unix_addr, conn->address)) {
  2632. found_port = wanted;
  2633. break;
  2634. }
  2635. } else {
  2636. /* Numeric values of old and new port match exactly. */
  2637. const int port_matches_exact = (wanted->port == conn->port);
  2638. /* Ports match semantically - either their specific values
  2639. match exactly, or new port is 'auto'.
  2640. */
  2641. const int port_matches = (wanted->port == CFG_AUTO_PORT ||
  2642. port_matches_exact);
  2643. if (port_matches && tor_addr_eq(&wanted->addr, &conn->addr)) {
  2644. found_port = wanted;
  2645. break;
  2646. }
  2647. #ifdef ENABLE_LISTENER_REBIND
  2648. /* Rebinding may be needed if all of the following are true:
  2649. * 1) Address family is the same in old and new listeners.
  2650. * 2) Port number matches exactly (numeric value is the same).
  2651. * 3) *One* of listeners (either old one or new one) has a
  2652. * wildcard IP address (0.0.0.0 or [::]).
  2653. *
  2654. * These are the exact conditions for a first bind() syscall
  2655. * to fail with EADDRINUSE.
  2656. */
  2657. const int may_need_rebind =
  2658. tor_addr_family(&wanted->addr) == tor_addr_family(&conn->addr) &&
  2659. port_matches_exact && bool_neq(tor_addr_is_null(&wanted->addr),
  2660. tor_addr_is_null(&conn->addr));
  2661. if (replacements && may_need_rebind) {
  2662. listener_replacement_t *replacement =
  2663. tor_malloc(sizeof(listener_replacement_t));
  2664. replacement->old_conn = conn;
  2665. replacement->new_port = wanted;
  2666. smartlist_add(replacements, replacement);
  2667. SMARTLIST_DEL_CURRENT(launch, wanted);
  2668. SMARTLIST_DEL_CURRENT(old_conns, conn);
  2669. break;
  2670. }
  2671. #endif /* defined(ENABLE_LISTENER_REBIND) */
  2672. }
  2673. } SMARTLIST_FOREACH_END(wanted);
  2674. if (found_port) {
  2675. /* This listener is already running; we don't need to launch it. */
  2676. //log_debug(LD_NET, "Already have %s on %s:%d",
  2677. // conn_type_to_string(found_port->type), conn->address, conn->port);
  2678. smartlist_remove(launch, found_port);
  2679. /* And we can remove the connection from old_conns too. */
  2680. SMARTLIST_DEL_CURRENT(old_conns, conn);
  2681. }
  2682. } SMARTLIST_FOREACH_END(conn);
  2683. /* Now open all the listeners that are configured but not opened. */
  2684. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, port) {
  2685. int skip = 0;
  2686. connection_t *conn = connection_listener_new_for_port(port, &skip, NULL);
  2687. if (conn && new_conns)
  2688. smartlist_add(new_conns, conn);
  2689. else if (!skip)
  2690. r = -1;
  2691. } SMARTLIST_FOREACH_END(port);
  2692. smartlist_free(launch);
  2693. return r;
  2694. }
  2695. /** Launch listeners for each port you should have open. Only launch
  2696. * listeners who are not already open, and only close listeners we no longer
  2697. * want.
  2698. *
  2699. * Add all new connections to <b>new_conns</b>.
  2700. *
  2701. * If <b>close_all_noncontrol</b> is true, then we only open control
  2702. * listeners, and we close all other listeners.
  2703. */
  2704. int
  2705. retry_all_listeners(smartlist_t *new_conns, int close_all_noncontrol)
  2706. {
  2707. smartlist_t *listeners = smartlist_new();
  2708. smartlist_t *replacements = smartlist_new();
  2709. const or_options_t *options = get_options();
  2710. int retval = 0;
  2711. const uint16_t old_or_port = router_get_advertised_or_port(options);
  2712. const uint16_t old_or_port_ipv6 =
  2713. router_get_advertised_or_port_by_af(options,AF_INET6);
  2714. const uint16_t old_dir_port = router_get_advertised_dir_port(options, 0);
  2715. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2716. if (connection_is_listener(conn) && !conn->marked_for_close)
  2717. smartlist_add(listeners, conn);
  2718. } SMARTLIST_FOREACH_END(conn);
  2719. if (retry_listener_ports(listeners,
  2720. get_configured_ports(),
  2721. new_conns,
  2722. replacements,
  2723. close_all_noncontrol) < 0)
  2724. retval = -1;
  2725. #ifdef ENABLE_LISTENER_REBIND
  2726. if (smartlist_len(replacements))
  2727. log_debug(LD_NET, "%d replacements - starting rebinding loop.",
  2728. smartlist_len(replacements));
  2729. SMARTLIST_FOREACH_BEGIN(replacements, listener_replacement_t *, r) {
  2730. int addr_in_use = 0;
  2731. int skip = 0;
  2732. tor_assert(r->new_port);
  2733. tor_assert(r->old_conn);
  2734. connection_t *new_conn =
  2735. connection_listener_new_for_port(r->new_port, &skip, &addr_in_use);
  2736. connection_t *old_conn = r->old_conn;
  2737. if (skip) {
  2738. log_debug(LD_NET, "Skipping creating new listener for %s:%d",
  2739. old_conn->address, old_conn->port);
  2740. continue;
  2741. }
  2742. connection_close_immediate(old_conn);
  2743. connection_mark_for_close(old_conn);
  2744. if (addr_in_use) {
  2745. new_conn = connection_listener_new_for_port(r->new_port,
  2746. &skip, &addr_in_use);
  2747. }
  2748. tor_assert(new_conn);
  2749. smartlist_add(new_conns, new_conn);
  2750. log_notice(LD_NET, "Closed no-longer-configured %s on %s:%d "
  2751. "(replaced by %s:%d)",
  2752. conn_type_to_string(old_conn->type), old_conn->address,
  2753. old_conn->port, new_conn->address, new_conn->port);
  2754. } SMARTLIST_FOREACH_END(r);
  2755. #endif /* defined(ENABLE_LISTENER_REBIND) */
  2756. /* Any members that were still in 'listeners' don't correspond to
  2757. * any configured port. Kill 'em. */
  2758. SMARTLIST_FOREACH_BEGIN(listeners, connection_t *, conn) {
  2759. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  2760. conn_type_to_string(conn->type), conn->address, conn->port);
  2761. connection_close_immediate(conn);
  2762. connection_mark_for_close(conn);
  2763. } SMARTLIST_FOREACH_END(conn);
  2764. smartlist_free(listeners);
  2765. /* Cleanup any remaining listener replacement. */
  2766. SMARTLIST_FOREACH(replacements, listener_replacement_t *, r, tor_free(r));
  2767. smartlist_free(replacements);
  2768. if (old_or_port != router_get_advertised_or_port(options) ||
  2769. old_or_port_ipv6 != router_get_advertised_or_port_by_af(options,
  2770. AF_INET6) ||
  2771. old_dir_port != router_get_advertised_dir_port(options, 0)) {
  2772. /* Our chosen ORPort or DirPort is not what it used to be: the
  2773. * descriptor we had (if any) should be regenerated. (We won't
  2774. * automatically notice this because of changes in the option,
  2775. * since the value could be "auto".) */
  2776. mark_my_descriptor_dirty("Chosen Or/DirPort changed");
  2777. }
  2778. return retval;
  2779. }
  2780. /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
  2781. void
  2782. connection_mark_all_noncontrol_listeners(void)
  2783. {
  2784. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2785. if (conn->marked_for_close)
  2786. continue;
  2787. if (conn->type == CONN_TYPE_CONTROL_LISTENER)
  2788. continue;
  2789. if (connection_is_listener(conn))
  2790. connection_mark_for_close(conn);
  2791. } SMARTLIST_FOREACH_END(conn);
  2792. }
  2793. /** Mark every external connection not used for controllers for close. */
  2794. void
  2795. connection_mark_all_noncontrol_connections(void)
  2796. {
  2797. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2798. if (conn->marked_for_close)
  2799. continue;
  2800. switch (conn->type) {
  2801. case CONN_TYPE_CONTROL_LISTENER:
  2802. case CONN_TYPE_CONTROL:
  2803. break;
  2804. case CONN_TYPE_AP:
  2805. connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
  2806. END_STREAM_REASON_HIBERNATING);
  2807. break;
  2808. case CONN_TYPE_OR:
  2809. {
  2810. or_connection_t *orconn = TO_OR_CONN(conn);
  2811. if (orconn->chan) {
  2812. connection_or_close_normally(orconn, 0);
  2813. } else {
  2814. /*
  2815. * There should have been one, but mark for close and hope
  2816. * for the best..
  2817. */
  2818. connection_mark_for_close(conn);
  2819. }
  2820. }
  2821. break;
  2822. default:
  2823. connection_mark_for_close(conn);
  2824. break;
  2825. }
  2826. } SMARTLIST_FOREACH_END(conn);
  2827. }
  2828. /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
  2829. * otherwise.
  2830. * Right now this just checks if it's an internal IP address or an
  2831. * internal connection. We also should, but don't, check if the connection
  2832. * uses pluggable transports, since we should then limit it even if it
  2833. * comes from an internal IP address. */
  2834. static int
  2835. connection_is_rate_limited(connection_t *conn)
  2836. {
  2837. const or_options_t *options = get_options();
  2838. if (conn->linked)
  2839. return 0; /* Internal connection */
  2840. else if (! options->CountPrivateBandwidth &&
  2841. (tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
  2842. tor_addr_family(&conn->addr) == AF_UNIX || /* no address */
  2843. tor_addr_is_internal(&conn->addr, 0)))
  2844. return 0; /* Internal address */
  2845. else
  2846. return 1;
  2847. }
  2848. /** When was either global write bucket last empty? If this was recent, then
  2849. * we're probably low on bandwidth, and we should be stingy with our bandwidth
  2850. * usage. */
  2851. static time_t write_buckets_last_empty_at = -100;
  2852. /** How many seconds of no active local circuits will make the
  2853. * connection revert to the "relayed" bandwidth class? */
  2854. #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
  2855. /** Return 1 if <b>conn</b> should use tokens from the "relayed"
  2856. * bandwidth rates, else 0. Currently, only OR conns with bandwidth
  2857. * class 1, and directory conns that are serving data out, count.
  2858. */
  2859. static int
  2860. connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
  2861. {
  2862. if (conn->type == CONN_TYPE_OR &&
  2863. connection_or_client_used(TO_OR_CONN(conn)) +
  2864. CLIENT_IDLE_TIME_FOR_PRIORITY < now)
  2865. return 1;
  2866. if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
  2867. return 1;
  2868. return 0;
  2869. }
  2870. /** Helper function to decide how many bytes out of <b>global_bucket</b>
  2871. * we're willing to use for this transaction. <b>base</b> is the size
  2872. * of a cell on the network; <b>priority</b> says whether we should
  2873. * write many of them or just a few; and <b>conn_bucket</b> (if
  2874. * non-negative) provides an upper limit for our answer. */
  2875. static ssize_t
  2876. connection_bucket_get_share(int base, int priority,
  2877. ssize_t global_bucket_val, ssize_t conn_bucket)
  2878. {
  2879. ssize_t at_most;
  2880. ssize_t num_bytes_high = (priority ? 32 : 16) * base;
  2881. ssize_t num_bytes_low = (priority ? 4 : 2) * base;
  2882. /* Do a rudimentary limiting so one circuit can't hog a connection.
  2883. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  2884. * the middle pick 1/8 of the available bandwidth. */
  2885. at_most = global_bucket_val / 8;
  2886. at_most -= (at_most % base); /* round down */
  2887. if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
  2888. at_most = num_bytes_high;
  2889. else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
  2890. at_most = num_bytes_low;
  2891. if (at_most > global_bucket_val)
  2892. at_most = global_bucket_val;
  2893. if (conn_bucket >= 0 && at_most > conn_bucket)
  2894. at_most = conn_bucket;
  2895. if (at_most < 0)
  2896. return 0;
  2897. return at_most;
  2898. }
  2899. /** How many bytes at most can we read onto this connection? */
  2900. static ssize_t
  2901. connection_bucket_read_limit(connection_t *conn, time_t now)
  2902. {
  2903. tor_assert(conn->type != CONN_TYPE_OR);
  2904. int base = RELAY_PAYLOAD_SIZE;
  2905. int priority = conn->type != CONN_TYPE_DIR;
  2906. ssize_t conn_bucket = -1;
  2907. size_t global_bucket_val = token_bucket_rw_get_read(&global_bucket);
  2908. //if (connection_speaks_cells(conn)) {
  2909. // or_connection_t *or_conn = TO_OR_CONN(conn);
  2910. // if (conn->state == OR_CONN_STATE_OPEN)
  2911. // conn_bucket = token_bucket_rw_get_read(&or_conn->bucket);
  2912. // base = get_cell_network_size(or_conn->wide_circ_ids);
  2913. //}
  2914. if (!connection_is_rate_limited(conn)) {
  2915. /* be willing to read on local conns even if our buckets are empty */
  2916. return conn_bucket>=0 ? conn_bucket : 1<<14;
  2917. }
  2918. if (connection_counts_as_relayed_traffic(conn, now)) {
  2919. size_t relayed = token_bucket_rw_get_read(&global_relayed_bucket);
  2920. global_bucket_val = MIN(global_bucket_val, relayed);
  2921. }
  2922. return connection_bucket_get_share(base, priority,
  2923. global_bucket_val, conn_bucket);
  2924. }
  2925. /** How many bytes at most can we write onto this connection? */
  2926. ssize_t
  2927. connection_bucket_write_limit(connection_t *conn, time_t now)
  2928. {
  2929. tor_assert(conn->type != CONN_TYPE_OR);
  2930. int base = RELAY_PAYLOAD_SIZE;
  2931. int priority = conn->type != CONN_TYPE_DIR;
  2932. size_t conn_bucket = conn->outbuf_flushlen;
  2933. size_t global_bucket_val = token_bucket_rw_get_write(&global_bucket);
  2934. if (!connection_is_rate_limited(conn)) {
  2935. /* be willing to write to local conns even if our buckets are empty */
  2936. return conn->outbuf_flushlen;
  2937. }
  2938. //if (connection_speaks_cells(conn)) {
  2939. // /* use the per-conn write limit if it's lower */
  2940. // or_connection_t *or_conn = TO_OR_CONN(conn);
  2941. // if (conn->state == OR_CONN_STATE_OPEN)
  2942. // conn_bucket = MIN(conn_bucket,
  2943. // token_bucket_rw_get_write(&or_conn->bucket));
  2944. // base = get_cell_network_size(or_conn->wide_circ_ids);
  2945. //}
  2946. if (connection_counts_as_relayed_traffic(conn, now)) {
  2947. size_t relayed = token_bucket_rw_get_write(&global_relayed_bucket);
  2948. global_bucket_val = MIN(global_bucket_val, relayed);
  2949. }
  2950. // TODO: how does the below work, and should we use it?
  2951. return connection_bucket_get_share(base, priority,
  2952. global_bucket_val, conn_bucket);
  2953. }
  2954. /** Return 1 if the global write buckets are low enough that we
  2955. * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
  2956. * out to <b>conn</b>. Else return 0.
  2957. * Priority was 1 for v1 requests (directories and running-routers),
  2958. * and 2 for v2 requests and later (statuses and descriptors).
  2959. *
  2960. * There are a lot of parameters we could use here:
  2961. * - global_relayed_write_bucket. Low is bad.
  2962. * - global_write_bucket. Low is bad.
  2963. * - bandwidthrate. Low is bad.
  2964. * - bandwidthburst. Not a big factor?
  2965. * - attempt. High is bad.
  2966. * - total bytes queued on outbufs. High is bad. But I'm wary of
  2967. * using this, since a few slow-flushing queues will pump up the
  2968. * number without meaning what we meant to mean. What we really
  2969. * mean is "total directory bytes added to outbufs recently", but
  2970. * that's harder to quantify and harder to keep track of.
  2971. */
  2972. int
  2973. global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
  2974. {
  2975. size_t smaller_bucket =
  2976. MIN(token_bucket_rw_get_write(&global_bucket),
  2977. token_bucket_rw_get_write(&global_relayed_bucket));
  2978. if (authdir_mode(get_options()) && priority>1)
  2979. return 0; /* there's always room to answer v2 if we're an auth dir */
  2980. if (!connection_is_rate_limited(conn))
  2981. return 0; /* local conns don't get limited */
  2982. if (smaller_bucket < attempt)
  2983. return 1; /* not enough space no matter the priority */
  2984. {
  2985. const time_t diff = approx_time() - write_buckets_last_empty_at;
  2986. if (diff <= 1)
  2987. return 1; /* we're already hitting our limits, no more please */
  2988. }
  2989. if (priority == 1) { /* old-style v1 query */
  2990. /* Could we handle *two* of these requests within the next two seconds? */
  2991. const or_options_t *options = get_options();
  2992. size_t can_write = (size_t) (smaller_bucket
  2993. + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
  2994. options->BandwidthRate));
  2995. if (can_write < 2*attempt)
  2996. return 1;
  2997. } else { /* v2 query */
  2998. /* no further constraints yet */
  2999. }
  3000. return 0;
  3001. }
  3002. /** When did we last tell the accounting subsystem about transmitted
  3003. * bandwidth? */
  3004. static time_t last_recorded_accounting_at = 0;
  3005. /** Helper: adjusts our bandwidth history and informs the controller as
  3006. * appropriate, given that we have just read <b>num_read</b> bytes and written
  3007. * <b>num_written</b> bytes on <b>conn</b>. */
  3008. static void
  3009. record_num_bytes_transferred_impl(connection_t *conn,
  3010. time_t now, size_t num_read, size_t num_written)
  3011. {
  3012. /* Count bytes of answering direct and tunneled directory requests */
  3013. if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
  3014. if (num_read > 0)
  3015. rep_hist_note_dir_bytes_read(num_read, now);
  3016. if (num_written > 0)
  3017. rep_hist_note_dir_bytes_written(num_written, now);
  3018. }
  3019. if (!connection_is_rate_limited(conn))
  3020. return; /* local IPs are free */
  3021. if (conn->type == CONN_TYPE_OR)
  3022. rep_hist_note_or_conn_bytes(conn->global_identifier, num_read,
  3023. num_written, now);
  3024. if (num_read > 0) {
  3025. rep_hist_note_bytes_read(num_read, now);
  3026. }
  3027. if (num_written > 0) {
  3028. rep_hist_note_bytes_written(num_written, now);
  3029. }
  3030. if (conn->type == CONN_TYPE_EXIT)
  3031. rep_hist_note_exit_bytes(conn->port, num_written, num_read);
  3032. /* Remember these bytes towards statistics. */
  3033. stats_increment_bytes_read_and_written(num_read, num_written);
  3034. /* Remember these bytes towards accounting. */
  3035. if (accounting_is_enabled(get_options())) {
  3036. if (now > last_recorded_accounting_at && last_recorded_accounting_at) {
  3037. accounting_add_bytes(num_read, num_written,
  3038. (int)(now - last_recorded_accounting_at));
  3039. } else {
  3040. accounting_add_bytes(num_read, num_written, 0);
  3041. }
  3042. last_recorded_accounting_at = now;
  3043. }
  3044. }
  3045. /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
  3046. * onto <b>conn</b>. Decrement buckets appropriately. */
  3047. static void
  3048. connection_buckets_decrement(connection_t *conn, time_t now,
  3049. size_t num_read, size_t num_written)
  3050. {
  3051. tor_assert(conn->type != CONN_TYPE_OR);
  3052. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  3053. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  3054. "connection type=%s, state=%s",
  3055. (unsigned long)num_read, (unsigned long)num_written,
  3056. conn_type_to_string(conn->type),
  3057. conn_state_to_string(conn->type, conn->state));
  3058. tor_assert_nonfatal_unreached();
  3059. if (num_written >= INT_MAX)
  3060. num_written = 1;
  3061. if (num_read >= INT_MAX)
  3062. num_read = 1;
  3063. }
  3064. record_num_bytes_transferred_impl(conn, now, num_read, num_written);
  3065. if (!connection_is_rate_limited(conn))
  3066. return; /* local IPs are free */
  3067. unsigned flags = 0;
  3068. if (connection_counts_as_relayed_traffic(conn, now)) {
  3069. flags = token_bucket_rw_dec(&global_relayed_bucket, num_read, num_written);
  3070. }
  3071. flags |= token_bucket_rw_dec(&global_bucket, num_read, num_written);
  3072. if (flags & TB_WRITE) {
  3073. write_buckets_last_empty_at = now;
  3074. }
  3075. //if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  3076. // or_connection_t *or_conn = TO_OR_CONN(conn);
  3077. // token_bucket_rw_dec(&or_conn->bucket, num_read, num_written);
  3078. //}
  3079. }
  3080. /**
  3081. * Mark <b>conn</b> as needing to stop reading because bandwidth has been
  3082. * exhausted. If <b>is_global_bw</b>, it is closing because global bandwidth
  3083. * limit has been exhausted. Otherwise, it is closing because its own
  3084. * bandwidth limit has been exhausted.
  3085. */
  3086. void
  3087. connection_read_bw_exhausted(connection_t *conn, bool is_global_bw)
  3088. {
  3089. (void)is_global_bw;
  3090. conn->read_blocked_on_bw = 1;
  3091. connection_stop_reading(conn);
  3092. reenable_blocked_connection_schedule();
  3093. }
  3094. /**
  3095. * Mark <b>conn</b> as needing to stop reading because write bandwidth has
  3096. * been exhausted. If <b>is_global_bw</b>, it is closing because global
  3097. * bandwidth limit has been exhausted. Otherwise, it is closing because its
  3098. * own bandwidth limit has been exhausted.
  3099. */
  3100. void
  3101. connection_write_bw_exhausted(connection_t *conn, bool is_global_bw)
  3102. {
  3103. (void)is_global_bw;
  3104. conn->write_blocked_on_bw = 1;
  3105. connection_stop_writing(conn);
  3106. reenable_blocked_connection_schedule();
  3107. }
  3108. /** If we have exhausted our global buckets, or the buckets for conn,
  3109. * stop reading. */
  3110. void
  3111. connection_consider_empty_read_buckets(connection_t *conn)
  3112. {
  3113. const char *reason;
  3114. if (!connection_is_rate_limited(conn))
  3115. return; /* Always okay. */
  3116. int is_global = 1;
  3117. tor_assert(conn->type != CONN_TYPE_OR);
  3118. if (token_bucket_rw_get_read(&global_bucket) <= 0) {
  3119. reason = "global read bucket exhausted. Pausing.";
  3120. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  3121. token_bucket_rw_get_read(&global_relayed_bucket) <= 0) {
  3122. reason = "global relayed read bucket exhausted. Pausing.";
  3123. //} else if (connection_speaks_cells(conn) &&
  3124. // conn->state == OR_CONN_STATE_OPEN &&
  3125. // token_bucket_rw_get_read(&TO_OR_CONN(conn)->bucket) <= 0) {
  3126. // reason = "connection read bucket exhausted. Pausing.";
  3127. // is_global = false;
  3128. } else
  3129. return; /* all good, no need to stop it */
  3130. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  3131. connection_read_bw_exhausted(conn, is_global);
  3132. }
  3133. /** If we have exhausted our global buckets, or the buckets for conn,
  3134. * stop writing. */
  3135. void
  3136. connection_consider_empty_write_buckets(connection_t *conn)
  3137. {
  3138. const char *reason;
  3139. if (!connection_is_rate_limited(conn))
  3140. return; /* Always okay. */
  3141. bool is_global = true;
  3142. tor_assert(conn->type != CONN_TYPE_OR);
  3143. if (token_bucket_rw_get_write(&global_bucket) <= 0) {
  3144. reason = "global write bucket exhausted. Pausing.";
  3145. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  3146. token_bucket_rw_get_write(&global_relayed_bucket) <= 0) {
  3147. reason = "global relayed write bucket exhausted. Pausing.";
  3148. //} else if (connection_speaks_cells(conn) &&
  3149. // conn->state == OR_CONN_STATE_OPEN &&
  3150. // token_bucket_rw_get_write(&TO_OR_CONN(conn)->bucket) <= 0) {
  3151. // reason = "connection write bucket exhausted. Pausing.";
  3152. // is_global = false;
  3153. } else
  3154. return; /* all good, no need to stop it */
  3155. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  3156. connection_write_bw_exhausted(conn, is_global);
  3157. }
  3158. /** Initialize the global buckets to the values configured in the
  3159. * options */
  3160. void
  3161. connection_bucket_init(void)
  3162. {
  3163. const or_options_t *options = get_options();
  3164. const uint32_t now_ts = monotime_coarse_get_stamp();
  3165. token_bucket_rw_init(&global_bucket,
  3166. (int32_t)options->BandwidthRate,
  3167. (int32_t)options->BandwidthBurst,
  3168. now_ts);
  3169. if (options->RelayBandwidthRate) {
  3170. token_bucket_rw_init(&global_relayed_bucket,
  3171. (int32_t)options->RelayBandwidthRate,
  3172. (int32_t)options->RelayBandwidthBurst,
  3173. now_ts);
  3174. } else {
  3175. token_bucket_rw_init(&global_relayed_bucket,
  3176. (int32_t)options->BandwidthRate,
  3177. (int32_t)options->BandwidthBurst,
  3178. now_ts);
  3179. }
  3180. reenable_blocked_connection_init(options);
  3181. }
  3182. /** Update the global connection bucket settings to a new value. */
  3183. void
  3184. connection_bucket_adjust(const or_options_t *options)
  3185. {
  3186. token_bucket_rw_adjust(&global_bucket,
  3187. (int32_t)options->BandwidthRate,
  3188. (int32_t)options->BandwidthBurst);
  3189. if (options->RelayBandwidthRate) {
  3190. token_bucket_rw_adjust(&global_relayed_bucket,
  3191. (int32_t)options->RelayBandwidthRate,
  3192. (int32_t)options->RelayBandwidthBurst);
  3193. } else {
  3194. token_bucket_rw_adjust(&global_relayed_bucket,
  3195. (int32_t)options->BandwidthRate,
  3196. (int32_t)options->BandwidthBurst);
  3197. }
  3198. }
  3199. /**
  3200. * Cached value of the last coarse-timestamp when we refilled the
  3201. * global buckets.
  3202. */
  3203. static uint32_t last_refilled_global_buckets_ts=0;
  3204. /**
  3205. * Refill the token buckets for a single connection <b>conn</b>, and the
  3206. * global token buckets as appropriate. Requires that <b>now_ts</b> is
  3207. * the time in coarse timestamp units.
  3208. */
  3209. static void
  3210. connection_bucket_refill_single(connection_t *conn, uint32_t now_ts)
  3211. {
  3212. /* Note that we only check for equality here: the underlying
  3213. * token bucket functions can handle moving backwards in time if they
  3214. * need to. */
  3215. if (now_ts != last_refilled_global_buckets_ts) {
  3216. token_bucket_rw_refill(&global_bucket, now_ts);
  3217. token_bucket_rw_refill(&global_relayed_bucket, now_ts);
  3218. last_refilled_global_buckets_ts = now_ts;
  3219. }
  3220. // TODO: we need to do this somewhere
  3221. //if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  3222. // or_connection_t *or_conn = TO_OR_CONN(conn);
  3223. // token_bucket_rw_refill(&or_conn->bucket, now_ts);
  3224. //}
  3225. }
  3226. /**
  3227. * Event to re-enable all connections that were previously blocked on read or
  3228. * write.
  3229. */
  3230. static mainloop_event_t *reenable_blocked_connections_ev = NULL;
  3231. /** True iff reenable_blocked_connections_ev is currently scheduled. */
  3232. static int reenable_blocked_connections_is_scheduled = 0;
  3233. /** Delay after which to run reenable_blocked_connections_ev. */
  3234. static struct timeval reenable_blocked_connections_delay;
  3235. /**
  3236. * Re-enable all connections that were previously blocked on read or write.
  3237. * This event is scheduled after enough time has elapsed to be sure
  3238. * that the buckets will refill when the connections have something to do.
  3239. */
  3240. static void
  3241. reenable_blocked_connections_cb(mainloop_event_t *ev, void *arg)
  3242. {
  3243. (void)ev;
  3244. (void)arg;
  3245. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  3246. if (conn->read_blocked_on_bw == 1) {
  3247. connection_start_reading(conn);
  3248. conn->read_blocked_on_bw = 0;
  3249. }
  3250. if (conn->write_blocked_on_bw == 1) {
  3251. connection_start_writing(conn);
  3252. conn->write_blocked_on_bw = 0;
  3253. }
  3254. } SMARTLIST_FOREACH_END(conn);
  3255. reenable_blocked_connections_is_scheduled = 0;
  3256. }
  3257. /**
  3258. * Initialize the mainloop event that we use to wake up connections that
  3259. * find themselves blocked on bandwidth.
  3260. */
  3261. static void
  3262. reenable_blocked_connection_init(const or_options_t *options)
  3263. {
  3264. if (! reenable_blocked_connections_ev) {
  3265. reenable_blocked_connections_ev =
  3266. mainloop_event_new(reenable_blocked_connections_cb, NULL);
  3267. reenable_blocked_connections_is_scheduled = 0;
  3268. }
  3269. time_t sec = options->TokenBucketRefillInterval / 1000;
  3270. int msec = (options->TokenBucketRefillInterval % 1000);
  3271. reenable_blocked_connections_delay.tv_sec = sec;
  3272. reenable_blocked_connections_delay.tv_usec = msec * 1000;
  3273. }
  3274. /**
  3275. * Called when we have blocked a connection for being low on bandwidth:
  3276. * schedule an event to reenable such connections, if it is not already
  3277. * scheduled.
  3278. */
  3279. static void
  3280. reenable_blocked_connection_schedule(void)
  3281. {
  3282. if (reenable_blocked_connections_is_scheduled)
  3283. return;
  3284. if (BUG(reenable_blocked_connections_ev == NULL)) {
  3285. reenable_blocked_connection_init(get_options());
  3286. }
  3287. mainloop_event_schedule(reenable_blocked_connections_ev,
  3288. &reenable_blocked_connections_delay);
  3289. reenable_blocked_connections_is_scheduled = 1;
  3290. }
  3291. /** Read bytes from conn-\>s and process them.
  3292. *
  3293. * It calls connection_buf_read_from_socket() to bring in any new bytes,
  3294. * and then calls connection_process_inbuf() to process them.
  3295. *
  3296. * Mark the connection and return -1 if you want to close it, else
  3297. * return 0.
  3298. */
  3299. static int
  3300. connection_handle_read_impl(connection_t *conn)
  3301. {
  3302. tor_assert(conn->safe_conn == NULL);
  3303. ssize_t max_to_read=-1, try_to_read;
  3304. size_t before, n_read = 0;
  3305. int socket_error = 0;
  3306. if (conn->marked_for_close)
  3307. return 0; /* do nothing */
  3308. conn->timestamp_last_read_allowed = approx_time();
  3309. connection_bucket_refill_single(conn, monotime_coarse_get_stamp());
  3310. switch (conn->type) {
  3311. case CONN_TYPE_OR_LISTENER:
  3312. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  3313. case CONN_TYPE_EXT_OR_LISTENER:
  3314. return connection_handle_listener_read(conn, CONN_TYPE_EXT_OR);
  3315. case CONN_TYPE_AP_LISTENER:
  3316. case CONN_TYPE_AP_TRANS_LISTENER:
  3317. case CONN_TYPE_AP_NATD_LISTENER:
  3318. case CONN_TYPE_AP_HTTP_CONNECT_LISTENER:
  3319. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  3320. case CONN_TYPE_DIR_LISTENER:
  3321. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  3322. case CONN_TYPE_CONTROL_LISTENER:
  3323. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  3324. case CONN_TYPE_AP_DNS_LISTENER:
  3325. /* This should never happen; eventdns.c handles the reads here. */
  3326. tor_fragile_assert();
  3327. return 0;
  3328. }
  3329. loop_again:
  3330. try_to_read = max_to_read;
  3331. tor_assert(!conn->marked_for_close);
  3332. before = buf_datalen(conn->inbuf);
  3333. if (connection_buf_read_from_socket(conn, &max_to_read, &socket_error) < 0) {
  3334. /* There's a read error; kill the connection.*/
  3335. if (conn->type == CONN_TYPE_OR) {
  3336. connection_or_notify_error(TO_OR_CONN(conn),
  3337. socket_error != 0 ?
  3338. errno_to_orconn_end_reason(socket_error) :
  3339. END_OR_CONN_REASON_CONNRESET,
  3340. socket_error != 0 ?
  3341. tor_socket_strerror(socket_error) :
  3342. "(unknown, errno was 0)");
  3343. }
  3344. if (CONN_IS_EDGE(conn)) {
  3345. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3346. connection_edge_end_errno(edge_conn);
  3347. if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
  3348. /* broken, don't send a socks reply back */
  3349. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  3350. }
  3351. }
  3352. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  3353. /*
  3354. * This can bypass normal channel checking since we did
  3355. * connection_or_notify_error() above.
  3356. */
  3357. connection_mark_for_close_internal(conn);
  3358. return -1;
  3359. }
  3360. n_read += buf_datalen(conn->inbuf) - before;
  3361. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  3362. /* instruct it not to try to package partial cells. */
  3363. if (connection_process_inbuf(conn, 0) < 0) {
  3364. return -1;
  3365. }
  3366. if (!conn->marked_for_close &&
  3367. connection_is_reading(conn) &&
  3368. !conn->inbuf_reached_eof &&
  3369. max_to_read > 0)
  3370. goto loop_again; /* try reading again, in case more is here now */
  3371. }
  3372. /* one last try, packaging partial cells and all. */
  3373. if (!conn->marked_for_close &&
  3374. connection_process_inbuf(conn, 1) < 0) {
  3375. return -1;
  3376. }
  3377. if (conn->linked_conn) {
  3378. /* The other side's handle_write() will never actually get called, so
  3379. * we need to invoke the appropriate callbacks ourself. */
  3380. connection_t *linked = conn->linked_conn;
  3381. if (n_read) {
  3382. /* Probably a no-op, since linked conns typically don't count for
  3383. * bandwidth rate limiting. But do it anyway so we can keep stats
  3384. * accurately. Note that since we read the bytes from conn, and
  3385. * we're writing the bytes onto the linked connection, we count
  3386. * these as <i>written</i> bytes. */
  3387. connection_buckets_decrement(linked, approx_time(), 0, n_read);
  3388. if (connection_flushed_some(linked) < 0)
  3389. connection_mark_for_close(linked);
  3390. if (!connection_wants_to_flush(linked))
  3391. connection_finished_flushing(linked);
  3392. }
  3393. if (!buf_datalen(linked->outbuf) && conn->active_on_link)
  3394. connection_stop_reading_from_linked_conn(conn);
  3395. }
  3396. /* If we hit the EOF, call connection_reached_eof(). */
  3397. if (!conn->marked_for_close &&
  3398. conn->inbuf_reached_eof &&
  3399. connection_reached_eof(conn) < 0) {
  3400. return -1;
  3401. }
  3402. return 0;
  3403. }
  3404. /* DOCDOC connection_handle_read */
  3405. int
  3406. connection_handle_read(connection_t *conn)
  3407. {
  3408. int res;
  3409. update_current_time(time(NULL));
  3410. res = connection_handle_read_impl(conn);
  3411. return res;
  3412. }
  3413. /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
  3414. * either directly or via TLS. Reduce the token buckets by the number of bytes
  3415. * read.
  3416. *
  3417. * If *max_to_read is -1, then decide it ourselves, else go with the
  3418. * value passed to us. When returning, if it's changed, subtract the
  3419. * number of bytes we read from *max_to_read.
  3420. *
  3421. * Return -1 if we want to break conn, else return 0.
  3422. */
  3423. static int
  3424. connection_buf_read_from_socket(connection_t *conn, ssize_t *max_to_read,
  3425. int *socket_error)
  3426. {
  3427. int result;
  3428. ssize_t at_most = *max_to_read;
  3429. size_t slack_in_buf, more_to_read;
  3430. size_t n_read = 0, n_written = 0;
  3431. if (at_most == -1) { /* we need to initialize it */
  3432. /* how many bytes are we allowed to read? */
  3433. at_most = connection_bucket_read_limit(conn, approx_time());
  3434. }
  3435. slack_in_buf = buf_slack(conn->inbuf);
  3436. again:
  3437. if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
  3438. more_to_read = at_most - slack_in_buf;
  3439. at_most = slack_in_buf;
  3440. } else {
  3441. more_to_read = 0;
  3442. }
  3443. tor_assert(conn->type != CONN_TYPE_OR);
  3444. //if (connection_speaks_cells(conn) &&
  3445. // conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  3446. // int pending;
  3447. // or_connection_t *or_conn = TO_OR_CONN(conn);
  3448. // size_t initial_size;
  3449. // if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  3450. // conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  3451. // /* continue handshaking even if global token bucket is empty */
  3452. // return connection_tls_continue_handshake(or_conn);
  3453. // }
  3454. // log_debug(LD_NET,
  3455. // "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
  3456. // " at_most %ld.",
  3457. // (int)conn->s,(long)buf_datalen(conn->inbuf),
  3458. // tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
  3459. // initial_size = buf_datalen(conn->inbuf);
  3460. // /* else open, or closing */
  3461. // result = buf_read_from_tls(conn->inbuf, or_conn->tls, at_most);
  3462. // if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
  3463. // or_conn->tls_error = result;
  3464. // else
  3465. // or_conn->tls_error = 0;
  3466. // switch (result) {
  3467. // case TOR_TLS_CLOSE:
  3468. // case TOR_TLS_ERROR_IO:
  3469. // log_debug(LD_NET,"TLS connection closed %son read. Closing. "
  3470. // "(Nickname %s, address %s)",
  3471. // result == TOR_TLS_CLOSE ? "cleanly " : "",
  3472. // or_conn->nickname ? or_conn->nickname : "not set",
  3473. // conn->address);
  3474. // return result;
  3475. // CASE_TOR_TLS_ERROR_ANY_NONIO:
  3476. // log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
  3477. // tor_tls_err_to_string(result),
  3478. // or_conn->nickname ? or_conn->nickname : "not set",
  3479. // conn->address);
  3480. // return result;
  3481. // case TOR_TLS_WANTWRITE:
  3482. // connection_start_writing(conn);
  3483. // return 0;
  3484. // case TOR_TLS_WANTREAD:
  3485. // if (conn->in_connection_handle_write) {
  3486. // /* We've been invoked from connection_handle_write, because we're
  3487. // * waiting for a TLS renegotiation, the renegotiation started, and
  3488. // * SSL_read returned WANTWRITE. But now SSL_read is saying WANTREAD
  3489. // * again. Stop waiting for write events now, or else we'll
  3490. // * busy-loop until data arrives for us to read.
  3491. // * XXX: remove this when v2 handshakes support is dropped. */
  3492. // connection_stop_writing(conn);
  3493. // if (!connection_is_reading(conn))
  3494. // connection_start_reading(conn);
  3495. // }
  3496. // /* we're already reading, one hopes */
  3497. // break;
  3498. // case TOR_TLS_DONE: /* no data read, so nothing to process */
  3499. // break; /* so we call bucket_decrement below */
  3500. // default:
  3501. // break;
  3502. // }
  3503. // pending = tor_tls_get_pending_bytes(or_conn->tls);
  3504. // if (pending) {
  3505. // /* If we have any pending bytes, we read them now. This *can*
  3506. // * take us over our read allotment, but really we shouldn't be
  3507. // * believing that SSL bytes are the same as TCP bytes anyway. */
  3508. // int r2 = buf_read_from_tls(conn->inbuf, or_conn->tls, pending);
  3509. // if (BUG(r2<0)) {
  3510. // log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
  3511. // return -1;
  3512. // }
  3513. // }
  3514. // result = (int)(buf_datalen(conn->inbuf)-initial_size);
  3515. // tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  3516. // log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
  3517. // result, (long)n_read, (long)n_written);
  3518. //} else if (conn->linked) {
  3519. if (conn->linked) {
  3520. if (conn->linked_conn) {
  3521. result = buf_move_to_buf(conn->inbuf, conn->linked_conn->outbuf,
  3522. &conn->linked_conn->outbuf_flushlen);
  3523. if (BUG(result<0)) {
  3524. log_warn(LD_BUG, "reading from linked connection buffer failed.");
  3525. return -1;
  3526. }
  3527. } else {
  3528. result = 0;
  3529. }
  3530. //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
  3531. /* If the other side has disappeared, or if it's been marked for close and
  3532. * we flushed its outbuf, then we should set our inbuf_reached_eof. */
  3533. if (!conn->linked_conn ||
  3534. (conn->linked_conn->marked_for_close &&
  3535. buf_datalen(conn->linked_conn->outbuf) == 0))
  3536. conn->inbuf_reached_eof = 1;
  3537. n_read = (size_t) result;
  3538. } else {
  3539. /* !connection_speaks_cells, !conn->linked_conn. */
  3540. int reached_eof = 0;
  3541. CONN_LOG_PROTECT(conn,
  3542. result = buf_read_from_socket(conn->inbuf, conn->s,
  3543. at_most,
  3544. &reached_eof,
  3545. socket_error));
  3546. if (reached_eof)
  3547. conn->inbuf_reached_eof = 1;
  3548. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  3549. if (result < 0)
  3550. return -1;
  3551. n_read = (size_t) result;
  3552. }
  3553. if (n_read > 0) {
  3554. /* change *max_to_read */
  3555. *max_to_read = at_most - n_read;
  3556. /* Update edge_conn->n_read */
  3557. if (conn->type == CONN_TYPE_AP) {
  3558. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3559. /* Check for overflow: */
  3560. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
  3561. edge_conn->n_read += (int)n_read;
  3562. else
  3563. edge_conn->n_read = UINT32_MAX;
  3564. }
  3565. /* If CONN_BW events are enabled, update conn->n_read_conn_bw for
  3566. * OR/DIR/EXIT connections, checking for overflow. */
  3567. if (get_options()->TestingEnableConnBwEvent &&
  3568. (conn->type == CONN_TYPE_OR ||
  3569. conn->type == CONN_TYPE_DIR ||
  3570. conn->type == CONN_TYPE_EXIT)) {
  3571. if (PREDICT_LIKELY(UINT32_MAX - conn->n_read_conn_bw > n_read))
  3572. conn->n_read_conn_bw += (int)n_read;
  3573. else
  3574. conn->n_read_conn_bw = UINT32_MAX;
  3575. }
  3576. }
  3577. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3578. if (more_to_read && result == at_most) {
  3579. slack_in_buf = buf_slack(conn->inbuf);
  3580. at_most = more_to_read;
  3581. goto again;
  3582. }
  3583. /* Call even if result is 0, since the global read bucket may
  3584. * have reached 0 on a different conn, and this connection needs to
  3585. * know to stop reading. */
  3586. connection_consider_empty_read_buckets(conn);
  3587. if (n_written > 0 && connection_is_writing(conn))
  3588. connection_consider_empty_write_buckets(conn);
  3589. return 0;
  3590. }
  3591. /** A pass-through to fetch_from_buf. */
  3592. int
  3593. connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
  3594. {
  3595. if (conn->safe_conn == NULL) {
  3596. tor_assert(!connection_uses_safe_conn(conn->type));
  3597. return buf_get_bytes(conn->inbuf, string, len);
  3598. } else {
  3599. tor_assert(connection_uses_safe_conn(conn->type));
  3600. // TODO: fix this ugly locking
  3601. tor_assert(conn->safe_conn != NULL);
  3602. tor_mutex_acquire(&(conn->safe_conn->lock));
  3603. struct buf_t *inbuf = conn->safe_conn->inbuf;
  3604. int rv = buf_get_bytes(inbuf, string, len);
  3605. safe_connection_inbuf_modified(conn->safe_conn);
  3606. tor_mutex_release(&(conn->safe_conn->lock));
  3607. return rv;
  3608. }
  3609. }
  3610. /** As buf_get_line(), but read from a connection's input buffer. */
  3611. int
  3612. connection_buf_get_line(connection_t *conn, char *data,
  3613. size_t *data_len)
  3614. {
  3615. if (conn->safe_conn == NULL) {
  3616. tor_assert(!connection_uses_safe_conn(conn->type));
  3617. return buf_get_line(conn->inbuf, data, data_len);
  3618. } else {
  3619. tor_assert(connection_uses_safe_conn(conn->type));
  3620. // TODO: fix this ugly locking
  3621. tor_assert(conn->safe_conn != NULL);
  3622. tor_mutex_acquire(&(conn->safe_conn->lock));
  3623. struct buf_t *inbuf = conn->safe_conn->inbuf;
  3624. int rv = buf_get_line(inbuf, data, data_len);
  3625. safe_connection_inbuf_modified(conn->safe_conn);
  3626. tor_mutex_release(&(conn->safe_conn->lock));
  3627. return rv;
  3628. }
  3629. }
  3630. /** As fetch_from_buf_http, but fetches from a connection's input buffer_t as
  3631. * appropriate. */
  3632. int
  3633. connection_fetch_from_buf_http(connection_t *conn,
  3634. char **headers_out, size_t max_headerlen,
  3635. char **body_out, size_t *body_used,
  3636. size_t max_bodylen, int force_complete)
  3637. {
  3638. if (conn->safe_conn == NULL) {
  3639. tor_assert(!connection_uses_safe_conn(conn->type));
  3640. return fetch_from_buf_http(conn->inbuf, headers_out, max_headerlen,
  3641. body_out, body_used, max_bodylen,
  3642. force_complete);
  3643. } else {
  3644. tor_assert(connection_uses_safe_conn(conn->type));
  3645. // TODO: fix this ugly locking
  3646. tor_assert(conn->safe_conn != NULL);
  3647. tor_mutex_acquire(&(conn->safe_conn->lock));
  3648. struct buf_t *inbuf = conn->safe_conn->inbuf;
  3649. int rv = fetch_from_buf_http(inbuf, headers_out, max_headerlen,
  3650. body_out, body_used, max_bodylen,
  3651. force_complete);
  3652. safe_connection_inbuf_modified(conn->safe_conn);
  3653. tor_mutex_release(&(conn->safe_conn->lock));
  3654. return rv;
  3655. }
  3656. }
  3657. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  3658. * from its outbuf. */
  3659. int
  3660. connection_wants_to_flush(connection_t *conn)
  3661. {
  3662. //tor_assert(conn->safe_conn == NULL);
  3663. //tor_assert(!connection_uses_safe_conn(conn->type));
  3664. if (!connection_uses_safe_conn(conn->type)) {
  3665. return conn->outbuf_flushlen > 0;
  3666. } else {
  3667. // TODO: fix this ugly locking
  3668. tor_assert(conn->safe_conn != NULL);
  3669. tor_mutex_acquire(&(conn->safe_conn->lock));
  3670. int rv = buf_datalen(conn->safe_conn->outbuf);
  3671. tor_mutex_release(&(conn->safe_conn->lock));
  3672. return rv;
  3673. }
  3674. }
  3675. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  3676. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  3677. * connection_edge_consider_sending_sendme().
  3678. */
  3679. int
  3680. connection_outbuf_too_full(connection_t *conn)
  3681. {
  3682. tor_assert(conn->safe_conn == NULL);
  3683. tor_assert(!connection_uses_safe_conn(conn->type));
  3684. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  3685. }
  3686. /**
  3687. * On Windows Vista and Windows 7, tune the send buffer size according to a
  3688. * hint from the OS.
  3689. *
  3690. * This should help fix slow upload rates.
  3691. */
  3692. static void
  3693. update_send_buffer_size(tor_socket_t sock)
  3694. {
  3695. #ifdef _WIN32
  3696. /* We only do this on Vista and 7, because earlier versions of Windows
  3697. * don't have the SIO_IDEAL_SEND_BACKLOG_QUERY functionality, and on
  3698. * later versions it isn't necessary. */
  3699. static int isVistaOr7 = -1;
  3700. if (isVistaOr7 == -1) {
  3701. isVistaOr7 = 0;
  3702. OSVERSIONINFO osvi = { 0 };
  3703. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3704. GetVersionEx(&osvi);
  3705. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion < 2)
  3706. isVistaOr7 = 1;
  3707. }
  3708. if (!isVistaOr7)
  3709. return;
  3710. if (get_options()->ConstrainedSockets)
  3711. return;
  3712. ULONG isb = 0;
  3713. DWORD bytesReturned = 0;
  3714. if (!WSAIoctl(sock, SIO_IDEAL_SEND_BACKLOG_QUERY, NULL, 0,
  3715. &isb, sizeof(isb), &bytesReturned, NULL, NULL)) {
  3716. setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (const char*)&isb, sizeof(isb));
  3717. }
  3718. #else /* !defined(_WIN32) */
  3719. (void) sock;
  3720. #endif /* defined(_WIN32) */
  3721. }
  3722. /** Try to flush more bytes onto <b>conn</b>-\>s.
  3723. *
  3724. * This function is called in connection_handle_write(), which gets
  3725. * called from conn_write_callback() in main.c when libevent tells us
  3726. * that <b>conn</b> wants to write.
  3727. *
  3728. * Update <b>conn</b>-\>timestamp_last_write_allowed to now, and call flush_buf
  3729. * or flush_buf_tls appropriately. If it succeeds and there are no more
  3730. * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
  3731. * on it too.
  3732. *
  3733. * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
  3734. * limits. (Used for flushing messages to controller connections on fatal
  3735. * errors.)
  3736. *
  3737. * Mark the connection and return -1 if you want to close it, else
  3738. * return 0.
  3739. */
  3740. static int
  3741. connection_handle_write_impl(connection_t *conn, int force)
  3742. {
  3743. tor_assert(conn->safe_conn == NULL);
  3744. int e;
  3745. socklen_t len=(socklen_t)sizeof(e);
  3746. int result;
  3747. ssize_t max_to_write;
  3748. time_t now = approx_time();
  3749. size_t n_read = 0, n_written = 0;
  3750. int dont_stop_writing = 0;
  3751. tor_assert(!connection_is_listener(conn));
  3752. if (conn->marked_for_close || !SOCKET_OK(conn->s))
  3753. return 0; /* do nothing */
  3754. if (conn->in_flushed_some) {
  3755. log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
  3756. return 0;
  3757. }
  3758. conn->timestamp_last_write_allowed = now;
  3759. connection_bucket_refill_single(conn, monotime_coarse_get_stamp());
  3760. /* Sometimes, "writable" means "connected". */
  3761. if (connection_state_is_connecting(conn)) {
  3762. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  3763. log_warn(LD_BUG, "getsockopt() syscall failed");
  3764. if (conn->type == CONN_TYPE_OR) {
  3765. or_connection_t *orconn = TO_OR_CONN(conn);
  3766. connection_or_close_for_error(orconn, 0);
  3767. } else {
  3768. if (CONN_IS_EDGE(conn)) {
  3769. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3770. }
  3771. connection_mark_for_close(conn);
  3772. }
  3773. return -1;
  3774. }
  3775. if (e) {
  3776. /* some sort of error, but maybe just inprogress still */
  3777. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  3778. log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
  3779. tor_socket_strerror(e));
  3780. if (CONN_IS_EDGE(conn))
  3781. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3782. if (conn->type == CONN_TYPE_OR)
  3783. connection_or_notify_error(TO_OR_CONN(conn),
  3784. errno_to_orconn_end_reason(e),
  3785. tor_socket_strerror(e));
  3786. connection_close_immediate(conn);
  3787. /*
  3788. * This can bypass normal channel checking since we did
  3789. * connection_or_notify_error() above.
  3790. */
  3791. connection_mark_for_close_internal(conn);
  3792. return -1;
  3793. } else {
  3794. return 0; /* no change, see if next time is better */
  3795. }
  3796. }
  3797. /* The connection is successful. */
  3798. if (connection_finished_connecting(conn)<0)
  3799. return -1;
  3800. }
  3801. max_to_write = force ? (ssize_t)conn->outbuf_flushlen
  3802. : connection_bucket_write_limit(conn, now);
  3803. tor_assert(conn->type != CONN_TYPE_OR);
  3804. //if (connection_speaks_cells(conn) &&
  3805. // conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  3806. // or_connection_t *or_conn = TO_OR_CONN(conn);
  3807. // size_t initial_size;
  3808. // if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  3809. // conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  3810. // connection_stop_writing(conn);
  3811. // if (connection_tls_continue_handshake(or_conn) < 0) {
  3812. // /* Don't flush; connection is dead. */
  3813. // connection_or_notify_error(or_conn,
  3814. // END_OR_CONN_REASON_MISC,
  3815. // "TLS error in connection_tls_"
  3816. // "continue_handshake()");
  3817. // connection_close_immediate(conn);
  3818. // /*
  3819. // * This can bypass normal channel checking since we did
  3820. // * connection_or_notify_error() above.
  3821. // */
  3822. // connection_mark_for_close_internal(conn);
  3823. // return -1;
  3824. // }
  3825. // return 0;
  3826. // } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
  3827. // return connection_handle_read(conn);
  3828. // }
  3829. // /* else open, or closing */
  3830. // initial_size = buf_datalen(conn->outbuf);
  3831. // result = buf_flush_to_tls(conn->outbuf, or_conn->tls,
  3832. // max_to_write, &conn->outbuf_flushlen);
  3833. // if (result >= 0)
  3834. // update_send_buffer_size(conn->s);
  3835. // /* If we just flushed the last bytes, tell the channel on the
  3836. // * or_conn to check if it needs to geoip_change_dirreq_state() */
  3837. // /* XXXX move this to flushed_some or finished_flushing -NM */
  3838. // if (buf_datalen(conn->outbuf) == 0 && or_conn->chan)
  3839. // channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn->chan));
  3840. // switch (result) {
  3841. // CASE_TOR_TLS_ERROR_ANY:
  3842. // case TOR_TLS_CLOSE:
  3843. // log_info(LD_NET, result != TOR_TLS_CLOSE ?
  3844. // "tls error. breaking.":"TLS connection closed on flush");
  3845. // /* Don't flush; connection is dead. */
  3846. // connection_or_notify_error(or_conn,
  3847. // END_OR_CONN_REASON_MISC,
  3848. // result != TOR_TLS_CLOSE ?
  3849. // "TLS error in during flush" :
  3850. // "TLS closed during flush");
  3851. // connection_close_immediate(conn);
  3852. // /*
  3853. // * This can bypass normal channel checking since we did
  3854. // * connection_or_notify_error() above.
  3855. // */
  3856. // connection_mark_for_close_internal(conn);
  3857. // return -1;
  3858. // case TOR_TLS_WANTWRITE:
  3859. // log_debug(LD_NET,"wanted write.");
  3860. // /* we're already writing */
  3861. // dont_stop_writing = 1;
  3862. // break;
  3863. // case TOR_TLS_WANTREAD:
  3864. // /* Make sure to avoid a loop if the receive buckets are empty. */
  3865. // log_debug(LD_NET,"wanted read.");
  3866. // if (!connection_is_reading(conn)) {
  3867. // connection_write_bw_exhausted(conn, true);
  3868. // /* we'll start reading again when we get more tokens in our
  3869. // * read bucket; then we'll start writing again too.
  3870. // */
  3871. // }
  3872. // /* else no problem, we're already reading */
  3873. // return 0;
  3874. // /* case TOR_TLS_DONE:
  3875. // * for TOR_TLS_DONE, fall through to check if the flushlen
  3876. // * is empty, so we can stop writing.
  3877. // */
  3878. // }
  3879. // tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  3880. // log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
  3881. // result, (long)n_read, (long)n_written);
  3882. // or_conn->bytes_xmitted += result;
  3883. // or_conn->bytes_xmitted_by_tls += n_written;
  3884. // /* So we notice bytes were written even on error */
  3885. // /* XXXX This cast is safe since we can never write INT_MAX bytes in a
  3886. // * single set of TLS operations. But it looks kinda ugly. If we refactor
  3887. // * the *_buf_tls functions, we should make them return ssize_t or size_t
  3888. // * or something. */
  3889. // result = (int)(initial_size-buf_datalen(conn->outbuf));
  3890. //} else {
  3891. if (1) {
  3892. CONN_LOG_PROTECT(conn,
  3893. result = buf_flush_to_socket(conn->outbuf, conn->s,
  3894. max_to_write, &conn->outbuf_flushlen));
  3895. if (result < 0) {
  3896. if (CONN_IS_EDGE(conn))
  3897. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3898. if (conn->type == CONN_TYPE_AP) {
  3899. /* writing failed; we couldn't send a SOCKS reply if we wanted to */
  3900. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  3901. }
  3902. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  3903. connection_mark_for_close(conn);
  3904. return -1;
  3905. }
  3906. update_send_buffer_size(conn->s);
  3907. n_written = (size_t) result;
  3908. }
  3909. if (n_written && conn->type == CONN_TYPE_AP) {
  3910. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3911. /* Check for overflow: */
  3912. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
  3913. edge_conn->n_written += (int)n_written;
  3914. else
  3915. edge_conn->n_written = UINT32_MAX;
  3916. }
  3917. /* If CONN_BW events are enabled, update conn->n_written_conn_bw for
  3918. * OR/DIR/EXIT connections, checking for overflow. */
  3919. if (n_written && get_options()->TestingEnableConnBwEvent &&
  3920. (conn->type == CONN_TYPE_OR ||
  3921. conn->type == CONN_TYPE_DIR ||
  3922. conn->type == CONN_TYPE_EXIT)) {
  3923. if (PREDICT_LIKELY(UINT32_MAX - conn->n_written_conn_bw > n_written))
  3924. conn->n_written_conn_bw += (int)n_written;
  3925. else
  3926. conn->n_written_conn_bw = UINT32_MAX;
  3927. }
  3928. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3929. if (result > 0) {
  3930. /* If we wrote any bytes from our buffer, then call the appropriate
  3931. * functions. */
  3932. if (connection_flushed_some(conn) < 0) {
  3933. if (connection_speaks_cells(conn)) {
  3934. connection_or_notify_error(TO_OR_CONN(conn),
  3935. END_OR_CONN_REASON_MISC,
  3936. "Got error back from "
  3937. "connection_flushed_some()");
  3938. }
  3939. /*
  3940. * This can bypass normal channel checking since we did
  3941. * connection_or_notify_error() above.
  3942. */
  3943. connection_mark_for_close_internal(conn);
  3944. }
  3945. }
  3946. if (!connection_wants_to_flush(conn) &&
  3947. !dont_stop_writing) { /* it's done flushing */
  3948. if (connection_finished_flushing(conn) < 0) {
  3949. /* already marked */
  3950. return -1;
  3951. }
  3952. return 0;
  3953. }
  3954. /* Call even if result is 0, since the global write bucket may
  3955. * have reached 0 on a different conn, and this connection needs to
  3956. * know to stop writing. */
  3957. connection_consider_empty_write_buckets(conn);
  3958. if (n_read > 0 && connection_is_reading(conn))
  3959. connection_consider_empty_read_buckets(conn);
  3960. return 0;
  3961. }
  3962. /* DOCDOC connection_handle_write */
  3963. int
  3964. connection_handle_write(connection_t *conn, int force)
  3965. {
  3966. int res;
  3967. update_current_time(time(NULL));
  3968. /* connection_handle_write_impl() might call connection_handle_read()
  3969. * if we're in the middle of a v2 handshake, in which case it needs this
  3970. * flag set. */
  3971. conn->in_connection_handle_write = 1;
  3972. res = connection_handle_write_impl(conn, force);
  3973. conn->in_connection_handle_write = 0;
  3974. return res;
  3975. }
  3976. /**
  3977. * Try to flush data that's waiting for a write on <b>conn</b>. Return
  3978. * -1 on failure, 0 on success.
  3979. *
  3980. * Don't use this function for regular writing; the buffers
  3981. * system should be good enough at scheduling writes there. Instead, this
  3982. * function is for cases when we're about to exit or something and we want
  3983. * to report it right away.
  3984. */
  3985. int
  3986. connection_flush(connection_t *conn)
  3987. {
  3988. tor_assert(conn->safe_conn == NULL);
  3989. tor_assert(!connection_uses_safe_conn(conn->type));
  3990. return connection_handle_write(conn, 1);
  3991. }
  3992. /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
  3993. *
  3994. * Return true iff it is okay to queue bytes on <b>conn</b>'s outbuf for
  3995. * writing.
  3996. */
  3997. static int
  3998. connection_may_write_to_buf(connection_t *conn)
  3999. {
  4000. /* if it's marked for close, only allow write if we mean to flush it */
  4001. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  4002. return 0;
  4003. return 1;
  4004. }
  4005. /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
  4006. *
  4007. * Called when an attempt to add bytes on <b>conn</b>'s outbuf has failed;
  4008. * mark the connection and warn as appropriate.
  4009. */
  4010. static void
  4011. connection_write_to_buf_failed(connection_t *conn)
  4012. {
  4013. if (CONN_IS_EDGE(conn)) {
  4014. /* if it failed, it means we have our package/delivery windows set
  4015. wrong compared to our max outbuf size. close the whole circuit. */
  4016. log_warn(LD_NET,
  4017. "write_to_buf failed. Closing circuit (fd %d).", (int)conn->s);
  4018. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  4019. END_CIRC_REASON_INTERNAL);
  4020. } else if (conn->type == CONN_TYPE_OR) {
  4021. or_connection_t *orconn = TO_OR_CONN(conn);
  4022. log_warn(LD_NET,
  4023. "write_to_buf failed on an orconn; notifying of error "
  4024. "(fd %d)", (int)(conn->s));
  4025. connection_or_close_for_error(orconn, 0);
  4026. } else {
  4027. log_warn(LD_NET,
  4028. "write_to_buf failed. Closing connection (fd %d).",
  4029. (int)conn->s);
  4030. connection_mark_for_close(conn);
  4031. }
  4032. }
  4033. /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
  4034. *
  4035. * Called when an attempt to add bytes on <b>conn</b>'s outbuf has succeeded:
  4036. * record the number of bytes added.
  4037. */
  4038. static void
  4039. connection_write_to_buf_commit(connection_t *conn, size_t len)
  4040. {
  4041. /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
  4042. * state, we don't want to try to write it right away, since
  4043. * conn->write_event won't be set yet. Otherwise, write data from
  4044. * this conn as the socket is available. */
  4045. tor_assert(conn->safe_conn == NULL);
  4046. tor_assert(!connection_uses_safe_conn(conn->type));
  4047. if (conn->write_event) {
  4048. connection_start_writing(conn);
  4049. }
  4050. conn->outbuf_flushlen += len;
  4051. }
  4052. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  4053. * outbuf, and ask it to start writing.
  4054. *
  4055. * If <b>zlib</b> is nonzero, this is a directory connection that should get
  4056. * its contents compressed or decompressed as they're written. If zlib is
  4057. * negative, this is the last data to be compressed, and the connection's zlib
  4058. * state should be flushed.
  4059. */
  4060. MOCK_IMPL(void,
  4061. connection_write_to_buf_impl_,(const char *string, size_t len,
  4062. connection_t *conn, int zlib))
  4063. {
  4064. /* XXXX This function really needs to return -1 on failure. */
  4065. int r;
  4066. if (!len && !(zlib<0))
  4067. return;
  4068. if (!connection_may_write_to_buf(conn))
  4069. return;
  4070. size_t written;
  4071. if (conn->safe_conn == NULL) {
  4072. if (zlib) {
  4073. size_t old_datalen = buf_datalen(conn->outbuf);
  4074. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  4075. int done = zlib < 0;
  4076. CONN_LOG_PROTECT(conn, r = buf_add_compress(conn->outbuf,
  4077. dir_conn->compress_state,
  4078. string, len, done));
  4079. written = buf_datalen(conn->outbuf) - old_datalen;
  4080. } else {
  4081. CONN_LOG_PROTECT(conn, r = buf_add(conn->outbuf, string, len));
  4082. written = len;
  4083. }
  4084. if (r < 0) {
  4085. connection_write_to_buf_failed(conn);
  4086. return;
  4087. }
  4088. connection_write_to_buf_commit(conn, written);
  4089. } else {
  4090. // TODO: fix this ugly locking
  4091. tor_mutex_acquire(&(conn->safe_conn->lock));
  4092. struct buf_t *outbuf = conn->safe_conn->outbuf;
  4093. if (zlib) {
  4094. size_t old_datalen = buf_datalen(conn->outbuf);
  4095. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  4096. int done = zlib < 0;
  4097. CONN_LOG_PROTECT(conn, r = buf_add_compress(outbuf,
  4098. dir_conn->compress_state,
  4099. string, len, done));
  4100. written = buf_datalen(outbuf) - old_datalen;
  4101. } else {
  4102. CONN_LOG_PROTECT(conn, r = buf_add(outbuf, string, len));
  4103. written = len;
  4104. }
  4105. if (written > 0) {
  4106. safe_connection_outbuf_modified(conn->safe_conn);
  4107. }
  4108. tor_mutex_release(&(conn->safe_conn->lock));
  4109. if (r < 0) {
  4110. connection_write_to_buf_failed(conn);
  4111. return;
  4112. }
  4113. }
  4114. }
  4115. /**
  4116. * Write a <b>string</b> (of size <b>len</b> to directory connection
  4117. * <b>dir_conn</b>. Apply compression if connection is configured to use
  4118. * it and finalize it if <b>done</b> is true.
  4119. */
  4120. void
  4121. connection_dir_buf_add(const char *string, size_t len,
  4122. dir_connection_t *dir_conn, int done)
  4123. {
  4124. if (dir_conn->compress_state != NULL) {
  4125. connection_buf_add_compress(string, len, dir_conn, done);
  4126. return;
  4127. }
  4128. connection_buf_add(string, len, TO_CONN(dir_conn));
  4129. }
  4130. void
  4131. connection_buf_add_compress(const char *string, size_t len,
  4132. dir_connection_t *conn, int done)
  4133. {
  4134. connection_write_to_buf_impl_(string, len, TO_CONN(conn), done ? -1 : 1);
  4135. }
  4136. /**
  4137. * Add all bytes from <b>buf</b> to <b>conn</b>'s outbuf, draining them
  4138. * from <b>buf</b>. (If the connection is marked and will soon be closed,
  4139. * nothing is drained.)
  4140. */
  4141. void
  4142. connection_buf_add_buf(connection_t *conn, buf_t *buf)
  4143. {
  4144. tor_assert(conn);
  4145. tor_assert(buf);
  4146. size_t len = buf_datalen(buf);
  4147. if (len == 0)
  4148. return;
  4149. if (!connection_may_write_to_buf(conn))
  4150. return;
  4151. buf_move_all(conn->outbuf, buf);
  4152. connection_write_to_buf_commit(conn, len);
  4153. }
  4154. #define CONN_GET_ALL_TEMPLATE(var, test) \
  4155. STMT_BEGIN \
  4156. smartlist_t *conns = get_connection_array(); \
  4157. smartlist_t *ret_conns = smartlist_new(); \
  4158. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, var) { \
  4159. if (var && (test) && !var->marked_for_close) \
  4160. smartlist_add(ret_conns, var); \
  4161. } SMARTLIST_FOREACH_END(var); \
  4162. return ret_conns; \
  4163. STMT_END
  4164. /* Return a list of connections that aren't close and matches the given type
  4165. * and state. The returned list can be empty and must be freed using
  4166. * smartlist_free(). The caller does NOT have ownership of the objects in the
  4167. * list so it must not free them nor reference them as they can disappear. */
  4168. smartlist_t *
  4169. connection_list_by_type_state(int type, int state)
  4170. {
  4171. CONN_GET_ALL_TEMPLATE(conn, (conn->type == type && conn->state == state));
  4172. }
  4173. /* Return a list of connections that aren't close and matches the given type
  4174. * and purpose. The returned list can be empty and must be freed using
  4175. * smartlist_free(). The caller does NOT have ownership of the objects in the
  4176. * list so it must not free them nor reference them as they can disappear. */
  4177. smartlist_t *
  4178. connection_list_by_type_purpose(int type, int purpose)
  4179. {
  4180. CONN_GET_ALL_TEMPLATE(conn,
  4181. (conn->type == type && conn->purpose == purpose));
  4182. }
  4183. /** Return a connection_t * from get_connection_array() that satisfies test on
  4184. * var, and that is not marked for close. */
  4185. #define CONN_GET_TEMPLATE(var, test) \
  4186. STMT_BEGIN \
  4187. smartlist_t *conns = get_connection_array(); \
  4188. SMARTLIST_FOREACH(conns, connection_t *, var, \
  4189. { \
  4190. if (var && (test) && !var->marked_for_close) \
  4191. return var; \
  4192. }); \
  4193. return NULL; \
  4194. STMT_END
  4195. /** Return a connection with given type, address, port, and purpose;
  4196. * or NULL if no such connection exists (or if all such connections are marked
  4197. * for close). */
  4198. MOCK_IMPL(connection_t *,
  4199. connection_get_by_type_addr_port_purpose,(int type,
  4200. const tor_addr_t *addr, uint16_t port,
  4201. int purpose))
  4202. {
  4203. CONN_GET_TEMPLATE(conn,
  4204. (conn->type == type &&
  4205. tor_addr_eq(&conn->addr, addr) &&
  4206. conn->port == port &&
  4207. conn->purpose == purpose));
  4208. }
  4209. /** Return the stream with id <b>id</b> if it is not already marked for
  4210. * close.
  4211. */
  4212. connection_t *
  4213. connection_get_by_global_id(uint64_t id)
  4214. {
  4215. CONN_GET_TEMPLATE(conn, conn->global_identifier == id);
  4216. }
  4217. /** Return a connection of type <b>type</b> that is not marked for close.
  4218. */
  4219. connection_t *
  4220. connection_get_by_type(int type)
  4221. {
  4222. CONN_GET_TEMPLATE(conn, conn->type == type);
  4223. }
  4224. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  4225. * and that is not marked for close.
  4226. */
  4227. connection_t *
  4228. connection_get_by_type_state(int type, int state)
  4229. {
  4230. CONN_GET_TEMPLATE(conn, conn->type == type && conn->state == state);
  4231. }
  4232. /**
  4233. * Return a connection of type <b>type</b> that is not an internally linked
  4234. * connection, and is not marked for close.
  4235. **/
  4236. MOCK_IMPL(connection_t *,
  4237. connection_get_by_type_nonlinked,(int type))
  4238. {
  4239. CONN_GET_TEMPLATE(conn, conn->type == type && !conn->linked);
  4240. }
  4241. /** Return a connection of type <b>type</b> that has rendquery equal
  4242. * to <b>rendquery</b>, and that is not marked for close. If state
  4243. * is non-zero, conn must be of that state too.
  4244. */
  4245. connection_t *
  4246. connection_get_by_type_state_rendquery(int type, int state,
  4247. const char *rendquery)
  4248. {
  4249. tor_assert(type == CONN_TYPE_DIR ||
  4250. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  4251. tor_assert(rendquery);
  4252. CONN_GET_TEMPLATE(conn,
  4253. (conn->type == type &&
  4254. (!state || state == conn->state)) &&
  4255. (
  4256. (type == CONN_TYPE_DIR &&
  4257. TO_DIR_CONN(conn)->rend_data &&
  4258. !rend_cmp_service_ids(rendquery,
  4259. rend_data_get_address(TO_DIR_CONN(conn)->rend_data)))
  4260. ||
  4261. (CONN_IS_EDGE(conn) &&
  4262. TO_EDGE_CONN(conn)->rend_data &&
  4263. !rend_cmp_service_ids(rendquery,
  4264. rend_data_get_address(TO_EDGE_CONN(conn)->rend_data)))
  4265. ));
  4266. }
  4267. /** Return a new smartlist of dir_connection_t * from get_connection_array()
  4268. * that satisfy conn_test on connection_t *conn_var, and dirconn_test on
  4269. * dir_connection_t *dirconn_var. conn_var must be of CONN_TYPE_DIR and not
  4270. * marked for close to be included in the list. */
  4271. #define DIR_CONN_LIST_TEMPLATE(conn_var, conn_test, \
  4272. dirconn_var, dirconn_test) \
  4273. STMT_BEGIN \
  4274. smartlist_t *conns = get_connection_array(); \
  4275. smartlist_t *dir_conns = smartlist_new(); \
  4276. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn_var) { \
  4277. if (conn_var && (conn_test) \
  4278. && conn_var->type == CONN_TYPE_DIR \
  4279. && !conn_var->marked_for_close) { \
  4280. dir_connection_t *dirconn_var = TO_DIR_CONN(conn_var); \
  4281. if (dirconn_var && (dirconn_test)) { \
  4282. smartlist_add(dir_conns, dirconn_var); \
  4283. } \
  4284. } \
  4285. } SMARTLIST_FOREACH_END(conn_var); \
  4286. return dir_conns; \
  4287. STMT_END
  4288. /** Return a list of directory connections that are fetching the item
  4289. * described by <b>purpose</b>/<b>resource</b>. If there are none,
  4290. * return an empty list. This list must be freed using smartlist_free,
  4291. * but the pointers in it must not be freed.
  4292. * Note that this list should not be cached, as the pointers in it can be
  4293. * freed if their connections close. */
  4294. smartlist_t *
  4295. connection_dir_list_by_purpose_and_resource(
  4296. int purpose,
  4297. const char *resource)
  4298. {
  4299. DIR_CONN_LIST_TEMPLATE(conn,
  4300. conn->purpose == purpose,
  4301. dirconn,
  4302. 0 == strcmp_opt(resource,
  4303. dirconn->requested_resource));
  4304. }
  4305. /** Return a list of directory connections that are fetching the item
  4306. * described by <b>purpose</b>/<b>resource</b>/<b>state</b>. If there are
  4307. * none, return an empty list. This list must be freed using smartlist_free,
  4308. * but the pointers in it must not be freed.
  4309. * Note that this list should not be cached, as the pointers in it can be
  4310. * freed if their connections close. */
  4311. smartlist_t *
  4312. connection_dir_list_by_purpose_resource_and_state(
  4313. int purpose,
  4314. const char *resource,
  4315. int state)
  4316. {
  4317. DIR_CONN_LIST_TEMPLATE(conn,
  4318. conn->purpose == purpose && conn->state == state,
  4319. dirconn,
  4320. 0 == strcmp_opt(resource,
  4321. dirconn->requested_resource));
  4322. }
  4323. #undef DIR_CONN_LIST_TEMPLATE
  4324. /** Return an arbitrary active OR connection that isn't <b>this_conn</b>.
  4325. *
  4326. * We use this to guess if we should tell the controller that we
  4327. * didn't manage to connect to any of our bridges. */
  4328. static connection_t *
  4329. connection_get_another_active_or_conn(const or_connection_t *this_conn)
  4330. {
  4331. CONN_GET_TEMPLATE(conn,
  4332. conn != TO_CONN(this_conn) && conn->type == CONN_TYPE_OR);
  4333. }
  4334. /** Return 1 if there are any active OR connections apart from
  4335. * <b>this_conn</b>.
  4336. *
  4337. * We use this to guess if we should tell the controller that we
  4338. * didn't manage to connect to any of our bridges. */
  4339. int
  4340. any_other_active_or_conns(const or_connection_t *this_conn)
  4341. {
  4342. connection_t *conn = connection_get_another_active_or_conn(this_conn);
  4343. if (conn != NULL) {
  4344. log_debug(LD_DIR, "%s: Found an OR connection: %s",
  4345. __func__, conn->address);
  4346. return 1;
  4347. }
  4348. return 0;
  4349. }
  4350. #undef CONN_GET_TEMPLATE
  4351. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  4352. int
  4353. connection_is_listener(connection_t *conn)
  4354. {
  4355. if (conn->type == CONN_TYPE_OR_LISTENER ||
  4356. conn->type == CONN_TYPE_EXT_OR_LISTENER ||
  4357. conn->type == CONN_TYPE_AP_LISTENER ||
  4358. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  4359. conn->type == CONN_TYPE_AP_DNS_LISTENER ||
  4360. conn->type == CONN_TYPE_AP_NATD_LISTENER ||
  4361. conn->type == CONN_TYPE_AP_HTTP_CONNECT_LISTENER ||
  4362. conn->type == CONN_TYPE_DIR_LISTENER ||
  4363. conn->type == CONN_TYPE_CONTROL_LISTENER)
  4364. return 1;
  4365. return 0;
  4366. }
  4367. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  4368. * for close, else return 0.
  4369. */
  4370. int
  4371. connection_state_is_open(connection_t *conn)
  4372. {
  4373. tor_assert(conn);
  4374. if (conn->marked_for_close)
  4375. return 0;
  4376. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  4377. (conn->type == CONN_TYPE_EXT_OR) ||
  4378. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  4379. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  4380. (conn->type == CONN_TYPE_CONTROL &&
  4381. conn->state == CONTROL_CONN_STATE_OPEN))
  4382. return 1;
  4383. return 0;
  4384. }
  4385. /** Return 1 if conn is in 'connecting' state, else return 0. */
  4386. int
  4387. connection_state_is_connecting(connection_t *conn)
  4388. {
  4389. tor_assert(conn);
  4390. if (conn->marked_for_close)
  4391. return 0;
  4392. switch (conn->type)
  4393. {
  4394. case CONN_TYPE_OR:
  4395. return conn->state == OR_CONN_STATE_CONNECTING;
  4396. case CONN_TYPE_EXIT:
  4397. return conn->state == EXIT_CONN_STATE_CONNECTING;
  4398. case CONN_TYPE_DIR:
  4399. return conn->state == DIR_CONN_STATE_CONNECTING;
  4400. }
  4401. return 0;
  4402. }
  4403. /** Allocates a base64'ed authenticator for use in http or https
  4404. * auth, based on the input string <b>authenticator</b>. Returns it
  4405. * if success, else returns NULL. */
  4406. char *
  4407. alloc_http_authenticator(const char *authenticator)
  4408. {
  4409. /* an authenticator in Basic authentication
  4410. * is just the string "username:password" */
  4411. const size_t authenticator_length = strlen(authenticator);
  4412. const size_t base64_authenticator_length =
  4413. base64_encode_size(authenticator_length, 0) + 1;
  4414. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  4415. if (base64_encode(base64_authenticator, base64_authenticator_length,
  4416. authenticator, authenticator_length, 0) < 0) {
  4417. tor_free(base64_authenticator); /* free and set to null */
  4418. }
  4419. return base64_authenticator;
  4420. }
  4421. /** Given a socket handle, check whether the local address (sockname) of the
  4422. * socket is one that we've connected from before. If so, double-check
  4423. * whether our address has changed and we need to generate keys. If we do,
  4424. * call init_keys().
  4425. */
  4426. static void
  4427. client_check_address_changed(tor_socket_t sock)
  4428. {
  4429. tor_addr_t out_addr, iface_addr;
  4430. tor_addr_t **last_interface_ip_ptr;
  4431. sa_family_t family;
  4432. if (!outgoing_addrs)
  4433. outgoing_addrs = smartlist_new();
  4434. if (tor_addr_from_getsockname(&out_addr, sock) < 0) {
  4435. int e = tor_socket_errno(sock);
  4436. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  4437. tor_socket_strerror(e));
  4438. return;
  4439. }
  4440. family = tor_addr_family(&out_addr);
  4441. if (family == AF_INET)
  4442. last_interface_ip_ptr = &last_interface_ipv4;
  4443. else if (family == AF_INET6)
  4444. last_interface_ip_ptr = &last_interface_ipv6;
  4445. else
  4446. return;
  4447. if (! *last_interface_ip_ptr) {
  4448. tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
  4449. if (get_interface_address6(LOG_INFO, family, a)==0) {
  4450. *last_interface_ip_ptr = a;
  4451. } else {
  4452. tor_free(a);
  4453. }
  4454. }
  4455. /* If we've used this address previously, we're okay. */
  4456. SMARTLIST_FOREACH(outgoing_addrs, const tor_addr_t *, a_ptr,
  4457. if (tor_addr_eq(a_ptr, &out_addr))
  4458. return;
  4459. );
  4460. /* Uh-oh. We haven't connected from this address before. Has the interface
  4461. * address changed? */
  4462. if (get_interface_address6(LOG_INFO, family, &iface_addr)<0)
  4463. return;
  4464. if (tor_addr_eq(&iface_addr, *last_interface_ip_ptr)) {
  4465. /* Nope, it hasn't changed. Add this address to the list. */
  4466. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  4467. } else {
  4468. /* The interface changed. We're a client, so we need to regenerate our
  4469. * keys. First, reset the state. */
  4470. log_notice(LD_NET, "Our IP address has changed. Rotating keys...");
  4471. tor_addr_copy(*last_interface_ip_ptr, &iface_addr);
  4472. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t*, a_ptr, tor_free(a_ptr));
  4473. smartlist_clear(outgoing_addrs);
  4474. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  4475. /* We'll need to resolve ourselves again. */
  4476. reset_last_resolved_addr();
  4477. /* Okay, now change our keys. */
  4478. ip_address_changed(1);
  4479. }
  4480. }
  4481. /** Some systems have limited system buffers for recv and xmit on
  4482. * sockets allocated in a virtual server or similar environment. For a Tor
  4483. * server this can produce the "Error creating network socket: No buffer
  4484. * space available" error once all available TCP buffer space is consumed.
  4485. * This method will attempt to constrain the buffers allocated for the socket
  4486. * to the desired size to stay below system TCP buffer limits.
  4487. */
  4488. static void
  4489. set_constrained_socket_buffers(tor_socket_t sock, int size)
  4490. {
  4491. void *sz = (void*)&size;
  4492. socklen_t sz_sz = (socklen_t) sizeof(size);
  4493. if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
  4494. int e = tor_socket_errno(sock);
  4495. log_warn(LD_NET, "setsockopt() to constrain send "
  4496. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  4497. }
  4498. if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
  4499. int e = tor_socket_errno(sock);
  4500. log_warn(LD_NET, "setsockopt() to constrain recv "
  4501. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  4502. }
  4503. }
  4504. /** Process new bytes that have arrived on conn-\>inbuf.
  4505. *
  4506. * This function just passes conn to the connection-specific
  4507. * connection_*_process_inbuf() function. It also passes in
  4508. * package_partial if wanted.
  4509. */
  4510. static int
  4511. connection_process_inbuf(connection_t *conn, int package_partial)
  4512. {
  4513. tor_assert(conn);
  4514. switch (conn->type) {
  4515. case CONN_TYPE_OR:
  4516. tor_assert(0);
  4517. return -1;
  4518. //return connection_or_process_inbuf(TO_OR_CONN(conn));
  4519. case CONN_TYPE_EXT_OR:
  4520. return connection_ext_or_process_inbuf(TO_OR_CONN(conn));
  4521. case CONN_TYPE_EXIT:
  4522. case CONN_TYPE_AP:
  4523. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  4524. package_partial);
  4525. case CONN_TYPE_DIR:
  4526. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  4527. case CONN_TYPE_CONTROL:
  4528. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  4529. default:
  4530. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4531. tor_fragile_assert();
  4532. return -1;
  4533. }
  4534. }
  4535. /** Called whenever we've written data on a connection. */
  4536. static int
  4537. connection_flushed_some(connection_t *conn)
  4538. {
  4539. int r = 0;
  4540. tor_assert(!conn->in_flushed_some);
  4541. conn->in_flushed_some = 1;
  4542. if (conn->type == CONN_TYPE_DIR &&
  4543. conn->state == DIR_CONN_STATE_SERVER_WRITING) {
  4544. r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  4545. } else if (conn->type == CONN_TYPE_OR) {
  4546. r = connection_or_flushed_some(TO_OR_CONN(conn));
  4547. } else if (CONN_IS_EDGE(conn)) {
  4548. r = connection_edge_flushed_some(TO_EDGE_CONN(conn));
  4549. }
  4550. conn->in_flushed_some = 0;
  4551. return r;
  4552. }
  4553. /** We just finished flushing bytes to the appropriately low network layer,
  4554. * and there are no more bytes remaining in conn-\>outbuf or
  4555. * conn-\>tls to be flushed.
  4556. *
  4557. * This function just passes conn to the connection-specific
  4558. * connection_*_finished_flushing() function.
  4559. */
  4560. static int
  4561. connection_finished_flushing(connection_t *conn)
  4562. {
  4563. tor_assert(conn);
  4564. /* If the connection is closed, don't try to do anything more here. */
  4565. if (CONN_IS_CLOSED(conn))
  4566. return 0;
  4567. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  4568. connection_stop_writing(conn);
  4569. switch (conn->type) {
  4570. case CONN_TYPE_OR:
  4571. return connection_or_finished_flushing(TO_OR_CONN(conn));
  4572. case CONN_TYPE_EXT_OR:
  4573. return connection_ext_or_finished_flushing(TO_OR_CONN(conn));
  4574. case CONN_TYPE_AP:
  4575. case CONN_TYPE_EXIT:
  4576. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  4577. case CONN_TYPE_DIR:
  4578. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  4579. case CONN_TYPE_CONTROL:
  4580. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  4581. default:
  4582. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4583. tor_fragile_assert();
  4584. return -1;
  4585. }
  4586. }
  4587. /** Called when our attempt to connect() to another server has just
  4588. * succeeded.
  4589. *
  4590. * This function just passes conn to the connection-specific
  4591. * connection_*_finished_connecting() function.
  4592. */
  4593. static int
  4594. connection_finished_connecting(connection_t *conn)
  4595. {
  4596. tor_assert(conn);
  4597. if (!server_mode(get_options())) {
  4598. /* See whether getsockname() says our address changed. We need to do this
  4599. * now that the connection has finished, because getsockname() on Windows
  4600. * won't work until then. */
  4601. client_check_address_changed(conn->s);
  4602. }
  4603. switch (conn->type)
  4604. {
  4605. case CONN_TYPE_OR:
  4606. return connection_or_finished_connecting(TO_OR_CONN(conn));
  4607. case CONN_TYPE_EXIT:
  4608. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  4609. case CONN_TYPE_DIR:
  4610. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  4611. default:
  4612. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4613. tor_fragile_assert();
  4614. return -1;
  4615. }
  4616. }
  4617. /** Callback: invoked when a connection reaches an EOF event. */
  4618. static int
  4619. connection_reached_eof(connection_t *conn)
  4620. {
  4621. switch (conn->type) {
  4622. case CONN_TYPE_OR:
  4623. case CONN_TYPE_EXT_OR:
  4624. return connection_or_reached_eof(TO_OR_CONN(conn));
  4625. case CONN_TYPE_AP:
  4626. case CONN_TYPE_EXIT:
  4627. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  4628. case CONN_TYPE_DIR:
  4629. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  4630. case CONN_TYPE_CONTROL:
  4631. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  4632. default:
  4633. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4634. tor_fragile_assert();
  4635. return -1;
  4636. }
  4637. }
  4638. /** Comparator for the two-orconn case in OOS victim sort */
  4639. static int
  4640. oos_victim_comparator_for_orconns(or_connection_t *a, or_connection_t *b)
  4641. {
  4642. int a_circs, b_circs;
  4643. /* Fewer circuits == higher priority for OOS kill, sort earlier */
  4644. a_circs = connection_or_get_num_circuits(a);
  4645. b_circs = connection_or_get_num_circuits(b);
  4646. if (a_circs < b_circs) return 1;
  4647. else if (a_circs > b_circs) return -1;
  4648. else return 0;
  4649. }
  4650. /** Sort comparator for OOS victims; better targets sort before worse
  4651. * ones. */
  4652. static int
  4653. oos_victim_comparator(const void **a_v, const void **b_v)
  4654. {
  4655. connection_t *a = NULL, *b = NULL;
  4656. /* Get connection pointers out */
  4657. a = (connection_t *)(*a_v);
  4658. b = (connection_t *)(*b_v);
  4659. tor_assert(a != NULL);
  4660. tor_assert(b != NULL);
  4661. /*
  4662. * We always prefer orconns as victims currently; we won't even see
  4663. * these non-orconn cases, but if we do, sort them after orconns.
  4664. */
  4665. if (a->type == CONN_TYPE_OR && b->type == CONN_TYPE_OR) {
  4666. return oos_victim_comparator_for_orconns(TO_OR_CONN(a), TO_OR_CONN(b));
  4667. } else {
  4668. /*
  4669. * One isn't an orconn; if one is, it goes first. We currently have no
  4670. * opinions about cases where neither is an orconn.
  4671. */
  4672. if (a->type == CONN_TYPE_OR) return -1;
  4673. else if (b->type == CONN_TYPE_OR) return 1;
  4674. else return 0;
  4675. }
  4676. }
  4677. /** Pick n victim connections for the OOS handler and return them in a
  4678. * smartlist.
  4679. */
  4680. MOCK_IMPL(STATIC smartlist_t *,
  4681. pick_oos_victims, (int n))
  4682. {
  4683. smartlist_t *eligible = NULL, *victims = NULL;
  4684. smartlist_t *conns;
  4685. int conn_counts_by_type[CONN_TYPE_MAX_ + 1], i;
  4686. /*
  4687. * Big damn assumption (someone improve this someday!):
  4688. *
  4689. * Socket exhaustion normally happens on high-volume relays, and so
  4690. * most of the connections involved are orconns. We should pick victims
  4691. * by assembling a list of all orconns, and sorting them in order of
  4692. * how much 'damage' by some metric we'd be doing by dropping them.
  4693. *
  4694. * If we move on from orconns, we should probably think about incoming
  4695. * directory connections next, or exit connections. Things we should
  4696. * probably never kill are controller connections and listeners.
  4697. *
  4698. * This function will count how many connections of different types
  4699. * exist and log it for purposes of gathering data on typical OOS
  4700. * situations to guide future improvements.
  4701. */
  4702. /* First, get the connection array */
  4703. conns = get_connection_array();
  4704. /*
  4705. * Iterate it and pick out eligible connection types, and log some stats
  4706. * along the way.
  4707. */
  4708. eligible = smartlist_new();
  4709. memset(conn_counts_by_type, 0, sizeof(conn_counts_by_type));
  4710. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4711. /* Bump the counter */
  4712. tor_assert(c->type <= CONN_TYPE_MAX_);
  4713. ++(conn_counts_by_type[c->type]);
  4714. /* Skip anything without a socket we can free */
  4715. if (!(SOCKET_OK(c->s))) {
  4716. continue;
  4717. }
  4718. /* Skip anything we would count as moribund */
  4719. if (connection_is_moribund(c)) {
  4720. continue;
  4721. }
  4722. switch (c->type) {
  4723. case CONN_TYPE_OR:
  4724. /* We've got an orconn, it's eligible to be OOSed */
  4725. smartlist_add(eligible, c);
  4726. break;
  4727. default:
  4728. /* We don't know what to do with it, ignore it */
  4729. break;
  4730. }
  4731. } SMARTLIST_FOREACH_END(c);
  4732. /* Log some stats */
  4733. if (smartlist_len(conns) > 0) {
  4734. /* At least one counter must be non-zero */
  4735. log_info(LD_NET, "Some stats on conn types seen during OOS follow");
  4736. for (i = CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
  4737. /* Did we see any? */
  4738. if (conn_counts_by_type[i] > 0) {
  4739. log_info(LD_NET, "%s: %d conns",
  4740. conn_type_to_string(i),
  4741. conn_counts_by_type[i]);
  4742. }
  4743. }
  4744. log_info(LD_NET, "Done with OOS conn type stats");
  4745. }
  4746. /* Did we find more eligible targets than we want to kill? */
  4747. if (smartlist_len(eligible) > n) {
  4748. /* Sort the list in order of target preference */
  4749. smartlist_sort(eligible, oos_victim_comparator);
  4750. /* Pick first n as victims */
  4751. victims = smartlist_new();
  4752. for (i = 0; i < n; ++i) {
  4753. smartlist_add(victims, smartlist_get(eligible, i));
  4754. }
  4755. /* Free the original list */
  4756. smartlist_free(eligible);
  4757. } else {
  4758. /* No, we can just call them all victims */
  4759. victims = eligible;
  4760. }
  4761. return victims;
  4762. }
  4763. /** Kill a list of connections for the OOS handler. */
  4764. MOCK_IMPL(STATIC void,
  4765. kill_conn_list_for_oos, (smartlist_t *conns))
  4766. {
  4767. if (!conns) return;
  4768. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4769. /* Make sure the channel layer gets told about orconns */
  4770. if (c->type == CONN_TYPE_OR) {
  4771. connection_or_close_for_error(TO_OR_CONN(c), 1);
  4772. } else {
  4773. connection_mark_for_close(c);
  4774. }
  4775. } SMARTLIST_FOREACH_END(c);
  4776. log_notice(LD_NET,
  4777. "OOS handler marked %d connections",
  4778. smartlist_len(conns));
  4779. }
  4780. /** Check if a connection is on the way out so the OOS handler doesn't try
  4781. * to kill more than it needs. */
  4782. int
  4783. connection_is_moribund(connection_t *conn)
  4784. {
  4785. if (conn != NULL &&
  4786. (conn->conn_array_index < 0 ||
  4787. conn->marked_for_close)) {
  4788. return 1;
  4789. } else {
  4790. return 0;
  4791. }
  4792. }
  4793. /** Out-of-Sockets handler; n_socks is the current number of open
  4794. * sockets, and failed is non-zero if a socket exhaustion related
  4795. * error immediately preceded this call. This is where to do
  4796. * circuit-killing heuristics as needed.
  4797. */
  4798. void
  4799. connection_check_oos(int n_socks, int failed)
  4800. {
  4801. int target_n_socks = 0, moribund_socks, socks_to_kill;
  4802. smartlist_t *conns;
  4803. /* Early exit: is OOS checking disabled? */
  4804. if (get_options()->DisableOOSCheck) {
  4805. return;
  4806. }
  4807. /* Sanity-check args */
  4808. tor_assert(n_socks >= 0);
  4809. /*
  4810. * Make some log noise; keep it at debug level since this gets a chance
  4811. * to run on every connection attempt.
  4812. */
  4813. log_debug(LD_NET,
  4814. "Running the OOS handler (%d open sockets, %s)",
  4815. n_socks, (failed != 0) ? "exhaustion seen" : "no exhaustion");
  4816. /*
  4817. * Check if we're really handling an OOS condition, and if so decide how
  4818. * many sockets we want to get down to. Be sure we check if the threshold
  4819. * is distinct from zero first; it's possible for this to be called a few
  4820. * times before we've finished reading the config.
  4821. */
  4822. if (n_socks >= get_options()->ConnLimit_high_thresh &&
  4823. get_options()->ConnLimit_high_thresh != 0 &&
  4824. get_options()->ConnLimit_ != 0) {
  4825. /* Try to get down to the low threshold */
  4826. target_n_socks = get_options()->ConnLimit_low_thresh;
  4827. log_notice(LD_NET,
  4828. "Current number of sockets %d is greater than configured "
  4829. "limit %d; OOS handler trying to get down to %d",
  4830. n_socks, get_options()->ConnLimit_high_thresh,
  4831. target_n_socks);
  4832. } else if (failed) {
  4833. /*
  4834. * If we're not at the limit but we hit a socket exhaustion error, try to
  4835. * drop some (but not as aggressively as ConnLimit_low_threshold, which is
  4836. * 3/4 of ConnLimit_)
  4837. */
  4838. target_n_socks = (n_socks * 9) / 10;
  4839. log_notice(LD_NET,
  4840. "We saw socket exhaustion at %d open sockets; OOS handler "
  4841. "trying to get down to %d",
  4842. n_socks, target_n_socks);
  4843. }
  4844. if (target_n_socks > 0) {
  4845. /*
  4846. * It's an OOS!
  4847. *
  4848. * Count moribund sockets; it's be important that anything we decide
  4849. * to get rid of here but don't immediately close get counted as moribund
  4850. * on subsequent invocations so we don't try to kill too many things if
  4851. * connection_check_oos() gets called multiple times.
  4852. */
  4853. moribund_socks = connection_count_moribund();
  4854. if (moribund_socks < n_socks - target_n_socks) {
  4855. socks_to_kill = n_socks - target_n_socks - moribund_socks;
  4856. conns = pick_oos_victims(socks_to_kill);
  4857. if (conns) {
  4858. kill_conn_list_for_oos(conns);
  4859. log_notice(LD_NET,
  4860. "OOS handler killed %d conns", smartlist_len(conns));
  4861. smartlist_free(conns);
  4862. } else {
  4863. log_notice(LD_NET, "OOS handler failed to pick any victim conns");
  4864. }
  4865. } else {
  4866. log_notice(LD_NET,
  4867. "Not killing any sockets for OOS because there are %d "
  4868. "already moribund, and we only want to eliminate %d",
  4869. moribund_socks, n_socks - target_n_socks);
  4870. }
  4871. }
  4872. }
  4873. /** Log how many bytes are used by buffers of different kinds and sizes. */
  4874. void
  4875. connection_dump_buffer_mem_stats(int severity)
  4876. {
  4877. log_warn(LD_NET, "Dumping memory stats has been disabled");
  4878. // uint64_t used_by_type[CONN_TYPE_MAX_+1];
  4879. // uint64_t alloc_by_type[CONN_TYPE_MAX_+1];
  4880. // int n_conns_by_type[CONN_TYPE_MAX_+1];
  4881. // uint64_t total_alloc = 0;
  4882. // uint64_t total_used = 0;
  4883. // int i;
  4884. // smartlist_t *conns = get_connection_array();
  4885. //
  4886. // memset(used_by_type, 0, sizeof(used_by_type));
  4887. // memset(alloc_by_type, 0, sizeof(alloc_by_type));
  4888. // memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
  4889. //
  4890. // SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4891. // int tp = c->type;
  4892. // ++n_conns_by_type[tp];
  4893. // if (c->inbuf) {
  4894. // used_by_type[tp] += buf_datalen(c->inbuf);
  4895. // alloc_by_type[tp] += buf_allocation(c->inbuf);
  4896. // }
  4897. // if (c->outbuf) {
  4898. // used_by_type[tp] += buf_datalen(c->outbuf);
  4899. // alloc_by_type[tp] += buf_allocation(c->outbuf);
  4900. // }
  4901. // } SMARTLIST_FOREACH_END(c);
  4902. // for (i=0; i <= CONN_TYPE_MAX_; ++i) {
  4903. // total_used += used_by_type[i];
  4904. // total_alloc += alloc_by_type[i];
  4905. // }
  4906. //
  4907. // tor_log(severity, LD_GENERAL,
  4908. // "In buffers for %d connections: %"PRIu64" used/%"PRIu64" allocated",
  4909. // smartlist_len(conns),
  4910. // (total_used), (total_alloc));
  4911. // for (i=CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
  4912. // if (!n_conns_by_type[i])
  4913. // continue;
  4914. // tor_log(severity, LD_GENERAL,
  4915. // " For %d %s connections: %"PRIu64" used/%"PRIu64" allocated",
  4916. // n_conns_by_type[i], conn_type_to_string(i),
  4917. // (used_by_type[i]), (alloc_by_type[i]));
  4918. // }
  4919. }
  4920. /** Verify that connection <b>conn</b> has all of its invariants
  4921. * correct. Trigger an assert if anything is invalid.
  4922. */
  4923. void
  4924. assert_connection_ok(connection_t *conn, time_t now)
  4925. {
  4926. (void) now; /* XXXX unused. */
  4927. tor_assert(conn);
  4928. tor_assert(conn->type >= CONN_TYPE_MIN_);
  4929. tor_assert(conn->type <= CONN_TYPE_MAX_);
  4930. switch (conn->type) {
  4931. case CONN_TYPE_OR:
  4932. case CONN_TYPE_EXT_OR:
  4933. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  4934. break;
  4935. case CONN_TYPE_AP:
  4936. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  4937. break;
  4938. case CONN_TYPE_EXIT:
  4939. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  4940. break;
  4941. case CONN_TYPE_DIR:
  4942. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  4943. break;
  4944. case CONN_TYPE_CONTROL:
  4945. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  4946. break;
  4947. CASE_ANY_LISTENER_TYPE:
  4948. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  4949. break;
  4950. default:
  4951. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  4952. break;
  4953. }
  4954. if (conn->linked_conn) {
  4955. tor_assert(conn->linked_conn->linked_conn == conn);
  4956. tor_assert(conn->linked);
  4957. }
  4958. if (conn->linked)
  4959. tor_assert(!SOCKET_OK(conn->s));
  4960. if (conn->outbuf_flushlen > 0) {
  4961. /* With optimistic data, we may have queued data in
  4962. * EXIT_CONN_STATE_RESOLVING while the conn is not yet marked to writing.
  4963. * */
  4964. tor_assert((conn->type == CONN_TYPE_EXIT &&
  4965. conn->state == EXIT_CONN_STATE_RESOLVING) ||
  4966. connection_is_writing(conn) ||
  4967. conn->write_blocked_on_bw ||
  4968. (CONN_IS_EDGE(conn) &&
  4969. TO_EDGE_CONN(conn)->edge_blocked_on_circ));
  4970. }
  4971. if (conn->hold_open_until_flushed)
  4972. tor_assert(conn->marked_for_close);
  4973. /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
  4974. * marked_for_close. */
  4975. /* buffers */
  4976. if (conn->inbuf)
  4977. buf_assert_ok(conn->inbuf);
  4978. if (conn->outbuf)
  4979. buf_assert_ok(conn->outbuf);
  4980. if (conn->type == CONN_TYPE_OR) {
  4981. or_connection_t *or_conn = TO_OR_CONN(conn);
  4982. if (conn->state == OR_CONN_STATE_OPEN) {
  4983. /* tor_assert(conn->bandwidth > 0); */
  4984. /* the above isn't necessarily true: if we just did a TLS
  4985. * handshake but we didn't recognize the other peer, or it
  4986. * gave a bad cert/etc, then we won't have assigned bandwidth,
  4987. * yet it will be open. -RD
  4988. */
  4989. // tor_assert(conn->read_bucket >= 0);
  4990. }
  4991. // tor_assert(conn->addr && conn->port);
  4992. tor_assert(conn->address);
  4993. //if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
  4994. // tor_assert(or_conn->tls);
  4995. }
  4996. if (CONN_IS_EDGE(conn)) {
  4997. /* XXX unchecked: package window, deliver window. */
  4998. if (conn->type == CONN_TYPE_AP) {
  4999. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  5000. if (entry_conn->chosen_exit_optional || entry_conn->chosen_exit_retries)
  5001. tor_assert(entry_conn->chosen_exit_name);
  5002. tor_assert(entry_conn->socks_request);
  5003. if (conn->state == AP_CONN_STATE_OPEN) {
  5004. tor_assert(entry_conn->socks_request->has_finished);
  5005. if (!conn->marked_for_close) {
  5006. tor_assert(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  5007. cpath_assert_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  5008. }
  5009. }
  5010. }
  5011. if (conn->type == CONN_TYPE_EXIT) {
  5012. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  5013. conn->purpose == EXIT_PURPOSE_RESOLVE);
  5014. }
  5015. } else if (conn->type == CONN_TYPE_DIR) {
  5016. } else {
  5017. /* Purpose is only used for dir and exit types currently */
  5018. tor_assert(!conn->purpose);
  5019. }
  5020. switch (conn->type)
  5021. {
  5022. CASE_ANY_LISTENER_TYPE:
  5023. tor_assert(conn->state == LISTENER_STATE_READY);
  5024. break;
  5025. case CONN_TYPE_OR:
  5026. tor_assert(conn->state >= OR_CONN_STATE_MIN_);
  5027. tor_assert(conn->state <= OR_CONN_STATE_MAX_);
  5028. break;
  5029. case CONN_TYPE_EXT_OR:
  5030. tor_assert(conn->state >= EXT_OR_CONN_STATE_MIN_);
  5031. tor_assert(conn->state <= EXT_OR_CONN_STATE_MAX_);
  5032. break;
  5033. case CONN_TYPE_EXIT:
  5034. tor_assert(conn->state >= EXIT_CONN_STATE_MIN_);
  5035. tor_assert(conn->state <= EXIT_CONN_STATE_MAX_);
  5036. tor_assert(conn->purpose >= EXIT_PURPOSE_MIN_);
  5037. tor_assert(conn->purpose <= EXIT_PURPOSE_MAX_);
  5038. break;
  5039. case CONN_TYPE_AP:
  5040. tor_assert(conn->state >= AP_CONN_STATE_MIN_);
  5041. tor_assert(conn->state <= AP_CONN_STATE_MAX_);
  5042. tor_assert(TO_ENTRY_CONN(conn)->socks_request);
  5043. break;
  5044. case CONN_TYPE_DIR:
  5045. tor_assert(conn->state >= DIR_CONN_STATE_MIN_);
  5046. tor_assert(conn->state <= DIR_CONN_STATE_MAX_);
  5047. tor_assert(conn->purpose >= DIR_PURPOSE_MIN_);
  5048. tor_assert(conn->purpose <= DIR_PURPOSE_MAX_);
  5049. break;
  5050. case CONN_TYPE_CONTROL:
  5051. tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
  5052. tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
  5053. break;
  5054. default:
  5055. tor_assert(0);
  5056. }
  5057. }
  5058. /** Fills <b>addr</b> and <b>port</b> with the details of the global
  5059. * proxy server we are using. Store a 1 to the int pointed to by
  5060. * <b>is_put_out</b> if the connection is using a pluggable
  5061. * transport; store 0 otherwise. <b>conn</b> contains the connection
  5062. * we are using the proxy for.
  5063. *
  5064. * Return 0 on success, -1 on failure.
  5065. */
  5066. int
  5067. get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type,
  5068. int *is_pt_out, const connection_t *conn)
  5069. {
  5070. const or_options_t *options = get_options();
  5071. *is_pt_out = 0;
  5072. /* Client Transport Plugins can use another proxy, but that should be hidden
  5073. * from the rest of tor (as the plugin is responsible for dealing with the
  5074. * proxy), check it first, then check the rest of the proxy types to allow
  5075. * the config to have unused ClientTransportPlugin entries.
  5076. */
  5077. if (options->ClientTransportPlugin) {
  5078. const transport_t *transport = NULL;
  5079. int r;
  5080. r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
  5081. if (r<0)
  5082. return -1;
  5083. if (transport) { /* transport found */
  5084. tor_addr_copy(addr, &transport->addr);
  5085. *port = transport->port;
  5086. *proxy_type = transport->socks_version;
  5087. *is_pt_out = 1;
  5088. return 0;
  5089. }
  5090. /* Unused ClientTransportPlugin. */
  5091. }
  5092. if (options->HTTPSProxy) {
  5093. tor_addr_copy(addr, &options->HTTPSProxyAddr);
  5094. *port = options->HTTPSProxyPort;
  5095. *proxy_type = PROXY_CONNECT;
  5096. return 0;
  5097. } else if (options->Socks4Proxy) {
  5098. tor_addr_copy(addr, &options->Socks4ProxyAddr);
  5099. *port = options->Socks4ProxyPort;
  5100. *proxy_type = PROXY_SOCKS4;
  5101. return 0;
  5102. } else if (options->Socks5Proxy) {
  5103. tor_addr_copy(addr, &options->Socks5ProxyAddr);
  5104. *port = options->Socks5ProxyPort;
  5105. *proxy_type = PROXY_SOCKS5;
  5106. return 0;
  5107. }
  5108. tor_addr_make_unspec(addr);
  5109. *port = 0;
  5110. *proxy_type = PROXY_NONE;
  5111. return 0;
  5112. }
  5113. /** Log a failed connection to a proxy server.
  5114. * <b>conn</b> is the connection we use the proxy server for. */
  5115. void
  5116. log_failed_proxy_connection(connection_t *conn)
  5117. {
  5118. tor_addr_t proxy_addr;
  5119. uint16_t proxy_port;
  5120. int proxy_type, is_pt;
  5121. if (get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
  5122. conn) != 0)
  5123. return; /* if we have no proxy set up, leave this function. */
  5124. (void)is_pt;
  5125. log_warn(LD_NET,
  5126. "The connection to the %s proxy server at %s just failed. "
  5127. "Make sure that the proxy server is up and running.",
  5128. proxy_type_to_string(proxy_type),
  5129. fmt_addrport(&proxy_addr, proxy_port));
  5130. }
  5131. /** Return string representation of <b>proxy_type</b>. */
  5132. static const char *
  5133. proxy_type_to_string(int proxy_type)
  5134. {
  5135. switch (proxy_type) {
  5136. case PROXY_CONNECT: return "HTTP";
  5137. case PROXY_SOCKS4: return "SOCKS4";
  5138. case PROXY_SOCKS5: return "SOCKS5";
  5139. case PROXY_PLUGGABLE: return "pluggable transports SOCKS";
  5140. case PROXY_NONE: return "NULL";
  5141. default: tor_assert(0);
  5142. }
  5143. return NULL; /*Unreached*/
  5144. }
  5145. /** Call connection_free_minimal() on every connection in our array, and
  5146. * release all storage held by connection.c.
  5147. *
  5148. * Don't do the checks in connection_free(), because they will
  5149. * fail.
  5150. */
  5151. void
  5152. connection_free_all(void)
  5153. {
  5154. smartlist_t *conns = get_connection_array();
  5155. /* We don't want to log any messages to controllers. */
  5156. SMARTLIST_FOREACH(conns, connection_t *, conn,
  5157. if (conn->type == CONN_TYPE_CONTROL)
  5158. TO_CONTROL_CONN(conn)->event_mask = 0);
  5159. control_update_global_event_mask();
  5160. /* Unlink everything from the identity map. */
  5161. connection_or_clear_identity_map();
  5162. connection_or_clear_ext_or_id_map();
  5163. /* Clear out our list of broken connections */
  5164. clear_broken_connection_map(0);
  5165. SMARTLIST_FOREACH(conns, connection_t *, conn,
  5166. connection_free_minimal(conn));
  5167. if (outgoing_addrs) {
  5168. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t *, addr, tor_free(addr));
  5169. smartlist_free(outgoing_addrs);
  5170. outgoing_addrs = NULL;
  5171. }
  5172. tor_free(last_interface_ipv4);
  5173. tor_free(last_interface_ipv6);
  5174. last_recorded_accounting_at = 0;
  5175. mainloop_event_free(reenable_blocked_connections_ev);
  5176. reenable_blocked_connections_is_scheduled = 0;
  5177. memset(&reenable_blocked_connections_delay, 0, sizeof(struct timeval));
  5178. }
  5179. /** Log a warning, and possibly emit a control event, that <b>received</b> came
  5180. * at a skewed time. <b>trusted</b> indicates that the <b>source</b> was one
  5181. * that we had more faith in and therefore the warning level should have higher
  5182. * severity.
  5183. */
  5184. MOCK_IMPL(void,
  5185. clock_skew_warning, (const connection_t *conn, long apparent_skew, int trusted,
  5186. log_domain_mask_t domain, const char *received,
  5187. const char *source))
  5188. {
  5189. char dbuf[64];
  5190. char *ext_source = NULL, *warn = NULL;
  5191. format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
  5192. if (conn)
  5193. tor_asprintf(&ext_source, "%s:%s:%d", source, conn->address, conn->port);
  5194. else
  5195. ext_source = tor_strdup(source);
  5196. log_fn(trusted ? LOG_WARN : LOG_INFO, domain,
  5197. "Received %s with skewed time (%s): "
  5198. "It seems that our clock is %s by %s, or that theirs is %s%s. "
  5199. "Tor requires an accurate clock to work: please check your time, "
  5200. "timezone, and date settings.", received, ext_source,
  5201. apparent_skew > 0 ? "ahead" : "behind", dbuf,
  5202. apparent_skew > 0 ? "behind" : "ahead",
  5203. (!conn || trusted) ? "" : ", or they are sending us the wrong time");
  5204. if (trusted) {
  5205. control_event_general_status(LOG_WARN, "CLOCK_SKEW SKEW=%ld SOURCE=%s",
  5206. apparent_skew, ext_source);
  5207. tor_asprintf(&warn, "Clock skew %ld in %s from %s", apparent_skew,
  5208. received, source);
  5209. control_event_bootstrap_problem(warn, "CLOCK_SKEW", conn, 1);
  5210. }
  5211. tor_free(warn);
  5212. tor_free(ext_source);
  5213. }