channel.c 100 KB

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