connection.c 176 KB

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