channel.c 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575
  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 listenier 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 listner 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/reigstration 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. *
  1196. * Two possible errors can happen. Either the channel is not opened or the
  1197. * lower layer (specialized channel) failed to write it. In both cases, it is
  1198. * the caller responsibility to free the cell.
  1199. */
  1200. static int
  1201. write_packed_cell(channel_t *chan, packed_cell_t *cell)
  1202. {
  1203. int ret = -1;
  1204. size_t cell_bytes;
  1205. tor_assert(chan);
  1206. tor_assert(cell);
  1207. /* Assert that the state makes sense for a cell write */
  1208. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  1209. {
  1210. circid_t circ_id;
  1211. if (packed_cell_is_destroy(chan, cell, &circ_id)) {
  1212. channel_note_destroy_not_pending(chan, circ_id);
  1213. }
  1214. }
  1215. /* For statistical purposes, figure out how big this cell is */
  1216. cell_bytes = get_cell_network_size(chan->wide_circ_ids);
  1217. /* Can we send it right out? If so, try */
  1218. if (!CHANNEL_IS_OPEN(chan)) {
  1219. goto done;
  1220. }
  1221. /* Write the cell on the connection's outbuf. */
  1222. if (chan->write_packed_cell(chan, cell) < 0) {
  1223. goto done;
  1224. }
  1225. /* Timestamp for transmission */
  1226. channel_timestamp_xmit(chan);
  1227. /* Update the counter */
  1228. ++(chan->n_cells_xmitted);
  1229. chan->n_bytes_xmitted += cell_bytes;
  1230. /* Successfully sent the cell. */
  1231. ret = 0;
  1232. done:
  1233. return ret;
  1234. }
  1235. /**
  1236. * Write a packed cell to a channel
  1237. *
  1238. * Write a packed cell to a channel using the write_cell() method. This is
  1239. * called by the transport-independent code to deliver a packed cell to a
  1240. * channel for transmission.
  1241. *
  1242. * Return 0 on success else a negative value. In both cases, the caller should
  1243. * not access the cell anymore, it is freed both on success and error.
  1244. */
  1245. int
  1246. channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
  1247. {
  1248. int ret = -1;
  1249. tor_assert(chan);
  1250. tor_assert(cell);
  1251. if (CHANNEL_IS_CLOSING(chan)) {
  1252. log_debug(LD_CHANNEL, "Discarding %p on closing channel %p with "
  1253. "global ID "U64_FORMAT, cell, chan,
  1254. U64_PRINTF_ARG(chan->global_identifier));
  1255. goto end;
  1256. }
  1257. log_debug(LD_CHANNEL,
  1258. "Writing %p to channel %p with global ID "
  1259. U64_FORMAT, cell, chan, U64_PRINTF_ARG(chan->global_identifier));
  1260. ret = write_packed_cell(chan, cell);
  1261. end:
  1262. /* Whatever happens, we free the cell. Either an error occurred or the cell
  1263. * was put on the connection outbuf, both cases we have ownership of the
  1264. * cell and we free it. */
  1265. packed_cell_free(cell);
  1266. return ret;
  1267. }
  1268. /**
  1269. * Change channel state
  1270. *
  1271. * This internal and subclass use only function is used to change channel
  1272. * state, performing all transition validity checks and whatever actions
  1273. * are appropriate to the state transition in question.
  1274. */
  1275. static void
  1276. channel_change_state_(channel_t *chan, channel_state_t to_state)
  1277. {
  1278. channel_state_t from_state;
  1279. unsigned char was_active, is_active;
  1280. unsigned char was_in_id_map, is_in_id_map;
  1281. tor_assert(chan);
  1282. from_state = chan->state;
  1283. tor_assert(channel_state_is_valid(from_state));
  1284. tor_assert(channel_state_is_valid(to_state));
  1285. tor_assert(channel_state_can_transition(chan->state, to_state));
  1286. /* Check for no-op transitions */
  1287. if (from_state == to_state) {
  1288. log_debug(LD_CHANNEL,
  1289. "Got no-op transition from \"%s\" to itself on channel %p"
  1290. "(global ID " U64_FORMAT ")",
  1291. channel_state_to_string(to_state),
  1292. chan, U64_PRINTF_ARG(chan->global_identifier));
  1293. return;
  1294. }
  1295. /* If we're going to a closing or closed state, we must have a reason set */
  1296. if (to_state == CHANNEL_STATE_CLOSING ||
  1297. to_state == CHANNEL_STATE_CLOSED ||
  1298. to_state == CHANNEL_STATE_ERROR) {
  1299. tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
  1300. }
  1301. log_debug(LD_CHANNEL,
  1302. "Changing state of channel %p (global ID " U64_FORMAT
  1303. ") from \"%s\" to \"%s\"",
  1304. chan,
  1305. U64_PRINTF_ARG(chan->global_identifier),
  1306. channel_state_to_string(chan->state),
  1307. channel_state_to_string(to_state));
  1308. chan->state = to_state;
  1309. /* Need to add to the right lists if the channel is registered */
  1310. if (chan->registered) {
  1311. was_active = !(from_state == CHANNEL_STATE_CLOSED ||
  1312. from_state == CHANNEL_STATE_ERROR);
  1313. is_active = !(to_state == CHANNEL_STATE_CLOSED ||
  1314. to_state == CHANNEL_STATE_ERROR);
  1315. /* Need to take off active list and put on finished list? */
  1316. if (was_active && !is_active) {
  1317. if (active_channels) smartlist_remove(active_channels, chan);
  1318. if (!finished_channels) finished_channels = smartlist_new();
  1319. smartlist_add(finished_channels, chan);
  1320. }
  1321. /* Need to put on active list? */
  1322. else if (!was_active && is_active) {
  1323. if (finished_channels) smartlist_remove(finished_channels, chan);
  1324. if (!active_channels) active_channels = smartlist_new();
  1325. smartlist_add(active_channels, chan);
  1326. }
  1327. if (!tor_digest_is_zero(chan->identity_digest)) {
  1328. /* Now we need to handle the identity map */
  1329. was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
  1330. from_state == CHANNEL_STATE_CLOSED ||
  1331. from_state == CHANNEL_STATE_ERROR);
  1332. is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
  1333. to_state == CHANNEL_STATE_CLOSED ||
  1334. to_state == CHANNEL_STATE_ERROR);
  1335. if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
  1336. else if (was_in_id_map && !is_in_id_map)
  1337. channel_remove_from_digest_map(chan);
  1338. }
  1339. }
  1340. /*
  1341. * If we're going to a closed/closing state, we don't need scheduling any
  1342. * more; in CHANNEL_STATE_MAINT we can't accept writes.
  1343. */
  1344. if (to_state == CHANNEL_STATE_CLOSING ||
  1345. to_state == CHANNEL_STATE_CLOSED ||
  1346. to_state == CHANNEL_STATE_ERROR) {
  1347. scheduler_release_channel(chan);
  1348. } else if (to_state == CHANNEL_STATE_MAINT) {
  1349. scheduler_channel_doesnt_want_writes(chan);
  1350. }
  1351. }
  1352. /**
  1353. * As channel_change_state_, but change the state to any state but open.
  1354. */
  1355. void
  1356. channel_change_state(channel_t *chan, channel_state_t to_state)
  1357. {
  1358. tor_assert(to_state != CHANNEL_STATE_OPEN);
  1359. channel_change_state_(chan, to_state);
  1360. }
  1361. /**
  1362. * As channel_change_state, but change the state to open.
  1363. */
  1364. void
  1365. channel_change_state_open(channel_t *chan)
  1366. {
  1367. channel_change_state_(chan, CHANNEL_STATE_OPEN);
  1368. /* Tell circuits if we opened and stuff */
  1369. channel_do_open_actions(chan);
  1370. chan->has_been_open = 1;
  1371. }
  1372. /**
  1373. * Change channel listener state
  1374. *
  1375. * This internal and subclass use only function is used to change channel
  1376. * listener state, performing all transition validity checks and whatever
  1377. * actions are appropriate to the state transition in question.
  1378. */
  1379. void
  1380. channel_listener_change_state(channel_listener_t *chan_l,
  1381. channel_listener_state_t to_state)
  1382. {
  1383. channel_listener_state_t from_state;
  1384. unsigned char was_active, is_active;
  1385. tor_assert(chan_l);
  1386. from_state = chan_l->state;
  1387. tor_assert(channel_listener_state_is_valid(from_state));
  1388. tor_assert(channel_listener_state_is_valid(to_state));
  1389. tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
  1390. /* Check for no-op transitions */
  1391. if (from_state == to_state) {
  1392. log_debug(LD_CHANNEL,
  1393. "Got no-op transition from \"%s\" to itself on channel "
  1394. "listener %p (global ID " U64_FORMAT ")",
  1395. channel_listener_state_to_string(to_state),
  1396. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1397. return;
  1398. }
  1399. /* If we're going to a closing or closed state, we must have a reason set */
  1400. if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
  1401. to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1402. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1403. tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
  1404. }
  1405. log_debug(LD_CHANNEL,
  1406. "Changing state of channel listener %p (global ID " U64_FORMAT
  1407. "from \"%s\" to \"%s\"",
  1408. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  1409. channel_listener_state_to_string(chan_l->state),
  1410. channel_listener_state_to_string(to_state));
  1411. chan_l->state = to_state;
  1412. /* Need to add to the right lists if the channel listener is registered */
  1413. if (chan_l->registered) {
  1414. was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1415. from_state == CHANNEL_LISTENER_STATE_ERROR);
  1416. is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1417. to_state == CHANNEL_LISTENER_STATE_ERROR);
  1418. /* Need to take off active list and put on finished list? */
  1419. if (was_active && !is_active) {
  1420. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  1421. if (!finished_listeners) finished_listeners = smartlist_new();
  1422. smartlist_add(finished_listeners, chan_l);
  1423. }
  1424. /* Need to put on active list? */
  1425. else if (!was_active && is_active) {
  1426. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  1427. if (!active_listeners) active_listeners = smartlist_new();
  1428. smartlist_add(active_listeners, chan_l);
  1429. }
  1430. }
  1431. if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1432. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1433. tor_assert(!(chan_l->incoming_list) ||
  1434. smartlist_len(chan_l->incoming_list) == 0);
  1435. }
  1436. }
  1437. /* Maximum number of cells that is allowed to flush at once within
  1438. * channel_flush_some_cells(). */
  1439. #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
  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 to 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. rep_hist_note_connect_succeeded(chan->identity_digest, now);
  1580. router_set_status(chan->identity_digest, 1);
  1581. } else {
  1582. /* only report it to the geoip module if it's not a known router */
  1583. if (!connection_or_digest_is_known_relay(chan->identity_digest)) {
  1584. if (channel_get_addr_if_possible(chan, &remote_addr)) {
  1585. char *transport_name = NULL;
  1586. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  1587. if (chan->get_transport_name(chan, &transport_name) < 0)
  1588. transport_name = NULL;
  1589. geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
  1590. &remote_addr, transport_name,
  1591. now);
  1592. tor_free(transport_name);
  1593. /* Notify the DoS subsystem of a new client. */
  1594. if (tlschan && tlschan->conn) {
  1595. dos_new_client_conn(tlschan->conn);
  1596. }
  1597. }
  1598. /* Otherwise the underlying transport can't tell us this, so skip it */
  1599. }
  1600. }
  1601. /* Disable or reduce padding according to user prefs. */
  1602. if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
  1603. if (!get_options()->ConnectionPadding) {
  1604. /* Disable if torrc disabled */
  1605. channelpadding_disable_padding_on_channel(chan);
  1606. } else if (get_options()->Tor2webMode &&
  1607. !networkstatus_get_param(NULL,
  1608. CHANNELPADDING_TOR2WEB_PARAM,
  1609. CHANNELPADDING_TOR2WEB_DEFAULT, 0, 1)) {
  1610. /* Disable if we're using tor2web and the consensus disabled padding
  1611. * for tor2web */
  1612. channelpadding_disable_padding_on_channel(chan);
  1613. } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
  1614. !networkstatus_get_param(NULL,
  1615. CHANNELPADDING_SOS_PARAM,
  1616. CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
  1617. /* Disable if we're using RSOS and the consensus disabled padding
  1618. * for RSOS */
  1619. channelpadding_disable_padding_on_channel(chan);
  1620. } else if (get_options()->ReducedConnectionPadding) {
  1621. /* Padding can be forced and/or reduced by clients, regardless of if
  1622. * the channel supports it */
  1623. channelpadding_reduce_padding_on_channel(chan);
  1624. }
  1625. }
  1626. circuit_n_chan_done(chan, 1, close_origin_circuits);
  1627. }
  1628. /**
  1629. * Queue an incoming channel on a listener
  1630. *
  1631. * Internal and subclass use only function to queue an incoming channel from
  1632. * a listener. A subclass of channel_listener_t should call this when a new
  1633. * incoming channel is created.
  1634. */
  1635. void
  1636. channel_listener_queue_incoming(channel_listener_t *listener,
  1637. channel_t *incoming)
  1638. {
  1639. int need_to_queue = 0;
  1640. tor_assert(listener);
  1641. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  1642. tor_assert(incoming);
  1643. log_debug(LD_CHANNEL,
  1644. "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
  1645. "channel listener %p (global ID " U64_FORMAT ")",
  1646. incoming, U64_PRINTF_ARG(incoming->global_identifier),
  1647. listener, U64_PRINTF_ARG(listener->global_identifier));
  1648. /* Do we need to queue it, or can we just call the listener right away? */
  1649. if (!(listener->listener)) need_to_queue = 1;
  1650. if (listener->incoming_list &&
  1651. (smartlist_len(listener->incoming_list) > 0))
  1652. need_to_queue = 1;
  1653. /* If we need to queue and have no queue, create one */
  1654. if (need_to_queue && !(listener->incoming_list)) {
  1655. listener->incoming_list = smartlist_new();
  1656. }
  1657. /* Bump the counter and timestamp it */
  1658. channel_listener_timestamp_active(listener);
  1659. channel_listener_timestamp_accepted(listener);
  1660. ++(listener->n_accepted);
  1661. /* If we don't need to queue, process it right away */
  1662. if (!need_to_queue) {
  1663. tor_assert(listener->listener);
  1664. listener->listener(listener, incoming);
  1665. }
  1666. /*
  1667. * Otherwise, we need to queue; queue and then process the queue if
  1668. * we can.
  1669. */
  1670. else {
  1671. tor_assert(listener->incoming_list);
  1672. smartlist_add(listener->incoming_list, incoming);
  1673. if (listener->listener) channel_listener_process_incoming(listener);
  1674. }
  1675. }
  1676. /**
  1677. * Process a cell from the given channel.
  1678. */
  1679. void
  1680. channel_process_cell(channel_t *chan, cell_t *cell)
  1681. {
  1682. tor_assert(chan);
  1683. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  1684. CHANNEL_IS_OPEN(chan));
  1685. tor_assert(cell);
  1686. /* Nothing we can do if we have no registered cell handlers */
  1687. if (!chan->cell_handler)
  1688. return;
  1689. /* Timestamp for receiving */
  1690. channel_timestamp_recv(chan);
  1691. /* Update received counter. */
  1692. ++(chan->n_cells_recved);
  1693. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  1694. log_debug(LD_CHANNEL,
  1695. "Processing incoming cell_t %p for channel %p (global ID "
  1696. U64_FORMAT ")", cell, chan,
  1697. U64_PRINTF_ARG(chan->global_identifier));
  1698. chan->cell_handler(chan, cell);
  1699. }
  1700. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  1701. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  1702. * false. */
  1703. /* XXXX Move this function. */
  1704. int
  1705. packed_cell_is_destroy(channel_t *chan,
  1706. const packed_cell_t *packed_cell,
  1707. circid_t *circid_out)
  1708. {
  1709. if (chan->wide_circ_ids) {
  1710. if (packed_cell->body[4] == CELL_DESTROY) {
  1711. *circid_out = ntohl(get_uint32(packed_cell->body));
  1712. return 1;
  1713. }
  1714. } else {
  1715. if (packed_cell->body[2] == CELL_DESTROY) {
  1716. *circid_out = ntohs(get_uint16(packed_cell->body));
  1717. return 1;
  1718. }
  1719. }
  1720. return 0;
  1721. }
  1722. /**
  1723. * Send destroy cell on a channel
  1724. *
  1725. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  1726. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  1727. * we may want to propagate reasons from other cells.
  1728. */
  1729. int
  1730. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  1731. {
  1732. tor_assert(chan);
  1733. if (circ_id == 0) {
  1734. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  1735. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  1736. U64_PRINTF_ARG(chan->global_identifier),
  1737. chan, channel_state_to_string(chan->state),
  1738. chan->state);
  1739. return 0;
  1740. }
  1741. /* Check to make sure we can send on this channel first */
  1742. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  1743. channel_note_destroy_pending(chan, circ_id);
  1744. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  1745. log_debug(LD_OR,
  1746. "Sending destroy (circID %u) on channel %p "
  1747. "(global ID " U64_FORMAT ")",
  1748. (unsigned)circ_id, chan,
  1749. U64_PRINTF_ARG(chan->global_identifier));
  1750. } else {
  1751. log_warn(LD_BUG,
  1752. "Someone called channel_send_destroy() for circID %u "
  1753. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  1754. (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
  1755. chan, channel_state_to_string(chan->state),
  1756. chan->state);
  1757. }
  1758. return 0;
  1759. }
  1760. /**
  1761. * Dump channel statistics to the log
  1762. *
  1763. * This is called from dumpstats() in main.c and spams the log with
  1764. * statistics on channels.
  1765. */
  1766. void
  1767. channel_dumpstats(int severity)
  1768. {
  1769. if (all_channels && smartlist_len(all_channels) > 0) {
  1770. tor_log(severity, LD_GENERAL,
  1771. "Dumping statistics about %d channels:",
  1772. smartlist_len(all_channels));
  1773. tor_log(severity, LD_GENERAL,
  1774. "%d are active, and %d are done and waiting for cleanup",
  1775. (active_channels != NULL) ?
  1776. smartlist_len(active_channels) : 0,
  1777. (finished_channels != NULL) ?
  1778. smartlist_len(finished_channels) : 0);
  1779. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  1780. channel_dump_statistics(chan, severity));
  1781. tor_log(severity, LD_GENERAL,
  1782. "Done spamming about channels now");
  1783. } else {
  1784. tor_log(severity, LD_GENERAL,
  1785. "No channels to dump");
  1786. }
  1787. }
  1788. /**
  1789. * Dump channel listener statistics to the log
  1790. *
  1791. * This is called from dumpstats() in main.c and spams the log with
  1792. * statistics on channel listeners.
  1793. */
  1794. void
  1795. channel_listener_dumpstats(int severity)
  1796. {
  1797. if (all_listeners && smartlist_len(all_listeners) > 0) {
  1798. tor_log(severity, LD_GENERAL,
  1799. "Dumping statistics about %d channel listeners:",
  1800. smartlist_len(all_listeners));
  1801. tor_log(severity, LD_GENERAL,
  1802. "%d are active and %d are done and waiting for cleanup",
  1803. (active_listeners != NULL) ?
  1804. smartlist_len(active_listeners) : 0,
  1805. (finished_listeners != NULL) ?
  1806. smartlist_len(finished_listeners) : 0);
  1807. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  1808. channel_listener_dump_statistics(chan_l, severity));
  1809. tor_log(severity, LD_GENERAL,
  1810. "Done spamming about channel listeners now");
  1811. } else {
  1812. tor_log(severity, LD_GENERAL,
  1813. "No channel listeners to dump");
  1814. }
  1815. }
  1816. /**
  1817. * Set the cmux policy on all active channels
  1818. */
  1819. void
  1820. channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
  1821. {
  1822. if (!active_channels) return;
  1823. SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
  1824. if (curr->cmux) {
  1825. circuitmux_set_policy(curr->cmux, pol);
  1826. }
  1827. } SMARTLIST_FOREACH_END(curr);
  1828. }
  1829. /**
  1830. * Clean up channels
  1831. *
  1832. * This gets called periodically from run_scheduled_events() in main.c;
  1833. * it cleans up after closed channels.
  1834. */
  1835. void
  1836. channel_run_cleanup(void)
  1837. {
  1838. channel_t *tmp = NULL;
  1839. /* Check if we need to do anything */
  1840. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  1841. /* Iterate through finished_channels and get rid of them */
  1842. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  1843. tmp = curr;
  1844. /* Remove it from the list */
  1845. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  1846. /* Also unregister it */
  1847. channel_unregister(tmp);
  1848. /* ... and free it */
  1849. channel_free(tmp);
  1850. } SMARTLIST_FOREACH_END(curr);
  1851. }
  1852. /**
  1853. * Clean up channel listeners
  1854. *
  1855. * This gets called periodically from run_scheduled_events() in main.c;
  1856. * it cleans up after closed channel listeners.
  1857. */
  1858. void
  1859. channel_listener_run_cleanup(void)
  1860. {
  1861. channel_listener_t *tmp = NULL;
  1862. /* Check if we need to do anything */
  1863. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  1864. /* Iterate through finished_channels and get rid of them */
  1865. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  1866. tmp = curr;
  1867. /* Remove it from the list */
  1868. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  1869. /* Also unregister it */
  1870. channel_listener_unregister(tmp);
  1871. /* ... and free it */
  1872. channel_listener_free(tmp);
  1873. } SMARTLIST_FOREACH_END(curr);
  1874. }
  1875. /**
  1876. * Free a list of channels for channel_free_all()
  1877. */
  1878. static void
  1879. channel_free_list(smartlist_t *channels, int mark_for_close)
  1880. {
  1881. if (!channels) return;
  1882. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  1883. /* Deregister and free it */
  1884. tor_assert(curr);
  1885. log_debug(LD_CHANNEL,
  1886. "Cleaning up channel %p (global ID " U64_FORMAT ") "
  1887. "in state %s (%d)",
  1888. curr, U64_PRINTF_ARG(curr->global_identifier),
  1889. channel_state_to_string(curr->state), curr->state);
  1890. /* Detach circuits early so they can find the channel */
  1891. if (curr->cmux) {
  1892. circuitmux_detach_all_circuits(curr->cmux, NULL);
  1893. }
  1894. SMARTLIST_DEL_CURRENT(channels, curr);
  1895. channel_unregister(curr);
  1896. if (mark_for_close) {
  1897. if (!CHANNEL_CONDEMNED(curr)) {
  1898. channel_mark_for_close(curr);
  1899. }
  1900. channel_force_xfree(curr);
  1901. } else channel_free(curr);
  1902. } SMARTLIST_FOREACH_END(curr);
  1903. }
  1904. /**
  1905. * Free a list of channel listeners for channel_free_all()
  1906. */
  1907. static void
  1908. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  1909. {
  1910. if (!listeners) return;
  1911. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  1912. /* Deregister and free it */
  1913. tor_assert(curr);
  1914. log_debug(LD_CHANNEL,
  1915. "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
  1916. "in state %s (%d)",
  1917. curr, U64_PRINTF_ARG(curr->global_identifier),
  1918. channel_listener_state_to_string(curr->state), curr->state);
  1919. channel_listener_unregister(curr);
  1920. if (mark_for_close) {
  1921. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1922. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1923. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  1924. channel_listener_mark_for_close(curr);
  1925. }
  1926. channel_listener_force_xfree(curr);
  1927. } else channel_listener_free(curr);
  1928. } SMARTLIST_FOREACH_END(curr);
  1929. }
  1930. /**
  1931. * Close all channels and free everything
  1932. *
  1933. * This gets called from tor_free_all() in main.c to clean up on exit.
  1934. * It will close all registered channels and free associated storage,
  1935. * then free the all_channels, active_channels, listening_channels and
  1936. * finished_channels lists and also channel_identity_map.
  1937. */
  1938. void
  1939. channel_free_all(void)
  1940. {
  1941. log_debug(LD_CHANNEL,
  1942. "Shutting down channels...");
  1943. /* First, let's go for finished channels */
  1944. if (finished_channels) {
  1945. channel_free_list(finished_channels, 0);
  1946. smartlist_free(finished_channels);
  1947. finished_channels = NULL;
  1948. }
  1949. /* Now the finished listeners */
  1950. if (finished_listeners) {
  1951. channel_listener_free_list(finished_listeners, 0);
  1952. smartlist_free(finished_listeners);
  1953. finished_listeners = NULL;
  1954. }
  1955. /* Now all active channels */
  1956. if (active_channels) {
  1957. channel_free_list(active_channels, 1);
  1958. smartlist_free(active_channels);
  1959. active_channels = NULL;
  1960. }
  1961. /* Now all active listeners */
  1962. if (active_listeners) {
  1963. channel_listener_free_list(active_listeners, 1);
  1964. smartlist_free(active_listeners);
  1965. active_listeners = NULL;
  1966. }
  1967. /* Now all channels, in case any are left over */
  1968. if (all_channels) {
  1969. channel_free_list(all_channels, 1);
  1970. smartlist_free(all_channels);
  1971. all_channels = NULL;
  1972. }
  1973. /* Now all listeners, in case any are left over */
  1974. if (all_listeners) {
  1975. channel_listener_free_list(all_listeners, 1);
  1976. smartlist_free(all_listeners);
  1977. all_listeners = NULL;
  1978. }
  1979. /* Now free channel_identity_map */
  1980. log_debug(LD_CHANNEL,
  1981. "Freeing channel_identity_map");
  1982. /* Geez, anything still left over just won't die ... let it leak then */
  1983. HT_CLEAR(channel_idmap, &channel_identity_map);
  1984. /* Same with channel_gid_map */
  1985. log_debug(LD_CHANNEL,
  1986. "Freeing channel_gid_map");
  1987. HT_CLEAR(channel_gid_map, &channel_gid_map);
  1988. log_debug(LD_CHANNEL,
  1989. "Done cleaning up after channels");
  1990. }
  1991. /**
  1992. * Connect to a given addr/port/digest
  1993. *
  1994. * This sets up a new outgoing channel; in the future if multiple
  1995. * channel_t subclasses are available, this is where the selection policy
  1996. * should go. It may also be desirable to fold port into tor_addr_t
  1997. * or make a new type including a tor_addr_t and port, so we have a
  1998. * single abstract object encapsulating all the protocol details of
  1999. * how to contact an OR.
  2000. */
  2001. channel_t *
  2002. channel_connect(const tor_addr_t *addr, uint16_t port,
  2003. const char *id_digest,
  2004. const ed25519_public_key_t *ed_id)
  2005. {
  2006. return channel_tls_connect(addr, port, id_digest, ed_id);
  2007. }
  2008. /**
  2009. * Decide which of two channels to prefer for extending a circuit
  2010. *
  2011. * This function is called while extending a circuit and returns true iff
  2012. * a is 'better' than b. The most important criterion here is that a
  2013. * canonical channel is always better than a non-canonical one, but the
  2014. * number of circuits and the age are used as tie-breakers.
  2015. *
  2016. * This is based on the former connection_or_is_better() of connection_or.c
  2017. */
  2018. int
  2019. channel_is_better(channel_t *a, channel_t *b)
  2020. {
  2021. int a_is_canonical, b_is_canonical;
  2022. tor_assert(a);
  2023. tor_assert(b);
  2024. /* If one channel is bad for new circuits, and the other isn't,
  2025. * use the one that is still good. */
  2026. if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
  2027. return 1;
  2028. if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
  2029. return 0;
  2030. /* Check if one is canonical and the other isn't first */
  2031. a_is_canonical = channel_is_canonical(a);
  2032. b_is_canonical = channel_is_canonical(b);
  2033. if (a_is_canonical && !b_is_canonical) return 1;
  2034. if (!a_is_canonical && b_is_canonical) return 0;
  2035. /* Check if we suspect that one of the channels will be preferred
  2036. * by the peer */
  2037. if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
  2038. if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
  2039. /*
  2040. * Okay, if we're here they tied on canonicity, the prefer the older
  2041. * connection, so that the adversary can't create a new connection
  2042. * and try to switch us over to it (which will leak information
  2043. * about long-lived circuits). Additionally, switching connections
  2044. * too often makes us more vulnerable to attacks like Torscan and
  2045. * passive netflow-based equivalents.
  2046. *
  2047. * Connections will still only live for at most a week, due to
  2048. * the check in connection_or_group_set_badness() against
  2049. * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
  2050. * unusable for new circuits after 1 week. That check sets
  2051. * is_bad_for_new_circs, which is checked in channel_get_for_extend().
  2052. *
  2053. * We check channel_is_bad_for_new_circs() above here anyway, for safety.
  2054. */
  2055. if (channel_when_created(a) < channel_when_created(b)) return 1;
  2056. else if (channel_when_created(a) > channel_when_created(b)) return 0;
  2057. if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
  2058. else return 0;
  2059. }
  2060. /**
  2061. * Get a channel to extend a circuit
  2062. *
  2063. * Pick a suitable channel to extend a circuit to given the desired digest
  2064. * the address we believe is correct for that digest; this tries to see
  2065. * if we already have one for the requested endpoint, but if there is no good
  2066. * channel, set *msg_out to a message describing the channel's state
  2067. * and our next action, and set *launch_out to a boolean indicated whether
  2068. * the caller should try to launch a new channel with channel_connect().
  2069. */
  2070. channel_t *
  2071. channel_get_for_extend(const char *rsa_id_digest,
  2072. const ed25519_public_key_t *ed_id,
  2073. const tor_addr_t *target_addr,
  2074. const char **msg_out,
  2075. int *launch_out)
  2076. {
  2077. channel_t *chan, *best = NULL;
  2078. int n_inprogress_goodaddr = 0, n_old = 0;
  2079. int n_noncanonical = 0, n_possible = 0;
  2080. tor_assert(msg_out);
  2081. tor_assert(launch_out);
  2082. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2083. /* Walk the list, unrefing the old one and refing the new at each
  2084. * iteration.
  2085. */
  2086. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2087. tor_assert(tor_memeq(chan->identity_digest,
  2088. rsa_id_digest, DIGEST_LEN));
  2089. if (CHANNEL_CONDEMNED(chan))
  2090. continue;
  2091. /* Never return a channel on which the other end appears to be
  2092. * a client. */
  2093. if (channel_is_client(chan)) {
  2094. continue;
  2095. }
  2096. /* The Ed25519 key has to match too */
  2097. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  2098. continue;
  2099. }
  2100. /* Never return a non-open connection. */
  2101. if (!CHANNEL_IS_OPEN(chan)) {
  2102. /* If the address matches, don't launch a new connection for this
  2103. * circuit. */
  2104. if (channel_matches_target_addr_for_extend(chan, target_addr))
  2105. ++n_inprogress_goodaddr;
  2106. continue;
  2107. }
  2108. /* Never return a connection that shouldn't be used for circs. */
  2109. if (channel_is_bad_for_new_circs(chan)) {
  2110. ++n_old;
  2111. continue;
  2112. }
  2113. /* Never return a non-canonical connection using a recent link protocol
  2114. * if the address is not what we wanted.
  2115. *
  2116. * The channel_is_canonical_is_reliable() function asks the lower layer
  2117. * if we should trust channel_is_canonical(). The below is from the
  2118. * comments of the old circuit_or_get_for_extend() and applies when
  2119. * the lower-layer transport is channel_tls_t.
  2120. *
  2121. * (For old link protocols, we can't rely on is_canonical getting
  2122. * set properly if we're talking to the right address, since we might
  2123. * have an out-of-date descriptor, and we will get no NETINFO cell to
  2124. * tell us about the right address.)
  2125. */
  2126. if (!channel_is_canonical(chan) &&
  2127. channel_is_canonical_is_reliable(chan) &&
  2128. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  2129. ++n_noncanonical;
  2130. continue;
  2131. }
  2132. ++n_possible;
  2133. if (!best) {
  2134. best = chan; /* If we have no 'best' so far, this one is good enough. */
  2135. continue;
  2136. }
  2137. if (channel_is_better(chan, best))
  2138. best = chan;
  2139. }
  2140. if (best) {
  2141. *msg_out = "Connection is fine; using it.";
  2142. *launch_out = 0;
  2143. return best;
  2144. } else if (n_inprogress_goodaddr) {
  2145. *msg_out = "Connection in progress; waiting.";
  2146. *launch_out = 0;
  2147. return NULL;
  2148. } else if (n_old || n_noncanonical) {
  2149. *msg_out = "Connections all too old, or too non-canonical. "
  2150. " Launching a new one.";
  2151. *launch_out = 1;
  2152. return NULL;
  2153. } else {
  2154. *msg_out = "Not connected. Connecting.";
  2155. *launch_out = 1;
  2156. return NULL;
  2157. }
  2158. }
  2159. /**
  2160. * Describe the transport subclass for a channel
  2161. *
  2162. * Invoke a method to get a string description of the lower-layer
  2163. * transport for this channel.
  2164. */
  2165. const char *
  2166. channel_describe_transport(channel_t *chan)
  2167. {
  2168. tor_assert(chan);
  2169. tor_assert(chan->describe_transport);
  2170. return chan->describe_transport(chan);
  2171. }
  2172. /**
  2173. * Describe the transport subclass for a channel listener
  2174. *
  2175. * Invoke a method to get a string description of the lower-layer
  2176. * transport for this channel listener.
  2177. */
  2178. const char *
  2179. channel_listener_describe_transport(channel_listener_t *chan_l)
  2180. {
  2181. tor_assert(chan_l);
  2182. tor_assert(chan_l->describe_transport);
  2183. return chan_l->describe_transport(chan_l);
  2184. }
  2185. /**
  2186. * Dump channel statistics
  2187. *
  2188. * Dump statistics for one channel to the log
  2189. */
  2190. MOCK_IMPL(void,
  2191. channel_dump_statistics, (channel_t *chan, int severity))
  2192. {
  2193. double avg, interval, age;
  2194. time_t now = time(NULL);
  2195. tor_addr_t remote_addr;
  2196. int have_remote_addr;
  2197. char *remote_addr_str;
  2198. tor_assert(chan);
  2199. age = (double)(now - chan->timestamp_created);
  2200. tor_log(severity, LD_GENERAL,
  2201. "Channel " U64_FORMAT " (at %p) with transport %s is in state "
  2202. "%s (%d)",
  2203. U64_PRINTF_ARG(chan->global_identifier), chan,
  2204. channel_describe_transport(chan),
  2205. channel_state_to_string(chan->state), chan->state);
  2206. tor_log(severity, LD_GENERAL,
  2207. " * Channel " U64_FORMAT " was created at " U64_FORMAT
  2208. " (" U64_FORMAT " seconds ago) "
  2209. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2210. U64_PRINTF_ARG(chan->global_identifier),
  2211. U64_PRINTF_ARG(chan->timestamp_created),
  2212. U64_PRINTF_ARG(now - chan->timestamp_created),
  2213. U64_PRINTF_ARG(chan->timestamp_active),
  2214. U64_PRINTF_ARG(now - chan->timestamp_active));
  2215. /* Handle digest. */
  2216. if (!tor_digest_is_zero(chan->identity_digest)) {
  2217. tor_log(severity, LD_GENERAL,
  2218. " * Channel " U64_FORMAT " says it is connected "
  2219. "to an OR with digest %s",
  2220. U64_PRINTF_ARG(chan->global_identifier),
  2221. hex_str(chan->identity_digest, DIGEST_LEN));
  2222. } else {
  2223. tor_log(severity, LD_GENERAL,
  2224. " * Channel " U64_FORMAT " does not know the digest"
  2225. " of the OR it is connected to",
  2226. U64_PRINTF_ARG(chan->global_identifier));
  2227. }
  2228. /* Handle remote address and descriptions */
  2229. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  2230. if (have_remote_addr) {
  2231. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  2232. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  2233. tor_log(severity, LD_GENERAL,
  2234. " * Channel " U64_FORMAT " says its remote address"
  2235. " is %s, and gives a canonical description of \"%s\" and an "
  2236. "actual description of \"%s\"",
  2237. U64_PRINTF_ARG(chan->global_identifier),
  2238. safe_str(remote_addr_str),
  2239. safe_str(channel_get_canonical_remote_descr(chan)),
  2240. safe_str(actual));
  2241. tor_free(remote_addr_str);
  2242. tor_free(actual);
  2243. } else {
  2244. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  2245. tor_log(severity, LD_GENERAL,
  2246. " * Channel " U64_FORMAT " does not know its remote "
  2247. "address, but gives a canonical description of \"%s\" and an "
  2248. "actual description of \"%s\"",
  2249. U64_PRINTF_ARG(chan->global_identifier),
  2250. channel_get_canonical_remote_descr(chan),
  2251. actual);
  2252. tor_free(actual);
  2253. }
  2254. /* Handle marks */
  2255. tor_log(severity, LD_GENERAL,
  2256. " * Channel " U64_FORMAT " has these marks: %s %s %s "
  2257. "%s %s %s",
  2258. U64_PRINTF_ARG(chan->global_identifier),
  2259. channel_is_bad_for_new_circs(chan) ?
  2260. "bad_for_new_circs" : "!bad_for_new_circs",
  2261. channel_is_canonical(chan) ?
  2262. "canonical" : "!canonical",
  2263. channel_is_canonical_is_reliable(chan) ?
  2264. "is_canonical_is_reliable" :
  2265. "!is_canonical_is_reliable",
  2266. channel_is_client(chan) ?
  2267. "client" : "!client",
  2268. channel_is_local(chan) ?
  2269. "local" : "!local",
  2270. channel_is_incoming(chan) ?
  2271. "incoming" : "outgoing");
  2272. /* Describe circuits */
  2273. tor_log(severity, LD_GENERAL,
  2274. " * Channel " U64_FORMAT " has %d active circuits out of"
  2275. " %d in total",
  2276. U64_PRINTF_ARG(chan->global_identifier),
  2277. (chan->cmux != NULL) ?
  2278. circuitmux_num_active_circuits(chan->cmux) : 0,
  2279. (chan->cmux != NULL) ?
  2280. circuitmux_num_circuits(chan->cmux) : 0);
  2281. /* Describe timestamps */
  2282. tor_log(severity, LD_GENERAL,
  2283. " * Channel " U64_FORMAT " was last used by a "
  2284. "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2285. U64_PRINTF_ARG(chan->global_identifier),
  2286. U64_PRINTF_ARG(chan->timestamp_client),
  2287. U64_PRINTF_ARG(now - chan->timestamp_client));
  2288. tor_log(severity, LD_GENERAL,
  2289. " * Channel " U64_FORMAT " last received a cell "
  2290. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2291. U64_PRINTF_ARG(chan->global_identifier),
  2292. U64_PRINTF_ARG(chan->timestamp_recv),
  2293. U64_PRINTF_ARG(now - chan->timestamp_recv));
  2294. tor_log(severity, LD_GENERAL,
  2295. " * Channel " U64_FORMAT " last transmitted a cell "
  2296. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2297. U64_PRINTF_ARG(chan->global_identifier),
  2298. U64_PRINTF_ARG(chan->timestamp_xmit),
  2299. U64_PRINTF_ARG(now - chan->timestamp_xmit));
  2300. /* Describe counters and rates */
  2301. tor_log(severity, LD_GENERAL,
  2302. " * Channel " U64_FORMAT " has received "
  2303. U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
  2304. U64_FORMAT " bytes in " U64_FORMAT " cells",
  2305. U64_PRINTF_ARG(chan->global_identifier),
  2306. U64_PRINTF_ARG(chan->n_bytes_recved),
  2307. U64_PRINTF_ARG(chan->n_cells_recved),
  2308. U64_PRINTF_ARG(chan->n_bytes_xmitted),
  2309. U64_PRINTF_ARG(chan->n_cells_xmitted));
  2310. if (now > chan->timestamp_created &&
  2311. chan->timestamp_created > 0) {
  2312. if (chan->n_bytes_recved > 0) {
  2313. avg = (double)(chan->n_bytes_recved) / age;
  2314. tor_log(severity, LD_GENERAL,
  2315. " * Channel " U64_FORMAT " has averaged %f "
  2316. "bytes received per second",
  2317. U64_PRINTF_ARG(chan->global_identifier), avg);
  2318. }
  2319. if (chan->n_cells_recved > 0) {
  2320. avg = (double)(chan->n_cells_recved) / age;
  2321. if (avg >= 1.0) {
  2322. tor_log(severity, LD_GENERAL,
  2323. " * Channel " U64_FORMAT " has averaged %f "
  2324. "cells received per second",
  2325. U64_PRINTF_ARG(chan->global_identifier), avg);
  2326. } else if (avg >= 0.0) {
  2327. interval = 1.0 / avg;
  2328. tor_log(severity, LD_GENERAL,
  2329. " * Channel " U64_FORMAT " has averaged %f "
  2330. "seconds between received cells",
  2331. U64_PRINTF_ARG(chan->global_identifier), interval);
  2332. }
  2333. }
  2334. if (chan->n_bytes_xmitted > 0) {
  2335. avg = (double)(chan->n_bytes_xmitted) / age;
  2336. tor_log(severity, LD_GENERAL,
  2337. " * Channel " U64_FORMAT " has averaged %f "
  2338. "bytes transmitted per second",
  2339. U64_PRINTF_ARG(chan->global_identifier), avg);
  2340. }
  2341. if (chan->n_cells_xmitted > 0) {
  2342. avg = (double)(chan->n_cells_xmitted) / age;
  2343. if (avg >= 1.0) {
  2344. tor_log(severity, LD_GENERAL,
  2345. " * Channel " U64_FORMAT " has averaged %f "
  2346. "cells transmitted per second",
  2347. U64_PRINTF_ARG(chan->global_identifier), avg);
  2348. } else if (avg >= 0.0) {
  2349. interval = 1.0 / avg;
  2350. tor_log(severity, LD_GENERAL,
  2351. " * Channel " U64_FORMAT " has averaged %f "
  2352. "seconds between transmitted cells",
  2353. U64_PRINTF_ARG(chan->global_identifier), interval);
  2354. }
  2355. }
  2356. }
  2357. /* Dump anything the lower layer has to say */
  2358. channel_dump_transport_statistics(chan, severity);
  2359. }
  2360. /**
  2361. * Dump channel listener statistics
  2362. *
  2363. * Dump statistics for one channel listener to the log
  2364. */
  2365. void
  2366. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  2367. {
  2368. double avg, interval, age;
  2369. time_t now = time(NULL);
  2370. tor_assert(chan_l);
  2371. age = (double)(now - chan_l->timestamp_created);
  2372. tor_log(severity, LD_GENERAL,
  2373. "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
  2374. "state %s (%d)",
  2375. U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
  2376. channel_listener_describe_transport(chan_l),
  2377. channel_listener_state_to_string(chan_l->state), chan_l->state);
  2378. tor_log(severity, LD_GENERAL,
  2379. " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
  2380. " (" U64_FORMAT " seconds ago) "
  2381. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2382. U64_PRINTF_ARG(chan_l->global_identifier),
  2383. U64_PRINTF_ARG(chan_l->timestamp_created),
  2384. U64_PRINTF_ARG(now - chan_l->timestamp_created),
  2385. U64_PRINTF_ARG(chan_l->timestamp_active),
  2386. U64_PRINTF_ARG(now - chan_l->timestamp_active));
  2387. tor_log(severity, LD_GENERAL,
  2388. " * Channel listener " U64_FORMAT " last accepted an incoming "
  2389. "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
  2390. "and has accepted " U64_FORMAT " channels in total",
  2391. U64_PRINTF_ARG(chan_l->global_identifier),
  2392. U64_PRINTF_ARG(chan_l->timestamp_accepted),
  2393. U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
  2394. U64_PRINTF_ARG(chan_l->n_accepted));
  2395. /*
  2396. * If it's sensible to do so, get the rate of incoming channels on this
  2397. * listener
  2398. */
  2399. if (now > chan_l->timestamp_created &&
  2400. chan_l->timestamp_created > 0 &&
  2401. chan_l->n_accepted > 0) {
  2402. avg = (double)(chan_l->n_accepted) / age;
  2403. if (avg >= 1.0) {
  2404. tor_log(severity, LD_GENERAL,
  2405. " * Channel listener " U64_FORMAT " has averaged %f incoming "
  2406. "channels per second",
  2407. U64_PRINTF_ARG(chan_l->global_identifier), avg);
  2408. } else if (avg >= 0.0) {
  2409. interval = 1.0 / avg;
  2410. tor_log(severity, LD_GENERAL,
  2411. " * Channel listener " U64_FORMAT " has averaged %f seconds "
  2412. "between incoming channels",
  2413. U64_PRINTF_ARG(chan_l->global_identifier), interval);
  2414. }
  2415. }
  2416. /* Dump anything the lower layer has to say */
  2417. channel_listener_dump_transport_statistics(chan_l, severity);
  2418. }
  2419. /**
  2420. * Invoke transport-specific stats dump for channel
  2421. *
  2422. * If there is a lower-layer statistics dump method, invoke it
  2423. */
  2424. void
  2425. channel_dump_transport_statistics(channel_t *chan, int severity)
  2426. {
  2427. tor_assert(chan);
  2428. if (chan->dumpstats) chan->dumpstats(chan, severity);
  2429. }
  2430. /**
  2431. * Invoke transport-specific stats dump for channel listener
  2432. *
  2433. * If there is a lower-layer statistics dump method, invoke it
  2434. */
  2435. void
  2436. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  2437. int severity)
  2438. {
  2439. tor_assert(chan_l);
  2440. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  2441. }
  2442. /**
  2443. * Return text description of the remote endpoint
  2444. *
  2445. * This function return a test provided by the lower layer of the remote
  2446. * endpoint for this channel; it should specify the actual address connected
  2447. * to/from.
  2448. *
  2449. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2450. * may invalidate the return value from this function.
  2451. */
  2452. const char *
  2453. channel_get_actual_remote_descr(channel_t *chan)
  2454. {
  2455. tor_assert(chan);
  2456. tor_assert(chan->get_remote_descr);
  2457. /* Param 1 indicates the actual description */
  2458. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  2459. }
  2460. /**
  2461. * Return the text address of the remote endpoint.
  2462. *
  2463. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2464. * may invalidate the return value from this function.
  2465. */
  2466. const char *
  2467. channel_get_actual_remote_address(channel_t *chan)
  2468. {
  2469. /* Param 1 indicates the actual description */
  2470. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  2471. }
  2472. /**
  2473. * Return text description of the remote endpoint canonical address
  2474. *
  2475. * This function return a test provided by the lower layer of the remote
  2476. * endpoint for this channel; it should use the known canonical address for
  2477. * this OR's identity digest if possible.
  2478. *
  2479. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2480. * may invalidate the return value from this function.
  2481. */
  2482. const char *
  2483. channel_get_canonical_remote_descr(channel_t *chan)
  2484. {
  2485. tor_assert(chan);
  2486. tor_assert(chan->get_remote_descr);
  2487. /* Param 0 indicates the canonicalized description */
  2488. return chan->get_remote_descr(chan, 0);
  2489. }
  2490. /**
  2491. * Get remote address if possible.
  2492. *
  2493. * Write the remote address out to a tor_addr_t if the underlying transport
  2494. * supports this operation, and return 1. Return 0 if the underlying transport
  2495. * doesn't let us do this.
  2496. */
  2497. MOCK_IMPL(int,
  2498. channel_get_addr_if_possible,(channel_t *chan, tor_addr_t *addr_out))
  2499. {
  2500. tor_assert(chan);
  2501. tor_assert(addr_out);
  2502. if (chan->get_remote_addr)
  2503. return chan->get_remote_addr(chan, addr_out);
  2504. /* Else no support, method not implemented */
  2505. else return 0;
  2506. }
  2507. /*
  2508. * Return true iff the channel has any cells on the connection outbuf waiting
  2509. * to be sent onto the network.
  2510. */
  2511. int
  2512. channel_has_queued_writes(channel_t *chan)
  2513. {
  2514. tor_assert(chan);
  2515. tor_assert(chan->has_queued_writes);
  2516. /* Check with the lower layer */
  2517. return chan->has_queued_writes(chan);
  2518. }
  2519. /**
  2520. * Check the is_bad_for_new_circs flag
  2521. *
  2522. * This function returns the is_bad_for_new_circs flag of the specified
  2523. * channel.
  2524. */
  2525. int
  2526. channel_is_bad_for_new_circs(channel_t *chan)
  2527. {
  2528. tor_assert(chan);
  2529. return chan->is_bad_for_new_circs;
  2530. }
  2531. /**
  2532. * Mark a channel as bad for new circuits
  2533. *
  2534. * Set the is_bad_for_new_circs_flag on chan.
  2535. */
  2536. void
  2537. channel_mark_bad_for_new_circs(channel_t *chan)
  2538. {
  2539. tor_assert(chan);
  2540. chan->is_bad_for_new_circs = 1;
  2541. }
  2542. /**
  2543. * Get the client flag
  2544. *
  2545. * This returns the client flag of a channel, which will be set if
  2546. * command_process_create_cell() in command.c thinks this is a connection
  2547. * from a client.
  2548. */
  2549. int
  2550. channel_is_client(const channel_t *chan)
  2551. {
  2552. tor_assert(chan);
  2553. return chan->is_client;
  2554. }
  2555. /**
  2556. * Set the client flag
  2557. *
  2558. * Mark a channel as being from a client
  2559. */
  2560. void
  2561. channel_mark_client(channel_t *chan)
  2562. {
  2563. tor_assert(chan);
  2564. chan->is_client = 1;
  2565. }
  2566. /**
  2567. * Clear the client flag
  2568. *
  2569. * Mark a channel as being _not_ from a client
  2570. */
  2571. void
  2572. channel_clear_client(channel_t *chan)
  2573. {
  2574. tor_assert(chan);
  2575. chan->is_client = 0;
  2576. }
  2577. /**
  2578. * Get the canonical flag for a channel
  2579. *
  2580. * This returns the is_canonical for a channel; this flag is determined by
  2581. * the lower layer and can't be set in a transport-independent way.
  2582. */
  2583. int
  2584. channel_is_canonical(channel_t *chan)
  2585. {
  2586. tor_assert(chan);
  2587. tor_assert(chan->is_canonical);
  2588. return chan->is_canonical(chan, 0);
  2589. }
  2590. /**
  2591. * Test if the canonical flag is reliable
  2592. *
  2593. * This function asks if the lower layer thinks it's safe to trust the
  2594. * result of channel_is_canonical()
  2595. */
  2596. int
  2597. channel_is_canonical_is_reliable(channel_t *chan)
  2598. {
  2599. tor_assert(chan);
  2600. tor_assert(chan->is_canonical);
  2601. return chan->is_canonical(chan, 1);
  2602. }
  2603. /**
  2604. * Test incoming flag
  2605. *
  2606. * This function gets the incoming flag; this is set when a listener spawns
  2607. * a channel. If this returns true the channel was remotely initiated.
  2608. */
  2609. int
  2610. channel_is_incoming(channel_t *chan)
  2611. {
  2612. tor_assert(chan);
  2613. return chan->is_incoming;
  2614. }
  2615. /**
  2616. * Set the incoming flag
  2617. *
  2618. * This function is called when a channel arrives on a listening channel
  2619. * to mark it as incoming.
  2620. */
  2621. void
  2622. channel_mark_incoming(channel_t *chan)
  2623. {
  2624. tor_assert(chan);
  2625. chan->is_incoming = 1;
  2626. }
  2627. /**
  2628. * Test local flag
  2629. *
  2630. * This function gets the local flag; the lower layer should set this when
  2631. * setting up the channel if is_local_addr() is true for all of the
  2632. * destinations it will communicate with on behalf of this channel. It's
  2633. * used to decide whether to declare the network reachable when seeing incoming
  2634. * traffic on the channel.
  2635. */
  2636. int
  2637. channel_is_local(channel_t *chan)
  2638. {
  2639. tor_assert(chan);
  2640. return chan->is_local;
  2641. }
  2642. /**
  2643. * Set the local flag
  2644. *
  2645. * This internal-only function should be called by the lower layer if the
  2646. * channel is to a local address. See channel_is_local() above or the
  2647. * description of the is_local bit in channel.h
  2648. */
  2649. void
  2650. channel_mark_local(channel_t *chan)
  2651. {
  2652. tor_assert(chan);
  2653. chan->is_local = 1;
  2654. }
  2655. /**
  2656. * Mark a channel as remote
  2657. *
  2658. * This internal-only function should be called by the lower layer if the
  2659. * channel is not to a local address but has previously been marked local.
  2660. * See channel_is_local() above or the description of the is_local bit in
  2661. * channel.h
  2662. */
  2663. void
  2664. channel_mark_remote(channel_t *chan)
  2665. {
  2666. tor_assert(chan);
  2667. chan->is_local = 0;
  2668. }
  2669. /**
  2670. * Test outgoing flag
  2671. *
  2672. * This function gets the outgoing flag; this is the inverse of the incoming
  2673. * bit set when a listener spawns a channel. If this returns true the channel
  2674. * was locally initiated.
  2675. */
  2676. int
  2677. channel_is_outgoing(channel_t *chan)
  2678. {
  2679. tor_assert(chan);
  2680. return !(chan->is_incoming);
  2681. }
  2682. /**
  2683. * Mark a channel as outgoing
  2684. *
  2685. * This function clears the incoming flag and thus marks a channel as
  2686. * outgoing.
  2687. */
  2688. void
  2689. channel_mark_outgoing(channel_t *chan)
  2690. {
  2691. tor_assert(chan);
  2692. chan->is_incoming = 0;
  2693. }
  2694. /************************
  2695. * Flow control queries *
  2696. ***********************/
  2697. /*
  2698. * Estimate the number of writeable cells
  2699. *
  2700. * Ask the lower layer for an estimate of how many cells it can accept.
  2701. */
  2702. int
  2703. channel_num_cells_writeable(channel_t *chan)
  2704. {
  2705. int result;
  2706. tor_assert(chan);
  2707. tor_assert(chan->num_cells_writeable);
  2708. if (chan->state == CHANNEL_STATE_OPEN) {
  2709. /* Query lower layer */
  2710. result = chan->num_cells_writeable(chan);
  2711. if (result < 0) result = 0;
  2712. } else {
  2713. /* No cells are writeable in any other state */
  2714. result = 0;
  2715. }
  2716. return result;
  2717. }
  2718. /*********************
  2719. * Timestamp updates *
  2720. ********************/
  2721. /**
  2722. * Update the created timestamp for a channel
  2723. *
  2724. * This updates the channel's created timestamp and should only be called
  2725. * from channel_init().
  2726. */
  2727. void
  2728. channel_timestamp_created(channel_t *chan)
  2729. {
  2730. time_t now = time(NULL);
  2731. tor_assert(chan);
  2732. chan->timestamp_created = now;
  2733. }
  2734. /**
  2735. * Update the created timestamp for a channel listener
  2736. *
  2737. * This updates the channel listener's created timestamp and should only be
  2738. * called from channel_init_listener().
  2739. */
  2740. void
  2741. channel_listener_timestamp_created(channel_listener_t *chan_l)
  2742. {
  2743. time_t now = time(NULL);
  2744. tor_assert(chan_l);
  2745. chan_l->timestamp_created = now;
  2746. }
  2747. /**
  2748. * Update the last active timestamp for a channel
  2749. *
  2750. * This function updates the channel's last active timestamp; it should be
  2751. * called by the lower layer whenever there is activity on the channel which
  2752. * does not lead to a cell being transmitted or received; the active timestamp
  2753. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  2754. * but it should be updated for things like the v3 handshake and stuff that
  2755. * produce activity only visible to the lower layer.
  2756. */
  2757. void
  2758. channel_timestamp_active(channel_t *chan)
  2759. {
  2760. time_t now = time(NULL);
  2761. tor_assert(chan);
  2762. monotime_coarse_get(&chan->timestamp_xfer);
  2763. chan->timestamp_active = now;
  2764. /* Clear any potential netflow padding timer. We're active */
  2765. monotime_coarse_zero(&chan->next_padding_time);
  2766. }
  2767. /**
  2768. * Update the last active timestamp for a channel listener
  2769. */
  2770. void
  2771. channel_listener_timestamp_active(channel_listener_t *chan_l)
  2772. {
  2773. time_t now = time(NULL);
  2774. tor_assert(chan_l);
  2775. chan_l->timestamp_active = now;
  2776. }
  2777. /**
  2778. * Update the last accepted timestamp.
  2779. *
  2780. * This function updates the channel listener's last accepted timestamp; it
  2781. * should be called whenever a new incoming channel is accepted on a
  2782. * listener.
  2783. */
  2784. void
  2785. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  2786. {
  2787. time_t now = time(NULL);
  2788. tor_assert(chan_l);
  2789. chan_l->timestamp_active = now;
  2790. chan_l->timestamp_accepted = now;
  2791. }
  2792. /**
  2793. * Update client timestamp
  2794. *
  2795. * This function is called by relay.c to timestamp a channel that appears to
  2796. * be used as a client.
  2797. */
  2798. void
  2799. channel_timestamp_client(channel_t *chan)
  2800. {
  2801. time_t now = time(NULL);
  2802. tor_assert(chan);
  2803. chan->timestamp_client = now;
  2804. }
  2805. /**
  2806. * Update the recv timestamp
  2807. *
  2808. * This is called whenever we get an incoming cell from the lower layer.
  2809. * This also updates the active timestamp.
  2810. */
  2811. void
  2812. channel_timestamp_recv(channel_t *chan)
  2813. {
  2814. time_t now = time(NULL);
  2815. tor_assert(chan);
  2816. monotime_coarse_get(&chan->timestamp_xfer);
  2817. chan->timestamp_active = now;
  2818. chan->timestamp_recv = now;
  2819. /* Clear any potential netflow padding timer. We're active */
  2820. monotime_coarse_zero(&chan->next_padding_time);
  2821. }
  2822. /**
  2823. * Update the xmit timestamp
  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. }