connection.c 195 KB

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