connection.c 164 KB

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