connection.c 181 KB

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