channel.c 100 KB

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