channel.c 129 KB

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