connection.c 195 KB

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