channel.c 117 KB

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