channel.c 129 KB

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