channel.c 130 KB

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