channel.c 101 KB

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