channel.c 101 KB

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