connection.c 175 KB

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