connection.c 175 KB

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