channel.c 133 KB

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