channel.c 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572
  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 seperation 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. }
  729. /**
  730. * Initialize a channel listener
  731. *
  732. * This function should be called by subclasses to set up some per-channel
  733. * variables. I.e., this is the superclass constructor. Before this, the
  734. * channel listener should be allocated with tor_malloc_zero().
  735. */
  736. void
  737. channel_init_listener(channel_listener_t *chan_l)
  738. {
  739. tor_assert(chan_l);
  740. /* Assign an ID and bump the counter */
  741. chan_l->global_identifier = ++n_channels_allocated;
  742. /* Timestamp it */
  743. channel_listener_timestamp_created(chan_l);
  744. }
  745. /**
  746. * Free a channel; nothing outside of channel.c and subclasses should call
  747. * this - it frees channels after they have closed and been unregistered.
  748. */
  749. void
  750. channel_free_(channel_t *chan)
  751. {
  752. if (!chan) return;
  753. /* It must be closed or errored */
  754. tor_assert(CHANNEL_FINISHED(chan));
  755. /* It must be deregistered */
  756. tor_assert(!(chan->registered));
  757. log_debug(LD_CHANNEL,
  758. "Freeing channel " U64_FORMAT " at %p",
  759. U64_PRINTF_ARG(chan->global_identifier), chan);
  760. /* Get this one out of the scheduler */
  761. scheduler_release_channel(chan);
  762. /*
  763. * Get rid of cmux policy before we do anything, so cmux policies don't
  764. * see channels in weird half-freed states.
  765. */
  766. if (chan->cmux) {
  767. circuitmux_set_policy(chan->cmux, NULL);
  768. }
  769. /* Remove all timers and associated handle entries now */
  770. timer_free(chan->padding_timer);
  771. channel_handle_free(chan->timer_handle);
  772. channel_handles_clear(chan);
  773. /* Call a free method if there is one */
  774. if (chan->free_fn) chan->free_fn(chan);
  775. channel_clear_remote_end(chan);
  776. /* Get rid of cmux */
  777. if (chan->cmux) {
  778. circuitmux_detach_all_circuits(chan->cmux, NULL);
  779. circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
  780. circuitmux_free(chan->cmux);
  781. chan->cmux = NULL;
  782. }
  783. tor_free(chan);
  784. }
  785. /**
  786. * Free a channel listener; nothing outside of channel.c and subclasses
  787. * should call this - it frees channel listeners after they have closed and
  788. * been unregistered.
  789. */
  790. void
  791. channel_listener_free_(channel_listener_t *chan_l)
  792. {
  793. if (!chan_l) return;
  794. log_debug(LD_CHANNEL,
  795. "Freeing channel_listener_t " U64_FORMAT " at %p",
  796. U64_PRINTF_ARG(chan_l->global_identifier),
  797. chan_l);
  798. /* It must be closed or errored */
  799. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  800. chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
  801. /* It must be deregistered */
  802. tor_assert(!(chan_l->registered));
  803. /* Call a free method if there is one */
  804. if (chan_l->free_fn) chan_l->free_fn(chan_l);
  805. tor_free(chan_l);
  806. }
  807. /**
  808. * Free a channel and skip the state/registration asserts; this internal-
  809. * use-only function should be called only from channel_free_all() when
  810. * shutting down the Tor process.
  811. */
  812. static void
  813. channel_force_xfree(channel_t *chan)
  814. {
  815. tor_assert(chan);
  816. log_debug(LD_CHANNEL,
  817. "Force-freeing channel " U64_FORMAT " at %p",
  818. U64_PRINTF_ARG(chan->global_identifier), chan);
  819. /* Get this one out of the scheduler */
  820. scheduler_release_channel(chan);
  821. /*
  822. * Get rid of cmux policy before we do anything, so cmux policies don't
  823. * see channels in weird half-freed states.
  824. */
  825. if (chan->cmux) {
  826. circuitmux_set_policy(chan->cmux, NULL);
  827. }
  828. /* Remove all timers and associated handle entries now */
  829. timer_free(chan->padding_timer);
  830. channel_handle_free(chan->timer_handle);
  831. channel_handles_clear(chan);
  832. /* Call a free method if there is one */
  833. if (chan->free_fn) chan->free_fn(chan);
  834. channel_clear_remote_end(chan);
  835. /* Get rid of cmux */
  836. if (chan->cmux) {
  837. circuitmux_free(chan->cmux);
  838. chan->cmux = NULL;
  839. }
  840. tor_free(chan);
  841. }
  842. /**
  843. * Free a channel listener and skip the state/reigstration asserts; this
  844. * internal-use-only function should be called only from channel_free_all()
  845. * when shutting down the Tor process.
  846. */
  847. static void
  848. channel_listener_force_xfree(channel_listener_t *chan_l)
  849. {
  850. tor_assert(chan_l);
  851. log_debug(LD_CHANNEL,
  852. "Force-freeing channel_listener_t " U64_FORMAT " at %p",
  853. U64_PRINTF_ARG(chan_l->global_identifier),
  854. chan_l);
  855. /* Call a free method if there is one */
  856. if (chan_l->free_fn) chan_l->free_fn(chan_l);
  857. /*
  858. * The incoming list just gets emptied and freed; we request close on
  859. * any channels we find there, but since we got called while shutting
  860. * down they will get deregistered and freed elsewhere anyway.
  861. */
  862. if (chan_l->incoming_list) {
  863. SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
  864. channel_t *, qchan) {
  865. channel_mark_for_close(qchan);
  866. } SMARTLIST_FOREACH_END(qchan);
  867. smartlist_free(chan_l->incoming_list);
  868. chan_l->incoming_list = NULL;
  869. }
  870. tor_free(chan_l);
  871. }
  872. /**
  873. * Set the listener for a channel listener
  874. *
  875. * This function sets the handler for new incoming channels on a channel
  876. * listener.
  877. */
  878. void
  879. channel_listener_set_listener_fn(channel_listener_t *chan_l,
  880. channel_listener_fn_ptr listener)
  881. {
  882. tor_assert(chan_l);
  883. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
  884. log_debug(LD_CHANNEL,
  885. "Setting listener callback for channel listener %p "
  886. "(global ID " U64_FORMAT ") to %p",
  887. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  888. listener);
  889. chan_l->listener = listener;
  890. if (chan_l->listener) channel_listener_process_incoming(chan_l);
  891. }
  892. /**
  893. * Return the fixed-length cell handler for a channel
  894. *
  895. * This function gets the handler for incoming fixed-length cells installed
  896. * on a channel.
  897. */
  898. channel_cell_handler_fn_ptr
  899. channel_get_cell_handler(channel_t *chan)
  900. {
  901. tor_assert(chan);
  902. if (CHANNEL_CAN_HANDLE_CELLS(chan))
  903. return chan->cell_handler;
  904. return NULL;
  905. }
  906. /**
  907. * Return the variable-length cell handler for a channel
  908. *
  909. * This function gets the handler for incoming variable-length cells
  910. * installed on a channel.
  911. */
  912. channel_var_cell_handler_fn_ptr
  913. channel_get_var_cell_handler(channel_t *chan)
  914. {
  915. tor_assert(chan);
  916. if (CHANNEL_CAN_HANDLE_CELLS(chan))
  917. return chan->var_cell_handler;
  918. return NULL;
  919. }
  920. /**
  921. * Set both cell handlers for a channel
  922. *
  923. * This function sets both the fixed-length and variable length cell handlers
  924. * for a channel.
  925. */
  926. void
  927. channel_set_cell_handlers(channel_t *chan,
  928. channel_cell_handler_fn_ptr cell_handler,
  929. channel_var_cell_handler_fn_ptr
  930. var_cell_handler)
  931. {
  932. tor_assert(chan);
  933. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  934. log_debug(LD_CHANNEL,
  935. "Setting cell_handler callback for channel %p to %p",
  936. chan, cell_handler);
  937. log_debug(LD_CHANNEL,
  938. "Setting var_cell_handler callback for channel %p to %p",
  939. chan, var_cell_handler);
  940. /* Change them */
  941. chan->cell_handler = cell_handler;
  942. chan->var_cell_handler = var_cell_handler;
  943. }
  944. /*
  945. * On closing channels
  946. *
  947. * There are three functions that close channels, for use in
  948. * different circumstances:
  949. *
  950. * - Use channel_mark_for_close() for most cases
  951. * - Use channel_close_from_lower_layer() if you are connection_or.c
  952. * and the other end closes the underlying connection.
  953. * - Use channel_close_for_error() if you are connection_or.c and
  954. * some sort of error has occurred.
  955. */
  956. /**
  957. * Mark a channel for closure
  958. *
  959. * This function tries to close a channel_t; it will go into the CLOSING
  960. * state, and eventually the lower layer should put it into the CLOSED or
  961. * ERROR state. Then, channel_run_cleanup() will eventually free it.
  962. */
  963. void
  964. channel_mark_for_close(channel_t *chan)
  965. {
  966. tor_assert(chan != NULL);
  967. tor_assert(chan->close != NULL);
  968. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  969. if (CHANNEL_CONDEMNED(chan))
  970. return;
  971. log_debug(LD_CHANNEL,
  972. "Closing channel %p (global ID " U64_FORMAT ") "
  973. "by request",
  974. chan, U64_PRINTF_ARG(chan->global_identifier));
  975. /* Note closing by request from above */
  976. chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
  977. /* Change state to CLOSING */
  978. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  979. /* Tell the lower layer */
  980. chan->close(chan);
  981. /*
  982. * It's up to the lower layer to change state to CLOSED or ERROR when we're
  983. * ready; we'll try to free channels that are in the finished list from
  984. * channel_run_cleanup(). The lower layer should do this by calling
  985. * channel_closed().
  986. */
  987. }
  988. /**
  989. * Mark a channel listener for closure
  990. *
  991. * This function tries to close a channel_listener_t; it will go into the
  992. * CLOSING state, and eventually the lower layer should put it into the CLOSED
  993. * or ERROR state. Then, channel_run_cleanup() will eventually free it.
  994. */
  995. void
  996. channel_listener_mark_for_close(channel_listener_t *chan_l)
  997. {
  998. tor_assert(chan_l != NULL);
  999. tor_assert(chan_l->close != NULL);
  1000. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1001. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1002. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1003. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1004. log_debug(LD_CHANNEL,
  1005. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1006. "by request",
  1007. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1008. /* Note closing by request from above */
  1009. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
  1010. /* Change state to CLOSING */
  1011. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1012. /* Tell the lower layer */
  1013. chan_l->close(chan_l);
  1014. /*
  1015. * It's up to the lower layer to change state to CLOSED or ERROR when we're
  1016. * ready; we'll try to free channels that are in the finished list from
  1017. * channel_run_cleanup(). The lower layer should do this by calling
  1018. * channel_listener_closed().
  1019. */
  1020. }
  1021. /**
  1022. * Close a channel from the lower layer
  1023. *
  1024. * Notify the channel code that the channel is being closed due to a non-error
  1025. * condition in the lower layer. This does not call the close() method, since
  1026. * the lower layer already knows.
  1027. */
  1028. void
  1029. channel_close_from_lower_layer(channel_t *chan)
  1030. {
  1031. tor_assert(chan != NULL);
  1032. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1033. if (CHANNEL_CONDEMNED(chan))
  1034. return;
  1035. log_debug(LD_CHANNEL,
  1036. "Closing channel %p (global ID " U64_FORMAT ") "
  1037. "due to lower-layer event",
  1038. chan, U64_PRINTF_ARG(chan->global_identifier));
  1039. /* Note closing by event from below */
  1040. chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
  1041. /* Change state to CLOSING */
  1042. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1043. }
  1044. /**
  1045. * Notify that the channel is being closed due to an error condition
  1046. *
  1047. * This function is called by the lower layer implementing the transport
  1048. * when a channel must be closed due to an error condition. This does not
  1049. * call the channel's close method, since the lower layer already knows.
  1050. */
  1051. void
  1052. channel_close_for_error(channel_t *chan)
  1053. {
  1054. tor_assert(chan != NULL);
  1055. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1056. if (CHANNEL_CONDEMNED(chan))
  1057. return;
  1058. log_debug(LD_CHANNEL,
  1059. "Closing channel %p due to lower-layer error",
  1060. chan);
  1061. /* Note closing by event from below */
  1062. chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
  1063. /* Change state to CLOSING */
  1064. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1065. }
  1066. /**
  1067. * Notify that the lower layer is finished closing the channel
  1068. *
  1069. * This function should be called by the lower layer when a channel
  1070. * is finished closing and it should be regarded as inactive and
  1071. * freed by the channel code.
  1072. */
  1073. void
  1074. channel_closed(channel_t *chan)
  1075. {
  1076. tor_assert(chan);
  1077. tor_assert(CHANNEL_CONDEMNED(chan));
  1078. /* No-op if already inactive */
  1079. if (CHANNEL_FINISHED(chan))
  1080. return;
  1081. /* Inform any pending (not attached) circs that they should
  1082. * give up. */
  1083. if (! chan->has_been_open)
  1084. circuit_n_chan_done(chan, 0, 0);
  1085. /* Now close all the attached circuits on it. */
  1086. circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
  1087. if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
  1088. channel_change_state(chan, CHANNEL_STATE_CLOSED);
  1089. } else {
  1090. channel_change_state(chan, CHANNEL_STATE_ERROR);
  1091. }
  1092. }
  1093. /**
  1094. * Clear the identity_digest of a channel
  1095. *
  1096. * This function clears the identity digest of the remote endpoint for a
  1097. * channel; this is intended for use by the lower layer.
  1098. */
  1099. void
  1100. channel_clear_identity_digest(channel_t *chan)
  1101. {
  1102. int state_not_in_map;
  1103. tor_assert(chan);
  1104. log_debug(LD_CHANNEL,
  1105. "Clearing remote endpoint digest on channel %p with "
  1106. "global ID " U64_FORMAT,
  1107. chan, U64_PRINTF_ARG(chan->global_identifier));
  1108. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1109. if (!state_not_in_map && chan->registered &&
  1110. !tor_digest_is_zero(chan->identity_digest))
  1111. /* if it's registered get it out of the digest map */
  1112. channel_remove_from_digest_map(chan);
  1113. memset(chan->identity_digest, 0,
  1114. sizeof(chan->identity_digest));
  1115. }
  1116. /**
  1117. * Set the identity_digest of a channel
  1118. *
  1119. * This function sets the identity digest of the remote endpoint for a
  1120. * channel; this is intended for use by the lower layer.
  1121. */
  1122. void
  1123. channel_set_identity_digest(channel_t *chan,
  1124. const char *identity_digest,
  1125. const ed25519_public_key_t *ed_identity)
  1126. {
  1127. int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
  1128. tor_assert(chan);
  1129. log_debug(LD_CHANNEL,
  1130. "Setting remote endpoint digest on channel %p with "
  1131. "global ID " U64_FORMAT " to digest %s",
  1132. chan, U64_PRINTF_ARG(chan->global_identifier),
  1133. identity_digest ?
  1134. hex_str(identity_digest, DIGEST_LEN) : "(null)");
  1135. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1136. was_in_digest_map =
  1137. !state_not_in_map &&
  1138. chan->registered &&
  1139. !tor_digest_is_zero(chan->identity_digest);
  1140. should_be_in_digest_map =
  1141. !state_not_in_map &&
  1142. chan->registered &&
  1143. (identity_digest &&
  1144. !tor_digest_is_zero(identity_digest));
  1145. if (was_in_digest_map)
  1146. /* We should always remove it; we'll add it back if we're writing
  1147. * in a new digest.
  1148. */
  1149. channel_remove_from_digest_map(chan);
  1150. if (identity_digest) {
  1151. memcpy(chan->identity_digest,
  1152. identity_digest,
  1153. sizeof(chan->identity_digest));
  1154. } else {
  1155. memset(chan->identity_digest, 0,
  1156. sizeof(chan->identity_digest));
  1157. }
  1158. if (ed_identity) {
  1159. memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
  1160. } else {
  1161. memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
  1162. }
  1163. /* Put it in the digest map if we should */
  1164. if (should_be_in_digest_map)
  1165. channel_add_to_digest_map(chan);
  1166. }
  1167. /**
  1168. * Clear the remote end metadata (identity_digest) of a channel
  1169. *
  1170. * This function clears all the remote end info from a channel; this is
  1171. * intended for use by the lower layer.
  1172. */
  1173. void
  1174. channel_clear_remote_end(channel_t *chan)
  1175. {
  1176. int state_not_in_map;
  1177. tor_assert(chan);
  1178. log_debug(LD_CHANNEL,
  1179. "Clearing remote endpoint identity on channel %p with "
  1180. "global ID " U64_FORMAT,
  1181. chan, U64_PRINTF_ARG(chan->global_identifier));
  1182. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1183. if (!state_not_in_map && chan->registered &&
  1184. !tor_digest_is_zero(chan->identity_digest))
  1185. /* if it's registered get it out of the digest map */
  1186. channel_remove_from_digest_map(chan);
  1187. memset(chan->identity_digest, 0,
  1188. sizeof(chan->identity_digest));
  1189. }
  1190. /**
  1191. * Write to a channel the given packed cell.
  1192. *
  1193. *
  1194. * Two possible errors can happen. Either the channel is not opened or the
  1195. * lower layer (specialized channel) failed to write it. In both cases, it is
  1196. * the caller responsability to free the cell.
  1197. */
  1198. static int
  1199. write_packed_cell(channel_t *chan, packed_cell_t *cell)
  1200. {
  1201. int ret = -1;
  1202. size_t cell_bytes;
  1203. tor_assert(chan);
  1204. tor_assert(cell);
  1205. /* Assert that the state makes sense for a cell write */
  1206. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  1207. {
  1208. circid_t circ_id;
  1209. if (packed_cell_is_destroy(chan, cell, &circ_id)) {
  1210. channel_note_destroy_not_pending(chan, circ_id);
  1211. }
  1212. }
  1213. /* For statistical purposes, figure out how big this cell is */
  1214. cell_bytes = get_cell_network_size(chan->wide_circ_ids);
  1215. /* Can we send it right out? If so, try */
  1216. if (!CHANNEL_IS_OPEN(chan)) {
  1217. goto done;
  1218. }
  1219. /* Write the cell on the connection's outbuf. */
  1220. if (chan->write_packed_cell(chan, cell) < 0) {
  1221. goto done;
  1222. }
  1223. /* Timestamp for transmission */
  1224. channel_timestamp_xmit(chan);
  1225. /* Update the counter */
  1226. ++(chan->n_cells_xmitted);
  1227. chan->n_bytes_xmitted += cell_bytes;
  1228. /* Successfully sent the cell. */
  1229. ret = 0;
  1230. done:
  1231. return ret;
  1232. }
  1233. /**
  1234. * Write a packed cell to a channel
  1235. *
  1236. * Write a packed cell to a channel using the write_cell() method. This is
  1237. * called by the transport-independent code to deliver a packed cell to a
  1238. * channel for transmission.
  1239. *
  1240. * Return 0 on success else a negative value. In both cases, the caller should
  1241. * not access the cell anymore, it is freed both on success and error.
  1242. */
  1243. int
  1244. channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
  1245. {
  1246. int ret = -1;
  1247. tor_assert(chan);
  1248. tor_assert(cell);
  1249. if (CHANNEL_IS_CLOSING(chan)) {
  1250. log_debug(LD_CHANNEL, "Discarding %p on closing channel %p with "
  1251. "global ID "U64_FORMAT, cell, chan,
  1252. U64_PRINTF_ARG(chan->global_identifier));
  1253. goto end;
  1254. }
  1255. log_debug(LD_CHANNEL,
  1256. "Writing %p to channel %p with global ID "
  1257. U64_FORMAT, cell, chan, U64_PRINTF_ARG(chan->global_identifier));
  1258. ret = write_packed_cell(chan, cell);
  1259. end:
  1260. /* Whatever happens, we free the cell. Either an error occured or the cell
  1261. * was put on the connection outbuf, both cases we have ownership of the
  1262. * cell and we free it. */
  1263. packed_cell_free(cell);
  1264. return ret;
  1265. }
  1266. /**
  1267. * Change channel state
  1268. *
  1269. * This internal and subclass use only function is used to change channel
  1270. * state, performing all transition validity checks and whatever actions
  1271. * are appropriate to the state transition in question.
  1272. */
  1273. static void
  1274. channel_change_state_(channel_t *chan, channel_state_t to_state)
  1275. {
  1276. channel_state_t from_state;
  1277. unsigned char was_active, is_active;
  1278. unsigned char was_in_id_map, is_in_id_map;
  1279. tor_assert(chan);
  1280. from_state = chan->state;
  1281. tor_assert(channel_state_is_valid(from_state));
  1282. tor_assert(channel_state_is_valid(to_state));
  1283. tor_assert(channel_state_can_transition(chan->state, to_state));
  1284. /* Check for no-op transitions */
  1285. if (from_state == to_state) {
  1286. log_debug(LD_CHANNEL,
  1287. "Got no-op transition from \"%s\" to itself on channel %p"
  1288. "(global ID " U64_FORMAT ")",
  1289. channel_state_to_string(to_state),
  1290. chan, U64_PRINTF_ARG(chan->global_identifier));
  1291. return;
  1292. }
  1293. /* If we're going to a closing or closed state, we must have a reason set */
  1294. if (to_state == CHANNEL_STATE_CLOSING ||
  1295. to_state == CHANNEL_STATE_CLOSED ||
  1296. to_state == CHANNEL_STATE_ERROR) {
  1297. tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
  1298. }
  1299. log_debug(LD_CHANNEL,
  1300. "Changing state of channel %p (global ID " U64_FORMAT
  1301. ") from \"%s\" to \"%s\"",
  1302. chan,
  1303. U64_PRINTF_ARG(chan->global_identifier),
  1304. channel_state_to_string(chan->state),
  1305. channel_state_to_string(to_state));
  1306. chan->state = to_state;
  1307. /* Need to add to the right lists if the channel is registered */
  1308. if (chan->registered) {
  1309. was_active = !(from_state == CHANNEL_STATE_CLOSED ||
  1310. from_state == CHANNEL_STATE_ERROR);
  1311. is_active = !(to_state == CHANNEL_STATE_CLOSED ||
  1312. to_state == CHANNEL_STATE_ERROR);
  1313. /* Need to take off active list and put on finished list? */
  1314. if (was_active && !is_active) {
  1315. if (active_channels) smartlist_remove(active_channels, chan);
  1316. if (!finished_channels) finished_channels = smartlist_new();
  1317. smartlist_add(finished_channels, chan);
  1318. }
  1319. /* Need to put on active list? */
  1320. else if (!was_active && is_active) {
  1321. if (finished_channels) smartlist_remove(finished_channels, chan);
  1322. if (!active_channels) active_channels = smartlist_new();
  1323. smartlist_add(active_channels, chan);
  1324. }
  1325. if (!tor_digest_is_zero(chan->identity_digest)) {
  1326. /* Now we need to handle the identity map */
  1327. was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
  1328. from_state == CHANNEL_STATE_CLOSED ||
  1329. from_state == CHANNEL_STATE_ERROR);
  1330. is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
  1331. to_state == CHANNEL_STATE_CLOSED ||
  1332. to_state == CHANNEL_STATE_ERROR);
  1333. if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
  1334. else if (was_in_id_map && !is_in_id_map)
  1335. channel_remove_from_digest_map(chan);
  1336. }
  1337. }
  1338. /*
  1339. * If we're going to a closed/closing state, we don't need scheduling any
  1340. * more; in CHANNEL_STATE_MAINT we can't accept writes.
  1341. */
  1342. if (to_state == CHANNEL_STATE_CLOSING ||
  1343. to_state == CHANNEL_STATE_CLOSED ||
  1344. to_state == CHANNEL_STATE_ERROR) {
  1345. scheduler_release_channel(chan);
  1346. } else if (to_state == CHANNEL_STATE_MAINT) {
  1347. scheduler_channel_doesnt_want_writes(chan);
  1348. }
  1349. }
  1350. /**
  1351. * As channel_change_state_, but change the state to any state but open.
  1352. */
  1353. void
  1354. channel_change_state(channel_t *chan, channel_state_t to_state)
  1355. {
  1356. tor_assert(to_state != CHANNEL_STATE_OPEN);
  1357. channel_change_state_(chan, to_state);
  1358. }
  1359. /**
  1360. * As channel_change_state, but change the state to open.
  1361. */
  1362. void
  1363. channel_change_state_open(channel_t *chan)
  1364. {
  1365. channel_change_state_(chan, CHANNEL_STATE_OPEN);
  1366. /* Tell circuits if we opened and stuff */
  1367. channel_do_open_actions(chan);
  1368. chan->has_been_open = 1;
  1369. }
  1370. /**
  1371. * Change channel listener state
  1372. *
  1373. * This internal and subclass use only function is used to change channel
  1374. * listener state, performing all transition validity checks and whatever
  1375. * actions are appropriate to the state transition in question.
  1376. */
  1377. void
  1378. channel_listener_change_state(channel_listener_t *chan_l,
  1379. channel_listener_state_t to_state)
  1380. {
  1381. channel_listener_state_t from_state;
  1382. unsigned char was_active, is_active;
  1383. tor_assert(chan_l);
  1384. from_state = chan_l->state;
  1385. tor_assert(channel_listener_state_is_valid(from_state));
  1386. tor_assert(channel_listener_state_is_valid(to_state));
  1387. tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
  1388. /* Check for no-op transitions */
  1389. if (from_state == to_state) {
  1390. log_debug(LD_CHANNEL,
  1391. "Got no-op transition from \"%s\" to itself on channel "
  1392. "listener %p (global ID " U64_FORMAT ")",
  1393. channel_listener_state_to_string(to_state),
  1394. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1395. return;
  1396. }
  1397. /* If we're going to a closing or closed state, we must have a reason set */
  1398. if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
  1399. to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1400. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1401. tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
  1402. }
  1403. log_debug(LD_CHANNEL,
  1404. "Changing state of channel listener %p (global ID " U64_FORMAT
  1405. "from \"%s\" to \"%s\"",
  1406. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  1407. channel_listener_state_to_string(chan_l->state),
  1408. channel_listener_state_to_string(to_state));
  1409. chan_l->state = to_state;
  1410. /* Need to add to the right lists if the channel listener is registered */
  1411. if (chan_l->registered) {
  1412. was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1413. from_state == CHANNEL_LISTENER_STATE_ERROR);
  1414. is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1415. to_state == CHANNEL_LISTENER_STATE_ERROR);
  1416. /* Need to take off active list and put on finished list? */
  1417. if (was_active && !is_active) {
  1418. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  1419. if (!finished_listeners) finished_listeners = smartlist_new();
  1420. smartlist_add(finished_listeners, chan_l);
  1421. }
  1422. /* Need to put on active list? */
  1423. else if (!was_active && is_active) {
  1424. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  1425. if (!active_listeners) active_listeners = smartlist_new();
  1426. smartlist_add(active_listeners, chan_l);
  1427. }
  1428. }
  1429. if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1430. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1431. tor_assert(!(chan_l->incoming_list) ||
  1432. smartlist_len(chan_l->incoming_list) == 0);
  1433. }
  1434. }
  1435. /* Maximum number of cells that is allowed to flush at once withing
  1436. * channel_flush_some_cells(). */
  1437. #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
  1438. /* Try to flush cells of the given channel chan up to a maximum of num_cells.
  1439. *
  1440. * This is called by the scheduler when it wants to flush cells from the
  1441. * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
  1442. *
  1443. * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
  1444. * will return 0 meaning no cells were flushed.
  1445. *
  1446. * If num_cells is -1, we'll try to flush up to the maximum cells allowed
  1447. * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
  1448. *
  1449. * On success, the number of flushed cells are returned and it can never be
  1450. * above num_cells. If 0 is returned, no cells were flushed either because the
  1451. * channel was not opened or we had no cells on the channel. A negative number
  1452. * can NOT be sent back.
  1453. *
  1454. * This function is part of the fast path. */
  1455. MOCK_IMPL(ssize_t,
  1456. channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
  1457. {
  1458. unsigned int unlimited = 0;
  1459. ssize_t flushed = 0;
  1460. int clamped_num_cells;
  1461. tor_assert(chan);
  1462. if (num_cells < 0) unlimited = 1;
  1463. if (!unlimited && num_cells <= flushed) goto done;
  1464. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1465. if (CHANNEL_IS_OPEN(chan)) {
  1466. if (circuitmux_num_cells(chan->cmux) > 0) {
  1467. /* Calculate number of cells, including clamp */
  1468. if (unlimited) {
  1469. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1470. } else {
  1471. if (num_cells - flushed >
  1472. MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
  1473. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1474. } else {
  1475. clamped_num_cells = (int)(num_cells - flushed);
  1476. }
  1477. }
  1478. /* Try to get more cells from any active circuits */
  1479. flushed = channel_flush_from_first_active_circuit(
  1480. chan, clamped_num_cells);
  1481. }
  1482. }
  1483. done:
  1484. return flushed;
  1485. }
  1486. /**
  1487. * Check if any cells are available
  1488. *
  1489. * This is used by the scheduler to know if the channel has more to flush
  1490. * after a scheduling round.
  1491. */
  1492. MOCK_IMPL(int,
  1493. channel_more_to_flush, (channel_t *chan))
  1494. {
  1495. tor_assert(chan);
  1496. if (circuitmux_num_cells(chan->cmux) > 0) return 1;
  1497. /* Else no */
  1498. return 0;
  1499. }
  1500. /**
  1501. * Notify the channel we're done flushing the output in the lower layer
  1502. *
  1503. * Connection.c will call this when we've flushed the output; there's some
  1504. * dirreq-related maintenance to do.
  1505. */
  1506. void
  1507. channel_notify_flushed(channel_t *chan)
  1508. {
  1509. tor_assert(chan);
  1510. if (chan->dirreq_id != 0)
  1511. geoip_change_dirreq_state(chan->dirreq_id,
  1512. DIRREQ_TUNNELED,
  1513. DIRREQ_CHANNEL_BUFFER_FLUSHED);
  1514. }
  1515. /**
  1516. * Process the queue of incoming channels on a listener
  1517. *
  1518. * Use a listener's registered callback to process as many entries in the
  1519. * queue of incoming channels as possible.
  1520. */
  1521. void
  1522. channel_listener_process_incoming(channel_listener_t *listener)
  1523. {
  1524. tor_assert(listener);
  1525. /*
  1526. * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
  1527. * while closing a listener.
  1528. */
  1529. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
  1530. listener->state == CHANNEL_LISTENER_STATE_CLOSING);
  1531. tor_assert(listener->listener);
  1532. log_debug(LD_CHANNEL,
  1533. "Processing queue of incoming connections for channel "
  1534. "listener %p (global ID " U64_FORMAT ")",
  1535. listener, U64_PRINTF_ARG(listener->global_identifier));
  1536. if (!(listener->incoming_list)) return;
  1537. SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
  1538. channel_t *, chan) {
  1539. tor_assert(chan);
  1540. log_debug(LD_CHANNEL,
  1541. "Handling incoming channel %p (" U64_FORMAT ") "
  1542. "for listener %p (" U64_FORMAT ")",
  1543. chan,
  1544. U64_PRINTF_ARG(chan->global_identifier),
  1545. listener,
  1546. U64_PRINTF_ARG(listener->global_identifier));
  1547. /* Make sure this is set correctly */
  1548. channel_mark_incoming(chan);
  1549. listener->listener(listener, chan);
  1550. } SMARTLIST_FOREACH_END(chan);
  1551. smartlist_free(listener->incoming_list);
  1552. listener->incoming_list = NULL;
  1553. }
  1554. /**
  1555. * Take actions required when a channel becomes open
  1556. *
  1557. * Handle actions we should do when we know a channel is open; a lot of
  1558. * this comes from the old connection_or_set_state_open() of connection_or.c.
  1559. *
  1560. * Because of this mechanism, future channel_t subclasses should take care
  1561. * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
  1562. * until there is positive confirmation that the network is operational.
  1563. * In particular, anything UDP-based should not make this transition until a
  1564. * packet is received from the other side.
  1565. */
  1566. void
  1567. channel_do_open_actions(channel_t *chan)
  1568. {
  1569. tor_addr_t remote_addr;
  1570. int started_here;
  1571. time_t now = time(NULL);
  1572. int close_origin_circuits = 0;
  1573. tor_assert(chan);
  1574. started_here = channel_is_outgoing(chan);
  1575. if (started_here) {
  1576. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  1577. rep_hist_note_connect_succeeded(chan->identity_digest, now);
  1578. router_set_status(chan->identity_digest, 1);
  1579. } else {
  1580. /* only report it to the geoip module if it's not a known router */
  1581. if (!connection_or_digest_is_known_relay(chan->identity_digest)) {
  1582. if (channel_get_addr_if_possible(chan, &remote_addr)) {
  1583. char *transport_name = NULL;
  1584. channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
  1585. if (chan->get_transport_name(chan, &transport_name) < 0)
  1586. transport_name = NULL;
  1587. geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
  1588. &remote_addr, transport_name,
  1589. now);
  1590. tor_free(transport_name);
  1591. /* Notify the DoS subsystem of a new client. */
  1592. if (tlschan && tlschan->conn) {
  1593. dos_new_client_conn(tlschan->conn);
  1594. }
  1595. }
  1596. /* Otherwise the underlying transport can't tell us this, so skip it */
  1597. }
  1598. }
  1599. /* Disable or reduce padding according to user prefs. */
  1600. if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
  1601. if (!get_options()->ConnectionPadding) {
  1602. /* Disable if torrc disabled */
  1603. channelpadding_disable_padding_on_channel(chan);
  1604. } else if (get_options()->Tor2webMode &&
  1605. !networkstatus_get_param(NULL,
  1606. CHANNELPADDING_TOR2WEB_PARAM,
  1607. CHANNELPADDING_TOR2WEB_DEFAULT, 0, 1)) {
  1608. /* Disable if we're using tor2web and the consensus disabled padding
  1609. * for tor2web */
  1610. channelpadding_disable_padding_on_channel(chan);
  1611. } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
  1612. !networkstatus_get_param(NULL,
  1613. CHANNELPADDING_SOS_PARAM,
  1614. CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
  1615. /* Disable if we're using RSOS and the consensus disabled padding
  1616. * for RSOS */
  1617. channelpadding_disable_padding_on_channel(chan);
  1618. } else if (get_options()->ReducedConnectionPadding) {
  1619. /* Padding can be forced and/or reduced by clients, regardless of if
  1620. * the channel supports it */
  1621. channelpadding_reduce_padding_on_channel(chan);
  1622. }
  1623. }
  1624. circuit_n_chan_done(chan, 1, close_origin_circuits);
  1625. }
  1626. /**
  1627. * Queue an incoming channel on a listener
  1628. *
  1629. * Internal and subclass use only function to queue an incoming channel from
  1630. * a listener. A subclass of channel_listener_t should call this when a new
  1631. * incoming channel is created.
  1632. */
  1633. void
  1634. channel_listener_queue_incoming(channel_listener_t *listener,
  1635. channel_t *incoming)
  1636. {
  1637. int need_to_queue = 0;
  1638. tor_assert(listener);
  1639. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  1640. tor_assert(incoming);
  1641. log_debug(LD_CHANNEL,
  1642. "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
  1643. "channel listener %p (global ID " U64_FORMAT ")",
  1644. incoming, U64_PRINTF_ARG(incoming->global_identifier),
  1645. listener, U64_PRINTF_ARG(listener->global_identifier));
  1646. /* Do we need to queue it, or can we just call the listener right away? */
  1647. if (!(listener->listener)) need_to_queue = 1;
  1648. if (listener->incoming_list &&
  1649. (smartlist_len(listener->incoming_list) > 0))
  1650. need_to_queue = 1;
  1651. /* If we need to queue and have no queue, create one */
  1652. if (need_to_queue && !(listener->incoming_list)) {
  1653. listener->incoming_list = smartlist_new();
  1654. }
  1655. /* Bump the counter and timestamp it */
  1656. channel_listener_timestamp_active(listener);
  1657. channel_listener_timestamp_accepted(listener);
  1658. ++(listener->n_accepted);
  1659. /* If we don't need to queue, process it right away */
  1660. if (!need_to_queue) {
  1661. tor_assert(listener->listener);
  1662. listener->listener(listener, incoming);
  1663. }
  1664. /*
  1665. * Otherwise, we need to queue; queue and then process the queue if
  1666. * we can.
  1667. */
  1668. else {
  1669. tor_assert(listener->incoming_list);
  1670. smartlist_add(listener->incoming_list, incoming);
  1671. if (listener->listener) channel_listener_process_incoming(listener);
  1672. }
  1673. }
  1674. /**
  1675. * Process a cell from the given channel.
  1676. */
  1677. void
  1678. channel_process_cell(channel_t *chan, cell_t *cell)
  1679. {
  1680. tor_assert(chan);
  1681. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  1682. CHANNEL_IS_OPEN(chan));
  1683. tor_assert(cell);
  1684. /* Nothing we can do if we have no registered cell handlers */
  1685. if (!chan->cell_handler)
  1686. return;
  1687. /* Timestamp for receiving */
  1688. channel_timestamp_recv(chan);
  1689. /* Update received counter. */
  1690. ++(chan->n_cells_recved);
  1691. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  1692. log_debug(LD_CHANNEL,
  1693. "Processing incoming cell_t %p for channel %p (global ID "
  1694. U64_FORMAT ")", cell, chan,
  1695. U64_PRINTF_ARG(chan->global_identifier));
  1696. chan->cell_handler(chan, cell);
  1697. }
  1698. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  1699. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  1700. * false. */
  1701. /* XXXX Move this function. */
  1702. int
  1703. packed_cell_is_destroy(channel_t *chan,
  1704. const packed_cell_t *packed_cell,
  1705. circid_t *circid_out)
  1706. {
  1707. if (chan->wide_circ_ids) {
  1708. if (packed_cell->body[4] == CELL_DESTROY) {
  1709. *circid_out = ntohl(get_uint32(packed_cell->body));
  1710. return 1;
  1711. }
  1712. } else {
  1713. if (packed_cell->body[2] == CELL_DESTROY) {
  1714. *circid_out = ntohs(get_uint16(packed_cell->body));
  1715. return 1;
  1716. }
  1717. }
  1718. return 0;
  1719. }
  1720. /**
  1721. * Send destroy cell on a channel
  1722. *
  1723. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  1724. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  1725. * we may want to propagate reasons from other cells.
  1726. */
  1727. int
  1728. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  1729. {
  1730. tor_assert(chan);
  1731. if (circ_id == 0) {
  1732. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  1733. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  1734. U64_PRINTF_ARG(chan->global_identifier),
  1735. chan, channel_state_to_string(chan->state),
  1736. chan->state);
  1737. return 0;
  1738. }
  1739. /* Check to make sure we can send on this channel first */
  1740. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  1741. channel_note_destroy_pending(chan, circ_id);
  1742. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  1743. log_debug(LD_OR,
  1744. "Sending destroy (circID %u) on channel %p "
  1745. "(global ID " U64_FORMAT ")",
  1746. (unsigned)circ_id, chan,
  1747. U64_PRINTF_ARG(chan->global_identifier));
  1748. } else {
  1749. log_warn(LD_BUG,
  1750. "Someone called channel_send_destroy() for circID %u "
  1751. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  1752. (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
  1753. chan, channel_state_to_string(chan->state),
  1754. chan->state);
  1755. }
  1756. return 0;
  1757. }
  1758. /**
  1759. * Dump channel statistics to the log
  1760. *
  1761. * This is called from dumpstats() in main.c and spams the log with
  1762. * statistics on channels.
  1763. */
  1764. void
  1765. channel_dumpstats(int severity)
  1766. {
  1767. if (all_channels && smartlist_len(all_channels) > 0) {
  1768. tor_log(severity, LD_GENERAL,
  1769. "Dumping statistics about %d channels:",
  1770. smartlist_len(all_channels));
  1771. tor_log(severity, LD_GENERAL,
  1772. "%d are active, and %d are done and waiting for cleanup",
  1773. (active_channels != NULL) ?
  1774. smartlist_len(active_channels) : 0,
  1775. (finished_channels != NULL) ?
  1776. smartlist_len(finished_channels) : 0);
  1777. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  1778. channel_dump_statistics(chan, severity));
  1779. tor_log(severity, LD_GENERAL,
  1780. "Done spamming about channels now");
  1781. } else {
  1782. tor_log(severity, LD_GENERAL,
  1783. "No channels to dump");
  1784. }
  1785. }
  1786. /**
  1787. * Dump channel listener statistics to the log
  1788. *
  1789. * This is called from dumpstats() in main.c and spams the log with
  1790. * statistics on channel listeners.
  1791. */
  1792. void
  1793. channel_listener_dumpstats(int severity)
  1794. {
  1795. if (all_listeners && smartlist_len(all_listeners) > 0) {
  1796. tor_log(severity, LD_GENERAL,
  1797. "Dumping statistics about %d channel listeners:",
  1798. smartlist_len(all_listeners));
  1799. tor_log(severity, LD_GENERAL,
  1800. "%d are active and %d are done and waiting for cleanup",
  1801. (active_listeners != NULL) ?
  1802. smartlist_len(active_listeners) : 0,
  1803. (finished_listeners != NULL) ?
  1804. smartlist_len(finished_listeners) : 0);
  1805. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  1806. channel_listener_dump_statistics(chan_l, severity));
  1807. tor_log(severity, LD_GENERAL,
  1808. "Done spamming about channel listeners now");
  1809. } else {
  1810. tor_log(severity, LD_GENERAL,
  1811. "No channel listeners to dump");
  1812. }
  1813. }
  1814. /**
  1815. * Set the cmux policy on all active channels
  1816. */
  1817. void
  1818. channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
  1819. {
  1820. if (!active_channels) return;
  1821. SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
  1822. if (curr->cmux) {
  1823. circuitmux_set_policy(curr->cmux, pol);
  1824. }
  1825. } SMARTLIST_FOREACH_END(curr);
  1826. }
  1827. /**
  1828. * Clean up channels
  1829. *
  1830. * This gets called periodically from run_scheduled_events() in main.c;
  1831. * it cleans up after closed channels.
  1832. */
  1833. void
  1834. channel_run_cleanup(void)
  1835. {
  1836. channel_t *tmp = NULL;
  1837. /* Check if we need to do anything */
  1838. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  1839. /* Iterate through finished_channels and get rid of them */
  1840. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  1841. tmp = curr;
  1842. /* Remove it from the list */
  1843. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  1844. /* Also unregister it */
  1845. channel_unregister(tmp);
  1846. /* ... and free it */
  1847. channel_free(tmp);
  1848. } SMARTLIST_FOREACH_END(curr);
  1849. }
  1850. /**
  1851. * Clean up channel listeners
  1852. *
  1853. * This gets called periodically from run_scheduled_events() in main.c;
  1854. * it cleans up after closed channel listeners.
  1855. */
  1856. void
  1857. channel_listener_run_cleanup(void)
  1858. {
  1859. channel_listener_t *tmp = NULL;
  1860. /* Check if we need to do anything */
  1861. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  1862. /* Iterate through finished_channels and get rid of them */
  1863. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  1864. tmp = curr;
  1865. /* Remove it from the list */
  1866. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  1867. /* Also unregister it */
  1868. channel_listener_unregister(tmp);
  1869. /* ... and free it */
  1870. channel_listener_free(tmp);
  1871. } SMARTLIST_FOREACH_END(curr);
  1872. }
  1873. /**
  1874. * Free a list of channels for channel_free_all()
  1875. */
  1876. static void
  1877. channel_free_list(smartlist_t *channels, int mark_for_close)
  1878. {
  1879. if (!channels) return;
  1880. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  1881. /* Deregister and free it */
  1882. tor_assert(curr);
  1883. log_debug(LD_CHANNEL,
  1884. "Cleaning up channel %p (global ID " U64_FORMAT ") "
  1885. "in state %s (%d)",
  1886. curr, U64_PRINTF_ARG(curr->global_identifier),
  1887. channel_state_to_string(curr->state), curr->state);
  1888. /* Detach circuits early so they can find the channel */
  1889. if (curr->cmux) {
  1890. circuitmux_detach_all_circuits(curr->cmux, NULL);
  1891. }
  1892. SMARTLIST_DEL_CURRENT(channels, curr);
  1893. channel_unregister(curr);
  1894. if (mark_for_close) {
  1895. if (!CHANNEL_CONDEMNED(curr)) {
  1896. channel_mark_for_close(curr);
  1897. }
  1898. channel_force_xfree(curr);
  1899. } else channel_free(curr);
  1900. } SMARTLIST_FOREACH_END(curr);
  1901. }
  1902. /**
  1903. * Free a list of channel listeners for channel_free_all()
  1904. */
  1905. static void
  1906. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  1907. {
  1908. if (!listeners) return;
  1909. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  1910. /* Deregister and free it */
  1911. tor_assert(curr);
  1912. log_debug(LD_CHANNEL,
  1913. "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
  1914. "in state %s (%d)",
  1915. curr, U64_PRINTF_ARG(curr->global_identifier),
  1916. channel_listener_state_to_string(curr->state), curr->state);
  1917. channel_listener_unregister(curr);
  1918. if (mark_for_close) {
  1919. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1920. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1921. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  1922. channel_listener_mark_for_close(curr);
  1923. }
  1924. channel_listener_force_xfree(curr);
  1925. } else channel_listener_free(curr);
  1926. } SMARTLIST_FOREACH_END(curr);
  1927. }
  1928. /**
  1929. * Close all channels and free everything
  1930. *
  1931. * This gets called from tor_free_all() in main.c to clean up on exit.
  1932. * It will close all registered channels and free associated storage,
  1933. * then free the all_channels, active_channels, listening_channels and
  1934. * finished_channels lists and also channel_identity_map.
  1935. */
  1936. void
  1937. channel_free_all(void)
  1938. {
  1939. log_debug(LD_CHANNEL,
  1940. "Shutting down channels...");
  1941. /* First, let's go for finished channels */
  1942. if (finished_channels) {
  1943. channel_free_list(finished_channels, 0);
  1944. smartlist_free(finished_channels);
  1945. finished_channels = NULL;
  1946. }
  1947. /* Now the finished listeners */
  1948. if (finished_listeners) {
  1949. channel_listener_free_list(finished_listeners, 0);
  1950. smartlist_free(finished_listeners);
  1951. finished_listeners = NULL;
  1952. }
  1953. /* Now all active channels */
  1954. if (active_channels) {
  1955. channel_free_list(active_channels, 1);
  1956. smartlist_free(active_channels);
  1957. active_channels = NULL;
  1958. }
  1959. /* Now all active listeners */
  1960. if (active_listeners) {
  1961. channel_listener_free_list(active_listeners, 1);
  1962. smartlist_free(active_listeners);
  1963. active_listeners = NULL;
  1964. }
  1965. /* Now all channels, in case any are left over */
  1966. if (all_channels) {
  1967. channel_free_list(all_channels, 1);
  1968. smartlist_free(all_channels);
  1969. all_channels = NULL;
  1970. }
  1971. /* Now all listeners, in case any are left over */
  1972. if (all_listeners) {
  1973. channel_listener_free_list(all_listeners, 1);
  1974. smartlist_free(all_listeners);
  1975. all_listeners = NULL;
  1976. }
  1977. /* Now free channel_identity_map */
  1978. log_debug(LD_CHANNEL,
  1979. "Freeing channel_identity_map");
  1980. /* Geez, anything still left over just won't die ... let it leak then */
  1981. HT_CLEAR(channel_idmap, &channel_identity_map);
  1982. /* Same with channel_gid_map */
  1983. log_debug(LD_CHANNEL,
  1984. "Freeing channel_gid_map");
  1985. HT_CLEAR(channel_gid_map, &channel_gid_map);
  1986. log_debug(LD_CHANNEL,
  1987. "Done cleaning up after channels");
  1988. }
  1989. /**
  1990. * Connect to a given addr/port/digest
  1991. *
  1992. * This sets up a new outgoing channel; in the future if multiple
  1993. * channel_t subclasses are available, this is where the selection policy
  1994. * should go. It may also be desirable to fold port into tor_addr_t
  1995. * or make a new type including a tor_addr_t and port, so we have a
  1996. * single abstract object encapsulating all the protocol details of
  1997. * how to contact an OR.
  1998. */
  1999. channel_t *
  2000. channel_connect(const tor_addr_t *addr, uint16_t port,
  2001. const char *id_digest,
  2002. const ed25519_public_key_t *ed_id)
  2003. {
  2004. return channel_tls_connect(addr, port, id_digest, ed_id);
  2005. }
  2006. /**
  2007. * Decide which of two channels to prefer for extending a circuit
  2008. *
  2009. * This function is called while extending a circuit and returns true iff
  2010. * a is 'better' than b. The most important criterion here is that a
  2011. * canonical channel is always better than a non-canonical one, but the
  2012. * number of circuits and the age are used as tie-breakers.
  2013. *
  2014. * This is based on the former connection_or_is_better() of connection_or.c
  2015. */
  2016. int
  2017. channel_is_better(channel_t *a, channel_t *b)
  2018. {
  2019. int a_is_canonical, b_is_canonical;
  2020. tor_assert(a);
  2021. tor_assert(b);
  2022. /* If one channel is bad for new circuits, and the other isn't,
  2023. * use the one that is still good. */
  2024. if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
  2025. return 1;
  2026. if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
  2027. return 0;
  2028. /* Check if one is canonical and the other isn't first */
  2029. a_is_canonical = channel_is_canonical(a);
  2030. b_is_canonical = channel_is_canonical(b);
  2031. if (a_is_canonical && !b_is_canonical) return 1;
  2032. if (!a_is_canonical && b_is_canonical) return 0;
  2033. /* Check if we suspect that one of the channels will be preferred
  2034. * by the peer */
  2035. if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
  2036. if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
  2037. /*
  2038. * Okay, if we're here they tied on canonicity, the prefer the older
  2039. * connection, so that the adversary can't create a new connection
  2040. * and try to switch us over to it (which will leak information
  2041. * about long-lived circuits). Additionally, switching connections
  2042. * too often makes us more vulnerable to attacks like Torscan and
  2043. * passive netflow-based equivalents.
  2044. *
  2045. * Connections will still only live for at most a week, due to
  2046. * the check in connection_or_group_set_badness() against
  2047. * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
  2048. * unusable for new circuits after 1 week. That check sets
  2049. * is_bad_for_new_circs, which is checked in channel_get_for_extend().
  2050. *
  2051. * We check channel_is_bad_for_new_circs() above here anyway, for safety.
  2052. */
  2053. if (channel_when_created(a) < channel_when_created(b)) return 1;
  2054. else if (channel_when_created(a) > channel_when_created(b)) return 0;
  2055. if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
  2056. else return 0;
  2057. }
  2058. /**
  2059. * Get a channel to extend a circuit
  2060. *
  2061. * Pick a suitable channel to extend a circuit to given the desired digest
  2062. * the address we believe is correct for that digest; this tries to see
  2063. * if we already have one for the requested endpoint, but if there is no good
  2064. * channel, set *msg_out to a message describing the channel's state
  2065. * and our next action, and set *launch_out to a boolean indicated whether
  2066. * the caller should try to launch a new channel with channel_connect().
  2067. */
  2068. channel_t *
  2069. channel_get_for_extend(const char *rsa_id_digest,
  2070. const ed25519_public_key_t *ed_id,
  2071. const tor_addr_t *target_addr,
  2072. const char **msg_out,
  2073. int *launch_out)
  2074. {
  2075. channel_t *chan, *best = NULL;
  2076. int n_inprogress_goodaddr = 0, n_old = 0;
  2077. int n_noncanonical = 0, n_possible = 0;
  2078. tor_assert(msg_out);
  2079. tor_assert(launch_out);
  2080. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2081. /* Walk the list, unrefing the old one and refing the new at each
  2082. * iteration.
  2083. */
  2084. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2085. tor_assert(tor_memeq(chan->identity_digest,
  2086. rsa_id_digest, DIGEST_LEN));
  2087. if (CHANNEL_CONDEMNED(chan))
  2088. continue;
  2089. /* Never return a channel on which the other end appears to be
  2090. * a client. */
  2091. if (channel_is_client(chan)) {
  2092. continue;
  2093. }
  2094. /* The Ed25519 key has to match too */
  2095. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  2096. continue;
  2097. }
  2098. /* Never return a non-open connection. */
  2099. if (!CHANNEL_IS_OPEN(chan)) {
  2100. /* If the address matches, don't launch a new connection for this
  2101. * circuit. */
  2102. if (channel_matches_target_addr_for_extend(chan, target_addr))
  2103. ++n_inprogress_goodaddr;
  2104. continue;
  2105. }
  2106. /* Never return a connection that shouldn't be used for circs. */
  2107. if (channel_is_bad_for_new_circs(chan)) {
  2108. ++n_old;
  2109. continue;
  2110. }
  2111. /* Never return a non-canonical connection using a recent link protocol
  2112. * if the address is not what we wanted.
  2113. *
  2114. * The channel_is_canonical_is_reliable() function asks the lower layer
  2115. * if we should trust channel_is_canonical(). The below is from the
  2116. * comments of the old circuit_or_get_for_extend() and applies when
  2117. * the lower-layer transport is channel_tls_t.
  2118. *
  2119. * (For old link protocols, we can't rely on is_canonical getting
  2120. * set properly if we're talking to the right address, since we might
  2121. * have an out-of-date descriptor, and we will get no NETINFO cell to
  2122. * tell us about the right address.)
  2123. */
  2124. if (!channel_is_canonical(chan) &&
  2125. channel_is_canonical_is_reliable(chan) &&
  2126. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  2127. ++n_noncanonical;
  2128. continue;
  2129. }
  2130. ++n_possible;
  2131. if (!best) {
  2132. best = chan; /* If we have no 'best' so far, this one is good enough. */
  2133. continue;
  2134. }
  2135. if (channel_is_better(chan, best))
  2136. best = chan;
  2137. }
  2138. if (best) {
  2139. *msg_out = "Connection is fine; using it.";
  2140. *launch_out = 0;
  2141. return best;
  2142. } else if (n_inprogress_goodaddr) {
  2143. *msg_out = "Connection in progress; waiting.";
  2144. *launch_out = 0;
  2145. return NULL;
  2146. } else if (n_old || n_noncanonical) {
  2147. *msg_out = "Connections all too old, or too non-canonical. "
  2148. " Launching a new one.";
  2149. *launch_out = 1;
  2150. return NULL;
  2151. } else {
  2152. *msg_out = "Not connected. Connecting.";
  2153. *launch_out = 1;
  2154. return NULL;
  2155. }
  2156. }
  2157. /**
  2158. * Describe the transport subclass for a channel
  2159. *
  2160. * Invoke a method to get a string description of the lower-layer
  2161. * transport for this channel.
  2162. */
  2163. const char *
  2164. channel_describe_transport(channel_t *chan)
  2165. {
  2166. tor_assert(chan);
  2167. tor_assert(chan->describe_transport);
  2168. return chan->describe_transport(chan);
  2169. }
  2170. /**
  2171. * Describe the transport subclass for a channel listener
  2172. *
  2173. * Invoke a method to get a string description of the lower-layer
  2174. * transport for this channel listener.
  2175. */
  2176. const char *
  2177. channel_listener_describe_transport(channel_listener_t *chan_l)
  2178. {
  2179. tor_assert(chan_l);
  2180. tor_assert(chan_l->describe_transport);
  2181. return chan_l->describe_transport(chan_l);
  2182. }
  2183. /**
  2184. * Dump channel statistics
  2185. *
  2186. * Dump statistics for one channel to the log
  2187. */
  2188. MOCK_IMPL(void,
  2189. channel_dump_statistics, (channel_t *chan, int severity))
  2190. {
  2191. double avg, interval, age;
  2192. time_t now = time(NULL);
  2193. tor_addr_t remote_addr;
  2194. int have_remote_addr;
  2195. char *remote_addr_str;
  2196. tor_assert(chan);
  2197. age = (double)(now - chan->timestamp_created);
  2198. tor_log(severity, LD_GENERAL,
  2199. "Channel " U64_FORMAT " (at %p) with transport %s is in state "
  2200. "%s (%d)",
  2201. U64_PRINTF_ARG(chan->global_identifier), chan,
  2202. channel_describe_transport(chan),
  2203. channel_state_to_string(chan->state), chan->state);
  2204. tor_log(severity, LD_GENERAL,
  2205. " * Channel " U64_FORMAT " was created at " U64_FORMAT
  2206. " (" U64_FORMAT " seconds ago) "
  2207. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2208. U64_PRINTF_ARG(chan->global_identifier),
  2209. U64_PRINTF_ARG(chan->timestamp_created),
  2210. U64_PRINTF_ARG(now - chan->timestamp_created),
  2211. U64_PRINTF_ARG(chan->timestamp_active),
  2212. U64_PRINTF_ARG(now - chan->timestamp_active));
  2213. /* Handle digest. */
  2214. if (!tor_digest_is_zero(chan->identity_digest)) {
  2215. tor_log(severity, LD_GENERAL,
  2216. " * Channel " U64_FORMAT " says it is connected "
  2217. "to an OR with digest %s",
  2218. U64_PRINTF_ARG(chan->global_identifier),
  2219. hex_str(chan->identity_digest, DIGEST_LEN));
  2220. } else {
  2221. tor_log(severity, LD_GENERAL,
  2222. " * Channel " U64_FORMAT " does not know the digest"
  2223. " of the OR it is connected to",
  2224. U64_PRINTF_ARG(chan->global_identifier));
  2225. }
  2226. /* Handle remote address and descriptions */
  2227. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  2228. if (have_remote_addr) {
  2229. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  2230. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  2231. tor_log(severity, LD_GENERAL,
  2232. " * Channel " U64_FORMAT " says its remote address"
  2233. " is %s, and gives a canonical description of \"%s\" and an "
  2234. "actual description of \"%s\"",
  2235. U64_PRINTF_ARG(chan->global_identifier),
  2236. safe_str(remote_addr_str),
  2237. safe_str(channel_get_canonical_remote_descr(chan)),
  2238. safe_str(actual));
  2239. tor_free(remote_addr_str);
  2240. tor_free(actual);
  2241. } else {
  2242. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  2243. tor_log(severity, LD_GENERAL,
  2244. " * Channel " U64_FORMAT " does not know its remote "
  2245. "address, but gives a canonical description of \"%s\" and an "
  2246. "actual description of \"%s\"",
  2247. U64_PRINTF_ARG(chan->global_identifier),
  2248. channel_get_canonical_remote_descr(chan),
  2249. actual);
  2250. tor_free(actual);
  2251. }
  2252. /* Handle marks */
  2253. tor_log(severity, LD_GENERAL,
  2254. " * Channel " U64_FORMAT " has these marks: %s %s %s "
  2255. "%s %s %s",
  2256. U64_PRINTF_ARG(chan->global_identifier),
  2257. channel_is_bad_for_new_circs(chan) ?
  2258. "bad_for_new_circs" : "!bad_for_new_circs",
  2259. channel_is_canonical(chan) ?
  2260. "canonical" : "!canonical",
  2261. channel_is_canonical_is_reliable(chan) ?
  2262. "is_canonical_is_reliable" :
  2263. "!is_canonical_is_reliable",
  2264. channel_is_client(chan) ?
  2265. "client" : "!client",
  2266. channel_is_local(chan) ?
  2267. "local" : "!local",
  2268. channel_is_incoming(chan) ?
  2269. "incoming" : "outgoing");
  2270. /* Describe circuits */
  2271. tor_log(severity, LD_GENERAL,
  2272. " * Channel " U64_FORMAT " has %d active circuits out of"
  2273. " %d in total",
  2274. U64_PRINTF_ARG(chan->global_identifier),
  2275. (chan->cmux != NULL) ?
  2276. circuitmux_num_active_circuits(chan->cmux) : 0,
  2277. (chan->cmux != NULL) ?
  2278. circuitmux_num_circuits(chan->cmux) : 0);
  2279. /* Describe timestamps */
  2280. tor_log(severity, LD_GENERAL,
  2281. " * Channel " U64_FORMAT " was last used by a "
  2282. "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2283. U64_PRINTF_ARG(chan->global_identifier),
  2284. U64_PRINTF_ARG(chan->timestamp_client),
  2285. U64_PRINTF_ARG(now - chan->timestamp_client));
  2286. tor_log(severity, LD_GENERAL,
  2287. " * Channel " U64_FORMAT " last received a cell "
  2288. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2289. U64_PRINTF_ARG(chan->global_identifier),
  2290. U64_PRINTF_ARG(chan->timestamp_recv),
  2291. U64_PRINTF_ARG(now - chan->timestamp_recv));
  2292. tor_log(severity, LD_GENERAL,
  2293. " * Channel " U64_FORMAT " last transmitted a cell "
  2294. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2295. U64_PRINTF_ARG(chan->global_identifier),
  2296. U64_PRINTF_ARG(chan->timestamp_xmit),
  2297. U64_PRINTF_ARG(now - chan->timestamp_xmit));
  2298. /* Describe counters and rates */
  2299. tor_log(severity, LD_GENERAL,
  2300. " * Channel " U64_FORMAT " has received "
  2301. U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
  2302. U64_FORMAT " bytes in " U64_FORMAT " cells",
  2303. U64_PRINTF_ARG(chan->global_identifier),
  2304. U64_PRINTF_ARG(chan->n_bytes_recved),
  2305. U64_PRINTF_ARG(chan->n_cells_recved),
  2306. U64_PRINTF_ARG(chan->n_bytes_xmitted),
  2307. U64_PRINTF_ARG(chan->n_cells_xmitted));
  2308. if (now > chan->timestamp_created &&
  2309. chan->timestamp_created > 0) {
  2310. if (chan->n_bytes_recved > 0) {
  2311. avg = (double)(chan->n_bytes_recved) / age;
  2312. tor_log(severity, LD_GENERAL,
  2313. " * Channel " U64_FORMAT " has averaged %f "
  2314. "bytes received per second",
  2315. U64_PRINTF_ARG(chan->global_identifier), avg);
  2316. }
  2317. if (chan->n_cells_recved > 0) {
  2318. avg = (double)(chan->n_cells_recved) / age;
  2319. if (avg >= 1.0) {
  2320. tor_log(severity, LD_GENERAL,
  2321. " * Channel " U64_FORMAT " has averaged %f "
  2322. "cells received per second",
  2323. U64_PRINTF_ARG(chan->global_identifier), avg);
  2324. } else if (avg >= 0.0) {
  2325. interval = 1.0 / avg;
  2326. tor_log(severity, LD_GENERAL,
  2327. " * Channel " U64_FORMAT " has averaged %f "
  2328. "seconds between received cells",
  2329. U64_PRINTF_ARG(chan->global_identifier), interval);
  2330. }
  2331. }
  2332. if (chan->n_bytes_xmitted > 0) {
  2333. avg = (double)(chan->n_bytes_xmitted) / age;
  2334. tor_log(severity, LD_GENERAL,
  2335. " * Channel " U64_FORMAT " has averaged %f "
  2336. "bytes transmitted per second",
  2337. U64_PRINTF_ARG(chan->global_identifier), avg);
  2338. }
  2339. if (chan->n_cells_xmitted > 0) {
  2340. avg = (double)(chan->n_cells_xmitted) / age;
  2341. if (avg >= 1.0) {
  2342. tor_log(severity, LD_GENERAL,
  2343. " * Channel " U64_FORMAT " has averaged %f "
  2344. "cells transmitted per second",
  2345. U64_PRINTF_ARG(chan->global_identifier), avg);
  2346. } else if (avg >= 0.0) {
  2347. interval = 1.0 / avg;
  2348. tor_log(severity, LD_GENERAL,
  2349. " * Channel " U64_FORMAT " has averaged %f "
  2350. "seconds between transmitted cells",
  2351. U64_PRINTF_ARG(chan->global_identifier), interval);
  2352. }
  2353. }
  2354. }
  2355. /* Dump anything the lower layer has to say */
  2356. channel_dump_transport_statistics(chan, severity);
  2357. }
  2358. /**
  2359. * Dump channel listener statistics
  2360. *
  2361. * Dump statistics for one channel listener to the log
  2362. */
  2363. void
  2364. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  2365. {
  2366. double avg, interval, age;
  2367. time_t now = time(NULL);
  2368. tor_assert(chan_l);
  2369. age = (double)(now - chan_l->timestamp_created);
  2370. tor_log(severity, LD_GENERAL,
  2371. "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
  2372. "state %s (%d)",
  2373. U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
  2374. channel_listener_describe_transport(chan_l),
  2375. channel_listener_state_to_string(chan_l->state), chan_l->state);
  2376. tor_log(severity, LD_GENERAL,
  2377. " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
  2378. " (" U64_FORMAT " seconds ago) "
  2379. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2380. U64_PRINTF_ARG(chan_l->global_identifier),
  2381. U64_PRINTF_ARG(chan_l->timestamp_created),
  2382. U64_PRINTF_ARG(now - chan_l->timestamp_created),
  2383. U64_PRINTF_ARG(chan_l->timestamp_active),
  2384. U64_PRINTF_ARG(now - chan_l->timestamp_active));
  2385. tor_log(severity, LD_GENERAL,
  2386. " * Channel listener " U64_FORMAT " last accepted an incoming "
  2387. "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
  2388. "and has accepted " U64_FORMAT " channels in total",
  2389. U64_PRINTF_ARG(chan_l->global_identifier),
  2390. U64_PRINTF_ARG(chan_l->timestamp_accepted),
  2391. U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
  2392. U64_PRINTF_ARG(chan_l->n_accepted));
  2393. /*
  2394. * If it's sensible to do so, get the rate of incoming channels on this
  2395. * listener
  2396. */
  2397. if (now > chan_l->timestamp_created &&
  2398. chan_l->timestamp_created > 0 &&
  2399. chan_l->n_accepted > 0) {
  2400. avg = (double)(chan_l->n_accepted) / age;
  2401. if (avg >= 1.0) {
  2402. tor_log(severity, LD_GENERAL,
  2403. " * Channel listener " U64_FORMAT " has averaged %f incoming "
  2404. "channels per second",
  2405. U64_PRINTF_ARG(chan_l->global_identifier), avg);
  2406. } else if (avg >= 0.0) {
  2407. interval = 1.0 / avg;
  2408. tor_log(severity, LD_GENERAL,
  2409. " * Channel listener " U64_FORMAT " has averaged %f seconds "
  2410. "between incoming channels",
  2411. U64_PRINTF_ARG(chan_l->global_identifier), interval);
  2412. }
  2413. }
  2414. /* Dump anything the lower layer has to say */
  2415. channel_listener_dump_transport_statistics(chan_l, severity);
  2416. }
  2417. /**
  2418. * Invoke transport-specific stats dump for channel
  2419. *
  2420. * If there is a lower-layer statistics dump method, invoke it
  2421. */
  2422. void
  2423. channel_dump_transport_statistics(channel_t *chan, int severity)
  2424. {
  2425. tor_assert(chan);
  2426. if (chan->dumpstats) chan->dumpstats(chan, severity);
  2427. }
  2428. /**
  2429. * Invoke transport-specific stats dump for channel listener
  2430. *
  2431. * If there is a lower-layer statistics dump method, invoke it
  2432. */
  2433. void
  2434. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  2435. int severity)
  2436. {
  2437. tor_assert(chan_l);
  2438. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  2439. }
  2440. /**
  2441. * Return text description of the remote endpoint
  2442. *
  2443. * This function return a test provided by the lower layer of the remote
  2444. * endpoint for this channel; it should specify the actual address connected
  2445. * to/from.
  2446. *
  2447. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2448. * may invalidate the return value from this function.
  2449. */
  2450. const char *
  2451. channel_get_actual_remote_descr(channel_t *chan)
  2452. {
  2453. tor_assert(chan);
  2454. tor_assert(chan->get_remote_descr);
  2455. /* Param 1 indicates the actual description */
  2456. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  2457. }
  2458. /**
  2459. * Return the text address of the remote endpoint.
  2460. *
  2461. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2462. * may invalidate the return value from this function.
  2463. */
  2464. const char *
  2465. channel_get_actual_remote_address(channel_t *chan)
  2466. {
  2467. /* Param 1 indicates the actual description */
  2468. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  2469. }
  2470. /**
  2471. * Return text description of the remote endpoint canonical address
  2472. *
  2473. * This function return a test provided by the lower layer of the remote
  2474. * endpoint for this channel; it should use the known canonical address for
  2475. * this OR's identity digest if possible.
  2476. *
  2477. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  2478. * may invalidate the return value from this function.
  2479. */
  2480. const char *
  2481. channel_get_canonical_remote_descr(channel_t *chan)
  2482. {
  2483. tor_assert(chan);
  2484. tor_assert(chan->get_remote_descr);
  2485. /* Param 0 indicates the canonicalized description */
  2486. return chan->get_remote_descr(chan, 0);
  2487. }
  2488. /**
  2489. * Get remote address if possible.
  2490. *
  2491. * Write the remote address out to a tor_addr_t if the underlying transport
  2492. * supports this operation, and return 1. Return 0 if the underlying transport
  2493. * doesn't let us do this.
  2494. */
  2495. MOCK_IMPL(int,
  2496. channel_get_addr_if_possible,(channel_t *chan, tor_addr_t *addr_out))
  2497. {
  2498. tor_assert(chan);
  2499. tor_assert(addr_out);
  2500. if (chan->get_remote_addr)
  2501. return chan->get_remote_addr(chan, addr_out);
  2502. /* Else no support, method not implemented */
  2503. else return 0;
  2504. }
  2505. /*
  2506. * Return true iff the channel has any cells on the connection outbuf waiting
  2507. * to be sent onto the network.
  2508. */
  2509. int
  2510. channel_has_queued_writes(channel_t *chan)
  2511. {
  2512. tor_assert(chan);
  2513. tor_assert(chan->has_queued_writes);
  2514. /* Check with the lower layer */
  2515. return chan->has_queued_writes(chan);
  2516. }
  2517. /**
  2518. * Check the is_bad_for_new_circs flag
  2519. *
  2520. * This function returns the is_bad_for_new_circs flag of the specified
  2521. * channel.
  2522. */
  2523. int
  2524. channel_is_bad_for_new_circs(channel_t *chan)
  2525. {
  2526. tor_assert(chan);
  2527. return chan->is_bad_for_new_circs;
  2528. }
  2529. /**
  2530. * Mark a channel as bad for new circuits
  2531. *
  2532. * Set the is_bad_for_new_circs_flag on chan.
  2533. */
  2534. void
  2535. channel_mark_bad_for_new_circs(channel_t *chan)
  2536. {
  2537. tor_assert(chan);
  2538. chan->is_bad_for_new_circs = 1;
  2539. }
  2540. /**
  2541. * Get the client flag
  2542. *
  2543. * This returns the client flag of a channel, which will be set if
  2544. * command_process_create_cell() in command.c thinks this is a connection
  2545. * from a client.
  2546. */
  2547. int
  2548. channel_is_client(const channel_t *chan)
  2549. {
  2550. tor_assert(chan);
  2551. return chan->is_client;
  2552. }
  2553. /**
  2554. * Set the client flag
  2555. *
  2556. * Mark a channel as being from a client
  2557. */
  2558. void
  2559. channel_mark_client(channel_t *chan)
  2560. {
  2561. tor_assert(chan);
  2562. chan->is_client = 1;
  2563. }
  2564. /**
  2565. * Clear the client flag
  2566. *
  2567. * Mark a channel as being _not_ from a client
  2568. */
  2569. void
  2570. channel_clear_client(channel_t *chan)
  2571. {
  2572. tor_assert(chan);
  2573. chan->is_client = 0;
  2574. }
  2575. /**
  2576. * Get the canonical flag for a channel
  2577. *
  2578. * This returns the is_canonical for a channel; this flag is determined by
  2579. * the lower layer and can't be set in a transport-independent way.
  2580. */
  2581. int
  2582. channel_is_canonical(channel_t *chan)
  2583. {
  2584. tor_assert(chan);
  2585. tor_assert(chan->is_canonical);
  2586. return chan->is_canonical(chan, 0);
  2587. }
  2588. /**
  2589. * Test if the canonical flag is reliable
  2590. *
  2591. * This function asks if the lower layer thinks it's safe to trust the
  2592. * result of channel_is_canonical()
  2593. */
  2594. int
  2595. channel_is_canonical_is_reliable(channel_t *chan)
  2596. {
  2597. tor_assert(chan);
  2598. tor_assert(chan->is_canonical);
  2599. return chan->is_canonical(chan, 1);
  2600. }
  2601. /**
  2602. * Test incoming flag
  2603. *
  2604. * This function gets the incoming flag; this is set when a listener spawns
  2605. * a channel. If this returns true the channel was remotely initiated.
  2606. */
  2607. int
  2608. channel_is_incoming(channel_t *chan)
  2609. {
  2610. tor_assert(chan);
  2611. return chan->is_incoming;
  2612. }
  2613. /**
  2614. * Set the incoming flag
  2615. *
  2616. * This function is called when a channel arrives on a listening channel
  2617. * to mark it as incoming.
  2618. */
  2619. void
  2620. channel_mark_incoming(channel_t *chan)
  2621. {
  2622. tor_assert(chan);
  2623. chan->is_incoming = 1;
  2624. }
  2625. /**
  2626. * Test local flag
  2627. *
  2628. * This function gets the local flag; the lower layer should set this when
  2629. * setting up the channel if is_local_addr() is true for all of the
  2630. * destinations it will communicate with on behalf of this channel. It's
  2631. * used to decide whether to declare the network reachable when seeing incoming
  2632. * traffic on the channel.
  2633. */
  2634. int
  2635. channel_is_local(channel_t *chan)
  2636. {
  2637. tor_assert(chan);
  2638. return chan->is_local;
  2639. }
  2640. /**
  2641. * Set the local flag
  2642. *
  2643. * This internal-only function should be called by the lower layer if the
  2644. * channel is to a local address. See channel_is_local() above or the
  2645. * description of the is_local bit in channel.h
  2646. */
  2647. void
  2648. channel_mark_local(channel_t *chan)
  2649. {
  2650. tor_assert(chan);
  2651. chan->is_local = 1;
  2652. }
  2653. /**
  2654. * Mark a channel as remote
  2655. *
  2656. * This internal-only function should be called by the lower layer if the
  2657. * channel is not to a local address but has previously been marked local.
  2658. * See channel_is_local() above or the description of the is_local bit in
  2659. * channel.h
  2660. */
  2661. void
  2662. channel_mark_remote(channel_t *chan)
  2663. {
  2664. tor_assert(chan);
  2665. chan->is_local = 0;
  2666. }
  2667. /**
  2668. * Test outgoing flag
  2669. *
  2670. * This function gets the outgoing flag; this is the inverse of the incoming
  2671. * bit set when a listener spawns a channel. If this returns true the channel
  2672. * was locally initiated.
  2673. */
  2674. int
  2675. channel_is_outgoing(channel_t *chan)
  2676. {
  2677. tor_assert(chan);
  2678. return !(chan->is_incoming);
  2679. }
  2680. /**
  2681. * Mark a channel as outgoing
  2682. *
  2683. * This function clears the incoming flag and thus marks a channel as
  2684. * outgoing.
  2685. */
  2686. void
  2687. channel_mark_outgoing(channel_t *chan)
  2688. {
  2689. tor_assert(chan);
  2690. chan->is_incoming = 0;
  2691. }
  2692. /************************
  2693. * Flow control queries *
  2694. ***********************/
  2695. /*
  2696. * Estimate the number of writeable cells
  2697. *
  2698. * Ask the lower layer for an estimate of how many cells it can accept.
  2699. */
  2700. int
  2701. channel_num_cells_writeable(channel_t *chan)
  2702. {
  2703. int result;
  2704. tor_assert(chan);
  2705. tor_assert(chan->num_cells_writeable);
  2706. if (chan->state == CHANNEL_STATE_OPEN) {
  2707. /* Query lower layer */
  2708. result = chan->num_cells_writeable(chan);
  2709. if (result < 0) result = 0;
  2710. } else {
  2711. /* No cells are writeable in any other state */
  2712. result = 0;
  2713. }
  2714. return result;
  2715. }
  2716. /*********************
  2717. * Timestamp updates *
  2718. ********************/
  2719. /**
  2720. * Update the created timestamp for a channel
  2721. *
  2722. * This updates the channel's created timestamp and should only be called
  2723. * from channel_init().
  2724. */
  2725. void
  2726. channel_timestamp_created(channel_t *chan)
  2727. {
  2728. time_t now = time(NULL);
  2729. tor_assert(chan);
  2730. chan->timestamp_created = now;
  2731. }
  2732. /**
  2733. * Update the created timestamp for a channel listener
  2734. *
  2735. * This updates the channel listener's created timestamp and should only be
  2736. * called from channel_init_listener().
  2737. */
  2738. void
  2739. channel_listener_timestamp_created(channel_listener_t *chan_l)
  2740. {
  2741. time_t now = time(NULL);
  2742. tor_assert(chan_l);
  2743. chan_l->timestamp_created = now;
  2744. }
  2745. /**
  2746. * Update the last active timestamp for a channel
  2747. *
  2748. * This function updates the channel's last active timestamp; it should be
  2749. * called by the lower layer whenever there is activity on the channel which
  2750. * does not lead to a cell being transmitted or received; the active timestamp
  2751. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  2752. * but it should be updated for things like the v3 handshake and stuff that
  2753. * produce activity only visible to the lower layer.
  2754. */
  2755. void
  2756. channel_timestamp_active(channel_t *chan)
  2757. {
  2758. time_t now = time(NULL);
  2759. tor_assert(chan);
  2760. monotime_coarse_get(&chan->timestamp_xfer);
  2761. chan->timestamp_active = now;
  2762. /* Clear any potential netflow padding timer. We're active */
  2763. monotime_coarse_zero(&chan->next_padding_time);
  2764. }
  2765. /**
  2766. * Update the last active timestamp for a channel listener
  2767. */
  2768. void
  2769. channel_listener_timestamp_active(channel_listener_t *chan_l)
  2770. {
  2771. time_t now = time(NULL);
  2772. tor_assert(chan_l);
  2773. chan_l->timestamp_active = now;
  2774. }
  2775. /**
  2776. * Update the last accepted timestamp.
  2777. *
  2778. * This function updates the channel listener's last accepted timestamp; it
  2779. * should be called whenever a new incoming channel is accepted on a
  2780. * listener.
  2781. */
  2782. void
  2783. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  2784. {
  2785. time_t now = time(NULL);
  2786. tor_assert(chan_l);
  2787. chan_l->timestamp_active = now;
  2788. chan_l->timestamp_accepted = now;
  2789. }
  2790. /**
  2791. * Update client timestamp
  2792. *
  2793. * This function is called by relay.c to timestamp a channel that appears to
  2794. * be used as a client.
  2795. */
  2796. void
  2797. channel_timestamp_client(channel_t *chan)
  2798. {
  2799. time_t now = time(NULL);
  2800. tor_assert(chan);
  2801. chan->timestamp_client = now;
  2802. }
  2803. /**
  2804. * Update the recv timestamp
  2805. *
  2806. * This is called whenever we get an incoming cell from the lower layer.
  2807. * This also updates the active timestamp.
  2808. */
  2809. void
  2810. channel_timestamp_recv(channel_t *chan)
  2811. {
  2812. time_t now = time(NULL);
  2813. tor_assert(chan);
  2814. monotime_coarse_get(&chan->timestamp_xfer);
  2815. chan->timestamp_active = now;
  2816. chan->timestamp_recv = now;
  2817. /* Clear any potential netflow padding timer. We're active */
  2818. monotime_coarse_zero(&chan->next_padding_time);
  2819. }
  2820. /**
  2821. * Update the xmit timestamp
  2822. * This is called whenever we pass an outgoing cell to the lower layer. This
  2823. * also updates the active timestamp.
  2824. */
  2825. void
  2826. channel_timestamp_xmit(channel_t *chan)
  2827. {
  2828. time_t now = time(NULL);
  2829. tor_assert(chan);
  2830. monotime_coarse_get(&chan->timestamp_xfer);
  2831. chan->timestamp_active = now;
  2832. chan->timestamp_xmit = now;
  2833. /* Clear any potential netflow padding timer. We're active */
  2834. monotime_coarse_zero(&chan->next_padding_time);
  2835. }
  2836. /***************************************************************
  2837. * Timestamp queries - see above for definitions of timestamps *
  2838. **************************************************************/
  2839. /**
  2840. * Query created timestamp for a channel
  2841. */
  2842. time_t
  2843. channel_when_created(channel_t *chan)
  2844. {
  2845. tor_assert(chan);
  2846. return chan->timestamp_created;
  2847. }
  2848. /**
  2849. * Query client timestamp
  2850. */
  2851. time_t
  2852. channel_when_last_client(channel_t *chan)
  2853. {
  2854. tor_assert(chan);
  2855. return chan->timestamp_client;
  2856. }
  2857. /**
  2858. * Query xmit timestamp
  2859. */
  2860. time_t
  2861. channel_when_last_xmit(channel_t *chan)
  2862. {
  2863. tor_assert(chan);
  2864. return chan->timestamp_xmit;
  2865. }
  2866. /**
  2867. * Check if a channel matches an extend_info_t
  2868. *
  2869. * This function calls the lower layer and asks if this channel matches a
  2870. * given extend_info_t.
  2871. */
  2872. int
  2873. channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
  2874. {
  2875. tor_assert(chan);
  2876. tor_assert(chan->matches_extend_info);
  2877. tor_assert(extend_info);
  2878. return chan->matches_extend_info(chan, extend_info);
  2879. }
  2880. /**
  2881. * Check if a channel matches a given target address; return true iff we do.
  2882. *
  2883. * This function calls into the lower layer and asks if this channel thinks
  2884. * it matches a given target address for circuit extension purposes.
  2885. */
  2886. int
  2887. channel_matches_target_addr_for_extend(channel_t *chan,
  2888. const tor_addr_t *target)
  2889. {
  2890. tor_assert(chan);
  2891. tor_assert(chan->matches_target);
  2892. tor_assert(target);
  2893. return chan->matches_target(chan, target);
  2894. }
  2895. /**
  2896. * Return the total number of circuits used by a channel
  2897. *
  2898. * @param chan Channel to query
  2899. * @return Number of circuits using this as n_chan or p_chan
  2900. */
  2901. unsigned int
  2902. channel_num_circuits(channel_t *chan)
  2903. {
  2904. tor_assert(chan);
  2905. return chan->num_n_circuits +
  2906. chan->num_p_circuits;
  2907. }
  2908. /**
  2909. * Set up circuit ID generation
  2910. *
  2911. * This is called when setting up a channel and replaces the old
  2912. * connection_or_set_circid_type()
  2913. */
  2914. MOCK_IMPL(void,
  2915. channel_set_circid_type,(channel_t *chan,
  2916. crypto_pk_t *identity_rcvd,
  2917. int consider_identity))
  2918. {
  2919. int started_here;
  2920. crypto_pk_t *our_identity;
  2921. tor_assert(chan);
  2922. started_here = channel_is_outgoing(chan);
  2923. if (! consider_identity) {
  2924. if (started_here)
  2925. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  2926. else
  2927. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  2928. return;
  2929. }
  2930. our_identity = started_here ?
  2931. get_tlsclient_identity_key() : get_server_identity_key();
  2932. if (identity_rcvd) {
  2933. if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
  2934. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  2935. } else {
  2936. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  2937. }
  2938. } else {
  2939. chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
  2940. }
  2941. }
  2942. static int
  2943. channel_sort_by_ed25519_identity(const void **a_, const void **b_)
  2944. {
  2945. const channel_t *a = *a_,
  2946. *b = *b_;
  2947. return fast_memcmp(&a->ed25519_identity.pubkey,
  2948. &b->ed25519_identity.pubkey,
  2949. sizeof(a->ed25519_identity.pubkey));
  2950. }
  2951. /** Helper for channel_update_bad_for_new_circs(): Perform the
  2952. * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
  2953. * all of which MUST have the same RSA ID. (They MAY have different
  2954. * Ed25519 IDs.) */
  2955. static void
  2956. channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
  2957. {
  2958. /*XXXX This function should really be about channels. 15056 */
  2959. channel_t *chan = TOR_LIST_FIRST(lst);
  2960. if (!chan)
  2961. return;
  2962. /* if there is only one channel, don't bother looping */
  2963. if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan, next_with_same_id))) {
  2964. connection_or_single_set_badness_(
  2965. time(NULL), BASE_CHAN_TO_TLS(chan)->conn, force);
  2966. return;
  2967. }
  2968. smartlist_t *channels = smartlist_new();
  2969. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  2970. if (BASE_CHAN_TO_TLS(chan)->conn) {
  2971. smartlist_add(channels, chan);
  2972. }
  2973. }
  2974. smartlist_sort(channels, channel_sort_by_ed25519_identity);
  2975. const ed25519_public_key_t *common_ed25519_identity = NULL;
  2976. /* it would be more efficient to do a slice, but this case is rare */
  2977. smartlist_t *or_conns = smartlist_new();
  2978. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, channel) {
  2979. if (!common_ed25519_identity)
  2980. common_ed25519_identity = &channel->ed25519_identity;
  2981. if (! ed25519_pubkey_eq(&channel->ed25519_identity,
  2982. common_ed25519_identity)) {
  2983. connection_or_group_set_badness_(or_conns, force);
  2984. smartlist_clear(or_conns);
  2985. common_ed25519_identity = &channel->ed25519_identity;
  2986. }
  2987. smartlist_add(or_conns, BASE_CHAN_TO_TLS(channel)->conn);
  2988. } SMARTLIST_FOREACH_END(channel);
  2989. connection_or_group_set_badness_(or_conns, force);
  2990. /* XXXX 15056 we may want to do something special with connections that have
  2991. * no set Ed25519 identity! */
  2992. smartlist_free(or_conns);
  2993. smartlist_free(channels);
  2994. }
  2995. /** Go through all the channels (or if <b>digest</b> is non-NULL, just
  2996. * the OR connections with that digest), and set the is_bad_for_new_circs
  2997. * flag based on the rules in connection_or_group_set_badness() (or just
  2998. * always set it if <b>force</b> is true).
  2999. */
  3000. void
  3001. channel_update_bad_for_new_circs(const char *digest, int force)
  3002. {
  3003. if (digest) {
  3004. channel_idmap_entry_t *ent;
  3005. channel_idmap_entry_t search;
  3006. memset(&search, 0, sizeof(search));
  3007. memcpy(search.digest, digest, DIGEST_LEN);
  3008. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  3009. if (ent) {
  3010. channel_rsa_id_group_set_badness(&ent->channel_list, force);
  3011. }
  3012. return;
  3013. }
  3014. /* no digest; just look at everything. */
  3015. channel_idmap_entry_t **iter;
  3016. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  3017. channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
  3018. }
  3019. }