connection.c 177 KB

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