channel.c 139 KB

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