channel.c 120 KB

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