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