connection.c 175 KB

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