connection.c 176 KB

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