channel.c 134 KB

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