channel.c 116 KB

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