connection.c 195 KB

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