connection.c 163 KB

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