channel.c 127 KB

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