connection.c 164 KB

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