connection.c 175 KB

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