connection.c 174 KB

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