channel.c 100 KB

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