channel.c 116 KB

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