channel.c 130 KB

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