channel.c 101 KB

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