channel.c 101 KB

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