connection.c 167 KB

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