connection.c 176 KB

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