channel.c 110 KB

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