connection.c 167 KB

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