connection.c 179 KB

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