connection.c 172 KB

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