channel.c 139 KB

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