connection.c 178 KB

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