connection.c 180 KB

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