channel.c 123 KB

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