channel.c 116 KB

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