channel.c 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707
  1. /* * Copyright (c) 2012-2016, 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. 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. /* Tell circuits if we opened and stuff */
  1752. if (to_state == CHANNEL_STATE_OPEN) {
  1753. channel_do_open_actions(chan);
  1754. chan->has_been_open = 1;
  1755. /* Check for queued cells to process */
  1756. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  1757. channel_process_cells(chan);
  1758. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
  1759. channel_flush_cells(chan);
  1760. } else if (to_state == CHANNEL_STATE_CLOSED ||
  1761. to_state == CHANNEL_STATE_ERROR) {
  1762. /* Assert that all queues are empty */
  1763. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
  1764. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
  1765. }
  1766. }
  1767. /**
  1768. * Change channel listener state
  1769. *
  1770. * This internal and subclass use only function is used to change channel
  1771. * listener state, performing all transition validity checks and whatever
  1772. * actions are appropriate to the state transition in question.
  1773. */
  1774. void
  1775. channel_listener_change_state(channel_listener_t *chan_l,
  1776. channel_listener_state_t to_state)
  1777. {
  1778. channel_listener_state_t from_state;
  1779. unsigned char was_active, is_active;
  1780. tor_assert(chan_l);
  1781. from_state = chan_l->state;
  1782. tor_assert(channel_listener_state_is_valid(from_state));
  1783. tor_assert(channel_listener_state_is_valid(to_state));
  1784. tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
  1785. /* Check for no-op transitions */
  1786. if (from_state == to_state) {
  1787. log_debug(LD_CHANNEL,
  1788. "Got no-op transition from \"%s\" to itself on channel "
  1789. "listener %p (global ID " U64_FORMAT ")",
  1790. channel_listener_state_to_string(to_state),
  1791. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1792. return;
  1793. }
  1794. /* If we're going to a closing or closed state, we must have a reason set */
  1795. if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
  1796. to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1797. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1798. tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
  1799. }
  1800. /*
  1801. * We need to maintain the queues here for some transitions:
  1802. * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
  1803. * we may have a backlog of cells to transmit, so drain the queues in
  1804. * that case, and when going to CHANNEL_STATE_CLOSED the subclass
  1805. * should have made sure to finish sending things (or gone to
  1806. * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
  1807. */
  1808. log_debug(LD_CHANNEL,
  1809. "Changing state of channel listener %p (global ID " U64_FORMAT
  1810. "from \"%s\" to \"%s\"",
  1811. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  1812. channel_listener_state_to_string(chan_l->state),
  1813. channel_listener_state_to_string(to_state));
  1814. chan_l->state = to_state;
  1815. /* Need to add to the right lists if the channel listener is registered */
  1816. if (chan_l->registered) {
  1817. was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1818. from_state == CHANNEL_LISTENER_STATE_ERROR);
  1819. is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1820. to_state == CHANNEL_LISTENER_STATE_ERROR);
  1821. /* Need to take off active list and put on finished list? */
  1822. if (was_active && !is_active) {
  1823. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  1824. if (!finished_listeners) finished_listeners = smartlist_new();
  1825. smartlist_add(finished_listeners, chan_l);
  1826. }
  1827. /* Need to put on active list? */
  1828. else if (!was_active && is_active) {
  1829. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  1830. if (!active_listeners) active_listeners = smartlist_new();
  1831. smartlist_add(active_listeners, chan_l);
  1832. }
  1833. }
  1834. if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1835. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1836. /* Assert that the queue is empty */
  1837. tor_assert(!(chan_l->incoming_list) ||
  1838. smartlist_len(chan_l->incoming_list) == 0);
  1839. }
  1840. }
  1841. /**
  1842. * Try to flush cells to the lower layer
  1843. *
  1844. * this is called by the lower layer to indicate that it wants more cells;
  1845. * it will try to write up to num_cells cells from the channel's cell queue or
  1846. * from circuits active on that channel, or as many as it has available if
  1847. * num_cells == -1.
  1848. */
  1849. #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
  1850. MOCK_IMPL(ssize_t,
  1851. channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
  1852. {
  1853. unsigned int unlimited = 0;
  1854. ssize_t flushed = 0;
  1855. int num_cells_from_circs, clamped_num_cells;
  1856. int q_len_before, q_len_after;
  1857. tor_assert(chan);
  1858. if (num_cells < 0) unlimited = 1;
  1859. if (!unlimited && num_cells <= flushed) goto done;
  1860. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1861. if (CHANNEL_IS_OPEN(chan)) {
  1862. /* Try to flush as much as we can that's already queued */
  1863. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  1864. (unlimited ? -1 : num_cells - flushed));
  1865. if (!unlimited && num_cells <= flushed) goto done;
  1866. if (circuitmux_num_cells(chan->cmux) > 0) {
  1867. /* Calculate number of cells, including clamp */
  1868. if (unlimited) {
  1869. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1870. } else {
  1871. if (num_cells - flushed >
  1872. MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
  1873. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1874. } else {
  1875. clamped_num_cells = (int)(num_cells - flushed);
  1876. }
  1877. }
  1878. /*
  1879. * Keep track of the change in queue size; we have to count cells
  1880. * channel_flush_from_first_active_circuit() writes out directly,
  1881. * but not double-count ones we might get later in
  1882. * channel_flush_some_cells_from_outgoing_queue()
  1883. */
  1884. q_len_before = chan_cell_queue_len(&(chan->outgoing_queue));
  1885. /* Try to get more cells from any active circuits */
  1886. num_cells_from_circs = channel_flush_from_first_active_circuit(
  1887. chan, clamped_num_cells);
  1888. q_len_after = chan_cell_queue_len(&(chan->outgoing_queue));
  1889. /*
  1890. * If it claims we got some, adjust the flushed counter and consider
  1891. * processing the queue again
  1892. */
  1893. if (num_cells_from_circs > 0) {
  1894. /*
  1895. * Adjust flushed by the number of cells counted in
  1896. * num_cells_from_circs that didn't go to the cell queue.
  1897. */
  1898. if (q_len_after > q_len_before) {
  1899. num_cells_from_circs -= (q_len_after - q_len_before);
  1900. if (num_cells_from_circs < 0) num_cells_from_circs = 0;
  1901. }
  1902. flushed += num_cells_from_circs;
  1903. /* Now process the queue if necessary */
  1904. if ((q_len_after > q_len_before) &&
  1905. (unlimited || (flushed < num_cells))) {
  1906. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  1907. (unlimited ? -1 : num_cells - flushed));
  1908. }
  1909. }
  1910. }
  1911. }
  1912. done:
  1913. return flushed;
  1914. }
  1915. /**
  1916. * Flush cells from just the channel's outgoing cell queue
  1917. *
  1918. * This gets called from channel_flush_some_cells() above to flush cells
  1919. * just from the queue without trying for active_circuits.
  1920. */
  1921. static ssize_t
  1922. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  1923. ssize_t num_cells)
  1924. {
  1925. unsigned int unlimited = 0;
  1926. ssize_t flushed = 0;
  1927. cell_queue_entry_t *q = NULL;
  1928. size_t cell_size;
  1929. int free_q = 0, handed_off = 0;
  1930. tor_assert(chan);
  1931. tor_assert(chan->write_cell);
  1932. tor_assert(chan->write_packed_cell);
  1933. tor_assert(chan->write_var_cell);
  1934. if (num_cells < 0) unlimited = 1;
  1935. if (!unlimited && num_cells <= flushed) return 0;
  1936. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1937. if (CHANNEL_IS_OPEN(chan)) {
  1938. while ((unlimited || num_cells > flushed) &&
  1939. NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
  1940. free_q = 0;
  1941. handed_off = 0;
  1942. /* Figure out how big it is for statistical purposes */
  1943. cell_size = channel_get_cell_queue_entry_size(chan, q);
  1944. /*
  1945. * Okay, we have a good queue entry, try to give it to the lower
  1946. * layer.
  1947. */
  1948. switch (q->type) {
  1949. case CELL_QUEUE_FIXED:
  1950. if (q->u.fixed.cell) {
  1951. if (chan->write_cell(chan,
  1952. q->u.fixed.cell)) {
  1953. ++flushed;
  1954. channel_timestamp_xmit(chan);
  1955. ++(chan->n_cells_xmitted);
  1956. chan->n_bytes_xmitted += cell_size;
  1957. free_q = 1;
  1958. handed_off = 1;
  1959. }
  1960. /* Else couldn't write it; leave it on the queue */
  1961. } else {
  1962. /* This shouldn't happen */
  1963. log_info(LD_CHANNEL,
  1964. "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
  1965. "with no cell on channel %p "
  1966. "(global ID " U64_FORMAT ").",
  1967. chan, U64_PRINTF_ARG(chan->global_identifier));
  1968. /* Throw it away */
  1969. free_q = 1;
  1970. handed_off = 0;
  1971. }
  1972. break;
  1973. case CELL_QUEUE_PACKED:
  1974. if (q->u.packed.packed_cell) {
  1975. if (chan->write_packed_cell(chan,
  1976. q->u.packed.packed_cell)) {
  1977. ++flushed;
  1978. channel_timestamp_xmit(chan);
  1979. ++(chan->n_cells_xmitted);
  1980. chan->n_bytes_xmitted += cell_size;
  1981. free_q = 1;
  1982. handed_off = 1;
  1983. }
  1984. /* Else couldn't write it; leave it on the queue */
  1985. } else {
  1986. /* This shouldn't happen */
  1987. log_info(LD_CHANNEL,
  1988. "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
  1989. "with no cell on channel %p "
  1990. "(global ID " U64_FORMAT ").",
  1991. chan, U64_PRINTF_ARG(chan->global_identifier));
  1992. /* Throw it away */
  1993. free_q = 1;
  1994. handed_off = 0;
  1995. }
  1996. break;
  1997. case CELL_QUEUE_VAR:
  1998. if (q->u.var.var_cell) {
  1999. if (chan->write_var_cell(chan,
  2000. q->u.var.var_cell)) {
  2001. ++flushed;
  2002. channel_timestamp_xmit(chan);
  2003. ++(chan->n_cells_xmitted);
  2004. chan->n_bytes_xmitted += cell_size;
  2005. free_q = 1;
  2006. handed_off = 1;
  2007. }
  2008. /* Else couldn't write it; leave it on the queue */
  2009. } else {
  2010. /* This shouldn't happen */
  2011. log_info(LD_CHANNEL,
  2012. "Saw broken cell queue entry of type CELL_QUEUE_VAR "
  2013. "with no cell on channel %p "
  2014. "(global ID " U64_FORMAT ").",
  2015. chan, U64_PRINTF_ARG(chan->global_identifier));
  2016. /* Throw it away */
  2017. free_q = 1;
  2018. handed_off = 0;
  2019. }
  2020. break;
  2021. default:
  2022. /* Unknown type, log and free it */
  2023. log_info(LD_CHANNEL,
  2024. "Saw an unknown cell queue entry type %d on channel %p "
  2025. "(global ID " U64_FORMAT "; ignoring it."
  2026. " Someone should fix this.",
  2027. q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
  2028. free_q = 1;
  2029. handed_off = 0;
  2030. }
  2031. /*
  2032. * if free_q is set, we used it and should remove the queue entry;
  2033. * we have to do the free down here so TOR_SIMPLEQ_REMOVE_HEAD isn't
  2034. * accessing freed memory
  2035. */
  2036. if (free_q) {
  2037. TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
  2038. /*
  2039. * ...and we handed a cell off to the lower layer, so we should
  2040. * update the counters.
  2041. */
  2042. ++n_channel_cells_passed_to_lower_layer;
  2043. --n_channel_cells_in_queues;
  2044. n_channel_bytes_passed_to_lower_layer += cell_size;
  2045. n_channel_bytes_in_queues -= cell_size;
  2046. channel_assert_counter_consistency();
  2047. /* Update the channel's queue size too */
  2048. chan->bytes_in_queue -= cell_size;
  2049. /* Finally, free q */
  2050. cell_queue_entry_free(q, handed_off);
  2051. q = NULL;
  2052. } else {
  2053. /* No cell removed from list, so we can't go on any further */
  2054. break;
  2055. }
  2056. }
  2057. }
  2058. /* Did we drain the queue? */
  2059. if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  2060. channel_timestamp_drained(chan);
  2061. }
  2062. /* Update the estimate queue size */
  2063. channel_update_xmit_queue_size(chan);
  2064. return flushed;
  2065. }
  2066. /**
  2067. * Flush as many cells as we possibly can from the queue
  2068. *
  2069. * This tries to flush as many cells from the queue as the lower layer
  2070. * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
  2071. * in unlimited mode.
  2072. */
  2073. void
  2074. channel_flush_cells(channel_t *chan)
  2075. {
  2076. channel_flush_some_cells_from_outgoing_queue(chan, -1);
  2077. }
  2078. /**
  2079. * Check if any cells are available
  2080. *
  2081. * This gets used from the lower layer to check if any more cells are
  2082. * available.
  2083. */
  2084. int
  2085. channel_more_to_flush(channel_t *chan)
  2086. {
  2087. tor_assert(chan);
  2088. /* Check if we have any queued */
  2089. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2090. return 1;
  2091. /* Check if any circuits would like to queue some */
  2092. if (circuitmux_num_cells(chan->cmux) > 0) return 1;
  2093. /* Else no */
  2094. return 0;
  2095. }
  2096. /**
  2097. * Notify the channel we're done flushing the output in the lower layer
  2098. *
  2099. * Connection.c will call this when we've flushed the output; there's some
  2100. * dirreq-related maintenance to do.
  2101. */
  2102. void
  2103. channel_notify_flushed(channel_t *chan)
  2104. {
  2105. tor_assert(chan);
  2106. if (chan->dirreq_id != 0)
  2107. geoip_change_dirreq_state(chan->dirreq_id,
  2108. DIRREQ_TUNNELED,
  2109. DIRREQ_CHANNEL_BUFFER_FLUSHED);
  2110. }
  2111. /**
  2112. * Process the queue of incoming channels on a listener
  2113. *
  2114. * Use a listener's registered callback to process as many entries in the
  2115. * queue of incoming channels as possible.
  2116. */
  2117. void
  2118. channel_listener_process_incoming(channel_listener_t *listener)
  2119. {
  2120. tor_assert(listener);
  2121. /*
  2122. * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
  2123. * while closing a listener.
  2124. */
  2125. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
  2126. listener->state == CHANNEL_LISTENER_STATE_CLOSING);
  2127. tor_assert(listener->listener);
  2128. log_debug(LD_CHANNEL,
  2129. "Processing queue of incoming connections for channel "
  2130. "listener %p (global ID " U64_FORMAT ")",
  2131. listener, U64_PRINTF_ARG(listener->global_identifier));
  2132. if (!(listener->incoming_list)) return;
  2133. SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
  2134. channel_t *, chan) {
  2135. tor_assert(chan);
  2136. log_debug(LD_CHANNEL,
  2137. "Handling incoming channel %p (" U64_FORMAT ") "
  2138. "for listener %p (" U64_FORMAT ")",
  2139. chan,
  2140. U64_PRINTF_ARG(chan->global_identifier),
  2141. listener,
  2142. U64_PRINTF_ARG(listener->global_identifier));
  2143. /* Make sure this is set correctly */
  2144. channel_mark_incoming(chan);
  2145. listener->listener(listener, chan);
  2146. } SMARTLIST_FOREACH_END(chan);
  2147. smartlist_free(listener->incoming_list);
  2148. listener->incoming_list = NULL;
  2149. }
  2150. /**
  2151. * Take actions required when a channel becomes open
  2152. *
  2153. * Handle actions we should do when we know a channel is open; a lot of
  2154. * this comes from the old connection_or_set_state_open() of connection_or.c.
  2155. *
  2156. * Because of this mechanism, future channel_t subclasses should take care
  2157. * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
  2158. * until there is positive confirmation that the network is operational.
  2159. * In particular, anything UDP-based should not make this transition until a
  2160. * packet is received from the other side.
  2161. */
  2162. void
  2163. channel_do_open_actions(channel_t *chan)
  2164. {
  2165. tor_addr_t remote_addr;
  2166. int started_here;
  2167. time_t now = time(NULL);
  2168. int close_origin_circuits = 0;
  2169. tor_assert(chan);
  2170. started_here = channel_is_outgoing(chan);
  2171. if (started_here) {
  2172. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2173. rep_hist_note_connect_succeeded(chan->identity_digest, now);
  2174. #ifdef ENABLE_LEGACY_GUARD_ALGORITHM
  2175. // XXXX prop271 this call is no longer useful with the new algorithm.
  2176. if (entry_guard_register_connect_status(
  2177. chan->identity_digest, 1, 0, now) < 0) {
  2178. /* Close any circuits pending on this channel. We leave it in state
  2179. * 'open' though, because it didn't actually *fail* -- we just
  2180. * chose not to use it. */
  2181. log_debug(LD_OR,
  2182. "New entry guard was reachable, but closing this "
  2183. "connection so we can retry the earlier entry guards.");
  2184. close_origin_circuits = 1;
  2185. }
  2186. #endif
  2187. router_set_status(chan->identity_digest, 1);
  2188. } else {
  2189. /* only report it to the geoip module if it's not a known router */
  2190. if (!router_get_by_id_digest(chan->identity_digest)) {
  2191. if (channel_get_addr_if_possible(chan, &remote_addr)) {
  2192. char *transport_name = NULL;
  2193. if (chan->get_transport_name(chan, &transport_name) < 0)
  2194. transport_name = NULL;
  2195. geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
  2196. &remote_addr, transport_name,
  2197. now);
  2198. tor_free(transport_name);
  2199. }
  2200. /* Otherwise the underlying transport can't tell us this, so skip it */
  2201. }
  2202. }
  2203. circuit_n_chan_done(chan, 1, close_origin_circuits);
  2204. }
  2205. /**
  2206. * Queue an incoming channel on a listener
  2207. *
  2208. * Internal and subclass use only function to queue an incoming channel from
  2209. * a listener. A subclass of channel_listener_t should call this when a new
  2210. * incoming channel is created.
  2211. */
  2212. void
  2213. channel_listener_queue_incoming(channel_listener_t *listener,
  2214. channel_t *incoming)
  2215. {
  2216. int need_to_queue = 0;
  2217. tor_assert(listener);
  2218. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  2219. tor_assert(incoming);
  2220. log_debug(LD_CHANNEL,
  2221. "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
  2222. "channel listener %p (global ID " U64_FORMAT ")",
  2223. incoming, U64_PRINTF_ARG(incoming->global_identifier),
  2224. listener, U64_PRINTF_ARG(listener->global_identifier));
  2225. /* Do we need to queue it, or can we just call the listener right away? */
  2226. if (!(listener->listener)) need_to_queue = 1;
  2227. if (listener->incoming_list &&
  2228. (smartlist_len(listener->incoming_list) > 0))
  2229. need_to_queue = 1;
  2230. /* If we need to queue and have no queue, create one */
  2231. if (need_to_queue && !(listener->incoming_list)) {
  2232. listener->incoming_list = smartlist_new();
  2233. }
  2234. /* Bump the counter and timestamp it */
  2235. channel_listener_timestamp_active(listener);
  2236. channel_listener_timestamp_accepted(listener);
  2237. ++(listener->n_accepted);
  2238. /* If we don't need to queue, process it right away */
  2239. if (!need_to_queue) {
  2240. tor_assert(listener->listener);
  2241. listener->listener(listener, incoming);
  2242. }
  2243. /*
  2244. * Otherwise, we need to queue; queue and then process the queue if
  2245. * we can.
  2246. */
  2247. else {
  2248. tor_assert(listener->incoming_list);
  2249. smartlist_add(listener->incoming_list, incoming);
  2250. if (listener->listener) channel_listener_process_incoming(listener);
  2251. }
  2252. }
  2253. /**
  2254. * Process queued incoming cells
  2255. *
  2256. * Process as many queued cells as we can from the incoming
  2257. * cell queue.
  2258. */
  2259. void
  2260. channel_process_cells(channel_t *chan)
  2261. {
  2262. cell_queue_entry_t *q;
  2263. tor_assert(chan);
  2264. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  2265. CHANNEL_IS_OPEN(chan));
  2266. log_debug(LD_CHANNEL,
  2267. "Processing as many incoming cells as we can for channel %p",
  2268. chan);
  2269. /* Nothing we can do if we have no registered cell handlers */
  2270. if (!(chan->cell_handler ||
  2271. chan->var_cell_handler)) return;
  2272. /* Nothing we can do if we have no cells */
  2273. if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
  2274. /*
  2275. * Process cells until we're done or find one we have no current handler
  2276. * for.
  2277. *
  2278. * We must free the cells here after calling the handler, since custody
  2279. * of the buffer was given to the channel layer when they were queued;
  2280. * see comments on memory management in channel_queue_cell() and in
  2281. * channel_queue_var_cell() below.
  2282. */
  2283. while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
  2284. tor_assert(q);
  2285. tor_assert(q->type == CELL_QUEUE_FIXED ||
  2286. q->type == CELL_QUEUE_VAR);
  2287. if (q->type == CELL_QUEUE_FIXED &&
  2288. chan->cell_handler) {
  2289. /* Handle a fixed-length cell */
  2290. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2291. tor_assert(q->u.fixed.cell);
  2292. log_debug(LD_CHANNEL,
  2293. "Processing incoming cell_t %p for channel %p (global ID "
  2294. U64_FORMAT ")",
  2295. q->u.fixed.cell, chan,
  2296. U64_PRINTF_ARG(chan->global_identifier));
  2297. chan->cell_handler(chan, q->u.fixed.cell);
  2298. tor_free(q->u.fixed.cell);
  2299. tor_free(q);
  2300. } else if (q->type == CELL_QUEUE_VAR &&
  2301. chan->var_cell_handler) {
  2302. /* Handle a variable-length cell */
  2303. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2304. tor_assert(q->u.var.var_cell);
  2305. log_debug(LD_CHANNEL,
  2306. "Processing incoming var_cell_t %p for channel %p (global ID "
  2307. U64_FORMAT ")",
  2308. q->u.var.var_cell, chan,
  2309. U64_PRINTF_ARG(chan->global_identifier));
  2310. chan->var_cell_handler(chan, q->u.var.var_cell);
  2311. tor_free(q->u.var.var_cell);
  2312. tor_free(q);
  2313. } else {
  2314. /* Can't handle this one */
  2315. break;
  2316. }
  2317. }
  2318. }
  2319. /**
  2320. * Queue incoming cell
  2321. *
  2322. * This should be called by a channel_t subclass to queue an incoming fixed-
  2323. * length cell for processing, and process it if possible.
  2324. */
  2325. void
  2326. channel_queue_cell(channel_t *chan, cell_t *cell)
  2327. {
  2328. int need_to_queue = 0;
  2329. cell_queue_entry_t *q;
  2330. cell_t *cell_copy = NULL;
  2331. tor_assert(chan);
  2332. tor_assert(cell);
  2333. tor_assert(CHANNEL_IS_OPEN(chan));
  2334. /* Do we need to queue it, or can we just call the handler right away? */
  2335. if (!(chan->cell_handler)) need_to_queue = 1;
  2336. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2337. need_to_queue = 1;
  2338. /* Timestamp for receiving */
  2339. channel_timestamp_recv(chan);
  2340. /* Update the counters */
  2341. ++(chan->n_cells_recved);
  2342. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  2343. /* If we don't need to queue we can just call cell_handler */
  2344. if (!need_to_queue) {
  2345. tor_assert(chan->cell_handler);
  2346. log_debug(LD_CHANNEL,
  2347. "Directly handling incoming cell_t %p for channel %p "
  2348. "(global ID " U64_FORMAT ")",
  2349. cell, chan,
  2350. U64_PRINTF_ARG(chan->global_identifier));
  2351. chan->cell_handler(chan, cell);
  2352. } else {
  2353. /*
  2354. * Otherwise queue it and then process the queue if possible.
  2355. *
  2356. * We queue a copy, not the original pointer - it might have been on the
  2357. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2358. * if we ever have a subclass other than channel_tls_t), or be freed
  2359. * there after we return. This is the uncommon case; the non-copying
  2360. * fast path occurs in the if (!need_to_queue) case above when the
  2361. * upper layer has installed cell handlers.
  2362. */
  2363. cell_copy = tor_malloc_zero(sizeof(cell_t));
  2364. memcpy(cell_copy, cell, sizeof(cell_t));
  2365. q = cell_queue_entry_new_fixed(cell_copy);
  2366. log_debug(LD_CHANNEL,
  2367. "Queueing incoming cell_t %p for channel %p "
  2368. "(global ID " U64_FORMAT ")",
  2369. cell, chan,
  2370. U64_PRINTF_ARG(chan->global_identifier));
  2371. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2372. if (chan->cell_handler ||
  2373. chan->var_cell_handler) {
  2374. channel_process_cells(chan);
  2375. }
  2376. }
  2377. }
  2378. /**
  2379. * Queue incoming variable-length cell
  2380. *
  2381. * This should be called by a channel_t subclass to queue an incoming
  2382. * variable-length cell for processing, and process it if possible.
  2383. */
  2384. void
  2385. channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
  2386. {
  2387. int need_to_queue = 0;
  2388. cell_queue_entry_t *q;
  2389. var_cell_t *cell_copy = NULL;
  2390. tor_assert(chan);
  2391. tor_assert(var_cell);
  2392. tor_assert(CHANNEL_IS_OPEN(chan));
  2393. /* Do we need to queue it, or can we just call the handler right away? */
  2394. if (!(chan->var_cell_handler)) need_to_queue = 1;
  2395. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2396. need_to_queue = 1;
  2397. /* Timestamp for receiving */
  2398. channel_timestamp_recv(chan);
  2399. /* Update the counter */
  2400. ++(chan->n_cells_recved);
  2401. chan->n_bytes_recved += get_var_cell_header_size(chan->wide_circ_ids) +
  2402. var_cell->payload_len;
  2403. /* If we don't need to queue we can just call cell_handler */
  2404. if (!need_to_queue) {
  2405. tor_assert(chan->var_cell_handler);
  2406. log_debug(LD_CHANNEL,
  2407. "Directly handling incoming var_cell_t %p for channel %p "
  2408. "(global ID " U64_FORMAT ")",
  2409. var_cell, chan,
  2410. U64_PRINTF_ARG(chan->global_identifier));
  2411. chan->var_cell_handler(chan, var_cell);
  2412. } else {
  2413. /*
  2414. * Otherwise queue it and then process the queue if possible.
  2415. *
  2416. * We queue a copy, not the original pointer - it might have been on the
  2417. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2418. * if we ever have a subclass other than channel_tls_t), or be freed
  2419. * there after we return. This is the uncommon case; the non-copying
  2420. * fast path occurs in the if (!need_to_queue) case above when the
  2421. * upper layer has installed cell handlers.
  2422. */
  2423. cell_copy = var_cell_copy(var_cell);
  2424. q = cell_queue_entry_new_var(cell_copy);
  2425. log_debug(LD_CHANNEL,
  2426. "Queueing incoming var_cell_t %p for channel %p "
  2427. "(global ID " U64_FORMAT ")",
  2428. var_cell, chan,
  2429. U64_PRINTF_ARG(chan->global_identifier));
  2430. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2431. if (chan->cell_handler ||
  2432. chan->var_cell_handler) {
  2433. channel_process_cells(chan);
  2434. }
  2435. }
  2436. }
  2437. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  2438. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  2439. * false. */
  2440. /* XXXX Move this function. */
  2441. int
  2442. packed_cell_is_destroy(channel_t *chan,
  2443. const packed_cell_t *packed_cell,
  2444. circid_t *circid_out)
  2445. {
  2446. if (chan->wide_circ_ids) {
  2447. if (packed_cell->body[4] == CELL_DESTROY) {
  2448. *circid_out = ntohl(get_uint32(packed_cell->body));
  2449. return 1;
  2450. }
  2451. } else {
  2452. if (packed_cell->body[2] == CELL_DESTROY) {
  2453. *circid_out = ntohs(get_uint16(packed_cell->body));
  2454. return 1;
  2455. }
  2456. }
  2457. return 0;
  2458. }
  2459. /**
  2460. * Assert that the global channel stats counters are internally consistent
  2461. */
  2462. static void
  2463. channel_assert_counter_consistency(void)
  2464. {
  2465. tor_assert(n_channel_cells_queued ==
  2466. (n_channel_cells_in_queues + n_channel_cells_passed_to_lower_layer));
  2467. tor_assert(n_channel_bytes_queued ==
  2468. (n_channel_bytes_in_queues + n_channel_bytes_passed_to_lower_layer));
  2469. }
  2470. /* DOCDOC */
  2471. static int
  2472. is_destroy_cell(channel_t *chan,
  2473. const cell_queue_entry_t *q, circid_t *circid_out)
  2474. {
  2475. *circid_out = 0;
  2476. switch (q->type) {
  2477. case CELL_QUEUE_FIXED:
  2478. if (q->u.fixed.cell->command == CELL_DESTROY) {
  2479. *circid_out = q->u.fixed.cell->circ_id;
  2480. return 1;
  2481. }
  2482. break;
  2483. case CELL_QUEUE_VAR:
  2484. if (q->u.var.var_cell->command == CELL_DESTROY) {
  2485. *circid_out = q->u.var.var_cell->circ_id;
  2486. return 1;
  2487. }
  2488. break;
  2489. case CELL_QUEUE_PACKED:
  2490. return packed_cell_is_destroy(chan, q->u.packed.packed_cell, circid_out);
  2491. }
  2492. return 0;
  2493. }
  2494. /**
  2495. * Send destroy cell on a channel
  2496. *
  2497. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  2498. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  2499. * we may want to propagate reasons from other cells.
  2500. */
  2501. int
  2502. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  2503. {
  2504. tor_assert(chan);
  2505. if (circ_id == 0) {
  2506. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  2507. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2508. U64_PRINTF_ARG(chan->global_identifier),
  2509. chan, channel_state_to_string(chan->state),
  2510. chan->state);
  2511. return 0;
  2512. }
  2513. /* Check to make sure we can send on this channel first */
  2514. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  2515. channel_note_destroy_pending(chan, circ_id);
  2516. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  2517. log_debug(LD_OR,
  2518. "Sending destroy (circID %u) on channel %p "
  2519. "(global ID " U64_FORMAT ")",
  2520. (unsigned)circ_id, chan,
  2521. U64_PRINTF_ARG(chan->global_identifier));
  2522. } else {
  2523. log_warn(LD_BUG,
  2524. "Someone called channel_send_destroy() for circID %u "
  2525. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2526. (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
  2527. chan, channel_state_to_string(chan->state),
  2528. chan->state);
  2529. }
  2530. return 0;
  2531. }
  2532. /**
  2533. * Dump channel statistics to the log
  2534. *
  2535. * This is called from dumpstats() in main.c and spams the log with
  2536. * statistics on channels.
  2537. */
  2538. void
  2539. channel_dumpstats(int severity)
  2540. {
  2541. if (all_channels && smartlist_len(all_channels) > 0) {
  2542. tor_log(severity, LD_GENERAL,
  2543. "Channels have queued " U64_FORMAT " bytes in " U64_FORMAT " cells, "
  2544. "and handed " U64_FORMAT " bytes in " U64_FORMAT " cells to the lower"
  2545. " layer.",
  2546. U64_PRINTF_ARG(n_channel_bytes_queued),
  2547. U64_PRINTF_ARG(n_channel_cells_queued),
  2548. U64_PRINTF_ARG(n_channel_bytes_passed_to_lower_layer),
  2549. U64_PRINTF_ARG(n_channel_cells_passed_to_lower_layer));
  2550. tor_log(severity, LD_GENERAL,
  2551. "There are currently " U64_FORMAT " bytes in " U64_FORMAT " cells "
  2552. "in channel queues.",
  2553. U64_PRINTF_ARG(n_channel_bytes_in_queues),
  2554. U64_PRINTF_ARG(n_channel_cells_in_queues));
  2555. tor_log(severity, LD_GENERAL,
  2556. "Dumping statistics about %d channels:",
  2557. smartlist_len(all_channels));
  2558. tor_log(severity, LD_GENERAL,
  2559. "%d are active, and %d are done and waiting for cleanup",
  2560. (active_channels != NULL) ?
  2561. smartlist_len(active_channels) : 0,
  2562. (finished_channels != NULL) ?
  2563. smartlist_len(finished_channels) : 0);
  2564. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  2565. channel_dump_statistics(chan, severity));
  2566. tor_log(severity, LD_GENERAL,
  2567. "Done spamming about channels now");
  2568. } else {
  2569. tor_log(severity, LD_GENERAL,
  2570. "No channels to dump");
  2571. }
  2572. }
  2573. /**
  2574. * Dump channel listener statistics to the log
  2575. *
  2576. * This is called from dumpstats() in main.c and spams the log with
  2577. * statistics on channel listeners.
  2578. */
  2579. void
  2580. channel_listener_dumpstats(int severity)
  2581. {
  2582. if (all_listeners && smartlist_len(all_listeners) > 0) {
  2583. tor_log(severity, LD_GENERAL,
  2584. "Dumping statistics about %d channel listeners:",
  2585. smartlist_len(all_listeners));
  2586. tor_log(severity, LD_GENERAL,
  2587. "%d are active and %d are done and waiting for cleanup",
  2588. (active_listeners != NULL) ?
  2589. smartlist_len(active_listeners) : 0,
  2590. (finished_listeners != NULL) ?
  2591. smartlist_len(finished_listeners) : 0);
  2592. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  2593. channel_listener_dump_statistics(chan_l, severity));
  2594. tor_log(severity, LD_GENERAL,
  2595. "Done spamming about channel listeners now");
  2596. } else {
  2597. tor_log(severity, LD_GENERAL,
  2598. "No channel listeners to dump");
  2599. }
  2600. }
  2601. /**
  2602. * Set the cmux policy on all active channels
  2603. */
  2604. void
  2605. channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
  2606. {
  2607. if (!active_channels) return;
  2608. SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
  2609. if (curr->cmux) {
  2610. circuitmux_set_policy(curr->cmux, pol);
  2611. }
  2612. } SMARTLIST_FOREACH_END(curr);
  2613. }
  2614. /**
  2615. * Clean up channels
  2616. *
  2617. * This gets called periodically from run_scheduled_events() in main.c;
  2618. * it cleans up after closed channels.
  2619. */
  2620. void
  2621. channel_run_cleanup(void)
  2622. {
  2623. channel_t *tmp = NULL;
  2624. /* Check if we need to do anything */
  2625. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  2626. /* Iterate through finished_channels and get rid of them */
  2627. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  2628. tmp = curr;
  2629. /* Remove it from the list */
  2630. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  2631. /* Also unregister it */
  2632. channel_unregister(tmp);
  2633. /* ... and free it */
  2634. channel_free(tmp);
  2635. } SMARTLIST_FOREACH_END(curr);
  2636. }
  2637. /**
  2638. * Clean up channel listeners
  2639. *
  2640. * This gets called periodically from run_scheduled_events() in main.c;
  2641. * it cleans up after closed channel listeners.
  2642. */
  2643. void
  2644. channel_listener_run_cleanup(void)
  2645. {
  2646. channel_listener_t *tmp = NULL;
  2647. /* Check if we need to do anything */
  2648. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  2649. /* Iterate through finished_channels and get rid of them */
  2650. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  2651. tmp = curr;
  2652. /* Remove it from the list */
  2653. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  2654. /* Also unregister it */
  2655. channel_listener_unregister(tmp);
  2656. /* ... and free it */
  2657. channel_listener_free(tmp);
  2658. } SMARTLIST_FOREACH_END(curr);
  2659. }
  2660. /**
  2661. * Free a list of channels for channel_free_all()
  2662. */
  2663. static void
  2664. channel_free_list(smartlist_t *channels, int mark_for_close)
  2665. {
  2666. if (!channels) return;
  2667. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  2668. /* Deregister and free it */
  2669. tor_assert(curr);
  2670. log_debug(LD_CHANNEL,
  2671. "Cleaning up channel %p (global ID " U64_FORMAT ") "
  2672. "in state %s (%d)",
  2673. curr, U64_PRINTF_ARG(curr->global_identifier),
  2674. channel_state_to_string(curr->state), curr->state);
  2675. /* Detach circuits early so they can find the channel */
  2676. if (curr->cmux) {
  2677. circuitmux_detach_all_circuits(curr->cmux, NULL);
  2678. }
  2679. SMARTLIST_DEL_CURRENT(channels, curr);
  2680. channel_unregister(curr);
  2681. if (mark_for_close) {
  2682. if (!CHANNEL_CONDEMNED(curr)) {
  2683. channel_mark_for_close(curr);
  2684. }
  2685. channel_force_free(curr);
  2686. } else channel_free(curr);
  2687. } SMARTLIST_FOREACH_END(curr);
  2688. }
  2689. /**
  2690. * Free a list of channel listeners for channel_free_all()
  2691. */
  2692. static void
  2693. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  2694. {
  2695. if (!listeners) return;
  2696. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  2697. /* Deregister and free it */
  2698. tor_assert(curr);
  2699. log_debug(LD_CHANNEL,
  2700. "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
  2701. "in state %s (%d)",
  2702. curr, U64_PRINTF_ARG(curr->global_identifier),
  2703. channel_listener_state_to_string(curr->state), curr->state);
  2704. channel_listener_unregister(curr);
  2705. if (mark_for_close) {
  2706. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  2707. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  2708. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  2709. channel_listener_mark_for_close(curr);
  2710. }
  2711. channel_listener_force_free(curr);
  2712. } else channel_listener_free(curr);
  2713. } SMARTLIST_FOREACH_END(curr);
  2714. }
  2715. /**
  2716. * Close all channels and free everything
  2717. *
  2718. * This gets called from tor_free_all() in main.c to clean up on exit.
  2719. * It will close all registered channels and free associated storage,
  2720. * then free the all_channels, active_channels, listening_channels and
  2721. * finished_channels lists and also channel_identity_map.
  2722. */
  2723. void
  2724. channel_free_all(void)
  2725. {
  2726. log_debug(LD_CHANNEL,
  2727. "Shutting down channels...");
  2728. /* First, let's go for finished channels */
  2729. if (finished_channels) {
  2730. channel_free_list(finished_channels, 0);
  2731. smartlist_free(finished_channels);
  2732. finished_channels = NULL;
  2733. }
  2734. /* Now the finished listeners */
  2735. if (finished_listeners) {
  2736. channel_listener_free_list(finished_listeners, 0);
  2737. smartlist_free(finished_listeners);
  2738. finished_listeners = NULL;
  2739. }
  2740. /* Now all active channels */
  2741. if (active_channels) {
  2742. channel_free_list(active_channels, 1);
  2743. smartlist_free(active_channels);
  2744. active_channels = NULL;
  2745. }
  2746. /* Now all active listeners */
  2747. if (active_listeners) {
  2748. channel_listener_free_list(active_listeners, 1);
  2749. smartlist_free(active_listeners);
  2750. active_listeners = NULL;
  2751. }
  2752. /* Now all channels, in case any are left over */
  2753. if (all_channels) {
  2754. channel_free_list(all_channels, 1);
  2755. smartlist_free(all_channels);
  2756. all_channels = NULL;
  2757. }
  2758. /* Now all listeners, in case any are left over */
  2759. if (all_listeners) {
  2760. channel_listener_free_list(all_listeners, 1);
  2761. smartlist_free(all_listeners);
  2762. all_listeners = NULL;
  2763. }
  2764. /* Now free channel_identity_map */
  2765. log_debug(LD_CHANNEL,
  2766. "Freeing channel_identity_map");
  2767. /* Geez, anything still left over just won't die ... let it leak then */
  2768. HT_CLEAR(channel_idmap, &channel_identity_map);
  2769. log_debug(LD_CHANNEL,
  2770. "Done cleaning up after channels");
  2771. }
  2772. /**
  2773. * Connect to a given addr/port/digest
  2774. *
  2775. * This sets up a new outgoing channel; in the future if multiple
  2776. * channel_t subclasses are available, this is where the selection policy
  2777. * should go. It may also be desirable to fold port into tor_addr_t
  2778. * or make a new type including a tor_addr_t and port, so we have a
  2779. * single abstract object encapsulating all the protocol details of
  2780. * how to contact an OR.
  2781. */
  2782. channel_t *
  2783. channel_connect(const tor_addr_t *addr, uint16_t port,
  2784. const char *id_digest,
  2785. const ed25519_public_key_t *ed_id)
  2786. {
  2787. return channel_tls_connect(addr, port, id_digest, ed_id);
  2788. }
  2789. /**
  2790. * Decide which of two channels to prefer for extending a circuit
  2791. *
  2792. * This function is called while extending a circuit and returns true iff
  2793. * a is 'better' than b. The most important criterion here is that a
  2794. * canonical channel is always better than a non-canonical one, but the
  2795. * number of circuits and the age are used as tie-breakers.
  2796. *
  2797. * This is based on the former connection_or_is_better() of connection_or.c
  2798. */
  2799. int
  2800. channel_is_better(time_t now, channel_t *a, channel_t *b,
  2801. int forgive_new_connections)
  2802. {
  2803. int a_grace, b_grace;
  2804. int a_is_canonical, b_is_canonical;
  2805. int a_has_circs, b_has_circs;
  2806. /*
  2807. * Do not definitively deprecate a new channel with no circuits on it
  2808. * until this much time has passed.
  2809. */
  2810. #define NEW_CHAN_GRACE_PERIOD (15*60)
  2811. tor_assert(a);
  2812. tor_assert(b);
  2813. /* Check if one is canonical and the other isn't first */
  2814. a_is_canonical = channel_is_canonical(a);
  2815. b_is_canonical = channel_is_canonical(b);
  2816. if (a_is_canonical && !b_is_canonical) return 1;
  2817. if (!a_is_canonical && b_is_canonical) return 0;
  2818. /*
  2819. * Okay, if we're here they tied on canonicity. Next we check if
  2820. * they have any circuits, and if one does and the other doesn't,
  2821. * we prefer the one that does, unless we are forgiving and the
  2822. * one that has no circuits is in its grace period.
  2823. */
  2824. a_has_circs = (channel_num_circuits(a) > 0);
  2825. b_has_circs = (channel_num_circuits(b) > 0);
  2826. a_grace = (forgive_new_connections &&
  2827. (now < channel_when_created(a) + NEW_CHAN_GRACE_PERIOD));
  2828. b_grace = (forgive_new_connections &&
  2829. (now < channel_when_created(b) + NEW_CHAN_GRACE_PERIOD));
  2830. if (a_has_circs && !b_has_circs && !b_grace) return 1;
  2831. if (!a_has_circs && b_has_circs && !a_grace) return 0;
  2832. /* They tied on circuits too; just prefer whichever is newer */
  2833. if (channel_when_created(a) > channel_when_created(b)) return 1;
  2834. else return 0;
  2835. }
  2836. /**
  2837. * Get a channel to extend a circuit
  2838. *
  2839. * Pick a suitable channel to extend a circuit to given the desired digest
  2840. * the address we believe is correct for that digest; this tries to see
  2841. * if we already have one for the requested endpoint, but if there is no good
  2842. * channel, set *msg_out to a message describing the channel's state
  2843. * and our next action, and set *launch_out to a boolean indicated whether
  2844. * the caller should try to launch a new channel with channel_connect().
  2845. */
  2846. channel_t *
  2847. channel_get_for_extend(const char *rsa_id_digest,
  2848. const ed25519_public_key_t *ed_id,
  2849. const tor_addr_t *target_addr,
  2850. const char **msg_out,
  2851. int *launch_out)
  2852. {
  2853. channel_t *chan, *best = NULL;
  2854. int n_inprogress_goodaddr = 0, n_old = 0;
  2855. int n_noncanonical = 0, n_possible = 0;
  2856. time_t now = approx_time();
  2857. tor_assert(msg_out);
  2858. tor_assert(launch_out);
  2859. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2860. /* Walk the list, unrefing the old one and refing the new at each
  2861. * iteration.
  2862. */
  2863. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2864. tor_assert(tor_memeq(chan->identity_digest,
  2865. rsa_id_digest, DIGEST_LEN));
  2866. if (CHANNEL_CONDEMNED(chan))
  2867. continue;
  2868. /* Never return a channel on which the other end appears to be
  2869. * a client. */
  2870. if (channel_is_client(chan)) {
  2871. continue;
  2872. }
  2873. /* The Ed25519 key has to match too */
  2874. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  2875. continue;
  2876. }
  2877. /* Never return a non-open connection. */
  2878. if (!CHANNEL_IS_OPEN(chan)) {
  2879. /* If the address matches, don't launch a new connection for this
  2880. * circuit. */
  2881. if (channel_matches_target_addr_for_extend(chan, target_addr))
  2882. ++n_inprogress_goodaddr;
  2883. continue;
  2884. }
  2885. /* Never return a connection that shouldn't be used for circs. */
  2886. if (channel_is_bad_for_new_circs(chan)) {
  2887. ++n_old;
  2888. continue;
  2889. }
  2890. /* Never return a non-canonical connection using a recent link protocol
  2891. * if the address is not what we wanted.
  2892. *
  2893. * The channel_is_canonical_is_reliable() function asks the lower layer
  2894. * if we should trust channel_is_canonical(). The below is from the
  2895. * comments of the old circuit_or_get_for_extend() and applies when
  2896. * the lower-layer transport is channel_tls_t.
  2897. *
  2898. * (For old link protocols, we can't rely on is_canonical getting
  2899. * set properly if we're talking to the right address, since we might
  2900. * have an out-of-date descriptor, and we will get no NETINFO cell to
  2901. * tell us about the right address.)
  2902. */
  2903. if (!channel_is_canonical(chan) &&
  2904. channel_is_canonical_is_reliable(chan) &&
  2905. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  2906. ++n_noncanonical;
  2907. continue;
  2908. }
  2909. ++n_possible;
  2910. if (!best) {
  2911. best = chan; /* If we have no 'best' so far, this one is good enough. */
  2912. continue;
  2913. }
  2914. if (channel_is_better(now, chan, best, 0))
  2915. best = chan;
  2916. }
  2917. if (best) {
  2918. *msg_out = "Connection is fine; using it.";
  2919. *launch_out = 0;
  2920. return best;
  2921. } else if (n_inprogress_goodaddr) {
  2922. *msg_out = "Connection in progress; waiting.";
  2923. *launch_out = 0;
  2924. return NULL;
  2925. } else if (n_old || n_noncanonical) {
  2926. *msg_out = "Connections all too old, or too non-canonical. "
  2927. " Launching a new one.";
  2928. *launch_out = 1;
  2929. return NULL;
  2930. } else {
  2931. *msg_out = "Not connected. Connecting.";
  2932. *launch_out = 1;
  2933. return NULL;
  2934. }
  2935. }
  2936. /**
  2937. * Describe the transport subclass for a channel
  2938. *
  2939. * Invoke a method to get a string description of the lower-layer
  2940. * transport for this channel.
  2941. */
  2942. const char *
  2943. channel_describe_transport(channel_t *chan)
  2944. {
  2945. tor_assert(chan);
  2946. tor_assert(chan->describe_transport);
  2947. return chan->describe_transport(chan);
  2948. }
  2949. /**
  2950. * Describe the transport subclass for a channel listener
  2951. *
  2952. * Invoke a method to get a string description of the lower-layer
  2953. * transport for this channel listener.
  2954. */
  2955. const char *
  2956. channel_listener_describe_transport(channel_listener_t *chan_l)
  2957. {
  2958. tor_assert(chan_l);
  2959. tor_assert(chan_l->describe_transport);
  2960. return chan_l->describe_transport(chan_l);
  2961. }
  2962. /**
  2963. * Return the number of entries in <b>queue</b>
  2964. */
  2965. STATIC int
  2966. chan_cell_queue_len(const chan_cell_queue_t *queue)
  2967. {
  2968. int r = 0;
  2969. cell_queue_entry_t *cell;
  2970. TOR_SIMPLEQ_FOREACH(cell, queue, next)
  2971. ++r;
  2972. return r;
  2973. }
  2974. /**
  2975. * Dump channel statistics
  2976. *
  2977. * Dump statistics for one channel to the log
  2978. */
  2979. MOCK_IMPL(void,
  2980. channel_dump_statistics, (channel_t *chan, int severity))
  2981. {
  2982. double avg, interval, age;
  2983. time_t now = time(NULL);
  2984. tor_addr_t remote_addr;
  2985. int have_remote_addr;
  2986. char *remote_addr_str;
  2987. tor_assert(chan);
  2988. age = (double)(now - chan->timestamp_created);
  2989. tor_log(severity, LD_GENERAL,
  2990. "Channel " U64_FORMAT " (at %p) with transport %s is in state "
  2991. "%s (%d)",
  2992. U64_PRINTF_ARG(chan->global_identifier), chan,
  2993. channel_describe_transport(chan),
  2994. channel_state_to_string(chan->state), chan->state);
  2995. tor_log(severity, LD_GENERAL,
  2996. " * Channel " U64_FORMAT " was created at " U64_FORMAT
  2997. " (" U64_FORMAT " seconds ago) "
  2998. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2999. U64_PRINTF_ARG(chan->global_identifier),
  3000. U64_PRINTF_ARG(chan->timestamp_created),
  3001. U64_PRINTF_ARG(now - chan->timestamp_created),
  3002. U64_PRINTF_ARG(chan->timestamp_active),
  3003. U64_PRINTF_ARG(now - chan->timestamp_active));
  3004. /* Handle digest and nickname */
  3005. if (!tor_digest_is_zero(chan->identity_digest)) {
  3006. if (chan->nickname) {
  3007. tor_log(severity, LD_GENERAL,
  3008. " * Channel " U64_FORMAT " says it is connected "
  3009. "to an OR with digest %s and nickname %s",
  3010. U64_PRINTF_ARG(chan->global_identifier),
  3011. hex_str(chan->identity_digest, DIGEST_LEN),
  3012. chan->nickname);
  3013. } else {
  3014. tor_log(severity, LD_GENERAL,
  3015. " * Channel " U64_FORMAT " says it is connected "
  3016. "to an OR with digest %s and no known nickname",
  3017. U64_PRINTF_ARG(chan->global_identifier),
  3018. hex_str(chan->identity_digest, DIGEST_LEN));
  3019. }
  3020. } else {
  3021. if (chan->nickname) {
  3022. tor_log(severity, LD_GENERAL,
  3023. " * Channel " U64_FORMAT " does not know the digest"
  3024. " of the OR it is connected to, but reports its nickname is %s",
  3025. U64_PRINTF_ARG(chan->global_identifier),
  3026. chan->nickname);
  3027. } else {
  3028. tor_log(severity, LD_GENERAL,
  3029. " * Channel " U64_FORMAT " does not know the digest"
  3030. " or the nickname of the OR it is connected to",
  3031. U64_PRINTF_ARG(chan->global_identifier));
  3032. }
  3033. }
  3034. /* Handle remote address and descriptions */
  3035. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  3036. if (have_remote_addr) {
  3037. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3038. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  3039. tor_log(severity, LD_GENERAL,
  3040. " * Channel " U64_FORMAT " says its remote address"
  3041. " is %s, and gives a canonical description of \"%s\" and an "
  3042. "actual description of \"%s\"",
  3043. U64_PRINTF_ARG(chan->global_identifier),
  3044. safe_str(remote_addr_str),
  3045. safe_str(channel_get_canonical_remote_descr(chan)),
  3046. safe_str(actual));
  3047. tor_free(remote_addr_str);
  3048. tor_free(actual);
  3049. } else {
  3050. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3051. tor_log(severity, LD_GENERAL,
  3052. " * Channel " U64_FORMAT " does not know its remote "
  3053. "address, but gives a canonical description of \"%s\" and an "
  3054. "actual description of \"%s\"",
  3055. U64_PRINTF_ARG(chan->global_identifier),
  3056. channel_get_canonical_remote_descr(chan),
  3057. actual);
  3058. tor_free(actual);
  3059. }
  3060. /* Handle marks */
  3061. tor_log(severity, LD_GENERAL,
  3062. " * Channel " U64_FORMAT " has these marks: %s %s %s "
  3063. "%s %s %s",
  3064. U64_PRINTF_ARG(chan->global_identifier),
  3065. channel_is_bad_for_new_circs(chan) ?
  3066. "bad_for_new_circs" : "!bad_for_new_circs",
  3067. channel_is_canonical(chan) ?
  3068. "canonical" : "!canonical",
  3069. channel_is_canonical_is_reliable(chan) ?
  3070. "is_canonical_is_reliable" :
  3071. "!is_canonical_is_reliable",
  3072. channel_is_client(chan) ?
  3073. "client" : "!client",
  3074. channel_is_local(chan) ?
  3075. "local" : "!local",
  3076. channel_is_incoming(chan) ?
  3077. "incoming" : "outgoing");
  3078. /* Describe queues */
  3079. tor_log(severity, LD_GENERAL,
  3080. " * Channel " U64_FORMAT " has %d queued incoming cells"
  3081. " and %d queued outgoing cells",
  3082. U64_PRINTF_ARG(chan->global_identifier),
  3083. chan_cell_queue_len(&chan->incoming_queue),
  3084. chan_cell_queue_len(&chan->outgoing_queue));
  3085. /* Describe circuits */
  3086. tor_log(severity, LD_GENERAL,
  3087. " * Channel " U64_FORMAT " has %d active circuits out of"
  3088. " %d in total",
  3089. U64_PRINTF_ARG(chan->global_identifier),
  3090. (chan->cmux != NULL) ?
  3091. circuitmux_num_active_circuits(chan->cmux) : 0,
  3092. (chan->cmux != NULL) ?
  3093. circuitmux_num_circuits(chan->cmux) : 0);
  3094. /* Describe timestamps */
  3095. tor_log(severity, LD_GENERAL,
  3096. " * Channel " U64_FORMAT " was last used by a "
  3097. "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3098. U64_PRINTF_ARG(chan->global_identifier),
  3099. U64_PRINTF_ARG(chan->timestamp_client),
  3100. U64_PRINTF_ARG(now - chan->timestamp_client));
  3101. tor_log(severity, LD_GENERAL,
  3102. " * Channel " U64_FORMAT " was last drained at "
  3103. U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3104. U64_PRINTF_ARG(chan->global_identifier),
  3105. U64_PRINTF_ARG(chan->timestamp_drained),
  3106. U64_PRINTF_ARG(now - chan->timestamp_drained));
  3107. tor_log(severity, LD_GENERAL,
  3108. " * Channel " U64_FORMAT " last received a cell "
  3109. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3110. U64_PRINTF_ARG(chan->global_identifier),
  3111. U64_PRINTF_ARG(chan->timestamp_recv),
  3112. U64_PRINTF_ARG(now - chan->timestamp_recv));
  3113. tor_log(severity, LD_GENERAL,
  3114. " * Channel " U64_FORMAT " last transmitted a cell "
  3115. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3116. U64_PRINTF_ARG(chan->global_identifier),
  3117. U64_PRINTF_ARG(chan->timestamp_xmit),
  3118. U64_PRINTF_ARG(now - chan->timestamp_xmit));
  3119. /* Describe counters and rates */
  3120. tor_log(severity, LD_GENERAL,
  3121. " * Channel " U64_FORMAT " has received "
  3122. U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
  3123. U64_FORMAT " bytes in " U64_FORMAT " cells",
  3124. U64_PRINTF_ARG(chan->global_identifier),
  3125. U64_PRINTF_ARG(chan->n_bytes_recved),
  3126. U64_PRINTF_ARG(chan->n_cells_recved),
  3127. U64_PRINTF_ARG(chan->n_bytes_xmitted),
  3128. U64_PRINTF_ARG(chan->n_cells_xmitted));
  3129. if (now > chan->timestamp_created &&
  3130. chan->timestamp_created > 0) {
  3131. if (chan->n_bytes_recved > 0) {
  3132. avg = (double)(chan->n_bytes_recved) / age;
  3133. tor_log(severity, LD_GENERAL,
  3134. " * Channel " U64_FORMAT " has averaged %f "
  3135. "bytes received per second",
  3136. U64_PRINTF_ARG(chan->global_identifier), avg);
  3137. }
  3138. if (chan->n_cells_recved > 0) {
  3139. avg = (double)(chan->n_cells_recved) / age;
  3140. if (avg >= 1.0) {
  3141. tor_log(severity, LD_GENERAL,
  3142. " * Channel " U64_FORMAT " has averaged %f "
  3143. "cells received per second",
  3144. U64_PRINTF_ARG(chan->global_identifier), avg);
  3145. } else if (avg >= 0.0) {
  3146. interval = 1.0 / avg;
  3147. tor_log(severity, LD_GENERAL,
  3148. " * Channel " U64_FORMAT " has averaged %f "
  3149. "seconds between received cells",
  3150. U64_PRINTF_ARG(chan->global_identifier), interval);
  3151. }
  3152. }
  3153. if (chan->n_bytes_xmitted > 0) {
  3154. avg = (double)(chan->n_bytes_xmitted) / age;
  3155. tor_log(severity, LD_GENERAL,
  3156. " * Channel " U64_FORMAT " has averaged %f "
  3157. "bytes transmitted per second",
  3158. U64_PRINTF_ARG(chan->global_identifier), avg);
  3159. }
  3160. if (chan->n_cells_xmitted > 0) {
  3161. avg = (double)(chan->n_cells_xmitted) / age;
  3162. if (avg >= 1.0) {
  3163. tor_log(severity, LD_GENERAL,
  3164. " * Channel " U64_FORMAT " has averaged %f "
  3165. "cells transmitted per second",
  3166. U64_PRINTF_ARG(chan->global_identifier), avg);
  3167. } else if (avg >= 0.0) {
  3168. interval = 1.0 / avg;
  3169. tor_log(severity, LD_GENERAL,
  3170. " * Channel " U64_FORMAT " has averaged %f "
  3171. "seconds between transmitted cells",
  3172. U64_PRINTF_ARG(chan->global_identifier), interval);
  3173. }
  3174. }
  3175. }
  3176. /* Dump anything the lower layer has to say */
  3177. channel_dump_transport_statistics(chan, severity);
  3178. }
  3179. /**
  3180. * Dump channel listener statistics
  3181. *
  3182. * Dump statistics for one channel listener to the log
  3183. */
  3184. void
  3185. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  3186. {
  3187. double avg, interval, age;
  3188. time_t now = time(NULL);
  3189. tor_assert(chan_l);
  3190. age = (double)(now - chan_l->timestamp_created);
  3191. tor_log(severity, LD_GENERAL,
  3192. "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
  3193. "state %s (%d)",
  3194. U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
  3195. channel_listener_describe_transport(chan_l),
  3196. channel_listener_state_to_string(chan_l->state), chan_l->state);
  3197. tor_log(severity, LD_GENERAL,
  3198. " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
  3199. " (" U64_FORMAT " seconds ago) "
  3200. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3201. U64_PRINTF_ARG(chan_l->global_identifier),
  3202. U64_PRINTF_ARG(chan_l->timestamp_created),
  3203. U64_PRINTF_ARG(now - chan_l->timestamp_created),
  3204. U64_PRINTF_ARG(chan_l->timestamp_active),
  3205. U64_PRINTF_ARG(now - chan_l->timestamp_active));
  3206. tor_log(severity, LD_GENERAL,
  3207. " * Channel listener " U64_FORMAT " last accepted an incoming "
  3208. "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
  3209. "and has accepted " U64_FORMAT " channels in total",
  3210. U64_PRINTF_ARG(chan_l->global_identifier),
  3211. U64_PRINTF_ARG(chan_l->timestamp_accepted),
  3212. U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
  3213. U64_PRINTF_ARG(chan_l->n_accepted));
  3214. /*
  3215. * If it's sensible to do so, get the rate of incoming channels on this
  3216. * listener
  3217. */
  3218. if (now > chan_l->timestamp_created &&
  3219. chan_l->timestamp_created > 0 &&
  3220. chan_l->n_accepted > 0) {
  3221. avg = (double)(chan_l->n_accepted) / age;
  3222. if (avg >= 1.0) {
  3223. tor_log(severity, LD_GENERAL,
  3224. " * Channel listener " U64_FORMAT " has averaged %f incoming "
  3225. "channels per second",
  3226. U64_PRINTF_ARG(chan_l->global_identifier), avg);
  3227. } else if (avg >= 0.0) {
  3228. interval = 1.0 / avg;
  3229. tor_log(severity, LD_GENERAL,
  3230. " * Channel listener " U64_FORMAT " has averaged %f seconds "
  3231. "between incoming channels",
  3232. U64_PRINTF_ARG(chan_l->global_identifier), interval);
  3233. }
  3234. }
  3235. /* Dump anything the lower layer has to say */
  3236. channel_listener_dump_transport_statistics(chan_l, severity);
  3237. }
  3238. /**
  3239. * Invoke transport-specific stats dump for channel
  3240. *
  3241. * If there is a lower-layer statistics dump method, invoke it
  3242. */
  3243. void
  3244. channel_dump_transport_statistics(channel_t *chan, int severity)
  3245. {
  3246. tor_assert(chan);
  3247. if (chan->dumpstats) chan->dumpstats(chan, severity);
  3248. }
  3249. /**
  3250. * Invoke transport-specific stats dump for channel listener
  3251. *
  3252. * If there is a lower-layer statistics dump method, invoke it
  3253. */
  3254. void
  3255. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  3256. int severity)
  3257. {
  3258. tor_assert(chan_l);
  3259. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  3260. }
  3261. /**
  3262. * Return text description of the remote endpoint
  3263. *
  3264. * This function return a test provided by the lower layer of the remote
  3265. * endpoint for this channel; it should specify the actual address connected
  3266. * to/from.
  3267. *
  3268. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3269. * may invalidate the return value from this function.
  3270. */
  3271. const char *
  3272. channel_get_actual_remote_descr(channel_t *chan)
  3273. {
  3274. tor_assert(chan);
  3275. tor_assert(chan->get_remote_descr);
  3276. /* Param 1 indicates the actual description */
  3277. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  3278. }
  3279. /**
  3280. * Return the text address of the remote endpoint.
  3281. *
  3282. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3283. * may invalidate the return value from this function.
  3284. */
  3285. const char *
  3286. channel_get_actual_remote_address(channel_t *chan)
  3287. {
  3288. /* Param 1 indicates the actual description */
  3289. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  3290. }
  3291. /**
  3292. * Return text description of the remote endpoint canonical address
  3293. *
  3294. * This function return a test provided by the lower layer of the remote
  3295. * endpoint for this channel; it should use the known canonical address for
  3296. * this OR's identity digest if possible.
  3297. *
  3298. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3299. * may invalidate the return value from this function.
  3300. */
  3301. const char *
  3302. channel_get_canonical_remote_descr(channel_t *chan)
  3303. {
  3304. tor_assert(chan);
  3305. tor_assert(chan->get_remote_descr);
  3306. /* Param 0 indicates the canonicalized description */
  3307. return chan->get_remote_descr(chan, 0);
  3308. }
  3309. /**
  3310. * Get remote address if possible.
  3311. *
  3312. * Write the remote address out to a tor_addr_t if the underlying transport
  3313. * supports this operation, and return 1. Return 0 if the underlying transport
  3314. * doesn't let us do this.
  3315. */
  3316. int
  3317. channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
  3318. {
  3319. tor_assert(chan);
  3320. tor_assert(addr_out);
  3321. if (chan->get_remote_addr)
  3322. return chan->get_remote_addr(chan, addr_out);
  3323. /* Else no support, method not implemented */
  3324. else return 0;
  3325. }
  3326. /**
  3327. * Check if there are outgoing queue writes on this channel
  3328. *
  3329. * Indicate if either we have queued cells, or if not, whether the underlying
  3330. * lower-layer transport thinks it has an output queue.
  3331. */
  3332. int
  3333. channel_has_queued_writes(channel_t *chan)
  3334. {
  3335. int has_writes = 0;
  3336. tor_assert(chan);
  3337. tor_assert(chan->has_queued_writes);
  3338. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  3339. has_writes = 1;
  3340. } else {
  3341. /* Check with the lower layer */
  3342. has_writes = chan->has_queued_writes(chan);
  3343. }
  3344. return has_writes;
  3345. }
  3346. /**
  3347. * Check the is_bad_for_new_circs flag
  3348. *
  3349. * This function returns the is_bad_for_new_circs flag of the specified
  3350. * channel.
  3351. */
  3352. int
  3353. channel_is_bad_for_new_circs(channel_t *chan)
  3354. {
  3355. tor_assert(chan);
  3356. return chan->is_bad_for_new_circs;
  3357. }
  3358. /**
  3359. * Mark a channel as bad for new circuits
  3360. *
  3361. * Set the is_bad_for_new_circs_flag on chan.
  3362. */
  3363. void
  3364. channel_mark_bad_for_new_circs(channel_t *chan)
  3365. {
  3366. tor_assert(chan);
  3367. chan->is_bad_for_new_circs = 1;
  3368. }
  3369. /**
  3370. * Get the client flag
  3371. *
  3372. * This returns the client flag of a channel, which will be set if
  3373. * command_process_create_cell() in command.c thinks this is a connection
  3374. * from a client.
  3375. */
  3376. int
  3377. channel_is_client(channel_t *chan)
  3378. {
  3379. tor_assert(chan);
  3380. return chan->is_client;
  3381. }
  3382. /**
  3383. * Set the client flag
  3384. *
  3385. * Mark a channel as being from a client
  3386. */
  3387. void
  3388. channel_mark_client(channel_t *chan)
  3389. {
  3390. tor_assert(chan);
  3391. chan->is_client = 1;
  3392. }
  3393. /**
  3394. * Get the canonical flag for a channel
  3395. *
  3396. * This returns the is_canonical for a channel; this flag is determined by
  3397. * the lower layer and can't be set in a transport-independent way.
  3398. */
  3399. int
  3400. channel_is_canonical(channel_t *chan)
  3401. {
  3402. tor_assert(chan);
  3403. tor_assert(chan->is_canonical);
  3404. return chan->is_canonical(chan, 0);
  3405. }
  3406. /**
  3407. * Test if the canonical flag is reliable
  3408. *
  3409. * This function asks if the lower layer thinks it's safe to trust the
  3410. * result of channel_is_canonical()
  3411. */
  3412. int
  3413. channel_is_canonical_is_reliable(channel_t *chan)
  3414. {
  3415. tor_assert(chan);
  3416. tor_assert(chan->is_canonical);
  3417. return chan->is_canonical(chan, 1);
  3418. }
  3419. /**
  3420. * Test incoming flag
  3421. *
  3422. * This function gets the incoming flag; this is set when a listener spawns
  3423. * a channel. If this returns true the channel was remotely initiated.
  3424. */
  3425. int
  3426. channel_is_incoming(channel_t *chan)
  3427. {
  3428. tor_assert(chan);
  3429. return chan->is_incoming;
  3430. }
  3431. /**
  3432. * Set the incoming flag
  3433. *
  3434. * This function is called when a channel arrives on a listening channel
  3435. * to mark it as incoming.
  3436. */
  3437. void
  3438. channel_mark_incoming(channel_t *chan)
  3439. {
  3440. tor_assert(chan);
  3441. chan->is_incoming = 1;
  3442. }
  3443. /**
  3444. * Test local flag
  3445. *
  3446. * This function gets the local flag; the lower layer should set this when
  3447. * setting up the channel if is_local_addr() is true for all of the
  3448. * destinations it will communicate with on behalf of this channel. It's
  3449. * used to decide whether to declare the network reachable when seeing incoming
  3450. * traffic on the channel.
  3451. */
  3452. int
  3453. channel_is_local(channel_t *chan)
  3454. {
  3455. tor_assert(chan);
  3456. return chan->is_local;
  3457. }
  3458. /**
  3459. * Set the local flag
  3460. *
  3461. * This internal-only function should be called by the lower layer if the
  3462. * channel is to a local address. See channel_is_local() above or the
  3463. * description of the is_local bit in channel.h
  3464. */
  3465. void
  3466. channel_mark_local(channel_t *chan)
  3467. {
  3468. tor_assert(chan);
  3469. chan->is_local = 1;
  3470. }
  3471. /**
  3472. * Mark a channel as remote
  3473. *
  3474. * This internal-only function should be called by the lower layer if the
  3475. * channel is not to a local address but has previously been marked local.
  3476. * See channel_is_local() above or the description of the is_local bit in
  3477. * channel.h
  3478. */
  3479. void
  3480. channel_mark_remote(channel_t *chan)
  3481. {
  3482. tor_assert(chan);
  3483. chan->is_local = 0;
  3484. }
  3485. /**
  3486. * Test outgoing flag
  3487. *
  3488. * This function gets the outgoing flag; this is the inverse of the incoming
  3489. * bit set when a listener spawns a channel. If this returns true the channel
  3490. * was locally initiated.
  3491. */
  3492. int
  3493. channel_is_outgoing(channel_t *chan)
  3494. {
  3495. tor_assert(chan);
  3496. return !(chan->is_incoming);
  3497. }
  3498. /**
  3499. * Mark a channel as outgoing
  3500. *
  3501. * This function clears the incoming flag and thus marks a channel as
  3502. * outgoing.
  3503. */
  3504. void
  3505. channel_mark_outgoing(channel_t *chan)
  3506. {
  3507. tor_assert(chan);
  3508. chan->is_incoming = 0;
  3509. }
  3510. /************************
  3511. * Flow control queries *
  3512. ***********************/
  3513. /*
  3514. * Get the latest estimate for the total queue size of all open channels
  3515. */
  3516. uint64_t
  3517. channel_get_global_queue_estimate(void)
  3518. {
  3519. return estimated_total_queue_size;
  3520. }
  3521. /*
  3522. * Estimate the number of writeable cells
  3523. *
  3524. * Ask the lower layer for an estimate of how many cells it can accept, and
  3525. * then subtract the length of our outgoing_queue, if any, to produce an
  3526. * estimate of the number of cells this channel can accept for writes.
  3527. */
  3528. int
  3529. channel_num_cells_writeable(channel_t *chan)
  3530. {
  3531. int result;
  3532. tor_assert(chan);
  3533. tor_assert(chan->num_cells_writeable);
  3534. if (chan->state == CHANNEL_STATE_OPEN) {
  3535. /* Query lower layer */
  3536. result = chan->num_cells_writeable(chan);
  3537. /* Subtract cell queue length, if any */
  3538. result -= chan_cell_queue_len(&chan->outgoing_queue);
  3539. if (result < 0) result = 0;
  3540. } else {
  3541. /* No cells are writeable in any other state */
  3542. result = 0;
  3543. }
  3544. return result;
  3545. }
  3546. /*********************
  3547. * Timestamp updates *
  3548. ********************/
  3549. /**
  3550. * Update the created timestamp for a channel
  3551. *
  3552. * This updates the channel's created timestamp and should only be called
  3553. * from channel_init().
  3554. */
  3555. void
  3556. channel_timestamp_created(channel_t *chan)
  3557. {
  3558. time_t now = time(NULL);
  3559. tor_assert(chan);
  3560. chan->timestamp_created = now;
  3561. }
  3562. /**
  3563. * Update the created timestamp for a channel listener
  3564. *
  3565. * This updates the channel listener's created timestamp and should only be
  3566. * called from channel_init_listener().
  3567. */
  3568. void
  3569. channel_listener_timestamp_created(channel_listener_t *chan_l)
  3570. {
  3571. time_t now = time(NULL);
  3572. tor_assert(chan_l);
  3573. chan_l->timestamp_created = now;
  3574. }
  3575. /**
  3576. * Update the last active timestamp for a channel
  3577. *
  3578. * This function updates the channel's last active timestamp; it should be
  3579. * called by the lower layer whenever there is activity on the channel which
  3580. * does not lead to a cell being transmitted or received; the active timestamp
  3581. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  3582. * but it should be updated for things like the v3 handshake and stuff that
  3583. * produce activity only visible to the lower layer.
  3584. */
  3585. void
  3586. channel_timestamp_active(channel_t *chan)
  3587. {
  3588. time_t now = time(NULL);
  3589. tor_assert(chan);
  3590. chan->timestamp_active = now;
  3591. }
  3592. /**
  3593. * Update the last active timestamp for a channel listener
  3594. */
  3595. void
  3596. channel_listener_timestamp_active(channel_listener_t *chan_l)
  3597. {
  3598. time_t now = time(NULL);
  3599. tor_assert(chan_l);
  3600. chan_l->timestamp_active = now;
  3601. }
  3602. /**
  3603. * Update the last accepted timestamp.
  3604. *
  3605. * This function updates the channel listener's last accepted timestamp; it
  3606. * should be called whenever a new incoming channel is accepted on a
  3607. * listener.
  3608. */
  3609. void
  3610. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  3611. {
  3612. time_t now = time(NULL);
  3613. tor_assert(chan_l);
  3614. chan_l->timestamp_active = now;
  3615. chan_l->timestamp_accepted = now;
  3616. }
  3617. /**
  3618. * Update client timestamp
  3619. *
  3620. * This function is called by relay.c to timestamp a channel that appears to
  3621. * be used as a client.
  3622. */
  3623. void
  3624. channel_timestamp_client(channel_t *chan)
  3625. {
  3626. time_t now = time(NULL);
  3627. tor_assert(chan);
  3628. chan->timestamp_client = now;
  3629. }
  3630. /**
  3631. * Update the last drained timestamp
  3632. *
  3633. * This is called whenever we transmit a cell which leaves the outgoing cell
  3634. * queue completely empty. It also updates the xmit time and the active time.
  3635. */
  3636. void
  3637. channel_timestamp_drained(channel_t *chan)
  3638. {
  3639. time_t now = time(NULL);
  3640. tor_assert(chan);
  3641. chan->timestamp_active = now;
  3642. chan->timestamp_drained = now;
  3643. chan->timestamp_xmit = now;
  3644. }
  3645. /**
  3646. * Update the recv timestamp
  3647. *
  3648. * This is called whenever we get an incoming cell from the lower layer.
  3649. * This also updates the active timestamp.
  3650. */
  3651. void
  3652. channel_timestamp_recv(channel_t *chan)
  3653. {
  3654. time_t now = time(NULL);
  3655. tor_assert(chan);
  3656. chan->timestamp_active = now;
  3657. chan->timestamp_recv = now;
  3658. }
  3659. /**
  3660. * Update the xmit timestamp
  3661. * This is called whenever we pass an outgoing cell to the lower layer. This
  3662. * also updates the active timestamp.
  3663. */
  3664. void
  3665. channel_timestamp_xmit(channel_t *chan)
  3666. {
  3667. time_t now = time(NULL);
  3668. tor_assert(chan);
  3669. chan->timestamp_active = now;
  3670. chan->timestamp_xmit = now;
  3671. }
  3672. /***************************************************************
  3673. * Timestamp queries - see above for definitions of timestamps *
  3674. **************************************************************/
  3675. /**
  3676. * Query created timestamp for a channel
  3677. */
  3678. time_t
  3679. channel_when_created(channel_t *chan)
  3680. {
  3681. tor_assert(chan);
  3682. return chan->timestamp_created;
  3683. }
  3684. /**
  3685. * Query created timestamp for a channel listener
  3686. */
  3687. time_t
  3688. channel_listener_when_created(channel_listener_t *chan_l)
  3689. {
  3690. tor_assert(chan_l);
  3691. return chan_l->timestamp_created;
  3692. }
  3693. /**
  3694. * Query last active timestamp for a channel
  3695. */
  3696. time_t
  3697. channel_when_last_active(channel_t *chan)
  3698. {
  3699. tor_assert(chan);
  3700. return chan->timestamp_active;
  3701. }
  3702. /**
  3703. * Query last active timestamp for a channel listener
  3704. */
  3705. time_t
  3706. channel_listener_when_last_active(channel_listener_t *chan_l)
  3707. {
  3708. tor_assert(chan_l);
  3709. return chan_l->timestamp_active;
  3710. }
  3711. /**
  3712. * Query last accepted timestamp for a channel listener
  3713. */
  3714. time_t
  3715. channel_listener_when_last_accepted(channel_listener_t *chan_l)
  3716. {
  3717. tor_assert(chan_l);
  3718. return chan_l->timestamp_accepted;
  3719. }
  3720. /**
  3721. * Query client timestamp
  3722. */
  3723. time_t
  3724. channel_when_last_client(channel_t *chan)
  3725. {
  3726. tor_assert(chan);
  3727. return chan->timestamp_client;
  3728. }
  3729. /**
  3730. * Query drained timestamp
  3731. */
  3732. time_t
  3733. channel_when_last_drained(channel_t *chan)
  3734. {
  3735. tor_assert(chan);
  3736. return chan->timestamp_drained;
  3737. }
  3738. /**
  3739. * Query recv timestamp
  3740. */
  3741. time_t
  3742. channel_when_last_recv(channel_t *chan)
  3743. {
  3744. tor_assert(chan);
  3745. return chan->timestamp_recv;
  3746. }
  3747. /**
  3748. * Query xmit timestamp
  3749. */
  3750. time_t
  3751. channel_when_last_xmit(channel_t *chan)
  3752. {
  3753. tor_assert(chan);
  3754. return chan->timestamp_xmit;
  3755. }
  3756. /**
  3757. * Query accepted counter
  3758. */
  3759. uint64_t
  3760. channel_listener_count_accepted(channel_listener_t *chan_l)
  3761. {
  3762. tor_assert(chan_l);
  3763. return chan_l->n_accepted;
  3764. }
  3765. /**
  3766. * Query received cell counter
  3767. */
  3768. uint64_t
  3769. channel_count_recved(channel_t *chan)
  3770. {
  3771. tor_assert(chan);
  3772. return chan->n_cells_recved;
  3773. }
  3774. /**
  3775. * Query transmitted cell counter
  3776. */
  3777. uint64_t
  3778. channel_count_xmitted(channel_t *chan)
  3779. {
  3780. tor_assert(chan);
  3781. return chan->n_cells_xmitted;
  3782. }
  3783. /**
  3784. * Check if a channel matches an extend_info_t
  3785. *
  3786. * This function calls the lower layer and asks if this channel matches a
  3787. * given extend_info_t.
  3788. */
  3789. int
  3790. channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
  3791. {
  3792. tor_assert(chan);
  3793. tor_assert(chan->matches_extend_info);
  3794. tor_assert(extend_info);
  3795. return chan->matches_extend_info(chan, extend_info);
  3796. }
  3797. /**
  3798. * Check if a channel matches a given target address; return true iff we do.
  3799. *
  3800. * This function calls into the lower layer and asks if this channel thinks
  3801. * it matches a given target address for circuit extension purposes.
  3802. */
  3803. int
  3804. channel_matches_target_addr_for_extend(channel_t *chan,
  3805. const tor_addr_t *target)
  3806. {
  3807. tor_assert(chan);
  3808. tor_assert(chan->matches_target);
  3809. tor_assert(target);
  3810. return chan->matches_target(chan, target);
  3811. }
  3812. /**
  3813. * Return the total number of circuits used by a channel
  3814. *
  3815. * @param chan Channel to query
  3816. * @return Number of circuits using this as n_chan or p_chan
  3817. */
  3818. unsigned int
  3819. channel_num_circuits(channel_t *chan)
  3820. {
  3821. tor_assert(chan);
  3822. return chan->num_n_circuits +
  3823. chan->num_p_circuits;
  3824. }
  3825. /**
  3826. * Set up circuit ID generation
  3827. *
  3828. * This is called when setting up a channel and replaces the old
  3829. * connection_or_set_circid_type()
  3830. */
  3831. MOCK_IMPL(void,
  3832. channel_set_circid_type,(channel_t *chan,
  3833. crypto_pk_t *identity_rcvd,
  3834. int consider_identity))
  3835. {
  3836. int started_here;
  3837. crypto_pk_t *our_identity;
  3838. tor_assert(chan);
  3839. started_here = channel_is_outgoing(chan);
  3840. if (! consider_identity) {
  3841. if (started_here)
  3842. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3843. else
  3844. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3845. return;
  3846. }
  3847. our_identity = started_here ?
  3848. get_tlsclient_identity_key() : get_server_identity_key();
  3849. if (identity_rcvd) {
  3850. if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
  3851. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3852. } else {
  3853. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3854. }
  3855. } else {
  3856. chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
  3857. }
  3858. }
  3859. /** Helper for channel_update_bad_for_new_circs(): Perform the
  3860. * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
  3861. * all of which MUST have the same RSA ID. (They MAY have different
  3862. * Ed25519 IDs.) */
  3863. static void
  3864. channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
  3865. {
  3866. /*XXXX This function should really be about channels. 15056 */
  3867. channel_t *chan;
  3868. /* First, get a minimal list of the ed25519 identites */
  3869. smartlist_t *ed_identities = smartlist_new();
  3870. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  3871. uint8_t *id_copy =
  3872. tor_memdup(&chan->ed25519_identity.pubkey, DIGEST256_LEN);
  3873. smartlist_add(ed_identities, id_copy);
  3874. }
  3875. smartlist_sort_digests256(ed_identities);
  3876. smartlist_uniq_digests256(ed_identities);
  3877. /* Now, for each Ed identity, build a smartlist and find the best entry on
  3878. * it. */
  3879. smartlist_t *or_conns = smartlist_new();
  3880. SMARTLIST_FOREACH_BEGIN(ed_identities, const uint8_t *, ed_id) {
  3881. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  3882. channel_tls_t *chantls = BASE_CHAN_TO_TLS(chan);
  3883. if (tor_memneq(ed_id, &chan->ed25519_identity.pubkey, DIGEST256_LEN))
  3884. continue;
  3885. or_connection_t *orconn = chantls->conn;
  3886. if (orconn) {
  3887. tor_assert(orconn->chan == chantls);
  3888. smartlist_add(or_conns, orconn);
  3889. }
  3890. }
  3891. connection_or_group_set_badness_(or_conns, force);
  3892. smartlist_clear(or_conns);
  3893. } SMARTLIST_FOREACH_END(ed_id);
  3894. /* XXXX 15056 we may want to do something special with connections that have
  3895. * no set Ed25519 identity! */
  3896. smartlist_free(or_conns);
  3897. SMARTLIST_FOREACH(ed_identities, uint8_t *, ed_id, tor_free(ed_id));
  3898. smartlist_free(ed_identities);
  3899. }
  3900. /** Go through all the channels (or if <b>digest</b> is non-NULL, just
  3901. * the OR connections with that digest), and set the is_bad_for_new_circs
  3902. * flag based on the rules in connection_or_group_set_badness() (or just
  3903. * always set it if <b>force</b> is true).
  3904. */
  3905. void
  3906. channel_update_bad_for_new_circs(const char *digest, int force)
  3907. {
  3908. if (digest) {
  3909. channel_idmap_entry_t *ent;
  3910. channel_idmap_entry_t search;
  3911. memset(&search, 0, sizeof(search));
  3912. memcpy(search.digest, digest, DIGEST_LEN);
  3913. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  3914. if (ent) {
  3915. channel_rsa_id_group_set_badness(&ent->channel_list, force);
  3916. }
  3917. return;
  3918. }
  3919. /* no digest; just look at everything. */
  3920. channel_idmap_entry_t **iter;
  3921. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  3922. channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
  3923. }
  3924. }
  3925. /**
  3926. * Update the estimated number of bytes queued to transmit for this channel,
  3927. * and notify the scheduler. The estimate includes both the channel queue and
  3928. * the queue size reported by the lower layer, and an overhead estimate
  3929. * optionally provided by the lower layer.
  3930. */
  3931. void
  3932. channel_update_xmit_queue_size(channel_t *chan)
  3933. {
  3934. uint64_t queued, adj;
  3935. double overhead;
  3936. tor_assert(chan);
  3937. tor_assert(chan->num_bytes_queued);
  3938. /*
  3939. * First, get the number of bytes we have queued without factoring in
  3940. * lower-layer overhead.
  3941. */
  3942. queued = chan->num_bytes_queued(chan) + chan->bytes_in_queue;
  3943. /* Next, adjust by the overhead factor, if any is available */
  3944. if (chan->get_overhead_estimate) {
  3945. overhead = chan->get_overhead_estimate(chan);
  3946. if (overhead >= 1.0) {
  3947. queued = (uint64_t)(queued * overhead);
  3948. } else {
  3949. /* Ignore silly overhead factors */
  3950. log_notice(LD_CHANNEL, "Ignoring silly overhead factor %f", overhead);
  3951. }
  3952. }
  3953. /* Now, compare to the previous estimate */
  3954. if (queued > chan->bytes_queued_for_xmit) {
  3955. adj = queued - chan->bytes_queued_for_xmit;
  3956. log_debug(LD_CHANNEL,
  3957. "Increasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  3958. " from " U64_FORMAT " to " U64_FORMAT,
  3959. U64_PRINTF_ARG(chan->global_identifier),
  3960. U64_PRINTF_ARG(adj),
  3961. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  3962. U64_PRINTF_ARG(queued));
  3963. /* Update the channel's estimate */
  3964. chan->bytes_queued_for_xmit = queued;
  3965. /* Update the global queue size estimate if appropriate */
  3966. if (chan->state == CHANNEL_STATE_OPEN ||
  3967. chan->state == CHANNEL_STATE_MAINT) {
  3968. estimated_total_queue_size += adj;
  3969. log_debug(LD_CHANNEL,
  3970. "Increasing global queue size by " U64_FORMAT " for channel "
  3971. U64_FORMAT ", new size is " U64_FORMAT,
  3972. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  3973. U64_PRINTF_ARG(estimated_total_queue_size));
  3974. /* Tell the scheduler we're increasing the queue size */
  3975. scheduler_adjust_queue_size(chan, 1, adj);
  3976. }
  3977. } else if (queued < chan->bytes_queued_for_xmit) {
  3978. adj = chan->bytes_queued_for_xmit - queued;
  3979. log_debug(LD_CHANNEL,
  3980. "Decreasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  3981. " from " U64_FORMAT " to " U64_FORMAT,
  3982. U64_PRINTF_ARG(chan->global_identifier),
  3983. U64_PRINTF_ARG(adj),
  3984. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  3985. U64_PRINTF_ARG(queued));
  3986. /* Update the channel's estimate */
  3987. chan->bytes_queued_for_xmit = queued;
  3988. /* Update the global queue size estimate if appropriate */
  3989. if (chan->state == CHANNEL_STATE_OPEN ||
  3990. chan->state == CHANNEL_STATE_MAINT) {
  3991. estimated_total_queue_size -= adj;
  3992. log_debug(LD_CHANNEL,
  3993. "Decreasing global queue size by " U64_FORMAT " for channel "
  3994. U64_FORMAT ", new size is " U64_FORMAT,
  3995. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  3996. U64_PRINTF_ARG(estimated_total_queue_size));
  3997. /* Tell the scheduler we're decreasing the queue size */
  3998. scheduler_adjust_queue_size(chan, -1, adj);
  3999. }
  4000. }
  4001. }