connection.c 177 KB

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