channel.c 100 KB

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