channel.c 102 KB

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