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