connection.c 175 KB

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