channel.c 139 KB

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