channel.c 115 KB

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