connection.c 180 KB

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