channel.c 140 KB

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