connection.c 167 KB

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