channel.c 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869
  1. /* * Copyright (c) 2012-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file channel.c
  5. *
  6. * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
  7. * transfer cells from Tor instance to Tor instance.
  8. * Currently, there is only one implementation of the channel abstraction: in
  9. * channeltls.c.
  10. *
  11. * Channels are a higher-level abstraction than or_connection_t: In general,
  12. * any means that two Tor relays use to exchange cells, or any means that a
  13. * relay and a client use to exchange cells, is a channel.
  14. *
  15. * Channels differ from pluggable transports in that they do not wrap an
  16. * underlying protocol over which cells are transmitted: they <em>are</em> the
  17. * underlying protocol.
  18. *
  19. * This module defines the generic parts of the channel_t interface, and
  20. * provides the machinery necessary for specialized implementations to be
  21. * created. At present, there is one specialized implementation in
  22. * channeltls.c, which uses connection_or.c to send cells over a TLS
  23. * connection.
  24. *
  25. * Every channel implementation is responsible for being able to transmit
  26. * cells that are added to it with channel_write_cell() and related functions,
  27. * and to receive incoming cells with the channel_queue_cell() and related
  28. * functions. See the channel_t documentation for more information.
  29. *
  30. * When new cells arrive on a channel, they are passed to cell handler
  31. * functions, which can be set by channel_set_cell_handlers()
  32. * functions. (Tor's cell handlers are in command.c.)
  33. *
  34. * Tor flushes cells to channels from relay.c in
  35. * channel_flush_from_first_active_circuit().
  36. **/
  37. /*
  38. * Define this so channel.h gives us things only channel_t subclasses
  39. * should touch.
  40. */
  41. #define TOR_CHANNEL_INTERNAL_
  42. /* This one's for stuff only channel.c and the test suite should see */
  43. #define CHANNEL_PRIVATE_
  44. #include "or.h"
  45. #include "channel.h"
  46. #include "channeltls.h"
  47. #include "channelpadding.h"
  48. #include "circuitbuild.h"
  49. #include "circuitlist.h"
  50. #include "circuitstats.h"
  51. #include "config.h"
  52. #include "connection_or.h" /* For var_cell_free() */
  53. #include "circuitmux.h"
  54. #include "entrynodes.h"
  55. #include "geoip.h"
  56. #include "nodelist.h"
  57. #include "relay.h"
  58. #include "rephist.h"
  59. #include "router.h"
  60. #include "routerlist.h"
  61. #include "scheduler.h"
  62. #include "compat_time.h"
  63. #include "networkstatus.h"
  64. #include "rendservice.h"
  65. /* Global lists of channels */
  66. /* All channel_t instances */
  67. static smartlist_t *all_channels = NULL;
  68. /* All channel_t instances not in ERROR or CLOSED states */
  69. static smartlist_t *active_channels = NULL;
  70. /* All channel_t instances in ERROR or CLOSED states */
  71. static smartlist_t *finished_channels = NULL;
  72. /* All channel_listener_t instances */
  73. static smartlist_t *all_listeners = NULL;
  74. /* All channel_listener_t instances in LISTENING state */
  75. static smartlist_t *active_listeners = NULL;
  76. /* All channel_listener_t instances in LISTENING state */
  77. static smartlist_t *finished_listeners = NULL;
  78. /** Map from channel->global_identifier to channel. Contains the same
  79. * elements as all_channels. */
  80. static HT_HEAD(channel_gid_map, channel_s) channel_gid_map = HT_INITIALIZER();
  81. static unsigned
  82. channel_id_hash(const channel_t *chan)
  83. {
  84. return (unsigned) chan->global_identifier;
  85. }
  86. static int
  87. channel_id_eq(const channel_t *a, const channel_t *b)
  88. {
  89. return a->global_identifier == b->global_identifier;
  90. }
  91. HT_PROTOTYPE(channel_gid_map, channel_s, gidmap_node,
  92. channel_id_hash, channel_id_eq)
  93. HT_GENERATE2(channel_gid_map, channel_s, gidmap_node,
  94. channel_id_hash, channel_id_eq,
  95. 0.6, tor_reallocarray_, tor_free_)
  96. HANDLE_IMPL(channel, channel_s,)
  97. /* Counter for ID numbers */
  98. static uint64_t n_channels_allocated = 0;
  99. /*
  100. * Channel global byte/cell counters, for statistics and for scheduler high
  101. * /low-water marks.
  102. */
  103. /*
  104. * Total number of cells ever given to any channel with the
  105. * channel_write_*_cell() functions.
  106. */
  107. static uint64_t n_channel_cells_queued = 0;
  108. /*
  109. * Total number of cells ever passed to a channel lower layer with the
  110. * write_*_cell() methods.
  111. */
  112. static uint64_t n_channel_cells_passed_to_lower_layer = 0;
  113. /*
  114. * Current number of cells in all channel queues; should be
  115. * n_channel_cells_queued - n_channel_cells_passed_to_lower_layer.
  116. */
  117. static uint64_t n_channel_cells_in_queues = 0;
  118. /*
  119. * Total number of bytes for all cells ever queued to a channel and
  120. * counted in n_channel_cells_queued.
  121. */
  122. static uint64_t n_channel_bytes_queued = 0;
  123. /*
  124. * Total number of bytes for all cells ever passed to a channel lower layer
  125. * and counted in n_channel_cells_passed_to_lower_layer.
  126. */
  127. static uint64_t n_channel_bytes_passed_to_lower_layer = 0;
  128. /*
  129. * Current number of bytes in all channel queues; should be
  130. * n_channel_bytes_queued - n_channel_bytes_passed_to_lower_layer.
  131. */
  132. static uint64_t n_channel_bytes_in_queues = 0;
  133. /*
  134. * Current total estimated queue size *including lower layer queues and
  135. * transmit overhead*
  136. */
  137. STATIC uint64_t estimated_total_queue_size = 0;
  138. /* Digest->channel map
  139. *
  140. * Similar to the one used in connection_or.c, this maps from the identity
  141. * digest of a remote endpoint to a channel_t to that endpoint. Channels
  142. * should be placed here when registered and removed when they close or error.
  143. * If more than one channel exists, follow the next_with_same_id pointer
  144. * as a linked list.
  145. */
  146. static HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
  147. HT_INITIALIZER();
  148. typedef struct channel_idmap_entry_s {
  149. HT_ENTRY(channel_idmap_entry_s) node;
  150. uint8_t digest[DIGEST_LEN];
  151. TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
  152. } channel_idmap_entry_t;
  153. static inline unsigned
  154. channel_idmap_hash(const channel_idmap_entry_t *ent)
  155. {
  156. return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
  157. }
  158. static inline int
  159. channel_idmap_eq(const channel_idmap_entry_t *a,
  160. const channel_idmap_entry_t *b)
  161. {
  162. return tor_memeq(a->digest, b->digest, DIGEST_LEN);
  163. }
  164. HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
  165. channel_idmap_eq)
  166. HT_GENERATE2(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
  167. channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_)
  168. static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
  169. #if 0
  170. static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
  171. #endif
  172. static cell_queue_entry_t *
  173. cell_queue_entry_new_fixed(cell_t *cell);
  174. static cell_queue_entry_t *
  175. cell_queue_entry_new_var(var_cell_t *var_cell);
  176. static int is_destroy_cell(channel_t *chan,
  177. const cell_queue_entry_t *q, circid_t *circid_out);
  178. static void channel_assert_counter_consistency(void);
  179. /* Functions to maintain the digest map */
  180. static void channel_add_to_digest_map(channel_t *chan);
  181. static void channel_remove_from_digest_map(channel_t *chan);
  182. /*
  183. * Flush cells from just the outgoing queue without trying to get them
  184. * from circuits; used internall by channel_flush_some_cells().
  185. */
  186. static ssize_t
  187. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  188. ssize_t num_cells);
  189. static void channel_force_free(channel_t *chan);
  190. static void
  191. channel_free_list(smartlist_t *channels, int mark_for_close);
  192. static void
  193. channel_listener_free_list(smartlist_t *channels, int mark_for_close);
  194. static void channel_listener_force_free(channel_listener_t *chan_l);
  195. static size_t channel_get_cell_queue_entry_size(channel_t *chan,
  196. cell_queue_entry_t *q);
  197. static void
  198. channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q);
  199. /***********************************
  200. * Channel state utility functions *
  201. **********************************/
  202. /**
  203. * Indicate whether a given channel state is valid
  204. */
  205. int
  206. channel_state_is_valid(channel_state_t state)
  207. {
  208. int is_valid;
  209. switch (state) {
  210. case CHANNEL_STATE_CLOSED:
  211. case CHANNEL_STATE_CLOSING:
  212. case CHANNEL_STATE_ERROR:
  213. case CHANNEL_STATE_MAINT:
  214. case CHANNEL_STATE_OPENING:
  215. case CHANNEL_STATE_OPEN:
  216. is_valid = 1;
  217. break;
  218. case CHANNEL_STATE_LAST:
  219. default:
  220. is_valid = 0;
  221. }
  222. return is_valid;
  223. }
  224. /**
  225. * Indicate whether a given channel listener state is valid
  226. */
  227. int
  228. channel_listener_state_is_valid(channel_listener_state_t state)
  229. {
  230. int is_valid;
  231. switch (state) {
  232. case CHANNEL_LISTENER_STATE_CLOSED:
  233. case CHANNEL_LISTENER_STATE_LISTENING:
  234. case CHANNEL_LISTENER_STATE_CLOSING:
  235. case CHANNEL_LISTENER_STATE_ERROR:
  236. is_valid = 1;
  237. break;
  238. case CHANNEL_LISTENER_STATE_LAST:
  239. default:
  240. is_valid = 0;
  241. }
  242. return is_valid;
  243. }
  244. /**
  245. * Indicate whether a channel state transition is valid
  246. *
  247. * This function takes two channel states and indicates whether a
  248. * transition between them is permitted (see the state definitions and
  249. * transition table in or.h at the channel_state_t typedef).
  250. */
  251. int
  252. channel_state_can_transition(channel_state_t from, channel_state_t to)
  253. {
  254. int is_valid;
  255. switch (from) {
  256. case CHANNEL_STATE_CLOSED:
  257. is_valid = (to == CHANNEL_STATE_OPENING);
  258. break;
  259. case CHANNEL_STATE_CLOSING:
  260. is_valid = (to == CHANNEL_STATE_CLOSED ||
  261. to == CHANNEL_STATE_ERROR);
  262. break;
  263. case CHANNEL_STATE_ERROR:
  264. is_valid = 0;
  265. break;
  266. case CHANNEL_STATE_MAINT:
  267. is_valid = (to == CHANNEL_STATE_CLOSING ||
  268. to == CHANNEL_STATE_ERROR ||
  269. to == CHANNEL_STATE_OPEN);
  270. break;
  271. case CHANNEL_STATE_OPENING:
  272. is_valid = (to == CHANNEL_STATE_CLOSING ||
  273. to == CHANNEL_STATE_ERROR ||
  274. to == CHANNEL_STATE_OPEN);
  275. break;
  276. case CHANNEL_STATE_OPEN:
  277. is_valid = (to == CHANNEL_STATE_CLOSING ||
  278. to == CHANNEL_STATE_ERROR ||
  279. to == CHANNEL_STATE_MAINT);
  280. break;
  281. case CHANNEL_STATE_LAST:
  282. default:
  283. is_valid = 0;
  284. }
  285. return is_valid;
  286. }
  287. /**
  288. * Indicate whether a channel listener state transition is valid
  289. *
  290. * This function takes two channel listener states and indicates whether a
  291. * transition between them is permitted (see the state definitions and
  292. * transition table in or.h at the channel_listener_state_t typedef).
  293. */
  294. int
  295. channel_listener_state_can_transition(channel_listener_state_t from,
  296. channel_listener_state_t to)
  297. {
  298. int is_valid;
  299. switch (from) {
  300. case CHANNEL_LISTENER_STATE_CLOSED:
  301. is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
  302. break;
  303. case CHANNEL_LISTENER_STATE_CLOSING:
  304. is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
  305. to == CHANNEL_LISTENER_STATE_ERROR);
  306. break;
  307. case CHANNEL_LISTENER_STATE_ERROR:
  308. is_valid = 0;
  309. break;
  310. case CHANNEL_LISTENER_STATE_LISTENING:
  311. is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
  312. to == CHANNEL_LISTENER_STATE_ERROR);
  313. break;
  314. case CHANNEL_LISTENER_STATE_LAST:
  315. default:
  316. is_valid = 0;
  317. }
  318. return is_valid;
  319. }
  320. /**
  321. * Return a human-readable description for a channel state
  322. */
  323. const char *
  324. channel_state_to_string(channel_state_t state)
  325. {
  326. const char *descr;
  327. switch (state) {
  328. case CHANNEL_STATE_CLOSED:
  329. descr = "closed";
  330. break;
  331. case CHANNEL_STATE_CLOSING:
  332. descr = "closing";
  333. break;
  334. case CHANNEL_STATE_ERROR:
  335. descr = "channel error";
  336. break;
  337. case CHANNEL_STATE_MAINT:
  338. descr = "temporarily suspended for maintenance";
  339. break;
  340. case CHANNEL_STATE_OPENING:
  341. descr = "opening";
  342. break;
  343. case CHANNEL_STATE_OPEN:
  344. descr = "open";
  345. break;
  346. case CHANNEL_STATE_LAST:
  347. default:
  348. descr = "unknown or invalid channel state";
  349. }
  350. return descr;
  351. }
  352. /**
  353. * Return a human-readable description for a channel listenier state
  354. */
  355. const char *
  356. channel_listener_state_to_string(channel_listener_state_t state)
  357. {
  358. const char *descr;
  359. switch (state) {
  360. case CHANNEL_LISTENER_STATE_CLOSED:
  361. descr = "closed";
  362. break;
  363. case CHANNEL_LISTENER_STATE_CLOSING:
  364. descr = "closing";
  365. break;
  366. case CHANNEL_LISTENER_STATE_ERROR:
  367. descr = "channel listener error";
  368. break;
  369. case CHANNEL_LISTENER_STATE_LISTENING:
  370. descr = "listening";
  371. break;
  372. case CHANNEL_LISTENER_STATE_LAST:
  373. default:
  374. descr = "unknown or invalid channel listener state";
  375. }
  376. return descr;
  377. }
  378. /***************************************
  379. * Channel registration/unregistration *
  380. ***************************************/
  381. /**
  382. * Register a channel
  383. *
  384. * This function registers a newly created channel in the global lists/maps
  385. * of active channels.
  386. */
  387. void
  388. channel_register(channel_t *chan)
  389. {
  390. tor_assert(chan);
  391. tor_assert(chan->global_identifier);
  392. /* No-op if already registered */
  393. if (chan->registered) return;
  394. log_debug(LD_CHANNEL,
  395. "Registering channel %p (ID " U64_FORMAT ") "
  396. "in state %s (%d) with digest %s",
  397. chan, U64_PRINTF_ARG(chan->global_identifier),
  398. channel_state_to_string(chan->state), chan->state,
  399. hex_str(chan->identity_digest, DIGEST_LEN));
  400. /* Make sure we have all_channels, then add it */
  401. if (!all_channels) all_channels = smartlist_new();
  402. smartlist_add(all_channels, chan);
  403. channel_t *oldval = HT_REPLACE(channel_gid_map, &channel_gid_map, chan);
  404. tor_assert(! oldval);
  405. /* Is it finished? */
  406. if (CHANNEL_FINISHED(chan)) {
  407. /* Put it in the finished list, creating it if necessary */
  408. if (!finished_channels) finished_channels = smartlist_new();
  409. smartlist_add(finished_channels, chan);
  410. } else {
  411. /* Put it in the active list, creating it if necessary */
  412. if (!active_channels) active_channels = smartlist_new();
  413. smartlist_add(active_channels, chan);
  414. if (!CHANNEL_IS_CLOSING(chan)) {
  415. /* It should have a digest set */
  416. if (!tor_digest_is_zero(chan->identity_digest)) {
  417. /* Yeah, we're good, add it to the map */
  418. channel_add_to_digest_map(chan);
  419. } else {
  420. log_info(LD_CHANNEL,
  421. "Channel %p (global ID " U64_FORMAT ") "
  422. "in state %s (%d) registered with no identity digest",
  423. chan, U64_PRINTF_ARG(chan->global_identifier),
  424. channel_state_to_string(chan->state), chan->state);
  425. }
  426. }
  427. }
  428. /* Mark it as registered */
  429. chan->registered = 1;
  430. }
  431. /**
  432. * Unregister a channel
  433. *
  434. * This function removes a channel from the global lists and maps and is used
  435. * when freeing a closed/errored channel.
  436. */
  437. void
  438. channel_unregister(channel_t *chan)
  439. {
  440. tor_assert(chan);
  441. /* No-op if not registered */
  442. if (!(chan->registered)) return;
  443. /* Is it finished? */
  444. if (CHANNEL_FINISHED(chan)) {
  445. /* Get it out of the finished list */
  446. if (finished_channels) smartlist_remove(finished_channels, chan);
  447. } else {
  448. /* Get it out of the active list */
  449. if (active_channels) smartlist_remove(active_channels, chan);
  450. }
  451. /* Get it out of all_channels */
  452. if (all_channels) smartlist_remove(all_channels, chan);
  453. channel_t *oldval = HT_REMOVE(channel_gid_map, &channel_gid_map, chan);
  454. tor_assert(oldval == NULL || oldval == chan);
  455. /* Mark it as unregistered */
  456. chan->registered = 0;
  457. /* Should it be in the digest map? */
  458. if (!tor_digest_is_zero(chan->identity_digest) &&
  459. !(CHANNEL_CONDEMNED(chan))) {
  460. /* Remove it */
  461. channel_remove_from_digest_map(chan);
  462. }
  463. }
  464. /**
  465. * Register a channel listener
  466. *
  467. * This function registers a newly created channel listner in the global
  468. * lists/maps of active channel listeners.
  469. */
  470. void
  471. channel_listener_register(channel_listener_t *chan_l)
  472. {
  473. tor_assert(chan_l);
  474. /* No-op if already registered */
  475. if (chan_l->registered) return;
  476. log_debug(LD_CHANNEL,
  477. "Registering channel listener %p (ID " U64_FORMAT ") "
  478. "in state %s (%d)",
  479. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  480. channel_listener_state_to_string(chan_l->state),
  481. chan_l->state);
  482. /* Make sure we have all_listeners, then add it */
  483. if (!all_listeners) all_listeners = smartlist_new();
  484. smartlist_add(all_listeners, chan_l);
  485. /* Is it finished? */
  486. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  487. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
  488. /* Put it in the finished list, creating it if necessary */
  489. if (!finished_listeners) finished_listeners = smartlist_new();
  490. smartlist_add(finished_listeners, chan_l);
  491. } else {
  492. /* Put it in the active list, creating it if necessary */
  493. if (!active_listeners) active_listeners = smartlist_new();
  494. smartlist_add(active_listeners, chan_l);
  495. }
  496. /* Mark it as registered */
  497. chan_l->registered = 1;
  498. }
  499. /**
  500. * Unregister a channel listener
  501. *
  502. * This function removes a channel listener from the global lists and maps
  503. * and is used when freeing a closed/errored channel listener.
  504. */
  505. void
  506. channel_listener_unregister(channel_listener_t *chan_l)
  507. {
  508. tor_assert(chan_l);
  509. /* No-op if not registered */
  510. if (!(chan_l->registered)) return;
  511. /* Is it finished? */
  512. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  513. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
  514. /* Get it out of the finished list */
  515. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  516. } else {
  517. /* Get it out of the active list */
  518. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  519. }
  520. /* Get it out of all_listeners */
  521. if (all_listeners) smartlist_remove(all_listeners, chan_l);
  522. /* Mark it as unregistered */
  523. chan_l->registered = 0;
  524. }
  525. /*********************************
  526. * Channel digest map maintenance
  527. *********************************/
  528. /**
  529. * Add a channel to the digest map
  530. *
  531. * This function adds a channel to the digest map and inserts it into the
  532. * correct linked list if channels with that remote endpoint identity digest
  533. * already exist.
  534. */
  535. static void
  536. channel_add_to_digest_map(channel_t *chan)
  537. {
  538. channel_idmap_entry_t *ent, search;
  539. tor_assert(chan);
  540. /* Assert that the state makes sense */
  541. tor_assert(!CHANNEL_CONDEMNED(chan));
  542. /* Assert that there is a digest */
  543. tor_assert(!tor_digest_is_zero(chan->identity_digest));
  544. memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
  545. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  546. if (! ent) {
  547. ent = tor_malloc(sizeof(channel_idmap_entry_t));
  548. memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
  549. TOR_LIST_INIT(&ent->channel_list);
  550. HT_INSERT(channel_idmap, &channel_identity_map, ent);
  551. }
  552. TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
  553. log_debug(LD_CHANNEL,
  554. "Added channel %p (global ID " U64_FORMAT ") "
  555. "to identity map in state %s (%d) with digest %s",
  556. chan, U64_PRINTF_ARG(chan->global_identifier),
  557. channel_state_to_string(chan->state), chan->state,
  558. hex_str(chan->identity_digest, DIGEST_LEN));
  559. }
  560. /**
  561. * Remove a channel from the digest map
  562. *
  563. * This function removes a channel from the digest map and the linked list of
  564. * channels for that digest if more than one exists.
  565. */
  566. static void
  567. channel_remove_from_digest_map(channel_t *chan)
  568. {
  569. channel_idmap_entry_t *ent, search;
  570. tor_assert(chan);
  571. /* Assert that there is a digest */
  572. tor_assert(!tor_digest_is_zero(chan->identity_digest));
  573. #if 0
  574. /* Make sure we have a map */
  575. if (!channel_identity_map) {
  576. /*
  577. * No identity map, so we can't find it by definition. This
  578. * case is similar to digestmap_get() failing below.
  579. */
  580. log_warn(LD_BUG,
  581. "Trying to remove channel %p (global ID " U64_FORMAT ") "
  582. "with digest %s from identity map, but didn't have any identity "
  583. "map",
  584. chan, U64_PRINTF_ARG(chan->global_identifier),
  585. hex_str(chan->identity_digest, DIGEST_LEN));
  586. /* Clear out its next/prev pointers */
  587. if (chan->next_with_same_id) {
  588. chan->next_with_same_id->prev_with_same_id = chan->prev_with_same_id;
  589. }
  590. if (chan->prev_with_same_id) {
  591. chan->prev_with_same_id->next_with_same_id = chan->next_with_same_id;
  592. }
  593. chan->next_with_same_id = NULL;
  594. chan->prev_with_same_id = NULL;
  595. return;
  596. }
  597. #endif
  598. /* Pull it out of its list, wherever that list is */
  599. TOR_LIST_REMOVE(chan, next_with_same_id);
  600. memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
  601. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  602. /* Look for it in the map */
  603. if (ent) {
  604. /* Okay, it's here */
  605. if (TOR_LIST_EMPTY(&ent->channel_list)) {
  606. HT_REMOVE(channel_idmap, &channel_identity_map, ent);
  607. tor_free(ent);
  608. }
  609. log_debug(LD_CHANNEL,
  610. "Removed channel %p (global ID " U64_FORMAT ") from "
  611. "identity map in state %s (%d) with digest %s",
  612. chan, U64_PRINTF_ARG(chan->global_identifier),
  613. channel_state_to_string(chan->state), chan->state,
  614. hex_str(chan->identity_digest, DIGEST_LEN));
  615. } else {
  616. /* Shouldn't happen */
  617. log_warn(LD_BUG,
  618. "Trying to remove channel %p (global ID " U64_FORMAT ") with "
  619. "digest %s from identity map, but couldn't find any with "
  620. "that digest",
  621. chan, U64_PRINTF_ARG(chan->global_identifier),
  622. hex_str(chan->identity_digest, DIGEST_LEN));
  623. }
  624. }
  625. /****************************
  626. * Channel lookup functions *
  627. ***************************/
  628. /**
  629. * Find channel by global ID
  630. *
  631. * This function searches for a channel by the global_identifier assigned
  632. * at initialization time. This identifier is unique for the lifetime of the
  633. * Tor process.
  634. */
  635. channel_t *
  636. channel_find_by_global_id(uint64_t global_identifier)
  637. {
  638. channel_t lookup;
  639. channel_t *rv = NULL;
  640. lookup.global_identifier = global_identifier;
  641. rv = HT_FIND(channel_gid_map, &channel_gid_map, &lookup);
  642. if (rv) {
  643. tor_assert(rv->global_identifier == global_identifier);
  644. }
  645. return rv;
  646. }
  647. /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
  648. * as its identity keys. If either is NULL, do not check for a match. */
  649. static int
  650. channel_remote_identity_matches(const channel_t *chan,
  651. const char *rsa_id_digest,
  652. const ed25519_public_key_t *ed_id)
  653. {
  654. if (BUG(!chan))
  655. return 0;
  656. if (rsa_id_digest) {
  657. if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
  658. return 0;
  659. }
  660. if (ed_id) {
  661. if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
  662. ED25519_PUBKEY_LEN))
  663. return 0;
  664. }
  665. return 1;
  666. }
  667. /**
  668. * Find channel by RSA/Ed25519 identity of of the remote endpoint
  669. *
  670. * This function looks up a channel by the digest of its remote endpoint's RSA
  671. * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
  672. * matching the <b>ed_id</b> will be returned.
  673. *
  674. * It's possible that more than one channel to a given endpoint exists. Use
  675. * channel_next_with_rsa_identity() to walk the list of channels; make sure
  676. * to test for Ed25519 identity match too (as appropriate)
  677. */
  678. channel_t *
  679. channel_find_by_remote_identity(const char *rsa_id_digest,
  680. const ed25519_public_key_t *ed_id)
  681. {
  682. channel_t *rv = NULL;
  683. channel_idmap_entry_t *ent, search;
  684. tor_assert(rsa_id_digest); /* For now, we require that every channel have
  685. * an RSA identity, and that every lookup
  686. * contain an RSA identity */
  687. if (ed_id && ed25519_public_key_is_zero(ed_id)) {
  688. /* Treat zero as meaning "We don't care about the presence or absence of
  689. * an Ed key", not "There must be no Ed key". */
  690. ed_id = NULL;
  691. }
  692. memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
  693. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  694. if (ent) {
  695. rv = TOR_LIST_FIRST(&ent->channel_list);
  696. }
  697. while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
  698. rv = channel_next_with_rsa_identity(rv);
  699. }
  700. return rv;
  701. }
  702. /**
  703. * Get next channel with digest
  704. *
  705. * This function takes a channel and finds the next channel in the list
  706. * with the same digest.
  707. */
  708. channel_t *
  709. channel_next_with_rsa_identity(channel_t *chan)
  710. {
  711. tor_assert(chan);
  712. return TOR_LIST_NEXT(chan, next_with_same_id);
  713. }
  714. /**
  715. * Relays run this once an hour to look over our list of channels to other
  716. * relays. It prints out some statistics if there are multiple connections
  717. * to many relays.
  718. *
  719. * This function is similar to connection_or_set_bad_connections(),
  720. * and probably could be adapted to replace it, if it was modified to actually
  721. * take action on any of these connections.
  722. */
  723. void
  724. channel_check_for_duplicates(void)
  725. {
  726. channel_idmap_entry_t **iter;
  727. channel_t *chan;
  728. int total_relay_connections = 0, total_relays = 0, total_canonical = 0;
  729. int total_half_canonical = 0;
  730. int total_gt_one_connection = 0, total_gt_two_connections = 0;
  731. int total_gt_four_connections = 0;
  732. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  733. int connections_to_relay = 0;
  734. /* Only consider relay connections */
  735. if (!connection_or_digest_is_known_relay((char*)(*iter)->digest))
  736. continue;
  737. total_relays++;
  738. for (chan = TOR_LIST_FIRST(&(*iter)->channel_list); chan;
  739. chan = channel_next_with_rsa_identity(chan)) {
  740. if (CHANNEL_CONDEMNED(chan) || !CHANNEL_IS_OPEN(chan))
  741. continue;
  742. connections_to_relay++;
  743. total_relay_connections++;
  744. if (chan->is_canonical(chan, 0)) total_canonical++;
  745. if (!chan->is_canonical_to_peer && chan->is_canonical(chan, 0)
  746. && chan->is_canonical(chan, 1)) {
  747. total_half_canonical++;
  748. }
  749. }
  750. if (connections_to_relay > 1) total_gt_one_connection++;
  751. if (connections_to_relay > 2) total_gt_two_connections++;
  752. if (connections_to_relay > 4) total_gt_four_connections++;
  753. }
  754. #define MIN_RELAY_CONNECTIONS_TO_WARN 5
  755. /* If we average 1.5 or more connections per relay, something is wrong */
  756. if (total_relays > MIN_RELAY_CONNECTIONS_TO_WARN &&
  757. total_relay_connections >= 1.5*total_relays) {
  758. log_notice(LD_OR,
  759. "Your relay has a very large number of connections to other relays. "
  760. "Is your outbound address the same as your relay address? "
  761. "Found %d connections to %d relays. Found %d current canonical "
  762. "connections, in %d of which we were a non-canonical peer. "
  763. "%d relays had more than 1 connection, %d had more than 2, and "
  764. "%d had more than 4 connections.",
  765. total_relay_connections, total_relays, total_canonical,
  766. total_half_canonical, total_gt_one_connection,
  767. total_gt_two_connections, total_gt_four_connections);
  768. } else {
  769. log_info(LD_OR, "Performed connection pruning. "
  770. "Found %d connections to %d relays. Found %d current canonical "
  771. "connections, in %d of which we were a non-canonical peer. "
  772. "%d relays had more than 1 connection, %d had more than 2, and "
  773. "%d had more than 4 connections.",
  774. total_relay_connections, total_relays, total_canonical,
  775. total_half_canonical, total_gt_one_connection,
  776. total_gt_two_connections, total_gt_four_connections);
  777. }
  778. }
  779. /**
  780. * Initialize a channel
  781. *
  782. * This function should be called by subclasses to set up some per-channel
  783. * variables. I.e., this is the superclass constructor. Before this, the
  784. * channel should be allocated with tor_malloc_zero().
  785. */
  786. void
  787. channel_init(channel_t *chan)
  788. {
  789. tor_assert(chan);
  790. /* Assign an ID and bump the counter */
  791. chan->global_identifier = ++n_channels_allocated;
  792. /* Init timestamp */
  793. chan->timestamp_last_had_circuits = time(NULL);
  794. /* Warn about exhausted circuit IDs no more than hourly. */
  795. chan->last_warned_circ_ids_exhausted.rate = 3600;
  796. /* Initialize queues. */
  797. TOR_SIMPLEQ_INIT(&chan->incoming_queue);
  798. TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
  799. /* Initialize list entries. */
  800. memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
  801. /* Timestamp it */
  802. channel_timestamp_created(chan);
  803. /* It hasn't been open yet. */
  804. chan->has_been_open = 0;
  805. /* Scheduler state is idle */
  806. chan->scheduler_state = SCHED_CHAN_IDLE;
  807. }
  808. /**
  809. * Initialize a channel listener
  810. *
  811. * This function should be called by subclasses to set up some per-channel
  812. * variables. I.e., this is the superclass constructor. Before this, the
  813. * channel listener should be allocated with tor_malloc_zero().
  814. */
  815. void
  816. channel_init_listener(channel_listener_t *chan_l)
  817. {
  818. tor_assert(chan_l);
  819. /* Assign an ID and bump the counter */
  820. chan_l->global_identifier = ++n_channels_allocated;
  821. /* Timestamp it */
  822. channel_listener_timestamp_created(chan_l);
  823. }
  824. /**
  825. * Free a channel; nothing outside of channel.c and subclasses should call
  826. * this - it frees channels after they have closed and been unregistered.
  827. */
  828. void
  829. channel_free(channel_t *chan)
  830. {
  831. if (!chan) return;
  832. /* It must be closed or errored */
  833. tor_assert(CHANNEL_FINISHED(chan));
  834. /* It must be deregistered */
  835. tor_assert(!(chan->registered));
  836. log_debug(LD_CHANNEL,
  837. "Freeing channel " U64_FORMAT " at %p",
  838. U64_PRINTF_ARG(chan->global_identifier), chan);
  839. /* Get this one out of the scheduler */
  840. scheduler_release_channel(chan);
  841. /*
  842. * Get rid of cmux policy before we do anything, so cmux policies don't
  843. * see channels in weird half-freed states.
  844. */
  845. if (chan->cmux) {
  846. circuitmux_set_policy(chan->cmux, NULL);
  847. }
  848. /* Remove all timers and associated handle entries now */
  849. timer_free(chan->padding_timer);
  850. channel_handle_free(chan->timer_handle);
  851. channel_handles_clear(chan);
  852. /* Call a free method if there is one */
  853. if (chan->free_fn) chan->free_fn(chan);
  854. channel_clear_remote_end(chan);
  855. /* Get rid of cmux */
  856. if (chan->cmux) {
  857. circuitmux_detach_all_circuits(chan->cmux, NULL);
  858. circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
  859. circuitmux_free(chan->cmux);
  860. chan->cmux = NULL;
  861. }
  862. /* We're in CLOSED or ERROR, so the cell queue is already empty */
  863. tor_free(chan);
  864. }
  865. /**
  866. * Free a channel listener; nothing outside of channel.c and subclasses
  867. * should call this - it frees channel listeners after they have closed and
  868. * been unregistered.
  869. */
  870. void
  871. channel_listener_free(channel_listener_t *chan_l)
  872. {
  873. if (!chan_l) return;
  874. log_debug(LD_CHANNEL,
  875. "Freeing channel_listener_t " U64_FORMAT " at %p",
  876. U64_PRINTF_ARG(chan_l->global_identifier),
  877. chan_l);
  878. /* It must be closed or errored */
  879. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  880. chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
  881. /* It must be deregistered */
  882. tor_assert(!(chan_l->registered));
  883. /* Call a free method if there is one */
  884. if (chan_l->free_fn) chan_l->free_fn(chan_l);
  885. /*
  886. * We're in CLOSED or ERROR, so the incoming channel queue is already
  887. * empty.
  888. */
  889. tor_free(chan_l);
  890. }
  891. /**
  892. * Free a channel and skip the state/registration asserts; this internal-
  893. * use-only function should be called only from channel_free_all() when
  894. * shutting down the Tor process.
  895. */
  896. static void
  897. channel_force_free(channel_t *chan)
  898. {
  899. cell_queue_entry_t *cell, *cell_tmp;
  900. tor_assert(chan);
  901. log_debug(LD_CHANNEL,
  902. "Force-freeing channel " U64_FORMAT " at %p",
  903. U64_PRINTF_ARG(chan->global_identifier), chan);
  904. /* Get this one out of the scheduler */
  905. scheduler_release_channel(chan);
  906. /*
  907. * Get rid of cmux policy before we do anything, so cmux policies don't
  908. * see channels in weird half-freed states.
  909. */
  910. if (chan->cmux) {
  911. circuitmux_set_policy(chan->cmux, NULL);
  912. }
  913. /* Remove all timers and associated handle entries now */
  914. timer_free(chan->padding_timer);
  915. channel_handle_free(chan->timer_handle);
  916. channel_handles_clear(chan);
  917. /* Call a free method if there is one */
  918. if (chan->free_fn) chan->free_fn(chan);
  919. channel_clear_remote_end(chan);
  920. /* Get rid of cmux */
  921. if (chan->cmux) {
  922. circuitmux_free(chan->cmux);
  923. chan->cmux = NULL;
  924. }
  925. /* We might still have a cell queue; kill it */
  926. TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
  927. cell_queue_entry_free(cell, 0);
  928. }
  929. TOR_SIMPLEQ_INIT(&chan->incoming_queue);
  930. /* Outgoing cell queue is similar, but we can have to free packed cells */
  931. TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
  932. cell_queue_entry_free(cell, 0);
  933. }
  934. TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
  935. tor_free(chan);
  936. }
  937. /**
  938. * Free a channel listener and skip the state/reigstration asserts; this
  939. * internal-use-only function should be called only from channel_free_all()
  940. * when shutting down the Tor process.
  941. */
  942. static void
  943. channel_listener_force_free(channel_listener_t *chan_l)
  944. {
  945. tor_assert(chan_l);
  946. log_debug(LD_CHANNEL,
  947. "Force-freeing channel_listener_t " U64_FORMAT " at %p",
  948. U64_PRINTF_ARG(chan_l->global_identifier),
  949. chan_l);
  950. /* Call a free method if there is one */
  951. if (chan_l->free_fn) chan_l->free_fn(chan_l);
  952. /*
  953. * The incoming list just gets emptied and freed; we request close on
  954. * any channels we find there, but since we got called while shutting
  955. * down they will get deregistered and freed elsewhere anyway.
  956. */
  957. if (chan_l->incoming_list) {
  958. SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
  959. channel_t *, qchan) {
  960. channel_mark_for_close(qchan);
  961. } SMARTLIST_FOREACH_END(qchan);
  962. smartlist_free(chan_l->incoming_list);
  963. chan_l->incoming_list = NULL;
  964. }
  965. tor_free(chan_l);
  966. }
  967. /**
  968. * Return the current registered listener for a channel listener
  969. *
  970. * This function returns a function pointer to the current registered
  971. * handler for new incoming channels on a channel listener.
  972. */
  973. channel_listener_fn_ptr
  974. channel_listener_get_listener_fn(channel_listener_t *chan_l)
  975. {
  976. tor_assert(chan_l);
  977. if (chan_l->state == CHANNEL_LISTENER_STATE_LISTENING)
  978. return chan_l->listener;
  979. return NULL;
  980. }
  981. /**
  982. * Set the listener for a channel listener
  983. *
  984. * This function sets the handler for new incoming channels on a channel
  985. * listener.
  986. */
  987. void
  988. channel_listener_set_listener_fn(channel_listener_t *chan_l,
  989. channel_listener_fn_ptr listener)
  990. {
  991. tor_assert(chan_l);
  992. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
  993. log_debug(LD_CHANNEL,
  994. "Setting listener callback for channel listener %p "
  995. "(global ID " U64_FORMAT ") to %p",
  996. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  997. listener);
  998. chan_l->listener = listener;
  999. if (chan_l->listener) channel_listener_process_incoming(chan_l);
  1000. }
  1001. /**
  1002. * Return the fixed-length cell handler for a channel
  1003. *
  1004. * This function gets the handler for incoming fixed-length cells installed
  1005. * on a channel.
  1006. */
  1007. channel_cell_handler_fn_ptr
  1008. channel_get_cell_handler(channel_t *chan)
  1009. {
  1010. tor_assert(chan);
  1011. if (CHANNEL_CAN_HANDLE_CELLS(chan))
  1012. return chan->cell_handler;
  1013. return NULL;
  1014. }
  1015. /**
  1016. * Return the variable-length cell handler for a channel
  1017. *
  1018. * This function gets the handler for incoming variable-length cells
  1019. * installed on a channel.
  1020. */
  1021. channel_var_cell_handler_fn_ptr
  1022. channel_get_var_cell_handler(channel_t *chan)
  1023. {
  1024. tor_assert(chan);
  1025. if (CHANNEL_CAN_HANDLE_CELLS(chan))
  1026. return chan->var_cell_handler;
  1027. return NULL;
  1028. }
  1029. /**
  1030. * Set both cell handlers for a channel
  1031. *
  1032. * This function sets both the fixed-length and variable length cell handlers
  1033. * for a channel and processes any incoming cells that had been blocked in the
  1034. * queue because none were available.
  1035. */
  1036. void
  1037. channel_set_cell_handlers(channel_t *chan,
  1038. channel_cell_handler_fn_ptr cell_handler,
  1039. channel_var_cell_handler_fn_ptr
  1040. var_cell_handler)
  1041. {
  1042. int try_again = 0;
  1043. tor_assert(chan);
  1044. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  1045. log_debug(LD_CHANNEL,
  1046. "Setting cell_handler callback for channel %p to %p",
  1047. chan, cell_handler);
  1048. log_debug(LD_CHANNEL,
  1049. "Setting var_cell_handler callback for channel %p to %p",
  1050. chan, var_cell_handler);
  1051. /* Should we try the queue? */
  1052. if (cell_handler &&
  1053. cell_handler != chan->cell_handler) try_again = 1;
  1054. if (var_cell_handler &&
  1055. var_cell_handler != chan->var_cell_handler) try_again = 1;
  1056. /* Change them */
  1057. chan->cell_handler = cell_handler;
  1058. chan->var_cell_handler = var_cell_handler;
  1059. /* Re-run the queue if we have one and there's any reason to */
  1060. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue) &&
  1061. try_again &&
  1062. (chan->cell_handler ||
  1063. chan->var_cell_handler)) channel_process_cells(chan);
  1064. }
  1065. /*
  1066. * On closing channels
  1067. *
  1068. * There are three functions that close channels, for use in
  1069. * different circumstances:
  1070. *
  1071. * - Use channel_mark_for_close() for most cases
  1072. * - Use channel_close_from_lower_layer() if you are connection_or.c
  1073. * and the other end closes the underlying connection.
  1074. * - Use channel_close_for_error() if you are connection_or.c and
  1075. * some sort of error has occurred.
  1076. */
  1077. /**
  1078. * Mark a channel for closure
  1079. *
  1080. * This function tries to close a channel_t; it will go into the CLOSING
  1081. * state, and eventually the lower layer should put it into the CLOSED or
  1082. * ERROR state. Then, channel_run_cleanup() will eventually free it.
  1083. */
  1084. void
  1085. channel_mark_for_close(channel_t *chan)
  1086. {
  1087. tor_assert(chan != NULL);
  1088. tor_assert(chan->close != NULL);
  1089. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1090. if (CHANNEL_CONDEMNED(chan))
  1091. return;
  1092. log_debug(LD_CHANNEL,
  1093. "Closing channel %p (global ID " U64_FORMAT ") "
  1094. "by request",
  1095. chan, U64_PRINTF_ARG(chan->global_identifier));
  1096. /* Note closing by request from above */
  1097. chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
  1098. /* Change state to CLOSING */
  1099. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1100. /* Tell the lower layer */
  1101. chan->close(chan);
  1102. /*
  1103. * It's up to the lower layer to change state to CLOSED or ERROR when we're
  1104. * ready; we'll try to free channels that are in the finished list from
  1105. * channel_run_cleanup(). The lower layer should do this by calling
  1106. * channel_closed().
  1107. */
  1108. }
  1109. /**
  1110. * Mark a channel listener for closure
  1111. *
  1112. * This function tries to close a channel_listener_t; it will go into the
  1113. * CLOSING state, and eventually the lower layer should put it into the CLOSED
  1114. * or ERROR state. Then, channel_run_cleanup() will eventually free it.
  1115. */
  1116. void
  1117. channel_listener_mark_for_close(channel_listener_t *chan_l)
  1118. {
  1119. tor_assert(chan_l != NULL);
  1120. tor_assert(chan_l->close != NULL);
  1121. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1122. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1123. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1124. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1125. log_debug(LD_CHANNEL,
  1126. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1127. "by request",
  1128. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1129. /* Note closing by request from above */
  1130. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
  1131. /* Change state to CLOSING */
  1132. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1133. /* Tell the lower layer */
  1134. chan_l->close(chan_l);
  1135. /*
  1136. * It's up to the lower layer to change state to CLOSED or ERROR when we're
  1137. * ready; we'll try to free channels that are in the finished list from
  1138. * channel_run_cleanup(). The lower layer should do this by calling
  1139. * channel_listener_closed().
  1140. */
  1141. }
  1142. /**
  1143. * Close a channel from the lower layer
  1144. *
  1145. * Notify the channel code that the channel is being closed due to a non-error
  1146. * condition in the lower layer. This does not call the close() method, since
  1147. * the lower layer already knows.
  1148. */
  1149. void
  1150. channel_close_from_lower_layer(channel_t *chan)
  1151. {
  1152. tor_assert(chan != NULL);
  1153. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1154. if (CHANNEL_CONDEMNED(chan))
  1155. return;
  1156. log_debug(LD_CHANNEL,
  1157. "Closing channel %p (global ID " U64_FORMAT ") "
  1158. "due to lower-layer event",
  1159. chan, U64_PRINTF_ARG(chan->global_identifier));
  1160. /* Note closing by event from below */
  1161. chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
  1162. /* Change state to CLOSING */
  1163. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1164. }
  1165. /**
  1166. * Close a channel listener from the lower layer
  1167. *
  1168. * Notify the channel code that the channel listener is being closed due to a
  1169. * non-error condition in the lower layer. This does not call the close()
  1170. * method, since the lower layer already knows.
  1171. */
  1172. void
  1173. channel_listener_close_from_lower_layer(channel_listener_t *chan_l)
  1174. {
  1175. tor_assert(chan_l != NULL);
  1176. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1177. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1178. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1179. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1180. log_debug(LD_CHANNEL,
  1181. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1182. "due to lower-layer event",
  1183. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1184. /* Note closing by event from below */
  1185. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FROM_BELOW;
  1186. /* Change state to CLOSING */
  1187. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1188. }
  1189. /**
  1190. * Notify that the channel is being closed due to an error condition
  1191. *
  1192. * This function is called by the lower layer implementing the transport
  1193. * when a channel must be closed due to an error condition. This does not
  1194. * call the channel's close method, since the lower layer already knows.
  1195. */
  1196. void
  1197. channel_close_for_error(channel_t *chan)
  1198. {
  1199. tor_assert(chan != NULL);
  1200. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1201. if (CHANNEL_CONDEMNED(chan))
  1202. return;
  1203. log_debug(LD_CHANNEL,
  1204. "Closing channel %p due to lower-layer error",
  1205. chan);
  1206. /* Note closing by event from below */
  1207. chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
  1208. /* Change state to CLOSING */
  1209. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1210. }
  1211. /**
  1212. * Notify that the channel listener is being closed due to an error condition
  1213. *
  1214. * This function is called by the lower layer implementing the transport
  1215. * when a channel listener must be closed due to an error condition. This
  1216. * does not call the channel listener's close method, since the lower layer
  1217. * already knows.
  1218. */
  1219. void
  1220. channel_listener_close_for_error(channel_listener_t *chan_l)
  1221. {
  1222. tor_assert(chan_l != NULL);
  1223. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1224. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1225. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1226. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1227. log_debug(LD_CHANNEL,
  1228. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1229. "due to lower-layer error",
  1230. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1231. /* Note closing by event from below */
  1232. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FOR_ERROR;
  1233. /* Change state to CLOSING */
  1234. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1235. }
  1236. /**
  1237. * Notify that the lower layer is finished closing the channel
  1238. *
  1239. * This function should be called by the lower layer when a channel
  1240. * is finished closing and it should be regarded as inactive and
  1241. * freed by the channel code.
  1242. */
  1243. void
  1244. channel_closed(channel_t *chan)
  1245. {
  1246. tor_assert(chan);
  1247. tor_assert(CHANNEL_CONDEMNED(chan));
  1248. /* No-op if already inactive */
  1249. if (CHANNEL_FINISHED(chan))
  1250. return;
  1251. /* Inform any pending (not attached) circs that they should
  1252. * give up. */
  1253. if (! chan->has_been_open)
  1254. circuit_n_chan_done(chan, 0, 0);
  1255. /* Now close all the attached circuits on it. */
  1256. circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
  1257. if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
  1258. channel_change_state(chan, CHANNEL_STATE_CLOSED);
  1259. } else {
  1260. channel_change_state(chan, CHANNEL_STATE_ERROR);
  1261. }
  1262. }
  1263. /**
  1264. * Notify that the lower layer is finished closing the channel listener
  1265. *
  1266. * This function should be called by the lower layer when a channel listener
  1267. * is finished closing and it should be regarded as inactive and
  1268. * freed by the channel code.
  1269. */
  1270. void
  1271. channel_listener_closed(channel_listener_t *chan_l)
  1272. {
  1273. tor_assert(chan_l);
  1274. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1275. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1276. chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
  1277. /* No-op if already inactive */
  1278. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1279. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1280. if (chan_l->reason_for_closing != CHANNEL_LISTENER_CLOSE_FOR_ERROR) {
  1281. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
  1282. } else {
  1283. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_ERROR);
  1284. }
  1285. }
  1286. /**
  1287. * Clear the identity_digest of a channel
  1288. *
  1289. * This function clears the identity digest of the remote endpoint for a
  1290. * channel; this is intended for use by the lower layer.
  1291. */
  1292. void
  1293. channel_clear_identity_digest(channel_t *chan)
  1294. {
  1295. int state_not_in_map;
  1296. tor_assert(chan);
  1297. log_debug(LD_CHANNEL,
  1298. "Clearing remote endpoint digest on channel %p with "
  1299. "global ID " U64_FORMAT,
  1300. chan, U64_PRINTF_ARG(chan->global_identifier));
  1301. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1302. if (!state_not_in_map && chan->registered &&
  1303. !tor_digest_is_zero(chan->identity_digest))
  1304. /* if it's registered get it out of the digest map */
  1305. channel_remove_from_digest_map(chan);
  1306. memset(chan->identity_digest, 0,
  1307. sizeof(chan->identity_digest));
  1308. }
  1309. /**
  1310. * Set the identity_digest of a channel
  1311. *
  1312. * This function sets the identity digest of the remote endpoint for a
  1313. * channel; this is intended for use by the lower layer.
  1314. */
  1315. void
  1316. channel_set_identity_digest(channel_t *chan,
  1317. const char *identity_digest,
  1318. const ed25519_public_key_t *ed_identity)
  1319. {
  1320. int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
  1321. tor_assert(chan);
  1322. log_debug(LD_CHANNEL,
  1323. "Setting remote endpoint digest on channel %p with "
  1324. "global ID " U64_FORMAT " to digest %s",
  1325. chan, U64_PRINTF_ARG(chan->global_identifier),
  1326. identity_digest ?
  1327. hex_str(identity_digest, DIGEST_LEN) : "(null)");
  1328. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1329. was_in_digest_map =
  1330. !state_not_in_map &&
  1331. chan->registered &&
  1332. !tor_digest_is_zero(chan->identity_digest);
  1333. should_be_in_digest_map =
  1334. !state_not_in_map &&
  1335. chan->registered &&
  1336. (identity_digest &&
  1337. !tor_digest_is_zero(identity_digest));
  1338. if (was_in_digest_map)
  1339. /* We should always remove it; we'll add it back if we're writing
  1340. * in a new digest.
  1341. */
  1342. channel_remove_from_digest_map(chan);
  1343. if (identity_digest) {
  1344. memcpy(chan->identity_digest,
  1345. identity_digest,
  1346. sizeof(chan->identity_digest));
  1347. } else {
  1348. memset(chan->identity_digest, 0,
  1349. sizeof(chan->identity_digest));
  1350. }
  1351. if (ed_identity) {
  1352. memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
  1353. } else {
  1354. memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
  1355. }
  1356. /* Put it in the digest map if we should */
  1357. if (should_be_in_digest_map)
  1358. channel_add_to_digest_map(chan);
  1359. }
  1360. /**
  1361. * Clear the remote end metadata (identity_digest/nickname) of a channel
  1362. *
  1363. * This function clears all the remote end info from a channel; this is
  1364. * intended for use by the lower layer.
  1365. */
  1366. void
  1367. channel_clear_remote_end(channel_t *chan)
  1368. {
  1369. int state_not_in_map;
  1370. tor_assert(chan);
  1371. log_debug(LD_CHANNEL,
  1372. "Clearing remote endpoint identity on channel %p with "
  1373. "global ID " U64_FORMAT,
  1374. chan, U64_PRINTF_ARG(chan->global_identifier));
  1375. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1376. if (!state_not_in_map && chan->registered &&
  1377. !tor_digest_is_zero(chan->identity_digest))
  1378. /* if it's registered get it out of the digest map */
  1379. channel_remove_from_digest_map(chan);
  1380. memset(chan->identity_digest, 0,
  1381. sizeof(chan->identity_digest));
  1382. tor_free(chan->nickname);
  1383. }
  1384. /**
  1385. * Set the remote end metadata (identity_digest/nickname) of a channel
  1386. *
  1387. * This function sets new remote end info on a channel; this is intended
  1388. * for use by the lower layer.
  1389. */
  1390. void
  1391. channel_set_remote_end(channel_t *chan,
  1392. const char *identity_digest,
  1393. const char *nickname)
  1394. {
  1395. int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
  1396. tor_assert(chan);
  1397. log_debug(LD_CHANNEL,
  1398. "Setting remote endpoint identity on channel %p with "
  1399. "global ID " U64_FORMAT " to nickname %s, digest %s",
  1400. chan, U64_PRINTF_ARG(chan->global_identifier),
  1401. nickname ? nickname : "(null)",
  1402. identity_digest ?
  1403. hex_str(identity_digest, DIGEST_LEN) : "(null)");
  1404. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1405. was_in_digest_map =
  1406. !state_not_in_map &&
  1407. chan->registered &&
  1408. !tor_digest_is_zero(chan->identity_digest);
  1409. should_be_in_digest_map =
  1410. !state_not_in_map &&
  1411. chan->registered &&
  1412. (identity_digest &&
  1413. !tor_digest_is_zero(identity_digest));
  1414. if (was_in_digest_map)
  1415. /* We should always remove it; we'll add it back if we're writing
  1416. * in a new digest.
  1417. */
  1418. channel_remove_from_digest_map(chan);
  1419. if (identity_digest) {
  1420. memcpy(chan->identity_digest,
  1421. identity_digest,
  1422. sizeof(chan->identity_digest));
  1423. } else {
  1424. memset(chan->identity_digest, 0,
  1425. sizeof(chan->identity_digest));
  1426. }
  1427. tor_free(chan->nickname);
  1428. if (nickname)
  1429. chan->nickname = tor_strdup(nickname);
  1430. /* Put it in the digest map if we should */
  1431. if (should_be_in_digest_map)
  1432. channel_add_to_digest_map(chan);
  1433. }
  1434. /**
  1435. * Duplicate a cell queue entry; this is a shallow copy intended for use
  1436. * in channel_write_cell_queue_entry().
  1437. */
  1438. static cell_queue_entry_t *
  1439. cell_queue_entry_dup(cell_queue_entry_t *q)
  1440. {
  1441. cell_queue_entry_t *rv = NULL;
  1442. tor_assert(q);
  1443. rv = tor_malloc(sizeof(*rv));
  1444. memcpy(rv, q, sizeof(*rv));
  1445. return rv;
  1446. }
  1447. /**
  1448. * Free a cell_queue_entry_t; the handed_off parameter indicates whether
  1449. * the contents were passed to the lower layer (it is responsible for
  1450. * them) or not (we should free).
  1451. */
  1452. STATIC void
  1453. cell_queue_entry_free(cell_queue_entry_t *q, int handed_off)
  1454. {
  1455. if (!q) return;
  1456. if (!handed_off) {
  1457. /*
  1458. * If we handed it off, the recipient becomes responsible (or
  1459. * with packed cells the channel_t subclass calls packed_cell
  1460. * free after writing out its contents; see, e.g.,
  1461. * channel_tls_write_packed_cell_method(). Otherwise, we have
  1462. * to take care of it here if possible.
  1463. */
  1464. switch (q->type) {
  1465. case CELL_QUEUE_FIXED:
  1466. if (q->u.fixed.cell) {
  1467. /*
  1468. * There doesn't seem to be a cell_free() function anywhere in the
  1469. * pre-channel code; just use tor_free()
  1470. */
  1471. tor_free(q->u.fixed.cell);
  1472. }
  1473. break;
  1474. case CELL_QUEUE_PACKED:
  1475. if (q->u.packed.packed_cell) {
  1476. packed_cell_free(q->u.packed.packed_cell);
  1477. }
  1478. break;
  1479. case CELL_QUEUE_VAR:
  1480. if (q->u.var.var_cell) {
  1481. /*
  1482. * This one's in connection_or.c; it'd be nice to figure out the
  1483. * whole flow of cells from one end to the other and factor the
  1484. * cell memory management functions like this out of the specific
  1485. * TLS lower layer.
  1486. */
  1487. var_cell_free(q->u.var.var_cell);
  1488. }
  1489. break;
  1490. default:
  1491. /*
  1492. * Nothing we can do if we don't know the type; this will
  1493. * have been warned about elsewhere.
  1494. */
  1495. break;
  1496. }
  1497. }
  1498. tor_free(q);
  1499. }
  1500. #if 0
  1501. /**
  1502. * Check whether a cell queue entry is padding; this is a helper function
  1503. * for channel_write_cell_queue_entry()
  1504. */
  1505. static int
  1506. cell_queue_entry_is_padding(cell_queue_entry_t *q)
  1507. {
  1508. tor_assert(q);
  1509. if (q->type == CELL_QUEUE_FIXED) {
  1510. if (q->u.fixed.cell) {
  1511. if (q->u.fixed.cell->command == CELL_PADDING ||
  1512. q->u.fixed.cell->command == CELL_VPADDING) {
  1513. return 1;
  1514. }
  1515. }
  1516. } else if (q->type == CELL_QUEUE_VAR) {
  1517. if (q->u.var.var_cell) {
  1518. if (q->u.var.var_cell->command == CELL_PADDING ||
  1519. q->u.var.var_cell->command == CELL_VPADDING) {
  1520. return 1;
  1521. }
  1522. }
  1523. }
  1524. return 0;
  1525. }
  1526. #endif
  1527. /**
  1528. * Allocate a new cell queue entry for a fixed-size cell
  1529. */
  1530. static cell_queue_entry_t *
  1531. cell_queue_entry_new_fixed(cell_t *cell)
  1532. {
  1533. cell_queue_entry_t *q = NULL;
  1534. tor_assert(cell);
  1535. q = tor_malloc(sizeof(*q));
  1536. q->type = CELL_QUEUE_FIXED;
  1537. q->u.fixed.cell = cell;
  1538. return q;
  1539. }
  1540. /**
  1541. * Allocate a new cell queue entry for a variable-size cell
  1542. */
  1543. static cell_queue_entry_t *
  1544. cell_queue_entry_new_var(var_cell_t *var_cell)
  1545. {
  1546. cell_queue_entry_t *q = NULL;
  1547. tor_assert(var_cell);
  1548. q = tor_malloc(sizeof(*q));
  1549. q->type = CELL_QUEUE_VAR;
  1550. q->u.var.var_cell = var_cell;
  1551. return q;
  1552. }
  1553. /**
  1554. * Ask how big the cell contained in a cell_queue_entry_t is
  1555. */
  1556. static size_t
  1557. channel_get_cell_queue_entry_size(channel_t *chan, cell_queue_entry_t *q)
  1558. {
  1559. size_t rv = 0;
  1560. tor_assert(chan);
  1561. tor_assert(q);
  1562. switch (q->type) {
  1563. case CELL_QUEUE_FIXED:
  1564. rv = get_cell_network_size(chan->wide_circ_ids);
  1565. break;
  1566. case CELL_QUEUE_VAR:
  1567. rv = get_var_cell_header_size(chan->wide_circ_ids) +
  1568. (q->u.var.var_cell ? q->u.var.var_cell->payload_len : 0);
  1569. break;
  1570. case CELL_QUEUE_PACKED:
  1571. rv = get_cell_network_size(chan->wide_circ_ids);
  1572. break;
  1573. default:
  1574. tor_assert_nonfatal_unreached_once();
  1575. }
  1576. return rv;
  1577. }
  1578. /**
  1579. * Write to a channel based on a cell_queue_entry_t
  1580. *
  1581. * Given a cell_queue_entry_t filled out by the caller, try to send the cell
  1582. * and queue it if we can't.
  1583. */
  1584. static void
  1585. channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q)
  1586. {
  1587. int result = 0, sent = 0;
  1588. cell_queue_entry_t *tmp = NULL;
  1589. size_t cell_bytes;
  1590. tor_assert(chan);
  1591. tor_assert(q);
  1592. /* Assert that the state makes sense for a cell write */
  1593. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  1594. {
  1595. circid_t circ_id;
  1596. if (is_destroy_cell(chan, q, &circ_id)) {
  1597. channel_note_destroy_not_pending(chan, circ_id);
  1598. }
  1599. }
  1600. /* For statistical purposes, figure out how big this cell is */
  1601. cell_bytes = channel_get_cell_queue_entry_size(chan, q);
  1602. /* Can we send it right out? If so, try */
  1603. if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue) &&
  1604. CHANNEL_IS_OPEN(chan)) {
  1605. /* Pick the right write function for this cell type and save the result */
  1606. switch (q->type) {
  1607. case CELL_QUEUE_FIXED:
  1608. tor_assert(chan->write_cell);
  1609. tor_assert(q->u.fixed.cell);
  1610. result = chan->write_cell(chan, q->u.fixed.cell);
  1611. break;
  1612. case CELL_QUEUE_PACKED:
  1613. tor_assert(chan->write_packed_cell);
  1614. tor_assert(q->u.packed.packed_cell);
  1615. result = chan->write_packed_cell(chan, q->u.packed.packed_cell);
  1616. break;
  1617. case CELL_QUEUE_VAR:
  1618. tor_assert(chan->write_var_cell);
  1619. tor_assert(q->u.var.var_cell);
  1620. result = chan->write_var_cell(chan, q->u.var.var_cell);
  1621. break;
  1622. default:
  1623. tor_assert(1);
  1624. }
  1625. /* Check if we got it out */
  1626. if (result > 0) {
  1627. sent = 1;
  1628. /* Timestamp for transmission */
  1629. channel_timestamp_xmit(chan);
  1630. /* If we're here the queue is empty, so it's drained too */
  1631. channel_timestamp_drained(chan);
  1632. /* Update the counter */
  1633. ++(chan->n_cells_xmitted);
  1634. chan->n_bytes_xmitted += cell_bytes;
  1635. /* Update global counters */
  1636. ++n_channel_cells_queued;
  1637. ++n_channel_cells_passed_to_lower_layer;
  1638. n_channel_bytes_queued += cell_bytes;
  1639. n_channel_bytes_passed_to_lower_layer += cell_bytes;
  1640. channel_assert_counter_consistency();
  1641. }
  1642. }
  1643. if (!sent) {
  1644. /* Not sent, queue it */
  1645. /*
  1646. * We have to copy the queue entry passed in, since the caller probably
  1647. * used the stack.
  1648. */
  1649. tmp = cell_queue_entry_dup(q);
  1650. TOR_SIMPLEQ_INSERT_TAIL(&chan->outgoing_queue, tmp, next);
  1651. /* Update global counters */
  1652. ++n_channel_cells_queued;
  1653. ++n_channel_cells_in_queues;
  1654. n_channel_bytes_queued += cell_bytes;
  1655. n_channel_bytes_in_queues += cell_bytes;
  1656. channel_assert_counter_consistency();
  1657. /* Update channel queue size */
  1658. chan->bytes_in_queue += cell_bytes;
  1659. /* Try to process the queue? */
  1660. if (CHANNEL_IS_OPEN(chan)) channel_flush_cells(chan);
  1661. }
  1662. }
  1663. /** Write a generic cell type to a channel
  1664. *
  1665. * Write a generic cell to a channel. It is called by channel_write_cell(),
  1666. * channel_write_var_cell() and channel_write_packed_cell() in order to reduce
  1667. * code duplication. Notice that it takes cell as pointer of type void,
  1668. * this can be dangerous because no type check is performed.
  1669. */
  1670. void
  1671. channel_write_cell_generic_(channel_t *chan, const char *cell_type,
  1672. void *cell, cell_queue_entry_t *q)
  1673. {
  1674. tor_assert(chan);
  1675. tor_assert(cell);
  1676. if (CHANNEL_IS_CLOSING(chan)) {
  1677. log_debug(LD_CHANNEL, "Discarding %c %p on closing channel %p with "
  1678. "global ID "U64_FORMAT, *cell_type, cell, chan,
  1679. U64_PRINTF_ARG(chan->global_identifier));
  1680. tor_free(cell);
  1681. return;
  1682. }
  1683. log_debug(LD_CHANNEL,
  1684. "Writing %c %p to channel %p with global ID "
  1685. U64_FORMAT, *cell_type,
  1686. cell, chan, U64_PRINTF_ARG(chan->global_identifier));
  1687. channel_write_cell_queue_entry(chan, q);
  1688. /* Update the queue size estimate */
  1689. channel_update_xmit_queue_size(chan);
  1690. }
  1691. /**
  1692. * Write a cell to a channel
  1693. *
  1694. * Write a fixed-length cell to a channel using the write_cell() method.
  1695. * This is equivalent to the pre-channels connection_or_write_cell_to_buf();
  1696. * it is called by the transport-independent code to deliver a cell to a
  1697. * channel for transmission.
  1698. */
  1699. void
  1700. channel_write_cell(channel_t *chan, cell_t *cell)
  1701. {
  1702. cell_queue_entry_t q;
  1703. q.type = CELL_QUEUE_FIXED;
  1704. q.u.fixed.cell = cell;
  1705. channel_write_cell_generic_(chan, "cell_t", cell, &q);
  1706. }
  1707. /**
  1708. * Write a packed cell to a channel
  1709. *
  1710. * Write a packed cell to a channel using the write_cell() method. This is
  1711. * called by the transport-independent code to deliver a packed cell to a
  1712. * channel for transmission.
  1713. */
  1714. void
  1715. channel_write_packed_cell(channel_t *chan, packed_cell_t *packed_cell)
  1716. {
  1717. cell_queue_entry_t q;
  1718. q.type = CELL_QUEUE_PACKED;
  1719. q.u.packed.packed_cell = packed_cell;
  1720. channel_write_cell_generic_(chan, "packed_cell_t", packed_cell, &q);
  1721. }
  1722. /**
  1723. * Write a variable-length cell to a channel
  1724. *
  1725. * Write a variable-length cell to a channel using the write_cell() method.
  1726. * This is equivalent to the pre-channels
  1727. * connection_or_write_var_cell_to_buf(); it's called by the transport-
  1728. * independent code to deliver a var_cell to a channel for transmission.
  1729. */
  1730. void
  1731. channel_write_var_cell(channel_t *chan, var_cell_t *var_cell)
  1732. {
  1733. cell_queue_entry_t q;
  1734. q.type = CELL_QUEUE_VAR;
  1735. q.u.var.var_cell = var_cell;
  1736. channel_write_cell_generic_(chan, "var_cell_t", var_cell, &q);
  1737. }
  1738. /**
  1739. * Change channel state
  1740. *
  1741. * This internal and subclass use only function is used to change channel
  1742. * state, performing all transition validity checks and whatever actions
  1743. * are appropriate to the state transition in question.
  1744. */
  1745. static void
  1746. channel_change_state_(channel_t *chan, channel_state_t to_state)
  1747. {
  1748. channel_state_t from_state;
  1749. unsigned char was_active, is_active;
  1750. unsigned char was_in_id_map, is_in_id_map;
  1751. tor_assert(chan);
  1752. from_state = chan->state;
  1753. tor_assert(channel_state_is_valid(from_state));
  1754. tor_assert(channel_state_is_valid(to_state));
  1755. tor_assert(channel_state_can_transition(chan->state, to_state));
  1756. /* Check for no-op transitions */
  1757. if (from_state == to_state) {
  1758. log_debug(LD_CHANNEL,
  1759. "Got no-op transition from \"%s\" to itself on channel %p"
  1760. "(global ID " U64_FORMAT ")",
  1761. channel_state_to_string(to_state),
  1762. chan, U64_PRINTF_ARG(chan->global_identifier));
  1763. return;
  1764. }
  1765. /* If we're going to a closing or closed state, we must have a reason set */
  1766. if (to_state == CHANNEL_STATE_CLOSING ||
  1767. to_state == CHANNEL_STATE_CLOSED ||
  1768. to_state == CHANNEL_STATE_ERROR) {
  1769. tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
  1770. }
  1771. /*
  1772. * We need to maintain the queues here for some transitions:
  1773. * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
  1774. * we may have a backlog of cells to transmit, so drain the queues in
  1775. * that case, and when going to CHANNEL_STATE_CLOSED the subclass
  1776. * should have made sure to finish sending things (or gone to
  1777. * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
  1778. */
  1779. log_debug(LD_CHANNEL,
  1780. "Changing state of channel %p (global ID " U64_FORMAT
  1781. ") from \"%s\" to \"%s\"",
  1782. chan,
  1783. U64_PRINTF_ARG(chan->global_identifier),
  1784. channel_state_to_string(chan->state),
  1785. channel_state_to_string(to_state));
  1786. chan->state = to_state;
  1787. /* Need to add to the right lists if the channel is registered */
  1788. if (chan->registered) {
  1789. was_active = !(from_state == CHANNEL_STATE_CLOSED ||
  1790. from_state == CHANNEL_STATE_ERROR);
  1791. is_active = !(to_state == CHANNEL_STATE_CLOSED ||
  1792. to_state == CHANNEL_STATE_ERROR);
  1793. /* Need to take off active list and put on finished list? */
  1794. if (was_active && !is_active) {
  1795. if (active_channels) smartlist_remove(active_channels, chan);
  1796. if (!finished_channels) finished_channels = smartlist_new();
  1797. smartlist_add(finished_channels, chan);
  1798. }
  1799. /* Need to put on active list? */
  1800. else if (!was_active && is_active) {
  1801. if (finished_channels) smartlist_remove(finished_channels, chan);
  1802. if (!active_channels) active_channels = smartlist_new();
  1803. smartlist_add(active_channels, chan);
  1804. }
  1805. if (!tor_digest_is_zero(chan->identity_digest)) {
  1806. /* Now we need to handle the identity map */
  1807. was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
  1808. from_state == CHANNEL_STATE_CLOSED ||
  1809. from_state == CHANNEL_STATE_ERROR);
  1810. is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
  1811. to_state == CHANNEL_STATE_CLOSED ||
  1812. to_state == CHANNEL_STATE_ERROR);
  1813. if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
  1814. else if (was_in_id_map && !is_in_id_map)
  1815. channel_remove_from_digest_map(chan);
  1816. }
  1817. }
  1818. /*
  1819. * If we're going to a closed/closing state, we don't need scheduling any
  1820. * more; in CHANNEL_STATE_MAINT we can't accept writes.
  1821. */
  1822. if (to_state == CHANNEL_STATE_CLOSING ||
  1823. to_state == CHANNEL_STATE_CLOSED ||
  1824. to_state == CHANNEL_STATE_ERROR) {
  1825. scheduler_release_channel(chan);
  1826. } else if (to_state == CHANNEL_STATE_MAINT) {
  1827. scheduler_channel_doesnt_want_writes(chan);
  1828. }
  1829. /*
  1830. * If we're closing, this channel no longer counts toward the global
  1831. * estimated queue size; if we're open, it now does.
  1832. */
  1833. if ((to_state == CHANNEL_STATE_CLOSING ||
  1834. to_state == CHANNEL_STATE_CLOSED ||
  1835. to_state == CHANNEL_STATE_ERROR) &&
  1836. (from_state == CHANNEL_STATE_OPEN ||
  1837. from_state == CHANNEL_STATE_MAINT)) {
  1838. estimated_total_queue_size -= chan->bytes_in_queue;
  1839. }
  1840. /*
  1841. * If we're opening, this channel now does count toward the global
  1842. * estimated queue size.
  1843. */
  1844. if ((to_state == CHANNEL_STATE_OPEN ||
  1845. to_state == CHANNEL_STATE_MAINT) &&
  1846. !(from_state == CHANNEL_STATE_OPEN ||
  1847. from_state == CHANNEL_STATE_MAINT)) {
  1848. estimated_total_queue_size += chan->bytes_in_queue;
  1849. }
  1850. if (to_state == CHANNEL_STATE_CLOSED ||
  1851. to_state == CHANNEL_STATE_ERROR) {
  1852. /* Assert that all queues are empty */
  1853. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
  1854. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
  1855. }
  1856. }
  1857. /**
  1858. * As channel_change_state_, but change the state to any state but open.
  1859. */
  1860. void
  1861. channel_change_state(channel_t *chan, channel_state_t to_state)
  1862. {
  1863. tor_assert(to_state != CHANNEL_STATE_OPEN);
  1864. channel_change_state_(chan, to_state);
  1865. }
  1866. /**
  1867. * As channel_change_state, but change the state to open.
  1868. */
  1869. void
  1870. channel_change_state_open(channel_t *chan)
  1871. {
  1872. channel_change_state_(chan, CHANNEL_STATE_OPEN);
  1873. /* Tell circuits if we opened and stuff */
  1874. channel_do_open_actions(chan);
  1875. chan->has_been_open = 1;
  1876. /* Check for queued cells to process */
  1877. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  1878. channel_process_cells(chan);
  1879. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
  1880. channel_flush_cells(chan);
  1881. }
  1882. /**
  1883. * Change channel listener state
  1884. *
  1885. * This internal and subclass use only function is used to change channel
  1886. * listener state, performing all transition validity checks and whatever
  1887. * actions are appropriate to the state transition in question.
  1888. */
  1889. void
  1890. channel_listener_change_state(channel_listener_t *chan_l,
  1891. channel_listener_state_t to_state)
  1892. {
  1893. channel_listener_state_t from_state;
  1894. unsigned char was_active, is_active;
  1895. tor_assert(chan_l);
  1896. from_state = chan_l->state;
  1897. tor_assert(channel_listener_state_is_valid(from_state));
  1898. tor_assert(channel_listener_state_is_valid(to_state));
  1899. tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
  1900. /* Check for no-op transitions */
  1901. if (from_state == to_state) {
  1902. log_debug(LD_CHANNEL,
  1903. "Got no-op transition from \"%s\" to itself on channel "
  1904. "listener %p (global ID " U64_FORMAT ")",
  1905. channel_listener_state_to_string(to_state),
  1906. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1907. return;
  1908. }
  1909. /* If we're going to a closing or closed state, we must have a reason set */
  1910. if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
  1911. to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1912. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1913. tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
  1914. }
  1915. /*
  1916. * We need to maintain the queues here for some transitions:
  1917. * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
  1918. * we may have a backlog of cells to transmit, so drain the queues in
  1919. * that case, and when going to CHANNEL_STATE_CLOSED the subclass
  1920. * should have made sure to finish sending things (or gone to
  1921. * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
  1922. */
  1923. log_debug(LD_CHANNEL,
  1924. "Changing state of channel listener %p (global ID " U64_FORMAT
  1925. "from \"%s\" to \"%s\"",
  1926. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  1927. channel_listener_state_to_string(chan_l->state),
  1928. channel_listener_state_to_string(to_state));
  1929. chan_l->state = to_state;
  1930. /* Need to add to the right lists if the channel listener is registered */
  1931. if (chan_l->registered) {
  1932. was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1933. from_state == CHANNEL_LISTENER_STATE_ERROR);
  1934. is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1935. to_state == CHANNEL_LISTENER_STATE_ERROR);
  1936. /* Need to take off active list and put on finished list? */
  1937. if (was_active && !is_active) {
  1938. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  1939. if (!finished_listeners) finished_listeners = smartlist_new();
  1940. smartlist_add(finished_listeners, chan_l);
  1941. }
  1942. /* Need to put on active list? */
  1943. else if (!was_active && is_active) {
  1944. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  1945. if (!active_listeners) active_listeners = smartlist_new();
  1946. smartlist_add(active_listeners, chan_l);
  1947. }
  1948. }
  1949. if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1950. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1951. /* Assert that the queue is empty */
  1952. tor_assert(!(chan_l->incoming_list) ||
  1953. smartlist_len(chan_l->incoming_list) == 0);
  1954. }
  1955. }
  1956. /**
  1957. * Try to flush cells to the lower layer
  1958. *
  1959. * this is called by the lower layer to indicate that it wants more cells;
  1960. * it will try to write up to num_cells cells from the channel's cell queue or
  1961. * from circuits active on that channel, or as many as it has available if
  1962. * num_cells == -1.
  1963. */
  1964. #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
  1965. MOCK_IMPL(ssize_t,
  1966. channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
  1967. {
  1968. unsigned int unlimited = 0;
  1969. ssize_t flushed = 0;
  1970. int num_cells_from_circs, clamped_num_cells;
  1971. int q_len_before, q_len_after;
  1972. tor_assert(chan);
  1973. if (num_cells < 0) unlimited = 1;
  1974. if (!unlimited && num_cells <= flushed) goto done;
  1975. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1976. if (CHANNEL_IS_OPEN(chan)) {
  1977. /* Try to flush as much as we can that's already queued */
  1978. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  1979. (unlimited ? -1 : num_cells - flushed));
  1980. if (!unlimited && num_cells <= flushed) goto done;
  1981. if (circuitmux_num_cells(chan->cmux) > 0) {
  1982. /* Calculate number of cells, including clamp */
  1983. if (unlimited) {
  1984. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1985. } else {
  1986. if (num_cells - flushed >
  1987. MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
  1988. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1989. } else {
  1990. clamped_num_cells = (int)(num_cells - flushed);
  1991. }
  1992. }
  1993. /*
  1994. * Keep track of the change in queue size; we have to count cells
  1995. * channel_flush_from_first_active_circuit() writes out directly,
  1996. * but not double-count ones we might get later in
  1997. * channel_flush_some_cells_from_outgoing_queue()
  1998. */
  1999. q_len_before = chan_cell_queue_len(&(chan->outgoing_queue));
  2000. /* Try to get more cells from any active circuits */
  2001. num_cells_from_circs = channel_flush_from_first_active_circuit(
  2002. chan, clamped_num_cells);
  2003. q_len_after = chan_cell_queue_len(&(chan->outgoing_queue));
  2004. /*
  2005. * If it claims we got some, adjust the flushed counter and consider
  2006. * processing the queue again
  2007. */
  2008. if (num_cells_from_circs > 0) {
  2009. /*
  2010. * Adjust flushed by the number of cells counted in
  2011. * num_cells_from_circs that didn't go to the cell queue.
  2012. */
  2013. if (q_len_after > q_len_before) {
  2014. num_cells_from_circs -= (q_len_after - q_len_before);
  2015. if (num_cells_from_circs < 0) num_cells_from_circs = 0;
  2016. }
  2017. flushed += num_cells_from_circs;
  2018. /* Now process the queue if necessary */
  2019. if ((q_len_after > q_len_before) &&
  2020. (unlimited || (flushed < num_cells))) {
  2021. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  2022. (unlimited ? -1 : num_cells - flushed));
  2023. }
  2024. }
  2025. }
  2026. }
  2027. done:
  2028. return flushed;
  2029. }
  2030. /**
  2031. * Flush cells from just the channel's outgoing cell queue
  2032. *
  2033. * This gets called from channel_flush_some_cells() above to flush cells
  2034. * just from the queue without trying for active_circuits.
  2035. */
  2036. static ssize_t
  2037. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  2038. ssize_t num_cells)
  2039. {
  2040. unsigned int unlimited = 0;
  2041. ssize_t flushed = 0;
  2042. cell_queue_entry_t *q = NULL;
  2043. size_t cell_size;
  2044. int free_q = 0, handed_off = 0;
  2045. tor_assert(chan);
  2046. tor_assert(chan->write_cell);
  2047. tor_assert(chan->write_packed_cell);
  2048. tor_assert(chan->write_var_cell);
  2049. if (num_cells < 0) unlimited = 1;
  2050. if (!unlimited && num_cells <= flushed) return 0;
  2051. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  2052. if (CHANNEL_IS_OPEN(chan)) {
  2053. while ((unlimited || num_cells > flushed) &&
  2054. NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
  2055. free_q = 0;
  2056. handed_off = 0;
  2057. /* Figure out how big it is for statistical purposes */
  2058. cell_size = channel_get_cell_queue_entry_size(chan, q);
  2059. /*
  2060. * Okay, we have a good queue entry, try to give it to the lower
  2061. * layer.
  2062. */
  2063. switch (q->type) {
  2064. case CELL_QUEUE_FIXED:
  2065. if (q->u.fixed.cell) {
  2066. if (chan->write_cell(chan,
  2067. q->u.fixed.cell)) {
  2068. ++flushed;
  2069. channel_timestamp_xmit(chan);
  2070. ++(chan->n_cells_xmitted);
  2071. chan->n_bytes_xmitted += cell_size;
  2072. free_q = 1;
  2073. handed_off = 1;
  2074. }
  2075. /* Else couldn't write it; leave it on the queue */
  2076. } else {
  2077. /* This shouldn't happen */
  2078. log_info(LD_CHANNEL,
  2079. "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
  2080. "with no cell on channel %p "
  2081. "(global ID " U64_FORMAT ").",
  2082. chan, U64_PRINTF_ARG(chan->global_identifier));
  2083. /* Throw it away */
  2084. free_q = 1;
  2085. handed_off = 0;
  2086. }
  2087. break;
  2088. case CELL_QUEUE_PACKED:
  2089. if (q->u.packed.packed_cell) {
  2090. if (chan->write_packed_cell(chan,
  2091. q->u.packed.packed_cell)) {
  2092. ++flushed;
  2093. channel_timestamp_xmit(chan);
  2094. ++(chan->n_cells_xmitted);
  2095. chan->n_bytes_xmitted += cell_size;
  2096. free_q = 1;
  2097. handed_off = 1;
  2098. }
  2099. /* Else couldn't write it; leave it on the queue */
  2100. } else {
  2101. /* This shouldn't happen */
  2102. log_info(LD_CHANNEL,
  2103. "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
  2104. "with no cell on channel %p "
  2105. "(global ID " U64_FORMAT ").",
  2106. chan, U64_PRINTF_ARG(chan->global_identifier));
  2107. /* Throw it away */
  2108. free_q = 1;
  2109. handed_off = 0;
  2110. }
  2111. break;
  2112. case CELL_QUEUE_VAR:
  2113. if (q->u.var.var_cell) {
  2114. if (chan->write_var_cell(chan,
  2115. q->u.var.var_cell)) {
  2116. ++flushed;
  2117. channel_timestamp_xmit(chan);
  2118. ++(chan->n_cells_xmitted);
  2119. chan->n_bytes_xmitted += cell_size;
  2120. free_q = 1;
  2121. handed_off = 1;
  2122. }
  2123. /* Else couldn't write it; leave it on the queue */
  2124. } else {
  2125. /* This shouldn't happen */
  2126. log_info(LD_CHANNEL,
  2127. "Saw broken cell queue entry of type CELL_QUEUE_VAR "
  2128. "with no cell on channel %p "
  2129. "(global ID " U64_FORMAT ").",
  2130. chan, U64_PRINTF_ARG(chan->global_identifier));
  2131. /* Throw it away */
  2132. free_q = 1;
  2133. handed_off = 0;
  2134. }
  2135. break;
  2136. default:
  2137. /* Unknown type, log and free it */
  2138. log_info(LD_CHANNEL,
  2139. "Saw an unknown cell queue entry type %d on channel %p "
  2140. "(global ID " U64_FORMAT "; ignoring it."
  2141. " Someone should fix this.",
  2142. q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
  2143. free_q = 1;
  2144. handed_off = 0;
  2145. }
  2146. /*
  2147. * if free_q is set, we used it and should remove the queue entry;
  2148. * we have to do the free down here so TOR_SIMPLEQ_REMOVE_HEAD isn't
  2149. * accessing freed memory
  2150. */
  2151. if (free_q) {
  2152. TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
  2153. /*
  2154. * ...and we handed a cell off to the lower layer, so we should
  2155. * update the counters.
  2156. */
  2157. ++n_channel_cells_passed_to_lower_layer;
  2158. --n_channel_cells_in_queues;
  2159. n_channel_bytes_passed_to_lower_layer += cell_size;
  2160. n_channel_bytes_in_queues -= cell_size;
  2161. channel_assert_counter_consistency();
  2162. /* Update the channel's queue size too */
  2163. chan->bytes_in_queue -= cell_size;
  2164. /* Finally, free q */
  2165. cell_queue_entry_free(q, handed_off);
  2166. q = NULL;
  2167. } else {
  2168. /* No cell removed from list, so we can't go on any further */
  2169. break;
  2170. }
  2171. }
  2172. }
  2173. /* Did we drain the queue? */
  2174. if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  2175. channel_timestamp_drained(chan);
  2176. }
  2177. /* Update the estimate queue size */
  2178. channel_update_xmit_queue_size(chan);
  2179. return flushed;
  2180. }
  2181. /**
  2182. * Flush as many cells as we possibly can from the queue
  2183. *
  2184. * This tries to flush as many cells from the queue as the lower layer
  2185. * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
  2186. * in unlimited mode.
  2187. */
  2188. void
  2189. channel_flush_cells(channel_t *chan)
  2190. {
  2191. channel_flush_some_cells_from_outgoing_queue(chan, -1);
  2192. }
  2193. /**
  2194. * Check if any cells are available
  2195. *
  2196. * This gets used from the lower layer to check if any more cells are
  2197. * available.
  2198. */
  2199. MOCK_IMPL(int,
  2200. channel_more_to_flush, (channel_t *chan))
  2201. {
  2202. tor_assert(chan);
  2203. /* Check if we have any queued */
  2204. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2205. return 1;
  2206. /* Check if any circuits would like to queue some */
  2207. if (circuitmux_num_cells(chan->cmux) > 0) return 1;
  2208. /* Else no */
  2209. return 0;
  2210. }
  2211. /**
  2212. * Notify the channel we're done flushing the output in the lower layer
  2213. *
  2214. * Connection.c will call this when we've flushed the output; there's some
  2215. * dirreq-related maintenance to do.
  2216. */
  2217. void
  2218. channel_notify_flushed(channel_t *chan)
  2219. {
  2220. tor_assert(chan);
  2221. if (chan->dirreq_id != 0)
  2222. geoip_change_dirreq_state(chan->dirreq_id,
  2223. DIRREQ_TUNNELED,
  2224. DIRREQ_CHANNEL_BUFFER_FLUSHED);
  2225. }
  2226. /**
  2227. * Process the queue of incoming channels on a listener
  2228. *
  2229. * Use a listener's registered callback to process as many entries in the
  2230. * queue of incoming channels as possible.
  2231. */
  2232. void
  2233. channel_listener_process_incoming(channel_listener_t *listener)
  2234. {
  2235. tor_assert(listener);
  2236. /*
  2237. * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
  2238. * while closing a listener.
  2239. */
  2240. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
  2241. listener->state == CHANNEL_LISTENER_STATE_CLOSING);
  2242. tor_assert(listener->listener);
  2243. log_debug(LD_CHANNEL,
  2244. "Processing queue of incoming connections for channel "
  2245. "listener %p (global ID " U64_FORMAT ")",
  2246. listener, U64_PRINTF_ARG(listener->global_identifier));
  2247. if (!(listener->incoming_list)) return;
  2248. SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
  2249. channel_t *, chan) {
  2250. tor_assert(chan);
  2251. log_debug(LD_CHANNEL,
  2252. "Handling incoming channel %p (" U64_FORMAT ") "
  2253. "for listener %p (" U64_FORMAT ")",
  2254. chan,
  2255. U64_PRINTF_ARG(chan->global_identifier),
  2256. listener,
  2257. U64_PRINTF_ARG(listener->global_identifier));
  2258. /* Make sure this is set correctly */
  2259. channel_mark_incoming(chan);
  2260. listener->listener(listener, chan);
  2261. } SMARTLIST_FOREACH_END(chan);
  2262. smartlist_free(listener->incoming_list);
  2263. listener->incoming_list = NULL;
  2264. }
  2265. /**
  2266. * Take actions required when a channel becomes open
  2267. *
  2268. * Handle actions we should do when we know a channel is open; a lot of
  2269. * this comes from the old connection_or_set_state_open() of connection_or.c.
  2270. *
  2271. * Because of this mechanism, future channel_t subclasses should take care
  2272. * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
  2273. * until there is positive confirmation that the network is operational.
  2274. * In particular, anything UDP-based should not make this transition until a
  2275. * packet is received from the other side.
  2276. */
  2277. void
  2278. channel_do_open_actions(channel_t *chan)
  2279. {
  2280. tor_addr_t remote_addr;
  2281. int started_here;
  2282. time_t now = time(NULL);
  2283. int close_origin_circuits = 0;
  2284. tor_assert(chan);
  2285. started_here = channel_is_outgoing(chan);
  2286. if (started_here) {
  2287. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2288. rep_hist_note_connect_succeeded(chan->identity_digest, now);
  2289. router_set_status(chan->identity_digest, 1);
  2290. } else {
  2291. /* only report it to the geoip module if it's not a known router */
  2292. if (!router_get_by_id_digest(chan->identity_digest)) {
  2293. if (channel_get_addr_if_possible(chan, &remote_addr)) {
  2294. char *transport_name = NULL;
  2295. if (chan->get_transport_name(chan, &transport_name) < 0)
  2296. transport_name = NULL;
  2297. geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
  2298. &remote_addr, transport_name,
  2299. now);
  2300. tor_free(transport_name);
  2301. }
  2302. /* Otherwise the underlying transport can't tell us this, so skip it */
  2303. }
  2304. }
  2305. /* Disable or reduce padding according to user prefs. */
  2306. if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
  2307. if (!get_options()->ConnectionPadding) {
  2308. /* Disable if torrc disabled */
  2309. channelpadding_disable_padding_on_channel(chan);
  2310. } else if (get_options()->Tor2webMode &&
  2311. !networkstatus_get_param(NULL,
  2312. CHANNELPADDING_TOR2WEB_PARAM,
  2313. CHANNELPADDING_TOR2WEB_DEFAULT, 0, 1)) {
  2314. /* Disable if we're using tor2web and the consensus disabled padding
  2315. * for tor2web */
  2316. channelpadding_disable_padding_on_channel(chan);
  2317. } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
  2318. !networkstatus_get_param(NULL,
  2319. CHANNELPADDING_SOS_PARAM,
  2320. CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
  2321. /* Disable if we're using RSOS and the consensus disabled padding
  2322. * for RSOS*/
  2323. channelpadding_disable_padding_on_channel(chan);
  2324. } else if (get_options()->ReducedConnectionPadding) {
  2325. /* Padding can be forced and/or reduced by clients, regardless of if
  2326. * the channel supports it */
  2327. channelpadding_reduce_padding_on_channel(chan);
  2328. }
  2329. }
  2330. circuit_n_chan_done(chan, 1, close_origin_circuits);
  2331. }
  2332. /**
  2333. * Queue an incoming channel on a listener
  2334. *
  2335. * Internal and subclass use only function to queue an incoming channel from
  2336. * a listener. A subclass of channel_listener_t should call this when a new
  2337. * incoming channel is created.
  2338. */
  2339. void
  2340. channel_listener_queue_incoming(channel_listener_t *listener,
  2341. channel_t *incoming)
  2342. {
  2343. int need_to_queue = 0;
  2344. tor_assert(listener);
  2345. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  2346. tor_assert(incoming);
  2347. log_debug(LD_CHANNEL,
  2348. "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
  2349. "channel listener %p (global ID " U64_FORMAT ")",
  2350. incoming, U64_PRINTF_ARG(incoming->global_identifier),
  2351. listener, U64_PRINTF_ARG(listener->global_identifier));
  2352. /* Do we need to queue it, or can we just call the listener right away? */
  2353. if (!(listener->listener)) need_to_queue = 1;
  2354. if (listener->incoming_list &&
  2355. (smartlist_len(listener->incoming_list) > 0))
  2356. need_to_queue = 1;
  2357. /* If we need to queue and have no queue, create one */
  2358. if (need_to_queue && !(listener->incoming_list)) {
  2359. listener->incoming_list = smartlist_new();
  2360. }
  2361. /* Bump the counter and timestamp it */
  2362. channel_listener_timestamp_active(listener);
  2363. channel_listener_timestamp_accepted(listener);
  2364. ++(listener->n_accepted);
  2365. /* If we don't need to queue, process it right away */
  2366. if (!need_to_queue) {
  2367. tor_assert(listener->listener);
  2368. listener->listener(listener, incoming);
  2369. }
  2370. /*
  2371. * Otherwise, we need to queue; queue and then process the queue if
  2372. * we can.
  2373. */
  2374. else {
  2375. tor_assert(listener->incoming_list);
  2376. smartlist_add(listener->incoming_list, incoming);
  2377. if (listener->listener) channel_listener_process_incoming(listener);
  2378. }
  2379. }
  2380. /**
  2381. * Process queued incoming cells
  2382. *
  2383. * Process as many queued cells as we can from the incoming
  2384. * cell queue.
  2385. */
  2386. void
  2387. channel_process_cells(channel_t *chan)
  2388. {
  2389. cell_queue_entry_t *q;
  2390. tor_assert(chan);
  2391. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  2392. CHANNEL_IS_OPEN(chan));
  2393. log_debug(LD_CHANNEL,
  2394. "Processing as many incoming cells as we can for channel %p",
  2395. chan);
  2396. /* Nothing we can do if we have no registered cell handlers */
  2397. if (!(chan->cell_handler ||
  2398. chan->var_cell_handler)) return;
  2399. /* Nothing we can do if we have no cells */
  2400. if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
  2401. /*
  2402. * Process cells until we're done or find one we have no current handler
  2403. * for.
  2404. *
  2405. * We must free the cells here after calling the handler, since custody
  2406. * of the buffer was given to the channel layer when they were queued;
  2407. * see comments on memory management in channel_queue_cell() and in
  2408. * channel_queue_var_cell() below.
  2409. */
  2410. while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
  2411. tor_assert(q);
  2412. tor_assert(q->type == CELL_QUEUE_FIXED ||
  2413. q->type == CELL_QUEUE_VAR);
  2414. if (q->type == CELL_QUEUE_FIXED &&
  2415. chan->cell_handler) {
  2416. /* Handle a fixed-length cell */
  2417. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2418. tor_assert(q->u.fixed.cell);
  2419. log_debug(LD_CHANNEL,
  2420. "Processing incoming cell_t %p for channel %p (global ID "
  2421. U64_FORMAT ")",
  2422. q->u.fixed.cell, chan,
  2423. U64_PRINTF_ARG(chan->global_identifier));
  2424. chan->cell_handler(chan, q->u.fixed.cell);
  2425. tor_free(q->u.fixed.cell);
  2426. tor_free(q);
  2427. } else if (q->type == CELL_QUEUE_VAR &&
  2428. chan->var_cell_handler) {
  2429. /* Handle a variable-length cell */
  2430. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2431. tor_assert(q->u.var.var_cell);
  2432. log_debug(LD_CHANNEL,
  2433. "Processing incoming var_cell_t %p for channel %p (global ID "
  2434. U64_FORMAT ")",
  2435. q->u.var.var_cell, chan,
  2436. U64_PRINTF_ARG(chan->global_identifier));
  2437. chan->var_cell_handler(chan, q->u.var.var_cell);
  2438. tor_free(q->u.var.var_cell);
  2439. tor_free(q);
  2440. } else {
  2441. /* Can't handle this one */
  2442. break;
  2443. }
  2444. }
  2445. }
  2446. /**
  2447. * Queue incoming cell
  2448. *
  2449. * This should be called by a channel_t subclass to queue an incoming fixed-
  2450. * length cell for processing, and process it if possible.
  2451. */
  2452. void
  2453. channel_queue_cell(channel_t *chan, cell_t *cell)
  2454. {
  2455. int need_to_queue = 0;
  2456. cell_queue_entry_t *q;
  2457. cell_t *cell_copy = NULL;
  2458. tor_assert(chan);
  2459. tor_assert(cell);
  2460. tor_assert(CHANNEL_IS_OPEN(chan));
  2461. /* Do we need to queue it, or can we just call the handler right away? */
  2462. if (!(chan->cell_handler)) need_to_queue = 1;
  2463. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2464. need_to_queue = 1;
  2465. /* Timestamp for receiving */
  2466. channel_timestamp_recv(chan);
  2467. /* Update the counters */
  2468. ++(chan->n_cells_recved);
  2469. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  2470. /* If we don't need to queue we can just call cell_handler */
  2471. if (!need_to_queue) {
  2472. tor_assert(chan->cell_handler);
  2473. log_debug(LD_CHANNEL,
  2474. "Directly handling incoming cell_t %p for channel %p "
  2475. "(global ID " U64_FORMAT ")",
  2476. cell, chan,
  2477. U64_PRINTF_ARG(chan->global_identifier));
  2478. chan->cell_handler(chan, cell);
  2479. } else {
  2480. /*
  2481. * Otherwise queue it and then process the queue if possible.
  2482. *
  2483. * We queue a copy, not the original pointer - it might have been on the
  2484. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2485. * if we ever have a subclass other than channel_tls_t), or be freed
  2486. * there after we return. This is the uncommon case; the non-copying
  2487. * fast path occurs in the if (!need_to_queue) case above when the
  2488. * upper layer has installed cell handlers.
  2489. */
  2490. cell_copy = tor_malloc_zero(sizeof(cell_t));
  2491. memcpy(cell_copy, cell, sizeof(cell_t));
  2492. q = cell_queue_entry_new_fixed(cell_copy);
  2493. log_debug(LD_CHANNEL,
  2494. "Queueing incoming cell_t %p for channel %p "
  2495. "(global ID " U64_FORMAT ")",
  2496. cell, chan,
  2497. U64_PRINTF_ARG(chan->global_identifier));
  2498. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2499. if (chan->cell_handler ||
  2500. chan->var_cell_handler) {
  2501. channel_process_cells(chan);
  2502. }
  2503. }
  2504. }
  2505. /**
  2506. * Queue incoming variable-length cell
  2507. *
  2508. * This should be called by a channel_t subclass to queue an incoming
  2509. * variable-length cell for processing, and process it if possible.
  2510. */
  2511. void
  2512. channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
  2513. {
  2514. int need_to_queue = 0;
  2515. cell_queue_entry_t *q;
  2516. var_cell_t *cell_copy = NULL;
  2517. tor_assert(chan);
  2518. tor_assert(var_cell);
  2519. tor_assert(CHANNEL_IS_OPEN(chan));
  2520. /* Do we need to queue it, or can we just call the handler right away? */
  2521. if (!(chan->var_cell_handler)) need_to_queue = 1;
  2522. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2523. need_to_queue = 1;
  2524. /* Timestamp for receiving */
  2525. channel_timestamp_recv(chan);
  2526. /* Update the counter */
  2527. ++(chan->n_cells_recved);
  2528. chan->n_bytes_recved += get_var_cell_header_size(chan->wide_circ_ids) +
  2529. var_cell->payload_len;
  2530. /* If we don't need to queue we can just call cell_handler */
  2531. if (!need_to_queue) {
  2532. tor_assert(chan->var_cell_handler);
  2533. log_debug(LD_CHANNEL,
  2534. "Directly handling incoming var_cell_t %p for channel %p "
  2535. "(global ID " U64_FORMAT ")",
  2536. var_cell, chan,
  2537. U64_PRINTF_ARG(chan->global_identifier));
  2538. chan->var_cell_handler(chan, var_cell);
  2539. } else {
  2540. /*
  2541. * Otherwise queue it and then process the queue if possible.
  2542. *
  2543. * We queue a copy, not the original pointer - it might have been on the
  2544. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2545. * if we ever have a subclass other than channel_tls_t), or be freed
  2546. * there after we return. This is the uncommon case; the non-copying
  2547. * fast path occurs in the if (!need_to_queue) case above when the
  2548. * upper layer has installed cell handlers.
  2549. */
  2550. cell_copy = var_cell_copy(var_cell);
  2551. q = cell_queue_entry_new_var(cell_copy);
  2552. log_debug(LD_CHANNEL,
  2553. "Queueing incoming var_cell_t %p for channel %p "
  2554. "(global ID " U64_FORMAT ")",
  2555. var_cell, chan,
  2556. U64_PRINTF_ARG(chan->global_identifier));
  2557. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2558. if (chan->cell_handler ||
  2559. chan->var_cell_handler) {
  2560. channel_process_cells(chan);
  2561. }
  2562. }
  2563. }
  2564. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  2565. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  2566. * false. */
  2567. /* XXXX Move this function. */
  2568. int
  2569. packed_cell_is_destroy(channel_t *chan,
  2570. const packed_cell_t *packed_cell,
  2571. circid_t *circid_out)
  2572. {
  2573. if (chan->wide_circ_ids) {
  2574. if (packed_cell->body[4] == CELL_DESTROY) {
  2575. *circid_out = ntohl(get_uint32(packed_cell->body));
  2576. return 1;
  2577. }
  2578. } else {
  2579. if (packed_cell->body[2] == CELL_DESTROY) {
  2580. *circid_out = ntohs(get_uint16(packed_cell->body));
  2581. return 1;
  2582. }
  2583. }
  2584. return 0;
  2585. }
  2586. /**
  2587. * Assert that the global channel stats counters are internally consistent
  2588. */
  2589. static void
  2590. channel_assert_counter_consistency(void)
  2591. {
  2592. tor_assert(n_channel_cells_queued ==
  2593. (n_channel_cells_in_queues + n_channel_cells_passed_to_lower_layer));
  2594. tor_assert(n_channel_bytes_queued ==
  2595. (n_channel_bytes_in_queues + n_channel_bytes_passed_to_lower_layer));
  2596. }
  2597. /* DOCDOC */
  2598. static int
  2599. is_destroy_cell(channel_t *chan,
  2600. const cell_queue_entry_t *q, circid_t *circid_out)
  2601. {
  2602. *circid_out = 0;
  2603. switch (q->type) {
  2604. case CELL_QUEUE_FIXED:
  2605. if (q->u.fixed.cell->command == CELL_DESTROY) {
  2606. *circid_out = q->u.fixed.cell->circ_id;
  2607. return 1;
  2608. }
  2609. break;
  2610. case CELL_QUEUE_VAR:
  2611. if (q->u.var.var_cell->command == CELL_DESTROY) {
  2612. *circid_out = q->u.var.var_cell->circ_id;
  2613. return 1;
  2614. }
  2615. break;
  2616. case CELL_QUEUE_PACKED:
  2617. return packed_cell_is_destroy(chan, q->u.packed.packed_cell, circid_out);
  2618. }
  2619. return 0;
  2620. }
  2621. /**
  2622. * Send destroy cell on a channel
  2623. *
  2624. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  2625. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  2626. * we may want to propagate reasons from other cells.
  2627. */
  2628. int
  2629. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  2630. {
  2631. tor_assert(chan);
  2632. if (circ_id == 0) {
  2633. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  2634. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2635. U64_PRINTF_ARG(chan->global_identifier),
  2636. chan, channel_state_to_string(chan->state),
  2637. chan->state);
  2638. return 0;
  2639. }
  2640. /* Check to make sure we can send on this channel first */
  2641. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  2642. channel_note_destroy_pending(chan, circ_id);
  2643. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  2644. log_debug(LD_OR,
  2645. "Sending destroy (circID %u) on channel %p "
  2646. "(global ID " U64_FORMAT ")",
  2647. (unsigned)circ_id, chan,
  2648. U64_PRINTF_ARG(chan->global_identifier));
  2649. } else {
  2650. log_warn(LD_BUG,
  2651. "Someone called channel_send_destroy() for circID %u "
  2652. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2653. (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
  2654. chan, channel_state_to_string(chan->state),
  2655. chan->state);
  2656. }
  2657. return 0;
  2658. }
  2659. /**
  2660. * Dump channel statistics to the log
  2661. *
  2662. * This is called from dumpstats() in main.c and spams the log with
  2663. * statistics on channels.
  2664. */
  2665. void
  2666. channel_dumpstats(int severity)
  2667. {
  2668. if (all_channels && smartlist_len(all_channels) > 0) {
  2669. tor_log(severity, LD_GENERAL,
  2670. "Channels have queued " U64_FORMAT " bytes in " U64_FORMAT " cells, "
  2671. "and handed " U64_FORMAT " bytes in " U64_FORMAT " cells to the lower"
  2672. " layer.",
  2673. U64_PRINTF_ARG(n_channel_bytes_queued),
  2674. U64_PRINTF_ARG(n_channel_cells_queued),
  2675. U64_PRINTF_ARG(n_channel_bytes_passed_to_lower_layer),
  2676. U64_PRINTF_ARG(n_channel_cells_passed_to_lower_layer));
  2677. tor_log(severity, LD_GENERAL,
  2678. "There are currently " U64_FORMAT " bytes in " U64_FORMAT " cells "
  2679. "in channel queues.",
  2680. U64_PRINTF_ARG(n_channel_bytes_in_queues),
  2681. U64_PRINTF_ARG(n_channel_cells_in_queues));
  2682. tor_log(severity, LD_GENERAL,
  2683. "Dumping statistics about %d channels:",
  2684. smartlist_len(all_channels));
  2685. tor_log(severity, LD_GENERAL,
  2686. "%d are active, and %d are done and waiting for cleanup",
  2687. (active_channels != NULL) ?
  2688. smartlist_len(active_channels) : 0,
  2689. (finished_channels != NULL) ?
  2690. smartlist_len(finished_channels) : 0);
  2691. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  2692. channel_dump_statistics(chan, severity));
  2693. tor_log(severity, LD_GENERAL,
  2694. "Done spamming about channels now");
  2695. } else {
  2696. tor_log(severity, LD_GENERAL,
  2697. "No channels to dump");
  2698. }
  2699. }
  2700. /**
  2701. * Dump channel listener statistics to the log
  2702. *
  2703. * This is called from dumpstats() in main.c and spams the log with
  2704. * statistics on channel listeners.
  2705. */
  2706. void
  2707. channel_listener_dumpstats(int severity)
  2708. {
  2709. if (all_listeners && smartlist_len(all_listeners) > 0) {
  2710. tor_log(severity, LD_GENERAL,
  2711. "Dumping statistics about %d channel listeners:",
  2712. smartlist_len(all_listeners));
  2713. tor_log(severity, LD_GENERAL,
  2714. "%d are active and %d are done and waiting for cleanup",
  2715. (active_listeners != NULL) ?
  2716. smartlist_len(active_listeners) : 0,
  2717. (finished_listeners != NULL) ?
  2718. smartlist_len(finished_listeners) : 0);
  2719. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  2720. channel_listener_dump_statistics(chan_l, severity));
  2721. tor_log(severity, LD_GENERAL,
  2722. "Done spamming about channel listeners now");
  2723. } else {
  2724. tor_log(severity, LD_GENERAL,
  2725. "No channel listeners to dump");
  2726. }
  2727. }
  2728. /**
  2729. * Set the cmux policy on all active channels
  2730. */
  2731. void
  2732. channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
  2733. {
  2734. if (!active_channels) return;
  2735. SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
  2736. if (curr->cmux) {
  2737. circuitmux_set_policy(curr->cmux, pol);
  2738. }
  2739. } SMARTLIST_FOREACH_END(curr);
  2740. }
  2741. /**
  2742. * Clean up channels
  2743. *
  2744. * This gets called periodically from run_scheduled_events() in main.c;
  2745. * it cleans up after closed channels.
  2746. */
  2747. void
  2748. channel_run_cleanup(void)
  2749. {
  2750. channel_t *tmp = NULL;
  2751. /* Check if we need to do anything */
  2752. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  2753. /* Iterate through finished_channels and get rid of them */
  2754. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  2755. tmp = curr;
  2756. /* Remove it from the list */
  2757. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  2758. /* Also unregister it */
  2759. channel_unregister(tmp);
  2760. /* ... and free it */
  2761. channel_free(tmp);
  2762. } SMARTLIST_FOREACH_END(curr);
  2763. }
  2764. /**
  2765. * Clean up channel listeners
  2766. *
  2767. * This gets called periodically from run_scheduled_events() in main.c;
  2768. * it cleans up after closed channel listeners.
  2769. */
  2770. void
  2771. channel_listener_run_cleanup(void)
  2772. {
  2773. channel_listener_t *tmp = NULL;
  2774. /* Check if we need to do anything */
  2775. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  2776. /* Iterate through finished_channels and get rid of them */
  2777. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  2778. tmp = curr;
  2779. /* Remove it from the list */
  2780. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  2781. /* Also unregister it */
  2782. channel_listener_unregister(tmp);
  2783. /* ... and free it */
  2784. channel_listener_free(tmp);
  2785. } SMARTLIST_FOREACH_END(curr);
  2786. }
  2787. /**
  2788. * Free a list of channels for channel_free_all()
  2789. */
  2790. static void
  2791. channel_free_list(smartlist_t *channels, int mark_for_close)
  2792. {
  2793. if (!channels) return;
  2794. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  2795. /* Deregister and free it */
  2796. tor_assert(curr);
  2797. log_debug(LD_CHANNEL,
  2798. "Cleaning up channel %p (global ID " U64_FORMAT ") "
  2799. "in state %s (%d)",
  2800. curr, U64_PRINTF_ARG(curr->global_identifier),
  2801. channel_state_to_string(curr->state), curr->state);
  2802. /* Detach circuits early so they can find the channel */
  2803. if (curr->cmux) {
  2804. circuitmux_detach_all_circuits(curr->cmux, NULL);
  2805. }
  2806. SMARTLIST_DEL_CURRENT(channels, curr);
  2807. channel_unregister(curr);
  2808. if (mark_for_close) {
  2809. if (!CHANNEL_CONDEMNED(curr)) {
  2810. channel_mark_for_close(curr);
  2811. }
  2812. channel_force_free(curr);
  2813. } else channel_free(curr);
  2814. } SMARTLIST_FOREACH_END(curr);
  2815. }
  2816. /**
  2817. * Free a list of channel listeners for channel_free_all()
  2818. */
  2819. static void
  2820. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  2821. {
  2822. if (!listeners) return;
  2823. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  2824. /* Deregister and free it */
  2825. tor_assert(curr);
  2826. log_debug(LD_CHANNEL,
  2827. "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
  2828. "in state %s (%d)",
  2829. curr, U64_PRINTF_ARG(curr->global_identifier),
  2830. channel_listener_state_to_string(curr->state), curr->state);
  2831. channel_listener_unregister(curr);
  2832. if (mark_for_close) {
  2833. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  2834. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  2835. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  2836. channel_listener_mark_for_close(curr);
  2837. }
  2838. channel_listener_force_free(curr);
  2839. } else channel_listener_free(curr);
  2840. } SMARTLIST_FOREACH_END(curr);
  2841. }
  2842. /**
  2843. * Close all channels and free everything
  2844. *
  2845. * This gets called from tor_free_all() in main.c to clean up on exit.
  2846. * It will close all registered channels and free associated storage,
  2847. * then free the all_channels, active_channels, listening_channels and
  2848. * finished_channels lists and also channel_identity_map.
  2849. */
  2850. void
  2851. channel_free_all(void)
  2852. {
  2853. log_debug(LD_CHANNEL,
  2854. "Shutting down channels...");
  2855. /* First, let's go for finished channels */
  2856. if (finished_channels) {
  2857. channel_free_list(finished_channels, 0);
  2858. smartlist_free(finished_channels);
  2859. finished_channels = NULL;
  2860. }
  2861. /* Now the finished listeners */
  2862. if (finished_listeners) {
  2863. channel_listener_free_list(finished_listeners, 0);
  2864. smartlist_free(finished_listeners);
  2865. finished_listeners = NULL;
  2866. }
  2867. /* Now all active channels */
  2868. if (active_channels) {
  2869. channel_free_list(active_channels, 1);
  2870. smartlist_free(active_channels);
  2871. active_channels = NULL;
  2872. }
  2873. /* Now all active listeners */
  2874. if (active_listeners) {
  2875. channel_listener_free_list(active_listeners, 1);
  2876. smartlist_free(active_listeners);
  2877. active_listeners = NULL;
  2878. }
  2879. /* Now all channels, in case any are left over */
  2880. if (all_channels) {
  2881. channel_free_list(all_channels, 1);
  2882. smartlist_free(all_channels);
  2883. all_channels = NULL;
  2884. }
  2885. /* Now all listeners, in case any are left over */
  2886. if (all_listeners) {
  2887. channel_listener_free_list(all_listeners, 1);
  2888. smartlist_free(all_listeners);
  2889. all_listeners = NULL;
  2890. }
  2891. /* Now free channel_identity_map */
  2892. log_debug(LD_CHANNEL,
  2893. "Freeing channel_identity_map");
  2894. /* Geez, anything still left over just won't die ... let it leak then */
  2895. HT_CLEAR(channel_idmap, &channel_identity_map);
  2896. /* Same with channel_gid_map */
  2897. log_debug(LD_CHANNEL,
  2898. "Freeing channel_gid_map");
  2899. HT_CLEAR(channel_gid_map, &channel_gid_map);
  2900. log_debug(LD_CHANNEL,
  2901. "Done cleaning up after channels");
  2902. }
  2903. /**
  2904. * Connect to a given addr/port/digest
  2905. *
  2906. * This sets up a new outgoing channel; in the future if multiple
  2907. * channel_t subclasses are available, this is where the selection policy
  2908. * should go. It may also be desirable to fold port into tor_addr_t
  2909. * or make a new type including a tor_addr_t and port, so we have a
  2910. * single abstract object encapsulating all the protocol details of
  2911. * how to contact an OR.
  2912. */
  2913. channel_t *
  2914. channel_connect(const tor_addr_t *addr, uint16_t port,
  2915. const char *id_digest,
  2916. const ed25519_public_key_t *ed_id)
  2917. {
  2918. return channel_tls_connect(addr, port, id_digest, ed_id);
  2919. }
  2920. /**
  2921. * Decide which of two channels to prefer for extending a circuit
  2922. *
  2923. * This function is called while extending a circuit and returns true iff
  2924. * a is 'better' than b. The most important criterion here is that a
  2925. * canonical channel is always better than a non-canonical one, but the
  2926. * number of circuits and the age are used as tie-breakers.
  2927. *
  2928. * This is based on the former connection_or_is_better() of connection_or.c
  2929. */
  2930. int
  2931. channel_is_better(channel_t *a, channel_t *b)
  2932. {
  2933. int a_is_canonical, b_is_canonical;
  2934. tor_assert(a);
  2935. tor_assert(b);
  2936. /* If one channel is bad for new circuits, and the other isn't,
  2937. * use the one that is still good. */
  2938. if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
  2939. return 1;
  2940. if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
  2941. return 0;
  2942. /* Check if one is canonical and the other isn't first */
  2943. a_is_canonical = channel_is_canonical(a);
  2944. b_is_canonical = channel_is_canonical(b);
  2945. if (a_is_canonical && !b_is_canonical) return 1;
  2946. if (!a_is_canonical && b_is_canonical) return 0;
  2947. /* Check if we suspect that one of the channels will be preferred
  2948. * by the peer */
  2949. if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
  2950. if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
  2951. /*
  2952. * Okay, if we're here they tied on canonicity, the prefer the older
  2953. * connection, so that the adversary can't create a new connection
  2954. * and try to switch us over to it (which will leak information
  2955. * about long-lived circuits). Additionally, switching connections
  2956. * too often makes us more vulnerable to attacks like Torscan and
  2957. * passive netflow-based equivalents.
  2958. *
  2959. * Connections will still only live for at most a week, due to
  2960. * the check in connection_or_group_set_badness() against
  2961. * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
  2962. * unusable for new circuits after 1 week. That check sets
  2963. * is_bad_for_new_circs, which is checked in channel_get_for_extend().
  2964. *
  2965. * We check channel_is_bad_for_new_circs() above here anyway, for safety.
  2966. */
  2967. if (channel_when_created(a) < channel_when_created(b)) return 1;
  2968. else if (channel_when_created(a) > channel_when_created(b)) return 0;
  2969. if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
  2970. else return 0;
  2971. }
  2972. /**
  2973. * Get a channel to extend a circuit
  2974. *
  2975. * Pick a suitable channel to extend a circuit to given the desired digest
  2976. * the address we believe is correct for that digest; this tries to see
  2977. * if we already have one for the requested endpoint, but if there is no good
  2978. * channel, set *msg_out to a message describing the channel's state
  2979. * and our next action, and set *launch_out to a boolean indicated whether
  2980. * the caller should try to launch a new channel with channel_connect().
  2981. */
  2982. channel_t *
  2983. channel_get_for_extend(const char *rsa_id_digest,
  2984. const ed25519_public_key_t *ed_id,
  2985. const tor_addr_t *target_addr,
  2986. const char **msg_out,
  2987. int *launch_out)
  2988. {
  2989. channel_t *chan, *best = NULL;
  2990. int n_inprogress_goodaddr = 0, n_old = 0;
  2991. int n_noncanonical = 0, n_possible = 0;
  2992. tor_assert(msg_out);
  2993. tor_assert(launch_out);
  2994. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2995. /* Walk the list, unrefing the old one and refing the new at each
  2996. * iteration.
  2997. */
  2998. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2999. tor_assert(tor_memeq(chan->identity_digest,
  3000. rsa_id_digest, DIGEST_LEN));
  3001. if (CHANNEL_CONDEMNED(chan))
  3002. continue;
  3003. /* Never return a channel on which the other end appears to be
  3004. * a client. */
  3005. if (channel_is_client(chan)) {
  3006. continue;
  3007. }
  3008. /* The Ed25519 key has to match too */
  3009. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  3010. continue;
  3011. }
  3012. /* Never return a non-open connection. */
  3013. if (!CHANNEL_IS_OPEN(chan)) {
  3014. /* If the address matches, don't launch a new connection for this
  3015. * circuit. */
  3016. if (channel_matches_target_addr_for_extend(chan, target_addr))
  3017. ++n_inprogress_goodaddr;
  3018. continue;
  3019. }
  3020. /* Never return a connection that shouldn't be used for circs. */
  3021. if (channel_is_bad_for_new_circs(chan)) {
  3022. ++n_old;
  3023. continue;
  3024. }
  3025. /* Never return a non-canonical connection using a recent link protocol
  3026. * if the address is not what we wanted.
  3027. *
  3028. * The channel_is_canonical_is_reliable() function asks the lower layer
  3029. * if we should trust channel_is_canonical(). The below is from the
  3030. * comments of the old circuit_or_get_for_extend() and applies when
  3031. * the lower-layer transport is channel_tls_t.
  3032. *
  3033. * (For old link protocols, we can't rely on is_canonical getting
  3034. * set properly if we're talking to the right address, since we might
  3035. * have an out-of-date descriptor, and we will get no NETINFO cell to
  3036. * tell us about the right address.)
  3037. */
  3038. if (!channel_is_canonical(chan) &&
  3039. channel_is_canonical_is_reliable(chan) &&
  3040. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  3041. ++n_noncanonical;
  3042. continue;
  3043. }
  3044. ++n_possible;
  3045. if (!best) {
  3046. best = chan; /* If we have no 'best' so far, this one is good enough. */
  3047. continue;
  3048. }
  3049. if (channel_is_better(chan, best))
  3050. best = chan;
  3051. }
  3052. if (best) {
  3053. *msg_out = "Connection is fine; using it.";
  3054. *launch_out = 0;
  3055. return best;
  3056. } else if (n_inprogress_goodaddr) {
  3057. *msg_out = "Connection in progress; waiting.";
  3058. *launch_out = 0;
  3059. return NULL;
  3060. } else if (n_old || n_noncanonical) {
  3061. *msg_out = "Connections all too old, or too non-canonical. "
  3062. " Launching a new one.";
  3063. *launch_out = 1;
  3064. return NULL;
  3065. } else {
  3066. *msg_out = "Not connected. Connecting.";
  3067. *launch_out = 1;
  3068. return NULL;
  3069. }
  3070. }
  3071. /**
  3072. * Describe the transport subclass for a channel
  3073. *
  3074. * Invoke a method to get a string description of the lower-layer
  3075. * transport for this channel.
  3076. */
  3077. const char *
  3078. channel_describe_transport(channel_t *chan)
  3079. {
  3080. tor_assert(chan);
  3081. tor_assert(chan->describe_transport);
  3082. return chan->describe_transport(chan);
  3083. }
  3084. /**
  3085. * Describe the transport subclass for a channel listener
  3086. *
  3087. * Invoke a method to get a string description of the lower-layer
  3088. * transport for this channel listener.
  3089. */
  3090. const char *
  3091. channel_listener_describe_transport(channel_listener_t *chan_l)
  3092. {
  3093. tor_assert(chan_l);
  3094. tor_assert(chan_l->describe_transport);
  3095. return chan_l->describe_transport(chan_l);
  3096. }
  3097. /**
  3098. * Return the number of entries in <b>queue</b>
  3099. */
  3100. STATIC int
  3101. chan_cell_queue_len(const chan_cell_queue_t *queue)
  3102. {
  3103. int r = 0;
  3104. cell_queue_entry_t *cell;
  3105. TOR_SIMPLEQ_FOREACH(cell, queue, next)
  3106. ++r;
  3107. return r;
  3108. }
  3109. /**
  3110. * Dump channel statistics
  3111. *
  3112. * Dump statistics for one channel to the log
  3113. */
  3114. MOCK_IMPL(void,
  3115. channel_dump_statistics, (channel_t *chan, int severity))
  3116. {
  3117. double avg, interval, age;
  3118. time_t now = time(NULL);
  3119. tor_addr_t remote_addr;
  3120. int have_remote_addr;
  3121. char *remote_addr_str;
  3122. tor_assert(chan);
  3123. age = (double)(now - chan->timestamp_created);
  3124. tor_log(severity, LD_GENERAL,
  3125. "Channel " U64_FORMAT " (at %p) with transport %s is in state "
  3126. "%s (%d)",
  3127. U64_PRINTF_ARG(chan->global_identifier), chan,
  3128. channel_describe_transport(chan),
  3129. channel_state_to_string(chan->state), chan->state);
  3130. tor_log(severity, LD_GENERAL,
  3131. " * Channel " U64_FORMAT " was created at " U64_FORMAT
  3132. " (" U64_FORMAT " seconds ago) "
  3133. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3134. U64_PRINTF_ARG(chan->global_identifier),
  3135. U64_PRINTF_ARG(chan->timestamp_created),
  3136. U64_PRINTF_ARG(now - chan->timestamp_created),
  3137. U64_PRINTF_ARG(chan->timestamp_active),
  3138. U64_PRINTF_ARG(now - chan->timestamp_active));
  3139. /* Handle digest and nickname */
  3140. if (!tor_digest_is_zero(chan->identity_digest)) {
  3141. if (chan->nickname) {
  3142. tor_log(severity, LD_GENERAL,
  3143. " * Channel " U64_FORMAT " says it is connected "
  3144. "to an OR with digest %s and nickname %s",
  3145. U64_PRINTF_ARG(chan->global_identifier),
  3146. hex_str(chan->identity_digest, DIGEST_LEN),
  3147. chan->nickname);
  3148. } else {
  3149. tor_log(severity, LD_GENERAL,
  3150. " * Channel " U64_FORMAT " says it is connected "
  3151. "to an OR with digest %s and no known nickname",
  3152. U64_PRINTF_ARG(chan->global_identifier),
  3153. hex_str(chan->identity_digest, DIGEST_LEN));
  3154. }
  3155. } else {
  3156. if (chan->nickname) {
  3157. tor_log(severity, LD_GENERAL,
  3158. " * Channel " U64_FORMAT " does not know the digest"
  3159. " of the OR it is connected to, but reports its nickname is %s",
  3160. U64_PRINTF_ARG(chan->global_identifier),
  3161. chan->nickname);
  3162. } else {
  3163. tor_log(severity, LD_GENERAL,
  3164. " * Channel " U64_FORMAT " does not know the digest"
  3165. " or the nickname of the OR it is connected to",
  3166. U64_PRINTF_ARG(chan->global_identifier));
  3167. }
  3168. }
  3169. /* Handle remote address and descriptions */
  3170. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  3171. if (have_remote_addr) {
  3172. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3173. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  3174. tor_log(severity, LD_GENERAL,
  3175. " * Channel " U64_FORMAT " says its remote address"
  3176. " is %s, and gives a canonical description of \"%s\" and an "
  3177. "actual description of \"%s\"",
  3178. U64_PRINTF_ARG(chan->global_identifier),
  3179. safe_str(remote_addr_str),
  3180. safe_str(channel_get_canonical_remote_descr(chan)),
  3181. safe_str(actual));
  3182. tor_free(remote_addr_str);
  3183. tor_free(actual);
  3184. } else {
  3185. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3186. tor_log(severity, LD_GENERAL,
  3187. " * Channel " U64_FORMAT " does not know its remote "
  3188. "address, but gives a canonical description of \"%s\" and an "
  3189. "actual description of \"%s\"",
  3190. U64_PRINTF_ARG(chan->global_identifier),
  3191. channel_get_canonical_remote_descr(chan),
  3192. actual);
  3193. tor_free(actual);
  3194. }
  3195. /* Handle marks */
  3196. tor_log(severity, LD_GENERAL,
  3197. " * Channel " U64_FORMAT " has these marks: %s %s %s "
  3198. "%s %s %s",
  3199. U64_PRINTF_ARG(chan->global_identifier),
  3200. channel_is_bad_for_new_circs(chan) ?
  3201. "bad_for_new_circs" : "!bad_for_new_circs",
  3202. channel_is_canonical(chan) ?
  3203. "canonical" : "!canonical",
  3204. channel_is_canonical_is_reliable(chan) ?
  3205. "is_canonical_is_reliable" :
  3206. "!is_canonical_is_reliable",
  3207. channel_is_client(chan) ?
  3208. "client" : "!client",
  3209. channel_is_local(chan) ?
  3210. "local" : "!local",
  3211. channel_is_incoming(chan) ?
  3212. "incoming" : "outgoing");
  3213. /* Describe queues */
  3214. tor_log(severity, LD_GENERAL,
  3215. " * Channel " U64_FORMAT " has %d queued incoming cells"
  3216. " and %d queued outgoing cells",
  3217. U64_PRINTF_ARG(chan->global_identifier),
  3218. chan_cell_queue_len(&chan->incoming_queue),
  3219. chan_cell_queue_len(&chan->outgoing_queue));
  3220. /* Describe circuits */
  3221. tor_log(severity, LD_GENERAL,
  3222. " * Channel " U64_FORMAT " has %d active circuits out of"
  3223. " %d in total",
  3224. U64_PRINTF_ARG(chan->global_identifier),
  3225. (chan->cmux != NULL) ?
  3226. circuitmux_num_active_circuits(chan->cmux) : 0,
  3227. (chan->cmux != NULL) ?
  3228. circuitmux_num_circuits(chan->cmux) : 0);
  3229. /* Describe timestamps */
  3230. tor_log(severity, LD_GENERAL,
  3231. " * Channel " U64_FORMAT " was last used by a "
  3232. "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3233. U64_PRINTF_ARG(chan->global_identifier),
  3234. U64_PRINTF_ARG(chan->timestamp_client),
  3235. U64_PRINTF_ARG(now - chan->timestamp_client));
  3236. tor_log(severity, LD_GENERAL,
  3237. " * Channel " U64_FORMAT " was last drained at "
  3238. U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3239. U64_PRINTF_ARG(chan->global_identifier),
  3240. U64_PRINTF_ARG(chan->timestamp_drained),
  3241. U64_PRINTF_ARG(now - chan->timestamp_drained));
  3242. tor_log(severity, LD_GENERAL,
  3243. " * Channel " U64_FORMAT " last received a cell "
  3244. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3245. U64_PRINTF_ARG(chan->global_identifier),
  3246. U64_PRINTF_ARG(chan->timestamp_recv),
  3247. U64_PRINTF_ARG(now - chan->timestamp_recv));
  3248. tor_log(severity, LD_GENERAL,
  3249. " * Channel " U64_FORMAT " last transmitted a cell "
  3250. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3251. U64_PRINTF_ARG(chan->global_identifier),
  3252. U64_PRINTF_ARG(chan->timestamp_xmit),
  3253. U64_PRINTF_ARG(now - chan->timestamp_xmit));
  3254. /* Describe counters and rates */
  3255. tor_log(severity, LD_GENERAL,
  3256. " * Channel " U64_FORMAT " has received "
  3257. U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
  3258. U64_FORMAT " bytes in " U64_FORMAT " cells",
  3259. U64_PRINTF_ARG(chan->global_identifier),
  3260. U64_PRINTF_ARG(chan->n_bytes_recved),
  3261. U64_PRINTF_ARG(chan->n_cells_recved),
  3262. U64_PRINTF_ARG(chan->n_bytes_xmitted),
  3263. U64_PRINTF_ARG(chan->n_cells_xmitted));
  3264. if (now > chan->timestamp_created &&
  3265. chan->timestamp_created > 0) {
  3266. if (chan->n_bytes_recved > 0) {
  3267. avg = (double)(chan->n_bytes_recved) / age;
  3268. tor_log(severity, LD_GENERAL,
  3269. " * Channel " U64_FORMAT " has averaged %f "
  3270. "bytes received per second",
  3271. U64_PRINTF_ARG(chan->global_identifier), avg);
  3272. }
  3273. if (chan->n_cells_recved > 0) {
  3274. avg = (double)(chan->n_cells_recved) / age;
  3275. if (avg >= 1.0) {
  3276. tor_log(severity, LD_GENERAL,
  3277. " * Channel " U64_FORMAT " has averaged %f "
  3278. "cells received per second",
  3279. U64_PRINTF_ARG(chan->global_identifier), avg);
  3280. } else if (avg >= 0.0) {
  3281. interval = 1.0 / avg;
  3282. tor_log(severity, LD_GENERAL,
  3283. " * Channel " U64_FORMAT " has averaged %f "
  3284. "seconds between received cells",
  3285. U64_PRINTF_ARG(chan->global_identifier), interval);
  3286. }
  3287. }
  3288. if (chan->n_bytes_xmitted > 0) {
  3289. avg = (double)(chan->n_bytes_xmitted) / age;
  3290. tor_log(severity, LD_GENERAL,
  3291. " * Channel " U64_FORMAT " has averaged %f "
  3292. "bytes transmitted per second",
  3293. U64_PRINTF_ARG(chan->global_identifier), avg);
  3294. }
  3295. if (chan->n_cells_xmitted > 0) {
  3296. avg = (double)(chan->n_cells_xmitted) / age;
  3297. if (avg >= 1.0) {
  3298. tor_log(severity, LD_GENERAL,
  3299. " * Channel " U64_FORMAT " has averaged %f "
  3300. "cells transmitted per second",
  3301. U64_PRINTF_ARG(chan->global_identifier), avg);
  3302. } else if (avg >= 0.0) {
  3303. interval = 1.0 / avg;
  3304. tor_log(severity, LD_GENERAL,
  3305. " * Channel " U64_FORMAT " has averaged %f "
  3306. "seconds between transmitted cells",
  3307. U64_PRINTF_ARG(chan->global_identifier), interval);
  3308. }
  3309. }
  3310. }
  3311. /* Dump anything the lower layer has to say */
  3312. channel_dump_transport_statistics(chan, severity);
  3313. }
  3314. /**
  3315. * Dump channel listener statistics
  3316. *
  3317. * Dump statistics for one channel listener to the log
  3318. */
  3319. void
  3320. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  3321. {
  3322. double avg, interval, age;
  3323. time_t now = time(NULL);
  3324. tor_assert(chan_l);
  3325. age = (double)(now - chan_l->timestamp_created);
  3326. tor_log(severity, LD_GENERAL,
  3327. "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
  3328. "state %s (%d)",
  3329. U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
  3330. channel_listener_describe_transport(chan_l),
  3331. channel_listener_state_to_string(chan_l->state), chan_l->state);
  3332. tor_log(severity, LD_GENERAL,
  3333. " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
  3334. " (" U64_FORMAT " seconds ago) "
  3335. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3336. U64_PRINTF_ARG(chan_l->global_identifier),
  3337. U64_PRINTF_ARG(chan_l->timestamp_created),
  3338. U64_PRINTF_ARG(now - chan_l->timestamp_created),
  3339. U64_PRINTF_ARG(chan_l->timestamp_active),
  3340. U64_PRINTF_ARG(now - chan_l->timestamp_active));
  3341. tor_log(severity, LD_GENERAL,
  3342. " * Channel listener " U64_FORMAT " last accepted an incoming "
  3343. "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
  3344. "and has accepted " U64_FORMAT " channels in total",
  3345. U64_PRINTF_ARG(chan_l->global_identifier),
  3346. U64_PRINTF_ARG(chan_l->timestamp_accepted),
  3347. U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
  3348. U64_PRINTF_ARG(chan_l->n_accepted));
  3349. /*
  3350. * If it's sensible to do so, get the rate of incoming channels on this
  3351. * listener
  3352. */
  3353. if (now > chan_l->timestamp_created &&
  3354. chan_l->timestamp_created > 0 &&
  3355. chan_l->n_accepted > 0) {
  3356. avg = (double)(chan_l->n_accepted) / age;
  3357. if (avg >= 1.0) {
  3358. tor_log(severity, LD_GENERAL,
  3359. " * Channel listener " U64_FORMAT " has averaged %f incoming "
  3360. "channels per second",
  3361. U64_PRINTF_ARG(chan_l->global_identifier), avg);
  3362. } else if (avg >= 0.0) {
  3363. interval = 1.0 / avg;
  3364. tor_log(severity, LD_GENERAL,
  3365. " * Channel listener " U64_FORMAT " has averaged %f seconds "
  3366. "between incoming channels",
  3367. U64_PRINTF_ARG(chan_l->global_identifier), interval);
  3368. }
  3369. }
  3370. /* Dump anything the lower layer has to say */
  3371. channel_listener_dump_transport_statistics(chan_l, severity);
  3372. }
  3373. /**
  3374. * Invoke transport-specific stats dump for channel
  3375. *
  3376. * If there is a lower-layer statistics dump method, invoke it
  3377. */
  3378. void
  3379. channel_dump_transport_statistics(channel_t *chan, int severity)
  3380. {
  3381. tor_assert(chan);
  3382. if (chan->dumpstats) chan->dumpstats(chan, severity);
  3383. }
  3384. /**
  3385. * Invoke transport-specific stats dump for channel listener
  3386. *
  3387. * If there is a lower-layer statistics dump method, invoke it
  3388. */
  3389. void
  3390. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  3391. int severity)
  3392. {
  3393. tor_assert(chan_l);
  3394. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  3395. }
  3396. /**
  3397. * Return text description of the remote endpoint
  3398. *
  3399. * This function return a test provided by the lower layer of the remote
  3400. * endpoint for this channel; it should specify the actual address connected
  3401. * to/from.
  3402. *
  3403. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3404. * may invalidate the return value from this function.
  3405. */
  3406. const char *
  3407. channel_get_actual_remote_descr(channel_t *chan)
  3408. {
  3409. tor_assert(chan);
  3410. tor_assert(chan->get_remote_descr);
  3411. /* Param 1 indicates the actual description */
  3412. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  3413. }
  3414. /**
  3415. * Return the text address of the remote endpoint.
  3416. *
  3417. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3418. * may invalidate the return value from this function.
  3419. */
  3420. const char *
  3421. channel_get_actual_remote_address(channel_t *chan)
  3422. {
  3423. /* Param 1 indicates the actual description */
  3424. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  3425. }
  3426. /**
  3427. * Return text description of the remote endpoint canonical address
  3428. *
  3429. * This function return a test provided by the lower layer of the remote
  3430. * endpoint for this channel; it should use the known canonical address for
  3431. * this OR's identity digest if possible.
  3432. *
  3433. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3434. * may invalidate the return value from this function.
  3435. */
  3436. const char *
  3437. channel_get_canonical_remote_descr(channel_t *chan)
  3438. {
  3439. tor_assert(chan);
  3440. tor_assert(chan->get_remote_descr);
  3441. /* Param 0 indicates the canonicalized description */
  3442. return chan->get_remote_descr(chan, 0);
  3443. }
  3444. /**
  3445. * Get remote address if possible.
  3446. *
  3447. * Write the remote address out to a tor_addr_t if the underlying transport
  3448. * supports this operation, and return 1. Return 0 if the underlying transport
  3449. * doesn't let us do this.
  3450. */
  3451. int
  3452. channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
  3453. {
  3454. tor_assert(chan);
  3455. tor_assert(addr_out);
  3456. if (chan->get_remote_addr)
  3457. return chan->get_remote_addr(chan, addr_out);
  3458. /* Else no support, method not implemented */
  3459. else return 0;
  3460. }
  3461. /**
  3462. * Check if there are outgoing queue writes on this channel
  3463. *
  3464. * Indicate if either we have queued cells, or if not, whether the underlying
  3465. * lower-layer transport thinks it has an output queue.
  3466. */
  3467. int
  3468. channel_has_queued_writes(channel_t *chan)
  3469. {
  3470. int has_writes = 0;
  3471. tor_assert(chan);
  3472. tor_assert(chan->has_queued_writes);
  3473. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  3474. has_writes = 1;
  3475. } else {
  3476. /* Check with the lower layer */
  3477. has_writes = chan->has_queued_writes(chan);
  3478. }
  3479. return has_writes;
  3480. }
  3481. /**
  3482. * Check the is_bad_for_new_circs flag
  3483. *
  3484. * This function returns the is_bad_for_new_circs flag of the specified
  3485. * channel.
  3486. */
  3487. int
  3488. channel_is_bad_for_new_circs(channel_t *chan)
  3489. {
  3490. tor_assert(chan);
  3491. return chan->is_bad_for_new_circs;
  3492. }
  3493. /**
  3494. * Mark a channel as bad for new circuits
  3495. *
  3496. * Set the is_bad_for_new_circs_flag on chan.
  3497. */
  3498. void
  3499. channel_mark_bad_for_new_circs(channel_t *chan)
  3500. {
  3501. tor_assert(chan);
  3502. chan->is_bad_for_new_circs = 1;
  3503. }
  3504. /**
  3505. * Get the client flag
  3506. *
  3507. * This returns the client flag of a channel, which will be set if
  3508. * command_process_create_cell() in command.c thinks this is a connection
  3509. * from a client.
  3510. */
  3511. int
  3512. channel_is_client(channel_t *chan)
  3513. {
  3514. tor_assert(chan);
  3515. return chan->is_client;
  3516. }
  3517. /**
  3518. * Set the client flag
  3519. *
  3520. * Mark a channel as being from a client
  3521. */
  3522. void
  3523. channel_mark_client(channel_t *chan)
  3524. {
  3525. tor_assert(chan);
  3526. chan->is_client = 1;
  3527. }
  3528. /**
  3529. * Get the canonical flag for a channel
  3530. *
  3531. * This returns the is_canonical for a channel; this flag is determined by
  3532. * the lower layer and can't be set in a transport-independent way.
  3533. */
  3534. int
  3535. channel_is_canonical(channel_t *chan)
  3536. {
  3537. tor_assert(chan);
  3538. tor_assert(chan->is_canonical);
  3539. return chan->is_canonical(chan, 0);
  3540. }
  3541. /**
  3542. * Test if the canonical flag is reliable
  3543. *
  3544. * This function asks if the lower layer thinks it's safe to trust the
  3545. * result of channel_is_canonical()
  3546. */
  3547. int
  3548. channel_is_canonical_is_reliable(channel_t *chan)
  3549. {
  3550. tor_assert(chan);
  3551. tor_assert(chan->is_canonical);
  3552. return chan->is_canonical(chan, 1);
  3553. }
  3554. /**
  3555. * Test incoming flag
  3556. *
  3557. * This function gets the incoming flag; this is set when a listener spawns
  3558. * a channel. If this returns true the channel was remotely initiated.
  3559. */
  3560. int
  3561. channel_is_incoming(channel_t *chan)
  3562. {
  3563. tor_assert(chan);
  3564. return chan->is_incoming;
  3565. }
  3566. /**
  3567. * Set the incoming flag
  3568. *
  3569. * This function is called when a channel arrives on a listening channel
  3570. * to mark it as incoming.
  3571. */
  3572. void
  3573. channel_mark_incoming(channel_t *chan)
  3574. {
  3575. tor_assert(chan);
  3576. chan->is_incoming = 1;
  3577. }
  3578. /**
  3579. * Test local flag
  3580. *
  3581. * This function gets the local flag; the lower layer should set this when
  3582. * setting up the channel if is_local_addr() is true for all of the
  3583. * destinations it will communicate with on behalf of this channel. It's
  3584. * used to decide whether to declare the network reachable when seeing incoming
  3585. * traffic on the channel.
  3586. */
  3587. int
  3588. channel_is_local(channel_t *chan)
  3589. {
  3590. tor_assert(chan);
  3591. return chan->is_local;
  3592. }
  3593. /**
  3594. * Set the local flag
  3595. *
  3596. * This internal-only function should be called by the lower layer if the
  3597. * channel is to a local address. See channel_is_local() above or the
  3598. * description of the is_local bit in channel.h
  3599. */
  3600. void
  3601. channel_mark_local(channel_t *chan)
  3602. {
  3603. tor_assert(chan);
  3604. chan->is_local = 1;
  3605. }
  3606. /**
  3607. * Mark a channel as remote
  3608. *
  3609. * This internal-only function should be called by the lower layer if the
  3610. * channel is not to a local address but has previously been marked local.
  3611. * See channel_is_local() above or the description of the is_local bit in
  3612. * channel.h
  3613. */
  3614. void
  3615. channel_mark_remote(channel_t *chan)
  3616. {
  3617. tor_assert(chan);
  3618. chan->is_local = 0;
  3619. }
  3620. /**
  3621. * Test outgoing flag
  3622. *
  3623. * This function gets the outgoing flag; this is the inverse of the incoming
  3624. * bit set when a listener spawns a channel. If this returns true the channel
  3625. * was locally initiated.
  3626. */
  3627. int
  3628. channel_is_outgoing(channel_t *chan)
  3629. {
  3630. tor_assert(chan);
  3631. return !(chan->is_incoming);
  3632. }
  3633. /**
  3634. * Mark a channel as outgoing
  3635. *
  3636. * This function clears the incoming flag and thus marks a channel as
  3637. * outgoing.
  3638. */
  3639. void
  3640. channel_mark_outgoing(channel_t *chan)
  3641. {
  3642. tor_assert(chan);
  3643. chan->is_incoming = 0;
  3644. }
  3645. /************************
  3646. * Flow control queries *
  3647. ***********************/
  3648. /*
  3649. * Get the latest estimate for the total queue size of all open channels
  3650. */
  3651. uint64_t
  3652. channel_get_global_queue_estimate(void)
  3653. {
  3654. return estimated_total_queue_size;
  3655. }
  3656. /*
  3657. * Estimate the number of writeable cells
  3658. *
  3659. * Ask the lower layer for an estimate of how many cells it can accept, and
  3660. * then subtract the length of our outgoing_queue, if any, to produce an
  3661. * estimate of the number of cells this channel can accept for writes.
  3662. */
  3663. int
  3664. channel_num_cells_writeable(channel_t *chan)
  3665. {
  3666. int result;
  3667. tor_assert(chan);
  3668. tor_assert(chan->num_cells_writeable);
  3669. if (chan->state == CHANNEL_STATE_OPEN) {
  3670. /* Query lower layer */
  3671. result = chan->num_cells_writeable(chan);
  3672. /* Subtract cell queue length, if any */
  3673. result -= chan_cell_queue_len(&chan->outgoing_queue);
  3674. if (result < 0) result = 0;
  3675. } else {
  3676. /* No cells are writeable in any other state */
  3677. result = 0;
  3678. }
  3679. return result;
  3680. }
  3681. /*********************
  3682. * Timestamp updates *
  3683. ********************/
  3684. /**
  3685. * Update the created timestamp for a channel
  3686. *
  3687. * This updates the channel's created timestamp and should only be called
  3688. * from channel_init().
  3689. */
  3690. void
  3691. channel_timestamp_created(channel_t *chan)
  3692. {
  3693. time_t now = time(NULL);
  3694. tor_assert(chan);
  3695. chan->timestamp_created = now;
  3696. }
  3697. /**
  3698. * Update the created timestamp for a channel listener
  3699. *
  3700. * This updates the channel listener's created timestamp and should only be
  3701. * called from channel_init_listener().
  3702. */
  3703. void
  3704. channel_listener_timestamp_created(channel_listener_t *chan_l)
  3705. {
  3706. time_t now = time(NULL);
  3707. tor_assert(chan_l);
  3708. chan_l->timestamp_created = now;
  3709. }
  3710. /**
  3711. * Update the last active timestamp for a channel
  3712. *
  3713. * This function updates the channel's last active timestamp; it should be
  3714. * called by the lower layer whenever there is activity on the channel which
  3715. * does not lead to a cell being transmitted or received; the active timestamp
  3716. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  3717. * but it should be updated for things like the v3 handshake and stuff that
  3718. * produce activity only visible to the lower layer.
  3719. */
  3720. void
  3721. channel_timestamp_active(channel_t *chan)
  3722. {
  3723. time_t now = time(NULL);
  3724. tor_assert(chan);
  3725. chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
  3726. chan->timestamp_active = now;
  3727. /* Clear any potential netflow padding timer. We're active */
  3728. chan->next_padding_time_ms = 0;
  3729. }
  3730. /**
  3731. * Update the last active timestamp for a channel listener
  3732. */
  3733. void
  3734. channel_listener_timestamp_active(channel_listener_t *chan_l)
  3735. {
  3736. time_t now = time(NULL);
  3737. tor_assert(chan_l);
  3738. chan_l->timestamp_active = now;
  3739. }
  3740. /**
  3741. * Update the last accepted timestamp.
  3742. *
  3743. * This function updates the channel listener's last accepted timestamp; it
  3744. * should be called whenever a new incoming channel is accepted on a
  3745. * listener.
  3746. */
  3747. void
  3748. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  3749. {
  3750. time_t now = time(NULL);
  3751. tor_assert(chan_l);
  3752. chan_l->timestamp_active = now;
  3753. chan_l->timestamp_accepted = now;
  3754. }
  3755. /**
  3756. * Update client timestamp
  3757. *
  3758. * This function is called by relay.c to timestamp a channel that appears to
  3759. * be used as a client.
  3760. */
  3761. void
  3762. channel_timestamp_client(channel_t *chan)
  3763. {
  3764. time_t now = time(NULL);
  3765. tor_assert(chan);
  3766. chan->timestamp_client = now;
  3767. }
  3768. /**
  3769. * Update the last drained timestamp
  3770. *
  3771. * This is called whenever we transmit a cell which leaves the outgoing cell
  3772. * queue completely empty. It also updates the xmit time and the active time.
  3773. */
  3774. void
  3775. channel_timestamp_drained(channel_t *chan)
  3776. {
  3777. time_t now = time(NULL);
  3778. tor_assert(chan);
  3779. chan->timestamp_active = now;
  3780. chan->timestamp_drained = now;
  3781. chan->timestamp_xmit = now;
  3782. }
  3783. /**
  3784. * Update the recv timestamp
  3785. *
  3786. * This is called whenever we get an incoming cell from the lower layer.
  3787. * This also updates the active timestamp.
  3788. */
  3789. void
  3790. channel_timestamp_recv(channel_t *chan)
  3791. {
  3792. time_t now = time(NULL);
  3793. tor_assert(chan);
  3794. chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
  3795. chan->timestamp_active = now;
  3796. chan->timestamp_recv = now;
  3797. /* Clear any potential netflow padding timer. We're active */
  3798. chan->next_padding_time_ms = 0;
  3799. }
  3800. /**
  3801. * Update the xmit timestamp
  3802. * This is called whenever we pass an outgoing cell to the lower layer. This
  3803. * also updates the active timestamp.
  3804. */
  3805. void
  3806. channel_timestamp_xmit(channel_t *chan)
  3807. {
  3808. time_t now = time(NULL);
  3809. tor_assert(chan);
  3810. chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
  3811. chan->timestamp_active = now;
  3812. chan->timestamp_xmit = now;
  3813. /* Clear any potential netflow padding timer. We're active */
  3814. chan->next_padding_time_ms = 0;
  3815. }
  3816. /***************************************************************
  3817. * Timestamp queries - see above for definitions of timestamps *
  3818. **************************************************************/
  3819. /**
  3820. * Query created timestamp for a channel
  3821. */
  3822. time_t
  3823. channel_when_created(channel_t *chan)
  3824. {
  3825. tor_assert(chan);
  3826. return chan->timestamp_created;
  3827. }
  3828. /**
  3829. * Query created timestamp for a channel listener
  3830. */
  3831. time_t
  3832. channel_listener_when_created(channel_listener_t *chan_l)
  3833. {
  3834. tor_assert(chan_l);
  3835. return chan_l->timestamp_created;
  3836. }
  3837. /**
  3838. * Query last active timestamp for a channel
  3839. */
  3840. time_t
  3841. channel_when_last_active(channel_t *chan)
  3842. {
  3843. tor_assert(chan);
  3844. return chan->timestamp_active;
  3845. }
  3846. /**
  3847. * Query last active timestamp for a channel listener
  3848. */
  3849. time_t
  3850. channel_listener_when_last_active(channel_listener_t *chan_l)
  3851. {
  3852. tor_assert(chan_l);
  3853. return chan_l->timestamp_active;
  3854. }
  3855. /**
  3856. * Query last accepted timestamp for a channel listener
  3857. */
  3858. time_t
  3859. channel_listener_when_last_accepted(channel_listener_t *chan_l)
  3860. {
  3861. tor_assert(chan_l);
  3862. return chan_l->timestamp_accepted;
  3863. }
  3864. /**
  3865. * Query client timestamp
  3866. */
  3867. time_t
  3868. channel_when_last_client(channel_t *chan)
  3869. {
  3870. tor_assert(chan);
  3871. return chan->timestamp_client;
  3872. }
  3873. /**
  3874. * Query drained timestamp
  3875. */
  3876. time_t
  3877. channel_when_last_drained(channel_t *chan)
  3878. {
  3879. tor_assert(chan);
  3880. return chan->timestamp_drained;
  3881. }
  3882. /**
  3883. * Query recv timestamp
  3884. */
  3885. time_t
  3886. channel_when_last_recv(channel_t *chan)
  3887. {
  3888. tor_assert(chan);
  3889. return chan->timestamp_recv;
  3890. }
  3891. /**
  3892. * Query xmit timestamp
  3893. */
  3894. time_t
  3895. channel_when_last_xmit(channel_t *chan)
  3896. {
  3897. tor_assert(chan);
  3898. return chan->timestamp_xmit;
  3899. }
  3900. /**
  3901. * Query accepted counter
  3902. */
  3903. uint64_t
  3904. channel_listener_count_accepted(channel_listener_t *chan_l)
  3905. {
  3906. tor_assert(chan_l);
  3907. return chan_l->n_accepted;
  3908. }
  3909. /**
  3910. * Query received cell counter
  3911. */
  3912. uint64_t
  3913. channel_count_recved(channel_t *chan)
  3914. {
  3915. tor_assert(chan);
  3916. return chan->n_cells_recved;
  3917. }
  3918. /**
  3919. * Query transmitted cell counter
  3920. */
  3921. uint64_t
  3922. channel_count_xmitted(channel_t *chan)
  3923. {
  3924. tor_assert(chan);
  3925. return chan->n_cells_xmitted;
  3926. }
  3927. /**
  3928. * Check if a channel matches an extend_info_t
  3929. *
  3930. * This function calls the lower layer and asks if this channel matches a
  3931. * given extend_info_t.
  3932. */
  3933. int
  3934. channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
  3935. {
  3936. tor_assert(chan);
  3937. tor_assert(chan->matches_extend_info);
  3938. tor_assert(extend_info);
  3939. return chan->matches_extend_info(chan, extend_info);
  3940. }
  3941. /**
  3942. * Check if a channel matches a given target address; return true iff we do.
  3943. *
  3944. * This function calls into the lower layer and asks if this channel thinks
  3945. * it matches a given target address for circuit extension purposes.
  3946. */
  3947. int
  3948. channel_matches_target_addr_for_extend(channel_t *chan,
  3949. const tor_addr_t *target)
  3950. {
  3951. tor_assert(chan);
  3952. tor_assert(chan->matches_target);
  3953. tor_assert(target);
  3954. return chan->matches_target(chan, target);
  3955. }
  3956. /**
  3957. * Return the total number of circuits used by a channel
  3958. *
  3959. * @param chan Channel to query
  3960. * @return Number of circuits using this as n_chan or p_chan
  3961. */
  3962. unsigned int
  3963. channel_num_circuits(channel_t *chan)
  3964. {
  3965. tor_assert(chan);
  3966. return chan->num_n_circuits +
  3967. chan->num_p_circuits;
  3968. }
  3969. /**
  3970. * Set up circuit ID generation
  3971. *
  3972. * This is called when setting up a channel and replaces the old
  3973. * connection_or_set_circid_type()
  3974. */
  3975. MOCK_IMPL(void,
  3976. channel_set_circid_type,(channel_t *chan,
  3977. crypto_pk_t *identity_rcvd,
  3978. int consider_identity))
  3979. {
  3980. int started_here;
  3981. crypto_pk_t *our_identity;
  3982. tor_assert(chan);
  3983. started_here = channel_is_outgoing(chan);
  3984. if (! consider_identity) {
  3985. if (started_here)
  3986. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3987. else
  3988. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3989. return;
  3990. }
  3991. our_identity = started_here ?
  3992. get_tlsclient_identity_key() : get_server_identity_key();
  3993. if (identity_rcvd) {
  3994. if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
  3995. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3996. } else {
  3997. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3998. }
  3999. } else {
  4000. chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
  4001. }
  4002. }
  4003. /** Helper for channel_update_bad_for_new_circs(): Perform the
  4004. * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
  4005. * all of which MUST have the same RSA ID. (They MAY have different
  4006. * Ed25519 IDs.) */
  4007. static void
  4008. channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
  4009. {
  4010. /*XXXX This function should really be about channels. 15056 */
  4011. channel_t *chan;
  4012. /* First, get a minimal list of the ed25519 identites */
  4013. smartlist_t *ed_identities = smartlist_new();
  4014. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  4015. uint8_t *id_copy =
  4016. tor_memdup(&chan->ed25519_identity.pubkey, DIGEST256_LEN);
  4017. smartlist_add(ed_identities, id_copy);
  4018. }
  4019. smartlist_sort_digests256(ed_identities);
  4020. smartlist_uniq_digests256(ed_identities);
  4021. /* Now, for each Ed identity, build a smartlist and find the best entry on
  4022. * it. */
  4023. smartlist_t *or_conns = smartlist_new();
  4024. SMARTLIST_FOREACH_BEGIN(ed_identities, const uint8_t *, ed_id) {
  4025. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  4026. channel_tls_t *chantls = BASE_CHAN_TO_TLS(chan);
  4027. if (tor_memneq(ed_id, &chan->ed25519_identity.pubkey, DIGEST256_LEN))
  4028. continue;
  4029. or_connection_t *orconn = chantls->conn;
  4030. if (orconn) {
  4031. tor_assert(orconn->chan == chantls);
  4032. smartlist_add(or_conns, orconn);
  4033. }
  4034. }
  4035. connection_or_group_set_badness_(or_conns, force);
  4036. smartlist_clear(or_conns);
  4037. } SMARTLIST_FOREACH_END(ed_id);
  4038. /* XXXX 15056 we may want to do something special with connections that have
  4039. * no set Ed25519 identity! */
  4040. smartlist_free(or_conns);
  4041. SMARTLIST_FOREACH(ed_identities, uint8_t *, ed_id, tor_free(ed_id));
  4042. smartlist_free(ed_identities);
  4043. }
  4044. /** Go through all the channels (or if <b>digest</b> is non-NULL, just
  4045. * the OR connections with that digest), and set the is_bad_for_new_circs
  4046. * flag based on the rules in connection_or_group_set_badness() (or just
  4047. * always set it if <b>force</b> is true).
  4048. */
  4049. void
  4050. channel_update_bad_for_new_circs(const char *digest, int force)
  4051. {
  4052. if (digest) {
  4053. channel_idmap_entry_t *ent;
  4054. channel_idmap_entry_t search;
  4055. memset(&search, 0, sizeof(search));
  4056. memcpy(search.digest, digest, DIGEST_LEN);
  4057. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  4058. if (ent) {
  4059. channel_rsa_id_group_set_badness(&ent->channel_list, force);
  4060. }
  4061. return;
  4062. }
  4063. /* no digest; just look at everything. */
  4064. channel_idmap_entry_t **iter;
  4065. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  4066. channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
  4067. }
  4068. }
  4069. /**
  4070. * Update the estimated number of bytes queued to transmit for this channel,
  4071. * and notify the scheduler. The estimate includes both the channel queue and
  4072. * the queue size reported by the lower layer, and an overhead estimate
  4073. * optionally provided by the lower layer.
  4074. */
  4075. void
  4076. channel_update_xmit_queue_size(channel_t *chan)
  4077. {
  4078. uint64_t queued, adj;
  4079. double overhead;
  4080. tor_assert(chan);
  4081. tor_assert(chan->num_bytes_queued);
  4082. /*
  4083. * First, get the number of bytes we have queued without factoring in
  4084. * lower-layer overhead.
  4085. */
  4086. queued = chan->num_bytes_queued(chan) + chan->bytes_in_queue;
  4087. /* Next, adjust by the overhead factor, if any is available */
  4088. if (chan->get_overhead_estimate) {
  4089. overhead = chan->get_overhead_estimate(chan);
  4090. if (overhead >= 1.0) {
  4091. queued = (uint64_t)(queued * overhead);
  4092. } else {
  4093. /* Ignore silly overhead factors */
  4094. log_notice(LD_CHANNEL, "Ignoring silly overhead factor %f", overhead);
  4095. }
  4096. }
  4097. /* Now, compare to the previous estimate */
  4098. if (queued > chan->bytes_queued_for_xmit) {
  4099. adj = queued - chan->bytes_queued_for_xmit;
  4100. log_debug(LD_CHANNEL,
  4101. "Increasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  4102. " from " U64_FORMAT " to " U64_FORMAT,
  4103. U64_PRINTF_ARG(chan->global_identifier),
  4104. U64_PRINTF_ARG(adj),
  4105. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  4106. U64_PRINTF_ARG(queued));
  4107. /* Update the channel's estimate */
  4108. chan->bytes_queued_for_xmit = queued;
  4109. /* Update the global queue size estimate if appropriate */
  4110. if (chan->state == CHANNEL_STATE_OPEN ||
  4111. chan->state == CHANNEL_STATE_MAINT) {
  4112. estimated_total_queue_size += adj;
  4113. log_debug(LD_CHANNEL,
  4114. "Increasing global queue size by " U64_FORMAT " for channel "
  4115. U64_FORMAT ", new size is " U64_FORMAT,
  4116. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  4117. U64_PRINTF_ARG(estimated_total_queue_size));
  4118. }
  4119. } else if (queued < chan->bytes_queued_for_xmit) {
  4120. adj = chan->bytes_queued_for_xmit - queued;
  4121. log_debug(LD_CHANNEL,
  4122. "Decreasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  4123. " from " U64_FORMAT " to " U64_FORMAT,
  4124. U64_PRINTF_ARG(chan->global_identifier),
  4125. U64_PRINTF_ARG(adj),
  4126. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  4127. U64_PRINTF_ARG(queued));
  4128. /* Update the channel's estimate */
  4129. chan->bytes_queued_for_xmit = queued;
  4130. /* Update the global queue size estimate if appropriate */
  4131. if (chan->state == CHANNEL_STATE_OPEN ||
  4132. chan->state == CHANNEL_STATE_MAINT) {
  4133. estimated_total_queue_size -= adj;
  4134. log_debug(LD_CHANNEL,
  4135. "Decreasing global queue size by " U64_FORMAT " for channel "
  4136. U64_FORMAT ", new size is " U64_FORMAT,
  4137. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  4138. U64_PRINTF_ARG(estimated_total_queue_size));
  4139. }
  4140. }
  4141. }