connection.c 152 KB

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