connection.c 195 KB

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