connection.c 155 KB

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