connection.c 175 KB

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