connection.c 158 KB

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