channel.c 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473
  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 "core/or/or.h"
  56. #include "core/or/channel.h"
  57. #include "core/or/channeltls.h"
  58. #include "core/or/channelpadding.h"
  59. #include "core/or/circuitbuild.h"
  60. #include "core/or/circuitlist.h"
  61. #include "core/or/circuitstats.h"
  62. #include "app/config/config.h"
  63. #include "core/or/connection_or.h" /* For var_cell_free() */
  64. #include "core/or/circuitmux.h"
  65. #include "feature/client/entrynodes.h"
  66. #include "feature/stats/geoip.h"
  67. #include "core/mainloop/main.h"
  68. #include "feature/nodelist/nodelist.h"
  69. #include "core/or/relay.h"
  70. #include "feature/stats/rephist.h"
  71. #include "feature/relay/router.h"
  72. #include "feature/nodelist/routerlist.h"
  73. #include "core/or/scheduler.h"
  74. #include "lib/time/compat_time.h"
  75. #include "feature/nodelist/networkstatus.h"
  76. #include "feature/rend/rendservice.h"
  77. #include "lib/evloop/timers.h"
  78. #include "core/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 (rend_service_allow_non_anonymous_connection(get_options()) &&
  1612. !networkstatus_get_param(NULL,
  1613. CHANNELPADDING_SOS_PARAM,
  1614. CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
  1615. /* Disable if we're using RSOS and the consensus disabled padding
  1616. * for RSOS */
  1617. channelpadding_disable_padding_on_channel(chan);
  1618. } else if (get_options()->ReducedConnectionPadding) {
  1619. /* Padding can be forced and/or reduced by clients, regardless of if
  1620. * the channel supports it */
  1621. channelpadding_reduce_padding_on_channel(chan);
  1622. }
  1623. }
  1624. circuit_n_chan_done(chan, 1, close_origin_circuits);
  1625. }
  1626. /**
  1627. * Queue an incoming channel on a listener.
  1628. *
  1629. * Internal and subclass use only function to queue an incoming channel from
  1630. * a listener. A subclass of channel_listener_t should call this when a new
  1631. * incoming channel is created.
  1632. */
  1633. void
  1634. channel_listener_queue_incoming(channel_listener_t *listener,
  1635. channel_t *incoming)
  1636. {
  1637. int need_to_queue = 0;
  1638. tor_assert(listener);
  1639. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  1640. tor_assert(incoming);
  1641. log_debug(LD_CHANNEL,
  1642. "Queueing incoming channel %p (global ID %"PRIu64 ") on "
  1643. "channel listener %p (global ID %"PRIu64 ")",
  1644. incoming, (incoming->global_identifier),
  1645. listener, (listener->global_identifier));
  1646. /* Do we need to queue it, or can we just call the listener right away? */
  1647. if (!(listener->listener)) need_to_queue = 1;
  1648. if (listener->incoming_list &&
  1649. (smartlist_len(listener->incoming_list) > 0))
  1650. need_to_queue = 1;
  1651. /* If we need to queue and have no queue, create one */
  1652. if (need_to_queue && !(listener->incoming_list)) {
  1653. listener->incoming_list = smartlist_new();
  1654. }
  1655. /* Bump the counter and timestamp it */
  1656. channel_listener_timestamp_active(listener);
  1657. channel_listener_timestamp_accepted(listener);
  1658. ++(listener->n_accepted);
  1659. /* If we don't need to queue, process it right away */
  1660. if (!need_to_queue) {
  1661. tor_assert(listener->listener);
  1662. listener->listener(listener, incoming);
  1663. }
  1664. /*
  1665. * Otherwise, we need to queue; queue and then process the queue if
  1666. * we can.
  1667. */
  1668. else {
  1669. tor_assert(listener->incoming_list);
  1670. smartlist_add(listener->incoming_list, incoming);
  1671. if (listener->listener) channel_listener_process_incoming(listener);
  1672. }
  1673. }
  1674. /**
  1675. * Process a cell from the given channel.
  1676. */
  1677. void
  1678. channel_process_cell(channel_t *chan, cell_t *cell)
  1679. {
  1680. tor_assert(chan);
  1681. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  1682. CHANNEL_IS_OPEN(chan));
  1683. tor_assert(cell);
  1684. /* Nothing we can do if we have no registered cell handlers */
  1685. if (!chan->cell_handler)
  1686. return;
  1687. /* Timestamp for receiving */
  1688. channel_timestamp_recv(chan);
  1689. /* Update received counter. */
  1690. ++(chan->n_cells_recved);
  1691. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  1692. log_debug(LD_CHANNEL,
  1693. "Processing incoming cell_t %p for channel %p (global ID "
  1694. "%"PRIu64 ")", cell, chan,
  1695. (chan->global_identifier));
  1696. chan->cell_handler(chan, cell);
  1697. }
  1698. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  1699. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  1700. * false. */
  1701. /* XXXX Move this function. */
  1702. int
  1703. packed_cell_is_destroy(channel_t *chan,
  1704. const packed_cell_t *packed_cell,
  1705. circid_t *circid_out)
  1706. {
  1707. if (chan->wide_circ_ids) {
  1708. if (packed_cell->body[4] == CELL_DESTROY) {
  1709. *circid_out = ntohl(get_uint32(packed_cell->body));
  1710. return 1;
  1711. }
  1712. } else {
  1713. if (packed_cell->body[2] == CELL_DESTROY) {
  1714. *circid_out = ntohs(get_uint16(packed_cell->body));
  1715. return 1;
  1716. }
  1717. }
  1718. return 0;
  1719. }
  1720. /**
  1721. * Send destroy cell on a channel.
  1722. *
  1723. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  1724. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  1725. * we may want to propagate reasons from other cells.
  1726. */
  1727. int
  1728. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  1729. {
  1730. tor_assert(chan);
  1731. if (circ_id == 0) {
  1732. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  1733. "on a channel %"PRIu64 " at %p in state %s (%d)",
  1734. (chan->global_identifier),
  1735. chan, channel_state_to_string(chan->state),
  1736. chan->state);
  1737. return 0;
  1738. }
  1739. /* Check to make sure we can send on this channel first */
  1740. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  1741. channel_note_destroy_pending(chan, circ_id);
  1742. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  1743. log_debug(LD_OR,
  1744. "Sending destroy (circID %u) on channel %p "
  1745. "(global ID %"PRIu64 ")",
  1746. (unsigned)circ_id, chan,
  1747. (chan->global_identifier));
  1748. } else {
  1749. log_warn(LD_BUG,
  1750. "Someone called channel_send_destroy() for circID %u "
  1751. "on a channel %"PRIu64 " at %p in state %s (%d)",
  1752. (unsigned)circ_id, (chan->global_identifier),
  1753. chan, channel_state_to_string(chan->state),
  1754. chan->state);
  1755. }
  1756. return 0;
  1757. }
  1758. /**
  1759. * Dump channel statistics to the log.
  1760. *
  1761. * This is called from dumpstats() in main.c and spams the log with
  1762. * statistics on channels.
  1763. */
  1764. void
  1765. channel_dumpstats(int severity)
  1766. {
  1767. if (all_channels && smartlist_len(all_channels) > 0) {
  1768. tor_log(severity, LD_GENERAL,
  1769. "Dumping statistics about %d channels:",
  1770. smartlist_len(all_channels));
  1771. tor_log(severity, LD_GENERAL,
  1772. "%d are active, and %d are done and waiting for cleanup",
  1773. (active_channels != NULL) ?
  1774. smartlist_len(active_channels) : 0,
  1775. (finished_channels != NULL) ?
  1776. smartlist_len(finished_channels) : 0);
  1777. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  1778. channel_dump_statistics(chan, severity));
  1779. tor_log(severity, LD_GENERAL,
  1780. "Done spamming about channels now");
  1781. } else {
  1782. tor_log(severity, LD_GENERAL,
  1783. "No channels to dump");
  1784. }
  1785. }
  1786. /**
  1787. * Dump channel listener statistics to the log.
  1788. *
  1789. * This is called from dumpstats() in main.c and spams the log with
  1790. * statistics on channel listeners.
  1791. */
  1792. void
  1793. channel_listener_dumpstats(int severity)
  1794. {
  1795. if (all_listeners && smartlist_len(all_listeners) > 0) {
  1796. tor_log(severity, LD_GENERAL,
  1797. "Dumping statistics about %d channel listeners:",
  1798. smartlist_len(all_listeners));
  1799. tor_log(severity, LD_GENERAL,
  1800. "%d are active and %d are done and waiting for cleanup",
  1801. (active_listeners != NULL) ?
  1802. smartlist_len(active_listeners) : 0,
  1803. (finished_listeners != NULL) ?
  1804. smartlist_len(finished_listeners) : 0);
  1805. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  1806. channel_listener_dump_statistics(chan_l, severity));
  1807. tor_log(severity, LD_GENERAL,
  1808. "Done spamming about channel listeners now");
  1809. } else {
  1810. tor_log(severity, LD_GENERAL,
  1811. "No channel listeners to dump");
  1812. }
  1813. }
  1814. /**
  1815. * Clean up channels.
  1816. *
  1817. * This gets called periodically from run_scheduled_events() in main.c;
  1818. * it cleans up after closed channels.
  1819. */
  1820. void
  1821. channel_run_cleanup(void)
  1822. {
  1823. channel_t *tmp = NULL;
  1824. /* Check if we need to do anything */
  1825. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  1826. /* Iterate through finished_channels and get rid of them */
  1827. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  1828. tmp = curr;
  1829. /* Remove it from the list */
  1830. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  1831. /* Also unregister it */
  1832. channel_unregister(tmp);
  1833. /* ... and free it */
  1834. channel_free(tmp);
  1835. } SMARTLIST_FOREACH_END(curr);
  1836. }
  1837. /**
  1838. * Clean up channel listeners.
  1839. *
  1840. * This gets called periodically from run_scheduled_events() in main.c;
  1841. * it cleans up after closed channel listeners.
  1842. */
  1843. void
  1844. channel_listener_run_cleanup(void)
  1845. {
  1846. channel_listener_t *tmp = NULL;
  1847. /* Check if we need to do anything */
  1848. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  1849. /* Iterate through finished_channels and get rid of them */
  1850. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  1851. tmp = curr;
  1852. /* Remove it from the list */
  1853. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  1854. /* Also unregister it */
  1855. channel_listener_unregister(tmp);
  1856. /* ... and free it */
  1857. channel_listener_free(tmp);
  1858. } SMARTLIST_FOREACH_END(curr);
  1859. }
  1860. /**
  1861. * Free a list of channels for channel_free_all().
  1862. */
  1863. static void
  1864. channel_free_list(smartlist_t *channels, int mark_for_close)
  1865. {
  1866. if (!channels) return;
  1867. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  1868. /* Deregister and free it */
  1869. tor_assert(curr);
  1870. log_debug(LD_CHANNEL,
  1871. "Cleaning up channel %p (global ID %"PRIu64 ") "
  1872. "in state %s (%d)",
  1873. curr, (curr->global_identifier),
  1874. channel_state_to_string(curr->state), curr->state);
  1875. /* Detach circuits early so they can find the channel */
  1876. if (curr->cmux) {
  1877. circuitmux_detach_all_circuits(curr->cmux, NULL);
  1878. }
  1879. SMARTLIST_DEL_CURRENT(channels, curr);
  1880. channel_unregister(curr);
  1881. if (mark_for_close) {
  1882. if (!CHANNEL_CONDEMNED(curr)) {
  1883. channel_mark_for_close(curr);
  1884. }
  1885. channel_force_xfree(curr);
  1886. } else channel_free(curr);
  1887. } SMARTLIST_FOREACH_END(curr);
  1888. }
  1889. /**
  1890. * Free a list of channel listeners for channel_free_all().
  1891. */
  1892. static void
  1893. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  1894. {
  1895. if (!listeners) return;
  1896. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  1897. /* Deregister and free it */
  1898. tor_assert(curr);
  1899. log_debug(LD_CHANNEL,
  1900. "Cleaning up channel listener %p (global ID %"PRIu64 ") "
  1901. "in state %s (%d)",
  1902. curr, (curr->global_identifier),
  1903. channel_listener_state_to_string(curr->state), curr->state);
  1904. channel_listener_unregister(curr);
  1905. if (mark_for_close) {
  1906. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1907. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1908. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  1909. channel_listener_mark_for_close(curr);
  1910. }
  1911. channel_listener_force_xfree(curr);
  1912. } else channel_listener_free(curr);
  1913. } SMARTLIST_FOREACH_END(curr);
  1914. }
  1915. /**
  1916. * Close all channels and free everything.
  1917. *
  1918. * This gets called from tor_free_all() in main.c to clean up on exit.
  1919. * It will close all registered channels and free associated storage,
  1920. * then free the all_channels, active_channels, listening_channels and
  1921. * finished_channels lists and also channel_identity_map.
  1922. */
  1923. void
  1924. channel_free_all(void)
  1925. {
  1926. log_debug(LD_CHANNEL,
  1927. "Shutting down channels...");
  1928. /* First, let's go for finished channels */
  1929. if (finished_channels) {
  1930. channel_free_list(finished_channels, 0);
  1931. smartlist_free(finished_channels);
  1932. finished_channels = NULL;
  1933. }
  1934. /* Now the finished listeners */
  1935. if (finished_listeners) {
  1936. channel_listener_free_list(finished_listeners, 0);
  1937. smartlist_free(finished_listeners);
  1938. finished_listeners = NULL;
  1939. }
  1940. /* Now all active channels */
  1941. if (active_channels) {
  1942. channel_free_list(active_channels, 1);
  1943. smartlist_free(active_channels);
  1944. active_channels = NULL;
  1945. }
  1946. /* Now all active listeners */
  1947. if (active_listeners) {
  1948. channel_listener_free_list(active_listeners, 1);
  1949. smartlist_free(active_listeners);
  1950. active_listeners = NULL;
  1951. }
  1952. /* Now all channels, in case any are left over */
  1953. if (all_channels) {
  1954. channel_free_list(all_channels, 1);
  1955. smartlist_free(all_channels);
  1956. all_channels = NULL;
  1957. }
  1958. /* Now all listeners, in case any are left over */
  1959. if (all_listeners) {
  1960. channel_listener_free_list(all_listeners, 1);
  1961. smartlist_free(all_listeners);
  1962. all_listeners = NULL;
  1963. }
  1964. /* Now free channel_identity_map */
  1965. log_debug(LD_CHANNEL,
  1966. "Freeing channel_identity_map");
  1967. /* Geez, anything still left over just won't die ... let it leak then */
  1968. HT_CLEAR(channel_idmap, &channel_identity_map);
  1969. /* Same with channel_gid_map */
  1970. log_debug(LD_CHANNEL,
  1971. "Freeing channel_gid_map");
  1972. HT_CLEAR(channel_gid_map, &channel_gid_map);
  1973. log_debug(LD_CHANNEL,
  1974. "Done cleaning up after channels");
  1975. }
  1976. /**
  1977. * Connect to a given addr/port/digest.
  1978. *
  1979. * This sets up a new outgoing channel; in the future if multiple
  1980. * channel_t subclasses are available, this is where the selection policy
  1981. * should go. It may also be desirable to fold port into tor_addr_t
  1982. * or make a new type including a tor_addr_t and port, so we have a
  1983. * single abstract object encapsulating all the protocol details of
  1984. * how to contact an OR.
  1985. */
  1986. channel_t *
  1987. channel_connect(const tor_addr_t *addr, uint16_t port,
  1988. const char *id_digest,
  1989. const ed25519_public_key_t *ed_id)
  1990. {
  1991. return channel_tls_connect(addr, port, id_digest, ed_id);
  1992. }
  1993. /**
  1994. * Decide which of two channels to prefer for extending a circuit.
  1995. *
  1996. * This function is called while extending a circuit and returns true iff
  1997. * a is 'better' than b. The most important criterion here is that a
  1998. * canonical channel is always better than a non-canonical one, but the
  1999. * number of circuits and the age are used as tie-breakers.
  2000. *
  2001. * This is based on the former connection_or_is_better() of connection_or.c
  2002. */
  2003. int
  2004. channel_is_better(channel_t *a, channel_t *b)
  2005. {
  2006. int a_is_canonical, b_is_canonical;
  2007. tor_assert(a);
  2008. tor_assert(b);
  2009. /* If one channel is bad for new circuits, and the other isn't,
  2010. * use the one that is still good. */
  2011. if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
  2012. return 1;
  2013. if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
  2014. return 0;
  2015. /* Check if one is canonical and the other isn't first */
  2016. a_is_canonical = channel_is_canonical(a);
  2017. b_is_canonical = channel_is_canonical(b);
  2018. if (a_is_canonical && !b_is_canonical) return 1;
  2019. if (!a_is_canonical && b_is_canonical) return 0;
  2020. /* Check if we suspect that one of the channels will be preferred
  2021. * by the peer */
  2022. if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
  2023. if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
  2024. /*
  2025. * Okay, if we're here they tied on canonicity, the prefer the older
  2026. * connection, so that the adversary can't create a new connection
  2027. * and try to switch us over to it (which will leak information
  2028. * about long-lived circuits). Additionally, switching connections
  2029. * too often makes us more vulnerable to attacks like Torscan and
  2030. * passive netflow-based equivalents.
  2031. *
  2032. * Connections will still only live for at most a week, due to
  2033. * the check in connection_or_group_set_badness() against
  2034. * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
  2035. * unusable for new circuits after 1 week. That check sets
  2036. * is_bad_for_new_circs, which is checked in channel_get_for_extend().
  2037. *
  2038. * We check channel_is_bad_for_new_circs() above here anyway, for safety.
  2039. */
  2040. if (channel_when_created(a) < channel_when_created(b)) return 1;
  2041. else if (channel_when_created(a) > channel_when_created(b)) return 0;
  2042. if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
  2043. else return 0;
  2044. }
  2045. /**
  2046. * Get a channel to extend a circuit.
  2047. *
  2048. * Pick a suitable channel to extend a circuit to given the desired digest
  2049. * the address we believe is correct for that digest; this tries to see
  2050. * if we already have one for the requested endpoint, but if there is no good
  2051. * channel, set *msg_out to a message describing the channel's state
  2052. * and our next action, and set *launch_out to a boolean indicated whether
  2053. * the caller should try to launch a new channel with channel_connect().
  2054. */
  2055. channel_t *
  2056. channel_get_for_extend(const char *rsa_id_digest,
  2057. const ed25519_public_key_t *ed_id,
  2058. const tor_addr_t *target_addr,
  2059. const char **msg_out,
  2060. int *launch_out)
  2061. {
  2062. channel_t *chan, *best = NULL;
  2063. int n_inprogress_goodaddr = 0, n_old = 0;
  2064. int n_noncanonical = 0;
  2065. tor_assert(msg_out);
  2066. tor_assert(launch_out);
  2067. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2068. /* Walk the list, unrefing the old one and refing the new at each
  2069. * iteration.
  2070. */
  2071. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2072. tor_assert(tor_memeq(chan->identity_digest,
  2073. rsa_id_digest, DIGEST_LEN));
  2074. if (CHANNEL_CONDEMNED(chan))
  2075. continue;
  2076. /* Never return a channel on which the other end appears to be
  2077. * a client. */
  2078. if (channel_is_client(chan)) {
  2079. continue;
  2080. }
  2081. /* The Ed25519 key has to match too */
  2082. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  2083. continue;
  2084. }
  2085. /* Never return a non-open connection. */
  2086. if (!CHANNEL_IS_OPEN(chan)) {
  2087. /* If the address matches, don't launch a new connection for this
  2088. * circuit. */
  2089. if (channel_matches_target_addr_for_extend(chan, target_addr))
  2090. ++n_inprogress_goodaddr;
  2091. continue;
  2092. }
  2093. /* Never return a connection that shouldn't be used for circs. */
  2094. if (channel_is_bad_for_new_circs(chan)) {
  2095. ++n_old;
  2096. continue;
  2097. }
  2098. /* Never return a non-canonical connection using a recent link protocol
  2099. * if the address is not what we wanted.
  2100. *
  2101. * The channel_is_canonical_is_reliable() function asks the lower layer
  2102. * if we should trust channel_is_canonical(). The below is from the
  2103. * comments of the old circuit_or_get_for_extend() and applies when
  2104. * the lower-layer transport is channel_tls_t.
  2105. *
  2106. * (For old link protocols, we can't rely on is_canonical getting
  2107. * set properly if we're talking to the right address, since we might
  2108. * have an out-of-date descriptor, and we will get no NETINFO cell to
  2109. * tell us about the right address.)
  2110. */
  2111. if (!channel_is_canonical(chan) &&
  2112. channel_is_canonical_is_reliable(chan) &&
  2113. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  2114. ++n_noncanonical;
  2115. continue;
  2116. }
  2117. if (!best) {
  2118. best = chan; /* If we have no 'best' so far, this one is good enough. */
  2119. continue;
  2120. }
  2121. if (channel_is_better(chan, best))
  2122. best = chan;
  2123. }
  2124. if (best) {
  2125. *msg_out = "Connection is fine; using it.";
  2126. *launch_out = 0;
  2127. return best;
  2128. } else if (n_inprogress_goodaddr) {
  2129. *msg_out = "Connection in progress; waiting.";
  2130. *launch_out = 0;
  2131. return NULL;
  2132. } else if (n_old || n_noncanonical) {
  2133. *msg_out = "Connections all too old, or too non-canonical. "
  2134. " Launching a new one.";
  2135. *launch_out = 1;
  2136. return NULL;
  2137. } else {
  2138. *msg_out = "Not connected. Connecting.";
  2139. *launch_out = 1;
  2140. return NULL;
  2141. }
  2142. }
  2143. /**
  2144. * Describe the transport subclass for a channel.
  2145. *
  2146. * Invoke a method to get a string description of the lower-layer
  2147. * transport for this channel.
  2148. */
  2149. const char *
  2150. channel_describe_transport(channel_t *chan)
  2151. {
  2152. tor_assert(chan);
  2153. tor_assert(chan->describe_transport);
  2154. return chan->describe_transport(chan);
  2155. }
  2156. /**
  2157. * Describe the transport subclass for a channel listener.
  2158. *
  2159. * Invoke a method to get a string description of the lower-layer
  2160. * transport for this channel listener.
  2161. */
  2162. const char *
  2163. channel_listener_describe_transport(channel_listener_t *chan_l)
  2164. {
  2165. tor_assert(chan_l);
  2166. tor_assert(chan_l->describe_transport);
  2167. return chan_l->describe_transport(chan_l);
  2168. }
  2169. /**
  2170. * Dump channel statistics.
  2171. *
  2172. * Dump statistics for one channel to the log.
  2173. */
  2174. MOCK_IMPL(void,
  2175. channel_dump_statistics, (channel_t *chan, int severity))
  2176. {
  2177. double avg, interval, age;
  2178. time_t now = time(NULL);
  2179. tor_addr_t remote_addr;
  2180. int have_remote_addr;
  2181. char *remote_addr_str;
  2182. tor_assert(chan);
  2183. age = (double)(now - chan->timestamp_created);
  2184. tor_log(severity, LD_GENERAL,
  2185. "Channel %"PRIu64 " (at %p) with transport %s is in state "
  2186. "%s (%d)",
  2187. (chan->global_identifier), chan,
  2188. channel_describe_transport(chan),
  2189. channel_state_to_string(chan->state), chan->state);
  2190. tor_log(severity, LD_GENERAL,
  2191. " * Channel %"PRIu64 " was created at %"PRIu64
  2192. " (%"PRIu64 " seconds ago) "
  2193. "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
  2194. (chan->global_identifier),
  2195. (uint64_t)(chan->timestamp_created),
  2196. (uint64_t)(now - chan->timestamp_created),
  2197. (uint64_t)(chan->timestamp_active),
  2198. (uint64_t)(now - chan->timestamp_active));
  2199. /* Handle digest. */
  2200. if (!tor_digest_is_zero(chan->identity_digest)) {
  2201. tor_log(severity, LD_GENERAL,
  2202. " * Channel %"PRIu64 " says it is connected "
  2203. "to an OR with digest %s",
  2204. (chan->global_identifier),
  2205. hex_str(chan->identity_digest, DIGEST_LEN));
  2206. } else {
  2207. tor_log(severity, LD_GENERAL,
  2208. " * Channel %"PRIu64 " does not know the digest"
  2209. " of the OR it is connected to",
  2210. (chan->global_identifier));
  2211. }
  2212. /* Handle remote address and descriptions */
  2213. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  2214. if (have_remote_addr) {
  2215. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  2216. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  2217. tor_log(severity, LD_GENERAL,
  2218. " * Channel %"PRIu64 " says its remote address"
  2219. " is %s, and gives a canonical description of \"%s\" and an "
  2220. "actual description of \"%s\"",
  2221. (chan->global_identifier),
  2222. safe_str(remote_addr_str),
  2223. safe_str(channel_get_canonical_remote_descr(chan)),
  2224. safe_str(actual));
  2225. tor_free(remote_addr_str);
  2226. tor_free(actual);
  2227. } else {
  2228. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  2229. tor_log(severity, LD_GENERAL,
  2230. " * Channel %"PRIu64 " does not know its remote "
  2231. "address, but gives a canonical description of \"%s\" and an "
  2232. "actual description of \"%s\"",
  2233. (chan->global_identifier),
  2234. channel_get_canonical_remote_descr(chan),
  2235. actual);
  2236. tor_free(actual);
  2237. }
  2238. /* Handle marks */
  2239. tor_log(severity, LD_GENERAL,
  2240. " * Channel %"PRIu64 " has these marks: %s %s %s "
  2241. "%s %s %s",
  2242. (chan->global_identifier),
  2243. channel_is_bad_for_new_circs(chan) ?
  2244. "bad_for_new_circs" : "!bad_for_new_circs",
  2245. channel_is_canonical(chan) ?
  2246. "canonical" : "!canonical",
  2247. channel_is_canonical_is_reliable(chan) ?
  2248. "is_canonical_is_reliable" :
  2249. "!is_canonical_is_reliable",
  2250. channel_is_client(chan) ?
  2251. "client" : "!client",
  2252. channel_is_local(chan) ?
  2253. "local" : "!local",
  2254. channel_is_incoming(chan) ?
  2255. "incoming" : "outgoing");
  2256. /* Describe circuits */
  2257. tor_log(severity, LD_GENERAL,
  2258. " * Channel %"PRIu64 " has %d active circuits out of"
  2259. " %d in total",
  2260. (chan->global_identifier),
  2261. (chan->cmux != NULL) ?
  2262. circuitmux_num_active_circuits(chan->cmux) : 0,
  2263. (chan->cmux != NULL) ?
  2264. circuitmux_num_circuits(chan->cmux) : 0);
  2265. /* Describe timestamps */
  2266. tor_log(severity, LD_GENERAL,
  2267. " * Channel %"PRIu64 " was last used by a "
  2268. "client at %"PRIu64 " (%"PRIu64 " seconds ago)",
  2269. (chan->global_identifier),
  2270. (uint64_t)(chan->timestamp_client),
  2271. (uint64_t)(now - chan->timestamp_client));
  2272. tor_log(severity, LD_GENERAL,
  2273. " * Channel %"PRIu64 " last received a cell "
  2274. "at %"PRIu64 " (%"PRIu64 " seconds ago)",
  2275. (chan->global_identifier),
  2276. (uint64_t)(chan->timestamp_recv),
  2277. (uint64_t)(now - chan->timestamp_recv));
  2278. tor_log(severity, LD_GENERAL,
  2279. " * Channel %"PRIu64 " last transmitted a cell "
  2280. "at %"PRIu64 " (%"PRIu64 " seconds ago)",
  2281. (chan->global_identifier),
  2282. (uint64_t)(chan->timestamp_xmit),
  2283. (uint64_t)(now - chan->timestamp_xmit));
  2284. /* Describe counters and rates */
  2285. tor_log(severity, LD_GENERAL,
  2286. " * Channel %"PRIu64 " has received "
  2287. "%"PRIu64 " bytes in %"PRIu64 " cells and transmitted "
  2288. "%"PRIu64 " bytes in %"PRIu64 " cells",
  2289. (chan->global_identifier),
  2290. (chan->n_bytes_recved),
  2291. (chan->n_cells_recved),
  2292. (chan->n_bytes_xmitted),
  2293. (chan->n_cells_xmitted));
  2294. if (now > chan->timestamp_created &&
  2295. chan->timestamp_created > 0) {
  2296. if (chan->n_bytes_recved > 0) {
  2297. avg = (double)(chan->n_bytes_recved) / age;
  2298. tor_log(severity, LD_GENERAL,
  2299. " * Channel %"PRIu64 " has averaged %f "
  2300. "bytes received per second",
  2301. (chan->global_identifier), avg);
  2302. }
  2303. if (chan->n_cells_recved > 0) {
  2304. avg = (double)(chan->n_cells_recved) / age;
  2305. if (avg >= 1.0) {
  2306. tor_log(severity, LD_GENERAL,
  2307. " * Channel %"PRIu64 " has averaged %f "
  2308. "cells received per second",
  2309. (chan->global_identifier), avg);
  2310. } else if (avg >= 0.0) {
  2311. interval = 1.0 / avg;
  2312. tor_log(severity, LD_GENERAL,
  2313. " * Channel %"PRIu64 " has averaged %f "
  2314. "seconds between received cells",
  2315. (chan->global_identifier), interval);
  2316. }
  2317. }
  2318. if (chan->n_bytes_xmitted > 0) {
  2319. avg = (double)(chan->n_bytes_xmitted) / age;
  2320. tor_log(severity, LD_GENERAL,
  2321. " * Channel %"PRIu64 " has averaged %f "
  2322. "bytes transmitted per second",
  2323. (chan->global_identifier), avg);
  2324. }
  2325. if (chan->n_cells_xmitted > 0) {
  2326. avg = (double)(chan->n_cells_xmitted) / age;
  2327. if (avg >= 1.0) {
  2328. tor_log(severity, LD_GENERAL,
  2329. " * Channel %"PRIu64 " has averaged %f "
  2330. "cells transmitted per second",
  2331. (chan->global_identifier), avg);
  2332. } else if (avg >= 0.0) {
  2333. interval = 1.0 / avg;
  2334. tor_log(severity, LD_GENERAL,
  2335. " * Channel %"PRIu64 " has averaged %f "
  2336. "seconds between transmitted cells",
  2337. (chan->global_identifier), interval);
  2338. }
  2339. }
  2340. }
  2341. /* Dump anything the lower layer has to say */
  2342. channel_dump_transport_statistics(chan, severity);
  2343. }
  2344. /**
  2345. * Dump channel listener statistics.
  2346. *
  2347. * Dump statistics for one channel listener to the log.
  2348. */
  2349. void
  2350. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  2351. {
  2352. double avg, interval, age;
  2353. time_t now = time(NULL);
  2354. tor_assert(chan_l);
  2355. age = (double)(now - chan_l->timestamp_created);
  2356. tor_log(severity, LD_GENERAL,
  2357. "Channel listener %"PRIu64 " (at %p) with transport %s is in "
  2358. "state %s (%d)",
  2359. (chan_l->global_identifier), chan_l,
  2360. channel_listener_describe_transport(chan_l),
  2361. channel_listener_state_to_string(chan_l->state), chan_l->state);
  2362. tor_log(severity, LD_GENERAL,
  2363. " * Channel listener %"PRIu64 " was created at %"PRIu64
  2364. " (%"PRIu64 " seconds ago) "
  2365. "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
  2366. (chan_l->global_identifier),
  2367. (uint64_t)(chan_l->timestamp_created),
  2368. (uint64_t)(now - chan_l->timestamp_created),
  2369. (uint64_t)(chan_l->timestamp_active),
  2370. (uint64_t)(now - chan_l->timestamp_active));
  2371. tor_log(severity, LD_GENERAL,
  2372. " * Channel listener %"PRIu64 " last accepted an incoming "
  2373. "channel at %"PRIu64 " (%"PRIu64 " seconds ago) "
  2374. "and has accepted %"PRIu64 " channels in total",
  2375. (chan_l->global_identifier),
  2376. (uint64_t)(chan_l->timestamp_accepted),
  2377. (uint64_t)(now - chan_l->timestamp_accepted),
  2378. (uint64_t)(chan_l->n_accepted));
  2379. /*
  2380. * If it's sensible to do so, get the rate of incoming channels on this
  2381. * listener
  2382. */
  2383. if (now > chan_l->timestamp_created &&
  2384. chan_l->timestamp_created > 0 &&
  2385. chan_l->n_accepted > 0) {
  2386. avg = (double)(chan_l->n_accepted) / age;
  2387. if (avg >= 1.0) {
  2388. tor_log(severity, LD_GENERAL,
  2389. " * Channel listener %"PRIu64 " has averaged %f incoming "
  2390. "channels per second",
  2391. (chan_l->global_identifier), avg);
  2392. } else if (avg >= 0.0) {
  2393. interval = 1.0 / avg;
  2394. tor_log(severity, LD_GENERAL,
  2395. " * Channel listener %"PRIu64 " has averaged %f seconds "
  2396. "between incoming channels",
  2397. (chan_l->global_identifier), interval);
  2398. }
  2399. }
  2400. /* Dump anything the lower layer has to say */
  2401. channel_listener_dump_transport_statistics(chan_l, severity);
  2402. }
  2403. /**
  2404. * Invoke transport-specific stats dump for channel.
  2405. *
  2406. * If there is a lower-layer statistics dump method, invoke it.
  2407. */
  2408. void
  2409. channel_dump_transport_statistics(channel_t *chan, int severity)
  2410. {
  2411. tor_assert(chan);
  2412. if (chan->dumpstats) chan->dumpstats(chan, severity);
  2413. }
  2414. /**
  2415. * Invoke transport-specific stats dump for channel listener.
  2416. *
  2417. * If there is a lower-layer statistics dump method, invoke it.
  2418. */
  2419. void
  2420. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  2421. int severity)
  2422. {
  2423. tor_assert(chan_l);
  2424. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  2425. }
  2426. /**
  2427. * Return text description of the remote endpoint.
  2428. *
  2429. * This function return a test provided by the lower layer of the remote
  2430. * endpoint for this channel; it should specify the actual address connected
  2431. * to/from.
  2432. *
  2433. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2434. * may invalidate the return value from this function.
  2435. */
  2436. const char *
  2437. channel_get_actual_remote_descr(channel_t *chan)
  2438. {
  2439. tor_assert(chan);
  2440. tor_assert(chan->get_remote_descr);
  2441. /* Param 1 indicates the actual description */
  2442. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  2443. }
  2444. /**
  2445. * Return the text address of the remote endpoint.
  2446. *
  2447. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2448. * may invalidate the return value from this function.
  2449. */
  2450. const char *
  2451. channel_get_actual_remote_address(channel_t *chan)
  2452. {
  2453. /* Param 1 indicates the actual description */
  2454. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  2455. }
  2456. /**
  2457. * Return text description of the remote endpoint canonical address.
  2458. *
  2459. * This function return a test provided by the lower layer of the remote
  2460. * endpoint for this channel; it should use the known canonical address for
  2461. * this OR's identity digest if possible.
  2462. *
  2463. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2464. * may invalidate the return value from this function.
  2465. */
  2466. const char *
  2467. channel_get_canonical_remote_descr(channel_t *chan)
  2468. {
  2469. tor_assert(chan);
  2470. tor_assert(chan->get_remote_descr);
  2471. /* Param 0 indicates the canonicalized description */
  2472. return chan->get_remote_descr(chan, 0);
  2473. }
  2474. /**
  2475. * Get remote address if possible.
  2476. *
  2477. * Write the remote address out to a tor_addr_t if the underlying transport
  2478. * supports this operation, and return 1. Return 0 if the underlying transport
  2479. * doesn't let us do this.
  2480. */
  2481. MOCK_IMPL(int,
  2482. channel_get_addr_if_possible,(channel_t *chan, tor_addr_t *addr_out))
  2483. {
  2484. tor_assert(chan);
  2485. tor_assert(addr_out);
  2486. if (chan->get_remote_addr)
  2487. return chan->get_remote_addr(chan, addr_out);
  2488. /* Else no support, method not implemented */
  2489. else return 0;
  2490. }
  2491. /**
  2492. * Return true iff the channel has any cells on the connection outbuf waiting
  2493. * to be sent onto the network.
  2494. */
  2495. int
  2496. channel_has_queued_writes(channel_t *chan)
  2497. {
  2498. tor_assert(chan);
  2499. tor_assert(chan->has_queued_writes);
  2500. /* Check with the lower layer */
  2501. return chan->has_queued_writes(chan);
  2502. }
  2503. /**
  2504. * Check the is_bad_for_new_circs flag.
  2505. *
  2506. * This function returns the is_bad_for_new_circs flag of the specified
  2507. * channel.
  2508. */
  2509. int
  2510. channel_is_bad_for_new_circs(channel_t *chan)
  2511. {
  2512. tor_assert(chan);
  2513. return chan->is_bad_for_new_circs;
  2514. }
  2515. /**
  2516. * Mark a channel as bad for new circuits.
  2517. *
  2518. * Set the is_bad_for_new_circs_flag on chan.
  2519. */
  2520. void
  2521. channel_mark_bad_for_new_circs(channel_t *chan)
  2522. {
  2523. tor_assert(chan);
  2524. chan->is_bad_for_new_circs = 1;
  2525. }
  2526. /**
  2527. * Get the client flag.
  2528. *
  2529. * This returns the client flag of a channel, which will be set if
  2530. * command_process_create_cell() in command.c thinks this is a connection
  2531. * from a client.
  2532. */
  2533. int
  2534. channel_is_client(const channel_t *chan)
  2535. {
  2536. tor_assert(chan);
  2537. return chan->is_client;
  2538. }
  2539. /**
  2540. * Set the client flag.
  2541. *
  2542. * Mark a channel as being from a client.
  2543. */
  2544. void
  2545. channel_mark_client(channel_t *chan)
  2546. {
  2547. tor_assert(chan);
  2548. chan->is_client = 1;
  2549. }
  2550. /**
  2551. * Clear the client flag.
  2552. *
  2553. * Mark a channel as being _not_ from a client.
  2554. */
  2555. void
  2556. channel_clear_client(channel_t *chan)
  2557. {
  2558. tor_assert(chan);
  2559. chan->is_client = 0;
  2560. }
  2561. /**
  2562. * Get the canonical flag for a channel.
  2563. *
  2564. * This returns the is_canonical for a channel; this flag is determined by
  2565. * the lower layer and can't be set in a transport-independent way.
  2566. */
  2567. int
  2568. channel_is_canonical(channel_t *chan)
  2569. {
  2570. tor_assert(chan);
  2571. tor_assert(chan->is_canonical);
  2572. return chan->is_canonical(chan, 0);
  2573. }
  2574. /**
  2575. * Test if the canonical flag is reliable.
  2576. *
  2577. * This function asks if the lower layer thinks it's safe to trust the
  2578. * result of channel_is_canonical().
  2579. */
  2580. int
  2581. channel_is_canonical_is_reliable(channel_t *chan)
  2582. {
  2583. tor_assert(chan);
  2584. tor_assert(chan->is_canonical);
  2585. return chan->is_canonical(chan, 1);
  2586. }
  2587. /**
  2588. * Test incoming flag.
  2589. *
  2590. * This function gets the incoming flag; this is set when a listener spawns
  2591. * a channel. If this returns true the channel was remotely initiated.
  2592. */
  2593. int
  2594. channel_is_incoming(channel_t *chan)
  2595. {
  2596. tor_assert(chan);
  2597. return chan->is_incoming;
  2598. }
  2599. /**
  2600. * Set the incoming flag.
  2601. *
  2602. * This function is called when a channel arrives on a listening channel
  2603. * to mark it as incoming.
  2604. */
  2605. void
  2606. channel_mark_incoming(channel_t *chan)
  2607. {
  2608. tor_assert(chan);
  2609. chan->is_incoming = 1;
  2610. }
  2611. /**
  2612. * Test local flag.
  2613. *
  2614. * This function gets the local flag; the lower layer should set this when
  2615. * setting up the channel if is_local_addr() is true for all of the
  2616. * destinations it will communicate with on behalf of this channel. It's
  2617. * used to decide whether to declare the network reachable when seeing incoming
  2618. * traffic on the channel.
  2619. */
  2620. int
  2621. channel_is_local(channel_t *chan)
  2622. {
  2623. tor_assert(chan);
  2624. return chan->is_local;
  2625. }
  2626. /**
  2627. * Set the local flag.
  2628. *
  2629. * This internal-only function should be called by the lower layer if the
  2630. * channel is to a local address. See channel_is_local() above or the
  2631. * description of the is_local bit in channel.h.
  2632. */
  2633. void
  2634. channel_mark_local(channel_t *chan)
  2635. {
  2636. tor_assert(chan);
  2637. chan->is_local = 1;
  2638. }
  2639. /**
  2640. * Mark a channel as remote.
  2641. *
  2642. * This internal-only function should be called by the lower layer if the
  2643. * channel is not to a local address but has previously been marked local.
  2644. * See channel_is_local() above or the description of the is_local bit in
  2645. * channel.h
  2646. */
  2647. void
  2648. channel_mark_remote(channel_t *chan)
  2649. {
  2650. tor_assert(chan);
  2651. chan->is_local = 0;
  2652. }
  2653. /**
  2654. * Test outgoing flag.
  2655. *
  2656. * This function gets the outgoing flag; this is the inverse of the incoming
  2657. * bit set when a listener spawns a channel. If this returns true the channel
  2658. * was locally initiated.
  2659. */
  2660. int
  2661. channel_is_outgoing(channel_t *chan)
  2662. {
  2663. tor_assert(chan);
  2664. return !(chan->is_incoming);
  2665. }
  2666. /**
  2667. * Mark a channel as outgoing.
  2668. *
  2669. * This function clears the incoming flag and thus marks a channel as
  2670. * outgoing.
  2671. */
  2672. void
  2673. channel_mark_outgoing(channel_t *chan)
  2674. {
  2675. tor_assert(chan);
  2676. chan->is_incoming = 0;
  2677. }
  2678. /************************
  2679. * Flow control queries *
  2680. ***********************/
  2681. /**
  2682. * Estimate the number of writeable cells.
  2683. *
  2684. * Ask the lower layer for an estimate of how many cells it can accept.
  2685. */
  2686. int
  2687. channel_num_cells_writeable(channel_t *chan)
  2688. {
  2689. int result;
  2690. tor_assert(chan);
  2691. tor_assert(chan->num_cells_writeable);
  2692. if (chan->state == CHANNEL_STATE_OPEN) {
  2693. /* Query lower layer */
  2694. result = chan->num_cells_writeable(chan);
  2695. if (result < 0) result = 0;
  2696. } else {
  2697. /* No cells are writeable in any other state */
  2698. result = 0;
  2699. }
  2700. return result;
  2701. }
  2702. /*********************
  2703. * Timestamp updates *
  2704. ********************/
  2705. /**
  2706. * Update the created timestamp for a channel.
  2707. *
  2708. * This updates the channel's created timestamp and should only be called
  2709. * from channel_init().
  2710. */
  2711. void
  2712. channel_timestamp_created(channel_t *chan)
  2713. {
  2714. time_t now = time(NULL);
  2715. tor_assert(chan);
  2716. chan->timestamp_created = now;
  2717. }
  2718. /**
  2719. * Update the created timestamp for a channel listener.
  2720. *
  2721. * This updates the channel listener's created timestamp and should only be
  2722. * called from channel_init_listener().
  2723. */
  2724. void
  2725. channel_listener_timestamp_created(channel_listener_t *chan_l)
  2726. {
  2727. time_t now = time(NULL);
  2728. tor_assert(chan_l);
  2729. chan_l->timestamp_created = now;
  2730. }
  2731. /**
  2732. * Update the last active timestamp for a channel.
  2733. *
  2734. * This function updates the channel's last active timestamp; it should be
  2735. * called by the lower layer whenever there is activity on the channel which
  2736. * does not lead to a cell being transmitted or received; the active timestamp
  2737. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  2738. * but it should be updated for things like the v3 handshake and stuff that
  2739. * produce activity only visible to the lower layer.
  2740. */
  2741. void
  2742. channel_timestamp_active(channel_t *chan)
  2743. {
  2744. time_t now = time(NULL);
  2745. tor_assert(chan);
  2746. monotime_coarse_get(&chan->timestamp_xfer);
  2747. chan->timestamp_active = now;
  2748. /* Clear any potential netflow padding timer. We're active */
  2749. monotime_coarse_zero(&chan->next_padding_time);
  2750. }
  2751. /**
  2752. * Update the last active timestamp for a channel listener.
  2753. */
  2754. void
  2755. channel_listener_timestamp_active(channel_listener_t *chan_l)
  2756. {
  2757. time_t now = time(NULL);
  2758. tor_assert(chan_l);
  2759. chan_l->timestamp_active = now;
  2760. }
  2761. /**
  2762. * Update the last accepted timestamp.
  2763. *
  2764. * This function updates the channel listener's last accepted timestamp; it
  2765. * should be called whenever a new incoming channel is accepted on a
  2766. * listener.
  2767. */
  2768. void
  2769. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  2770. {
  2771. time_t now = time(NULL);
  2772. tor_assert(chan_l);
  2773. chan_l->timestamp_active = now;
  2774. chan_l->timestamp_accepted = now;
  2775. }
  2776. /**
  2777. * Update client timestamp.
  2778. *
  2779. * This function is called by relay.c to timestamp a channel that appears to
  2780. * be used as a client.
  2781. */
  2782. void
  2783. channel_timestamp_client(channel_t *chan)
  2784. {
  2785. time_t now = time(NULL);
  2786. tor_assert(chan);
  2787. chan->timestamp_client = now;
  2788. }
  2789. /**
  2790. * Update the recv timestamp.
  2791. *
  2792. * This is called whenever we get an incoming cell from the lower layer.
  2793. * This also updates the active timestamp.
  2794. */
  2795. void
  2796. channel_timestamp_recv(channel_t *chan)
  2797. {
  2798. time_t now = time(NULL);
  2799. tor_assert(chan);
  2800. monotime_coarse_get(&chan->timestamp_xfer);
  2801. chan->timestamp_active = now;
  2802. chan->timestamp_recv = now;
  2803. /* Clear any potential netflow padding timer. We're active */
  2804. monotime_coarse_zero(&chan->next_padding_time);
  2805. }
  2806. /**
  2807. * Update the xmit timestamp.
  2808. *
  2809. * This is called whenever we pass an outgoing cell to the lower layer. This
  2810. * also updates the active timestamp.
  2811. */
  2812. void
  2813. channel_timestamp_xmit(channel_t *chan)
  2814. {
  2815. time_t now = time(NULL);
  2816. tor_assert(chan);
  2817. monotime_coarse_get(&chan->timestamp_xfer);
  2818. chan->timestamp_active = now;
  2819. chan->timestamp_xmit = now;
  2820. /* Clear any potential netflow padding timer. We're active */
  2821. monotime_coarse_zero(&chan->next_padding_time);
  2822. }
  2823. /***************************************************************
  2824. * Timestamp queries - see above for definitions of timestamps *
  2825. **************************************************************/
  2826. /**
  2827. * Query created timestamp for a channel.
  2828. */
  2829. time_t
  2830. channel_when_created(channel_t *chan)
  2831. {
  2832. tor_assert(chan);
  2833. return chan->timestamp_created;
  2834. }
  2835. /**
  2836. * Query client timestamp.
  2837. */
  2838. time_t
  2839. channel_when_last_client(channel_t *chan)
  2840. {
  2841. tor_assert(chan);
  2842. return chan->timestamp_client;
  2843. }
  2844. /**
  2845. * Query xmit timestamp.
  2846. */
  2847. time_t
  2848. channel_when_last_xmit(channel_t *chan)
  2849. {
  2850. tor_assert(chan);
  2851. return chan->timestamp_xmit;
  2852. }
  2853. /**
  2854. * Check if a channel matches an extend_info_t.
  2855. *
  2856. * This function calls the lower layer and asks if this channel matches a
  2857. * given extend_info_t.
  2858. */
  2859. int
  2860. channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
  2861. {
  2862. tor_assert(chan);
  2863. tor_assert(chan->matches_extend_info);
  2864. tor_assert(extend_info);
  2865. return chan->matches_extend_info(chan, extend_info);
  2866. }
  2867. /**
  2868. * Check if a channel matches a given target address; return true iff we do.
  2869. *
  2870. * This function calls into the lower layer and asks if this channel thinks
  2871. * it matches a given target address for circuit extension purposes.
  2872. */
  2873. int
  2874. channel_matches_target_addr_for_extend(channel_t *chan,
  2875. const tor_addr_t *target)
  2876. {
  2877. tor_assert(chan);
  2878. tor_assert(chan->matches_target);
  2879. tor_assert(target);
  2880. return chan->matches_target(chan, target);
  2881. }
  2882. /**
  2883. * Return the total number of circuits used by a channel.
  2884. *
  2885. * @param chan Channel to query
  2886. * @return Number of circuits using this as n_chan or p_chan
  2887. */
  2888. unsigned int
  2889. channel_num_circuits(channel_t *chan)
  2890. {
  2891. tor_assert(chan);
  2892. return chan->num_n_circuits +
  2893. chan->num_p_circuits;
  2894. }
  2895. /**
  2896. * Set up circuit ID generation.
  2897. *
  2898. * This is called when setting up a channel and replaces the old
  2899. * connection_or_set_circid_type().
  2900. */
  2901. MOCK_IMPL(void,
  2902. channel_set_circid_type,(channel_t *chan,
  2903. crypto_pk_t *identity_rcvd,
  2904. int consider_identity))
  2905. {
  2906. int started_here;
  2907. crypto_pk_t *our_identity;
  2908. tor_assert(chan);
  2909. started_here = channel_is_outgoing(chan);
  2910. if (! consider_identity) {
  2911. if (started_here)
  2912. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  2913. else
  2914. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  2915. return;
  2916. }
  2917. our_identity = started_here ?
  2918. get_tlsclient_identity_key() : get_server_identity_key();
  2919. if (identity_rcvd) {
  2920. if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
  2921. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  2922. } else {
  2923. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  2924. }
  2925. } else {
  2926. chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
  2927. }
  2928. }
  2929. static int
  2930. channel_sort_by_ed25519_identity(const void **a_, const void **b_)
  2931. {
  2932. const channel_t *a = *a_,
  2933. *b = *b_;
  2934. return fast_memcmp(&a->ed25519_identity.pubkey,
  2935. &b->ed25519_identity.pubkey,
  2936. sizeof(a->ed25519_identity.pubkey));
  2937. }
  2938. /** Helper for channel_update_bad_for_new_circs(): Perform the
  2939. * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
  2940. * all of which MUST have the same RSA ID. (They MAY have different
  2941. * Ed25519 IDs.) */
  2942. static void
  2943. channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
  2944. {
  2945. /*XXXX This function should really be about channels. 15056 */
  2946. channel_t *chan = TOR_LIST_FIRST(lst);
  2947. if (!chan)
  2948. return;
  2949. /* if there is only one channel, don't bother looping */
  2950. if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan, next_with_same_id))) {
  2951. connection_or_single_set_badness_(
  2952. time(NULL), BASE_CHAN_TO_TLS(chan)->conn, force);
  2953. return;
  2954. }
  2955. smartlist_t *channels = smartlist_new();
  2956. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  2957. if (BASE_CHAN_TO_TLS(chan)->conn) {
  2958. smartlist_add(channels, chan);
  2959. }
  2960. }
  2961. smartlist_sort(channels, channel_sort_by_ed25519_identity);
  2962. const ed25519_public_key_t *common_ed25519_identity = NULL;
  2963. /* it would be more efficient to do a slice, but this case is rare */
  2964. smartlist_t *or_conns = smartlist_new();
  2965. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, channel) {
  2966. if (!common_ed25519_identity)
  2967. common_ed25519_identity = &channel->ed25519_identity;
  2968. if (! ed25519_pubkey_eq(&channel->ed25519_identity,
  2969. common_ed25519_identity)) {
  2970. connection_or_group_set_badness_(or_conns, force);
  2971. smartlist_clear(or_conns);
  2972. common_ed25519_identity = &channel->ed25519_identity;
  2973. }
  2974. smartlist_add(or_conns, BASE_CHAN_TO_TLS(channel)->conn);
  2975. } SMARTLIST_FOREACH_END(channel);
  2976. connection_or_group_set_badness_(or_conns, force);
  2977. /* XXXX 15056 we may want to do something special with connections that have
  2978. * no set Ed25519 identity! */
  2979. smartlist_free(or_conns);
  2980. smartlist_free(channels);
  2981. }
  2982. /** Go through all the channels (or if <b>digest</b> is non-NULL, just
  2983. * the OR connections with that digest), and set the is_bad_for_new_circs
  2984. * flag based on the rules in connection_or_group_set_badness() (or just
  2985. * always set it if <b>force</b> is true).
  2986. */
  2987. void
  2988. channel_update_bad_for_new_circs(const char *digest, int force)
  2989. {
  2990. if (digest) {
  2991. channel_idmap_entry_t *ent;
  2992. channel_idmap_entry_t search;
  2993. memset(&search, 0, sizeof(search));
  2994. memcpy(search.digest, digest, DIGEST_LEN);
  2995. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  2996. if (ent) {
  2997. channel_rsa_id_group_set_badness(&ent->channel_list, force);
  2998. }
  2999. return;
  3000. }
  3001. /* no digest; just look at everything. */
  3002. channel_idmap_entry_t **iter;
  3003. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  3004. channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
  3005. }
  3006. }