channel.c 135 KB

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