channel.c 101 KB

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