connection.c 152 KB

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