connection.c 181 KB

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