connection.c 172 KB

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