channel.c 140 KB

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