channel.c 129 KB

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