channel.c 100 KB

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