connection.c 185 KB

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