channel.c 133 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694
  1. /* * Copyright (c) 2012-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file channel.c
  5. *
  6. * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
  7. * transfer cells from Tor instance to Tor instance.
  8. * Currently, there is only one implementation of the channel abstraction: in
  9. * channeltls.c.
  10. *
  11. * Channels are a higher-level abstraction than or_connection_t: In general,
  12. * any means that two Tor relays use to exchange cells, or any means that a
  13. * relay and a client use to exchange cells, is a channel.
  14. *
  15. * Channels differ from pluggable transports in that they do not wrap an
  16. * underlying protocol over which cells are transmitted: they <em>are</em> the
  17. * underlying protocol.
  18. *
  19. * This module defines the generic parts of the channel_t interface, and
  20. * provides the machinery necessary for specialized implementations to be
  21. * created. At present, there is one specialized implementation in
  22. * channeltls.c, which uses connection_or.c to send cells over a TLS
  23. * connection.
  24. *
  25. * Every channel implementation is responsible for being able to transmit
  26. * cells that are added to it with channel_write_cell() and related functions,
  27. * and to receive incoming cells with the channel_queue_cell() and related
  28. * functions. See the channel_t documentation for more information.
  29. *
  30. * When new cells arrive on a channel, they are passed to cell handler
  31. * functions, which can be set by channel_set_cell_handlers()
  32. * functions. (Tor's cell handlers are in command.c.)
  33. *
  34. * Tor flushes cells to channels from relay.c in
  35. * channel_flush_from_first_active_circuit().
  36. **/
  37. /*
  38. * Define this so channel.h gives us things only channel_t subclasses
  39. * should touch.
  40. */
  41. #define TOR_CHANNEL_INTERNAL_
  42. /* This one's for stuff only channel.c and the test suite should see */
  43. #define CHANNEL_PRIVATE_
  44. #include "or.h"
  45. #include "channel.h"
  46. #include "channeltls.h"
  47. #include "circuitbuild.h"
  48. #include "circuitlist.h"
  49. #include "circuitstats.h"
  50. #include "config.h"
  51. #include "connection_or.h" /* For var_cell_free() */
  52. #include "circuitmux.h"
  53. #include "entrynodes.h"
  54. #include "geoip.h"
  55. #include "nodelist.h"
  56. #include "relay.h"
  57. #include "rephist.h"
  58. #include "router.h"
  59. #include "routerlist.h"
  60. #include "scheduler.h"
  61. /* Global lists of channels */
  62. /* All channel_t instances */
  63. static smartlist_t *all_channels = NULL;
  64. /* All channel_t instances not in ERROR or CLOSED states */
  65. static smartlist_t *active_channels = NULL;
  66. /* All channel_t instances in ERROR or CLOSED states */
  67. static smartlist_t *finished_channels = NULL;
  68. /* All channel_listener_t instances */
  69. static smartlist_t *all_listeners = NULL;
  70. /* All channel_listener_t instances in LISTENING state */
  71. static smartlist_t *active_listeners = NULL;
  72. /* All channel_listener_t instances in LISTENING state */
  73. static smartlist_t *finished_listeners = NULL;
  74. /* Counter for ID numbers */
  75. static uint64_t n_channels_allocated = 0;
  76. /*
  77. * Channel global byte/cell counters, for statistics and for scheduler high
  78. * /low-water marks.
  79. */
  80. /*
  81. * Total number of cells ever given to any channel with the
  82. * channel_write_*_cell() functions.
  83. */
  84. static uint64_t n_channel_cells_queued = 0;
  85. /*
  86. * Total number of cells ever passed to a channel lower layer with the
  87. * write_*_cell() methods.
  88. */
  89. static uint64_t n_channel_cells_passed_to_lower_layer = 0;
  90. /*
  91. * Current number of cells in all channel queues; should be
  92. * n_channel_cells_queued - n_channel_cells_passed_to_lower_layer.
  93. */
  94. static uint64_t n_channel_cells_in_queues = 0;
  95. /*
  96. * Total number of bytes for all cells ever queued to a channel and
  97. * counted in n_channel_cells_queued.
  98. */
  99. static uint64_t n_channel_bytes_queued = 0;
  100. /*
  101. * Total number of bytes for all cells ever passed to a channel lower layer
  102. * and counted in n_channel_cells_passed_to_lower_layer.
  103. */
  104. static uint64_t n_channel_bytes_passed_to_lower_layer = 0;
  105. /*
  106. * Current number of bytes in all channel queues; should be
  107. * n_channel_bytes_queued - n_channel_bytes_passed_to_lower_layer.
  108. */
  109. static uint64_t n_channel_bytes_in_queues = 0;
  110. /*
  111. * Current total estimated queue size *including lower layer queues and
  112. * transmit overhead*
  113. */
  114. STATIC uint64_t estimated_total_queue_size = 0;
  115. /* Digest->channel map
  116. *
  117. * Similar to the one used in connection_or.c, this maps from the identity
  118. * digest of a remote endpoint to a channel_t to that endpoint. Channels
  119. * should be placed here when registered and removed when they close or error.
  120. * If more than one channel exists, follow the next_with_same_id pointer
  121. * as a linked list.
  122. */
  123. static HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
  124. HT_INITIALIZER();
  125. typedef struct channel_idmap_entry_s {
  126. HT_ENTRY(channel_idmap_entry_s) node;
  127. uint8_t digest[DIGEST_LEN];
  128. TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
  129. } channel_idmap_entry_t;
  130. static inline unsigned
  131. channel_idmap_hash(const channel_idmap_entry_t *ent)
  132. {
  133. return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
  134. }
  135. static inline int
  136. channel_idmap_eq(const channel_idmap_entry_t *a,
  137. const channel_idmap_entry_t *b)
  138. {
  139. return tor_memeq(a->digest, b->digest, DIGEST_LEN);
  140. }
  141. HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
  142. channel_idmap_eq)
  143. HT_GENERATE2(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
  144. channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_)
  145. static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
  146. #if 0
  147. static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
  148. #endif
  149. static cell_queue_entry_t *
  150. cell_queue_entry_new_fixed(cell_t *cell);
  151. static cell_queue_entry_t *
  152. cell_queue_entry_new_var(var_cell_t *var_cell);
  153. static int is_destroy_cell(channel_t *chan,
  154. const cell_queue_entry_t *q, circid_t *circid_out);
  155. static void channel_assert_counter_consistency(void);
  156. /* Functions to maintain the digest map */
  157. static void channel_add_to_digest_map(channel_t *chan);
  158. static void channel_remove_from_digest_map(channel_t *chan);
  159. /*
  160. * Flush cells from just the outgoing queue without trying to get them
  161. * from circuits; used internall by channel_flush_some_cells().
  162. */
  163. static ssize_t
  164. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  165. ssize_t num_cells);
  166. static void channel_force_free(channel_t *chan);
  167. static void
  168. channel_free_list(smartlist_t *channels, int mark_for_close);
  169. static void
  170. channel_listener_free_list(smartlist_t *channels, int mark_for_close);
  171. static void channel_listener_force_free(channel_listener_t *chan_l);
  172. static size_t channel_get_cell_queue_entry_size(channel_t *chan,
  173. cell_queue_entry_t *q);
  174. static void
  175. channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q);
  176. /***********************************
  177. * Channel state utility functions *
  178. **********************************/
  179. /**
  180. * Indicate whether a given channel state is valid
  181. */
  182. int
  183. channel_state_is_valid(channel_state_t state)
  184. {
  185. int is_valid;
  186. switch (state) {
  187. case CHANNEL_STATE_CLOSED:
  188. case CHANNEL_STATE_CLOSING:
  189. case CHANNEL_STATE_ERROR:
  190. case CHANNEL_STATE_MAINT:
  191. case CHANNEL_STATE_OPENING:
  192. case CHANNEL_STATE_OPEN:
  193. is_valid = 1;
  194. break;
  195. case CHANNEL_STATE_LAST:
  196. default:
  197. is_valid = 0;
  198. }
  199. return is_valid;
  200. }
  201. /**
  202. * Indicate whether a given channel listener state is valid
  203. */
  204. int
  205. channel_listener_state_is_valid(channel_listener_state_t state)
  206. {
  207. int is_valid;
  208. switch (state) {
  209. case CHANNEL_LISTENER_STATE_CLOSED:
  210. case CHANNEL_LISTENER_STATE_LISTENING:
  211. case CHANNEL_LISTENER_STATE_CLOSING:
  212. case CHANNEL_LISTENER_STATE_ERROR:
  213. is_valid = 1;
  214. break;
  215. case CHANNEL_LISTENER_STATE_LAST:
  216. default:
  217. is_valid = 0;
  218. }
  219. return is_valid;
  220. }
  221. /**
  222. * Indicate whether a channel state transition is valid
  223. *
  224. * This function takes two channel states and indicates whether a
  225. * transition between them is permitted (see the state definitions and
  226. * transition table in or.h at the channel_state_t typedef).
  227. */
  228. int
  229. channel_state_can_transition(channel_state_t from, channel_state_t to)
  230. {
  231. int is_valid;
  232. switch (from) {
  233. case CHANNEL_STATE_CLOSED:
  234. is_valid = (to == CHANNEL_STATE_OPENING);
  235. break;
  236. case CHANNEL_STATE_CLOSING:
  237. is_valid = (to == CHANNEL_STATE_CLOSED ||
  238. to == CHANNEL_STATE_ERROR);
  239. break;
  240. case CHANNEL_STATE_ERROR:
  241. is_valid = 0;
  242. break;
  243. case CHANNEL_STATE_MAINT:
  244. is_valid = (to == CHANNEL_STATE_CLOSING ||
  245. to == CHANNEL_STATE_ERROR ||
  246. to == CHANNEL_STATE_OPEN);
  247. break;
  248. case CHANNEL_STATE_OPENING:
  249. is_valid = (to == CHANNEL_STATE_CLOSING ||
  250. to == CHANNEL_STATE_ERROR ||
  251. to == CHANNEL_STATE_OPEN);
  252. break;
  253. case CHANNEL_STATE_OPEN:
  254. is_valid = (to == CHANNEL_STATE_CLOSING ||
  255. to == CHANNEL_STATE_ERROR ||
  256. to == CHANNEL_STATE_MAINT);
  257. break;
  258. case CHANNEL_STATE_LAST:
  259. default:
  260. is_valid = 0;
  261. }
  262. return is_valid;
  263. }
  264. /**
  265. * Indicate whether a channel listener state transition is valid
  266. *
  267. * This function takes two channel listener states and indicates whether a
  268. * transition between them is permitted (see the state definitions and
  269. * transition table in or.h at the channel_listener_state_t typedef).
  270. */
  271. int
  272. channel_listener_state_can_transition(channel_listener_state_t from,
  273. channel_listener_state_t to)
  274. {
  275. int is_valid;
  276. switch (from) {
  277. case CHANNEL_LISTENER_STATE_CLOSED:
  278. is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
  279. break;
  280. case CHANNEL_LISTENER_STATE_CLOSING:
  281. is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
  282. to == CHANNEL_LISTENER_STATE_ERROR);
  283. break;
  284. case CHANNEL_LISTENER_STATE_ERROR:
  285. is_valid = 0;
  286. break;
  287. case CHANNEL_LISTENER_STATE_LISTENING:
  288. is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
  289. to == CHANNEL_LISTENER_STATE_ERROR);
  290. break;
  291. case CHANNEL_LISTENER_STATE_LAST:
  292. default:
  293. is_valid = 0;
  294. }
  295. return is_valid;
  296. }
  297. /**
  298. * Return a human-readable description for a channel state
  299. */
  300. const char *
  301. channel_state_to_string(channel_state_t state)
  302. {
  303. const char *descr;
  304. switch (state) {
  305. case CHANNEL_STATE_CLOSED:
  306. descr = "closed";
  307. break;
  308. case CHANNEL_STATE_CLOSING:
  309. descr = "closing";
  310. break;
  311. case CHANNEL_STATE_ERROR:
  312. descr = "channel error";
  313. break;
  314. case CHANNEL_STATE_MAINT:
  315. descr = "temporarily suspended for maintenance";
  316. break;
  317. case CHANNEL_STATE_OPENING:
  318. descr = "opening";
  319. break;
  320. case CHANNEL_STATE_OPEN:
  321. descr = "open";
  322. break;
  323. case CHANNEL_STATE_LAST:
  324. default:
  325. descr = "unknown or invalid channel state";
  326. }
  327. return descr;
  328. }
  329. /**
  330. * Return a human-readable description for a channel listenier state
  331. */
  332. const char *
  333. channel_listener_state_to_string(channel_listener_state_t state)
  334. {
  335. const char *descr;
  336. switch (state) {
  337. case CHANNEL_LISTENER_STATE_CLOSED:
  338. descr = "closed";
  339. break;
  340. case CHANNEL_LISTENER_STATE_CLOSING:
  341. descr = "closing";
  342. break;
  343. case CHANNEL_LISTENER_STATE_ERROR:
  344. descr = "channel listener error";
  345. break;
  346. case CHANNEL_LISTENER_STATE_LISTENING:
  347. descr = "listening";
  348. break;
  349. case CHANNEL_LISTENER_STATE_LAST:
  350. default:
  351. descr = "unknown or invalid channel listener state";
  352. }
  353. return descr;
  354. }
  355. /***************************************
  356. * Channel registration/unregistration *
  357. ***************************************/
  358. /**
  359. * Register a channel
  360. *
  361. * This function registers a newly created channel in the global lists/maps
  362. * of active channels.
  363. */
  364. void
  365. channel_register(channel_t *chan)
  366. {
  367. tor_assert(chan);
  368. /* No-op if already registered */
  369. if (chan->registered) return;
  370. log_debug(LD_CHANNEL,
  371. "Registering channel %p (ID " U64_FORMAT ") "
  372. "in state %s (%d) with digest %s",
  373. chan, U64_PRINTF_ARG(chan->global_identifier),
  374. channel_state_to_string(chan->state), chan->state,
  375. hex_str(chan->identity_digest, DIGEST_LEN));
  376. /* Make sure we have all_channels, then add it */
  377. if (!all_channels) all_channels = smartlist_new();
  378. smartlist_add(all_channels, chan);
  379. /* Is it finished? */
  380. if (CHANNEL_FINISHED(chan)) {
  381. /* Put it in the finished list, creating it if necessary */
  382. if (!finished_channels) finished_channels = smartlist_new();
  383. smartlist_add(finished_channels, chan);
  384. } else {
  385. /* Put it in the active list, creating it if necessary */
  386. if (!active_channels) active_channels = smartlist_new();
  387. smartlist_add(active_channels, chan);
  388. if (!CHANNEL_IS_CLOSING(chan)) {
  389. /* It should have a digest set */
  390. if (!tor_digest_is_zero(chan->identity_digest)) {
  391. /* Yeah, we're good, add it to the map */
  392. channel_add_to_digest_map(chan);
  393. } else {
  394. log_info(LD_CHANNEL,
  395. "Channel %p (global ID " U64_FORMAT ") "
  396. "in state %s (%d) registered with no identity digest",
  397. chan, U64_PRINTF_ARG(chan->global_identifier),
  398. channel_state_to_string(chan->state), chan->state);
  399. }
  400. }
  401. }
  402. /* Mark it as registered */
  403. chan->registered = 1;
  404. }
  405. /**
  406. * Unregister a channel
  407. *
  408. * This function removes a channel from the global lists and maps and is used
  409. * when freeing a closed/errored channel.
  410. */
  411. void
  412. channel_unregister(channel_t *chan)
  413. {
  414. tor_assert(chan);
  415. /* No-op if not registered */
  416. if (!(chan->registered)) return;
  417. /* Is it finished? */
  418. if (CHANNEL_FINISHED(chan)) {
  419. /* Get it out of the finished list */
  420. if (finished_channels) smartlist_remove(finished_channels, chan);
  421. } else {
  422. /* Get it out of the active list */
  423. if (active_channels) smartlist_remove(active_channels, chan);
  424. }
  425. /* Get it out of all_channels */
  426. if (all_channels) smartlist_remove(all_channels, chan);
  427. /* Mark it as unregistered */
  428. chan->registered = 0;
  429. /* Should it be in the digest map? */
  430. if (!tor_digest_is_zero(chan->identity_digest) &&
  431. !(CHANNEL_CONDEMNED(chan))) {
  432. /* Remove it */
  433. channel_remove_from_digest_map(chan);
  434. }
  435. }
  436. /**
  437. * Register a channel listener
  438. *
  439. * This function registers a newly created channel listner in the global
  440. * lists/maps of active channel listeners.
  441. */
  442. void
  443. channel_listener_register(channel_listener_t *chan_l)
  444. {
  445. tor_assert(chan_l);
  446. /* No-op if already registered */
  447. if (chan_l->registered) return;
  448. log_debug(LD_CHANNEL,
  449. "Registering channel listener %p (ID " U64_FORMAT ") "
  450. "in state %s (%d)",
  451. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  452. channel_listener_state_to_string(chan_l->state),
  453. chan_l->state);
  454. /* Make sure we have all_channels, then add it */
  455. if (!all_listeners) all_listeners = smartlist_new();
  456. smartlist_add(all_listeners, chan_l);
  457. /* Is it finished? */
  458. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  459. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
  460. /* Put it in the finished list, creating it if necessary */
  461. if (!finished_listeners) finished_listeners = smartlist_new();
  462. smartlist_add(finished_listeners, chan_l);
  463. } else {
  464. /* Put it in the active list, creating it if necessary */
  465. if (!active_listeners) active_listeners = smartlist_new();
  466. smartlist_add(active_listeners, chan_l);
  467. }
  468. /* Mark it as registered */
  469. chan_l->registered = 1;
  470. }
  471. /**
  472. * Unregister a channel listener
  473. *
  474. * This function removes a channel listener from the global lists and maps
  475. * and is used when freeing a closed/errored channel listener.
  476. */
  477. void
  478. channel_listener_unregister(channel_listener_t *chan_l)
  479. {
  480. tor_assert(chan_l);
  481. /* No-op if not registered */
  482. if (!(chan_l->registered)) return;
  483. /* Is it finished? */
  484. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  485. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
  486. /* Get it out of the finished list */
  487. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  488. } else {
  489. /* Get it out of the active list */
  490. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  491. }
  492. /* Get it out of all_channels */
  493. if (all_listeners) smartlist_remove(all_listeners, chan_l);
  494. /* Mark it as unregistered */
  495. chan_l->registered = 0;
  496. }
  497. /*********************************
  498. * Channel digest map maintenance
  499. *********************************/
  500. /**
  501. * Add a channel to the digest map
  502. *
  503. * This function adds a channel to the digest map and inserts it into the
  504. * correct linked list if channels with that remote endpoint identity digest
  505. * already exist.
  506. */
  507. static void
  508. channel_add_to_digest_map(channel_t *chan)
  509. {
  510. channel_idmap_entry_t *ent, search;
  511. tor_assert(chan);
  512. /* Assert that the state makes sense */
  513. tor_assert(!CHANNEL_CONDEMNED(chan));
  514. /* Assert that there is a digest */
  515. tor_assert(!tor_digest_is_zero(chan->identity_digest));
  516. memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
  517. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  518. if (! ent) {
  519. ent = tor_malloc(sizeof(channel_idmap_entry_t));
  520. memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
  521. TOR_LIST_INIT(&ent->channel_list);
  522. HT_INSERT(channel_idmap, &channel_identity_map, ent);
  523. }
  524. TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
  525. log_debug(LD_CHANNEL,
  526. "Added channel %p (global ID " U64_FORMAT ") "
  527. "to identity map in state %s (%d) with digest %s",
  528. chan, U64_PRINTF_ARG(chan->global_identifier),
  529. channel_state_to_string(chan->state), chan->state,
  530. hex_str(chan->identity_digest, DIGEST_LEN));
  531. }
  532. /**
  533. * Remove a channel from the digest map
  534. *
  535. * This function removes a channel from the digest map and the linked list of
  536. * channels for that digest if more than one exists.
  537. */
  538. static void
  539. channel_remove_from_digest_map(channel_t *chan)
  540. {
  541. channel_idmap_entry_t *ent, search;
  542. tor_assert(chan);
  543. /* Assert that there is a digest */
  544. tor_assert(!tor_digest_is_zero(chan->identity_digest));
  545. #if 0
  546. /* Make sure we have a map */
  547. if (!channel_identity_map) {
  548. /*
  549. * No identity map, so we can't find it by definition. This
  550. * case is similar to digestmap_get() failing below.
  551. */
  552. log_warn(LD_BUG,
  553. "Trying to remove channel %p (global ID " U64_FORMAT ") "
  554. "with digest %s from identity map, but didn't have any identity "
  555. "map",
  556. chan, U64_PRINTF_ARG(chan->global_identifier),
  557. hex_str(chan->identity_digest, DIGEST_LEN));
  558. /* Clear out its next/prev pointers */
  559. if (chan->next_with_same_id) {
  560. chan->next_with_same_id->prev_with_same_id = chan->prev_with_same_id;
  561. }
  562. if (chan->prev_with_same_id) {
  563. chan->prev_with_same_id->next_with_same_id = chan->next_with_same_id;
  564. }
  565. chan->next_with_same_id = NULL;
  566. chan->prev_with_same_id = NULL;
  567. return;
  568. }
  569. #endif
  570. /* Pull it out of its list, wherever that list is */
  571. TOR_LIST_REMOVE(chan, next_with_same_id);
  572. memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
  573. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  574. /* Look for it in the map */
  575. if (ent) {
  576. /* Okay, it's here */
  577. if (TOR_LIST_EMPTY(&ent->channel_list)) {
  578. HT_REMOVE(channel_idmap, &channel_identity_map, ent);
  579. tor_free(ent);
  580. }
  581. log_debug(LD_CHANNEL,
  582. "Removed channel %p (global ID " U64_FORMAT ") from "
  583. "identity map in state %s (%d) with digest %s",
  584. chan, U64_PRINTF_ARG(chan->global_identifier),
  585. channel_state_to_string(chan->state), chan->state,
  586. hex_str(chan->identity_digest, DIGEST_LEN));
  587. } else {
  588. /* Shouldn't happen */
  589. log_warn(LD_BUG,
  590. "Trying to remove channel %p (global ID " U64_FORMAT ") with "
  591. "digest %s from identity map, but couldn't find any with "
  592. "that digest",
  593. chan, U64_PRINTF_ARG(chan->global_identifier),
  594. hex_str(chan->identity_digest, DIGEST_LEN));
  595. }
  596. }
  597. /****************************
  598. * Channel lookup functions *
  599. ***************************/
  600. /**
  601. * Find channel by global ID
  602. *
  603. * This function searches for a channel by the global_identifier assigned
  604. * at initialization time. This identifier is unique for the lifetime of the
  605. * Tor process.
  606. */
  607. channel_t *
  608. channel_find_by_global_id(uint64_t global_identifier)
  609. {
  610. channel_t *rv = NULL;
  611. if (all_channels && smartlist_len(all_channels) > 0) {
  612. SMARTLIST_FOREACH_BEGIN(all_channels, channel_t *, curr) {
  613. if (curr->global_identifier == global_identifier) {
  614. rv = curr;
  615. break;
  616. }
  617. } SMARTLIST_FOREACH_END(curr);
  618. }
  619. return rv;
  620. }
  621. /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
  622. * as its identity keys. If either is NULL, do not check for a match. */
  623. static int
  624. channel_remote_identity_matches(const channel_t *chan,
  625. const char *rsa_id_digest,
  626. const ed25519_public_key_t *ed_id)
  627. {
  628. if (BUG(!chan))
  629. return 0;
  630. if (rsa_id_digest) {
  631. if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
  632. return 0;
  633. }
  634. if (ed_id) {
  635. if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
  636. ED25519_PUBKEY_LEN))
  637. return 0;
  638. }
  639. return 1;
  640. }
  641. /**
  642. * Find channel by RSA/Ed25519 identity of of the remote endpoint
  643. *
  644. * This function looks up a channel by the digest of its remote endpoint's RSA
  645. * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
  646. * matching the <b>ed_id</b> will be returned.
  647. *
  648. * It's possible that more than one channel to a given endpoint exists. Use
  649. * channel_next_with_rsa_identity() to walk the list of channels; make sure
  650. * to test for Ed25519 identity match too (as appropriate)
  651. */
  652. channel_t *
  653. channel_find_by_remote_identity(const char *rsa_id_digest,
  654. const ed25519_public_key_t *ed_id)
  655. {
  656. channel_t *rv = NULL;
  657. channel_idmap_entry_t *ent, search;
  658. tor_assert(rsa_id_digest); /* For now, we require that every channel have
  659. * an RSA identity, and that every lookup
  660. * contain an RSA identity */
  661. if (ed_id && ed25519_public_key_is_zero(ed_id)) {
  662. /* Treat zero as meaning "We don't care about the presence or absence of
  663. * an Ed key", not "There must be no Ed key". */
  664. ed_id = NULL;
  665. }
  666. memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
  667. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  668. if (ent) {
  669. rv = TOR_LIST_FIRST(&ent->channel_list);
  670. }
  671. while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
  672. rv = channel_next_with_rsa_identity(rv);
  673. }
  674. return rv;
  675. }
  676. /**
  677. * Get next channel with digest
  678. *
  679. * This function takes a channel and finds the next channel in the list
  680. * with the same digest.
  681. */
  682. channel_t *
  683. channel_next_with_rsa_identity(channel_t *chan)
  684. {
  685. tor_assert(chan);
  686. return TOR_LIST_NEXT(chan, next_with_same_id);
  687. }
  688. /**
  689. * Initialize a channel
  690. *
  691. * This function should be called by subclasses to set up some per-channel
  692. * variables. I.e., this is the superclass constructor. Before this, the
  693. * channel should be allocated with tor_malloc_zero().
  694. */
  695. void
  696. channel_init(channel_t *chan)
  697. {
  698. tor_assert(chan);
  699. /* Assign an ID and bump the counter */
  700. chan->global_identifier = n_channels_allocated++;
  701. /* Init timestamp */
  702. chan->timestamp_last_had_circuits = time(NULL);
  703. /* Warn about exhausted circuit IDs no more than hourly. */
  704. chan->last_warned_circ_ids_exhausted.rate = 3600;
  705. /* Initialize queues. */
  706. TOR_SIMPLEQ_INIT(&chan->incoming_queue);
  707. TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
  708. /* Initialize list entries. */
  709. memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
  710. /* Timestamp it */
  711. channel_timestamp_created(chan);
  712. /* It hasn't been open yet. */
  713. chan->has_been_open = 0;
  714. /* Scheduler state is idle */
  715. chan->scheduler_state = SCHED_CHAN_IDLE;
  716. }
  717. /**
  718. * Initialize a channel listener
  719. *
  720. * This function should be called by subclasses to set up some per-channel
  721. * variables. I.e., this is the superclass constructor. Before this, the
  722. * channel listener should be allocated with tor_malloc_zero().
  723. */
  724. void
  725. channel_init_listener(channel_listener_t *chan_l)
  726. {
  727. tor_assert(chan_l);
  728. /* Assign an ID and bump the counter */
  729. chan_l->global_identifier = n_channels_allocated++;
  730. /* Timestamp it */
  731. channel_listener_timestamp_created(chan_l);
  732. }
  733. /**
  734. * Free a channel; nothing outside of channel.c and subclasses should call
  735. * this - it frees channels after they have closed and been unregistered.
  736. */
  737. void
  738. channel_free(channel_t *chan)
  739. {
  740. if (!chan) return;
  741. /* It must be closed or errored */
  742. tor_assert(CHANNEL_FINISHED(chan));
  743. /* It must be deregistered */
  744. tor_assert(!(chan->registered));
  745. log_debug(LD_CHANNEL,
  746. "Freeing channel " U64_FORMAT " at %p",
  747. U64_PRINTF_ARG(chan->global_identifier), chan);
  748. /* Get this one out of the scheduler */
  749. scheduler_release_channel(chan);
  750. /*
  751. * Get rid of cmux policy before we do anything, so cmux policies don't
  752. * see channels in weird half-freed states.
  753. */
  754. if (chan->cmux) {
  755. circuitmux_set_policy(chan->cmux, NULL);
  756. }
  757. /* Call a free method if there is one */
  758. if (chan->free_fn) chan->free_fn(chan);
  759. channel_clear_remote_end(chan);
  760. /* Get rid of cmux */
  761. if (chan->cmux) {
  762. circuitmux_detach_all_circuits(chan->cmux, NULL);
  763. circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
  764. circuitmux_free(chan->cmux);
  765. chan->cmux = NULL;
  766. }
  767. /* We're in CLOSED or ERROR, so the cell queue is already empty */
  768. tor_free(chan);
  769. }
  770. /**
  771. * Free a channel listener; nothing outside of channel.c and subclasses
  772. * should call this - it frees channel listeners after they have closed and
  773. * been unregistered.
  774. */
  775. void
  776. channel_listener_free(channel_listener_t *chan_l)
  777. {
  778. if (!chan_l) return;
  779. log_debug(LD_CHANNEL,
  780. "Freeing channel_listener_t " U64_FORMAT " at %p",
  781. U64_PRINTF_ARG(chan_l->global_identifier),
  782. chan_l);
  783. /* It must be closed or errored */
  784. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  785. chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
  786. /* It must be deregistered */
  787. tor_assert(!(chan_l->registered));
  788. /* Call a free method if there is one */
  789. if (chan_l->free_fn) chan_l->free_fn(chan_l);
  790. /*
  791. * We're in CLOSED or ERROR, so the incoming channel queue is already
  792. * empty.
  793. */
  794. tor_free(chan_l);
  795. }
  796. /**
  797. * Free a channel and skip the state/registration asserts; this internal-
  798. * use-only function should be called only from channel_free_all() when
  799. * shutting down the Tor process.
  800. */
  801. static void
  802. channel_force_free(channel_t *chan)
  803. {
  804. cell_queue_entry_t *cell, *cell_tmp;
  805. tor_assert(chan);
  806. log_debug(LD_CHANNEL,
  807. "Force-freeing channel " U64_FORMAT " at %p",
  808. U64_PRINTF_ARG(chan->global_identifier), chan);
  809. /* Get this one out of the scheduler */
  810. scheduler_release_channel(chan);
  811. /*
  812. * Get rid of cmux policy before we do anything, so cmux policies don't
  813. * see channels in weird half-freed states.
  814. */
  815. if (chan->cmux) {
  816. circuitmux_set_policy(chan->cmux, NULL);
  817. }
  818. /* Call a free method if there is one */
  819. if (chan->free_fn) chan->free_fn(chan);
  820. channel_clear_remote_end(chan);
  821. /* Get rid of cmux */
  822. if (chan->cmux) {
  823. circuitmux_free(chan->cmux);
  824. chan->cmux = NULL;
  825. }
  826. /* We might still have a cell queue; kill it */
  827. TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
  828. cell_queue_entry_free(cell, 0);
  829. }
  830. TOR_SIMPLEQ_INIT(&chan->incoming_queue);
  831. /* Outgoing cell queue is similar, but we can have to free packed cells */
  832. TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
  833. cell_queue_entry_free(cell, 0);
  834. }
  835. TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
  836. tor_free(chan);
  837. }
  838. /**
  839. * Free a channel listener and skip the state/reigstration asserts; this
  840. * internal-use-only function should be called only from channel_free_all()
  841. * when shutting down the Tor process.
  842. */
  843. static void
  844. channel_listener_force_free(channel_listener_t *chan_l)
  845. {
  846. tor_assert(chan_l);
  847. log_debug(LD_CHANNEL,
  848. "Force-freeing channel_listener_t " U64_FORMAT " at %p",
  849. U64_PRINTF_ARG(chan_l->global_identifier),
  850. chan_l);
  851. /* Call a free method if there is one */
  852. if (chan_l->free_fn) chan_l->free_fn(chan_l);
  853. /*
  854. * The incoming list just gets emptied and freed; we request close on
  855. * any channels we find there, but since we got called while shutting
  856. * down they will get deregistered and freed elsewhere anyway.
  857. */
  858. if (chan_l->incoming_list) {
  859. SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
  860. channel_t *, qchan) {
  861. channel_mark_for_close(qchan);
  862. } SMARTLIST_FOREACH_END(qchan);
  863. smartlist_free(chan_l->incoming_list);
  864. chan_l->incoming_list = NULL;
  865. }
  866. tor_free(chan_l);
  867. }
  868. /**
  869. * Return the current registered listener for a channel listener
  870. *
  871. * This function returns a function pointer to the current registered
  872. * handler for new incoming channels on a channel listener.
  873. */
  874. channel_listener_fn_ptr
  875. channel_listener_get_listener_fn(channel_listener_t *chan_l)
  876. {
  877. tor_assert(chan_l);
  878. if (chan_l->state == CHANNEL_LISTENER_STATE_LISTENING)
  879. return chan_l->listener;
  880. return NULL;
  881. }
  882. /**
  883. * Set the listener for a channel listener
  884. *
  885. * This function sets the handler for new incoming channels on a channel
  886. * listener.
  887. */
  888. void
  889. channel_listener_set_listener_fn(channel_listener_t *chan_l,
  890. channel_listener_fn_ptr listener)
  891. {
  892. tor_assert(chan_l);
  893. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
  894. log_debug(LD_CHANNEL,
  895. "Setting listener callback for channel listener %p "
  896. "(global ID " U64_FORMAT ") to %p",
  897. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  898. listener);
  899. chan_l->listener = listener;
  900. if (chan_l->listener) channel_listener_process_incoming(chan_l);
  901. }
  902. /**
  903. * Return the fixed-length cell handler for a channel
  904. *
  905. * This function gets the handler for incoming fixed-length cells installed
  906. * on a channel.
  907. */
  908. channel_cell_handler_fn_ptr
  909. channel_get_cell_handler(channel_t *chan)
  910. {
  911. tor_assert(chan);
  912. if (CHANNEL_CAN_HANDLE_CELLS(chan))
  913. return chan->cell_handler;
  914. return NULL;
  915. }
  916. /**
  917. * Return the variable-length cell handler for a channel
  918. *
  919. * This function gets the handler for incoming variable-length cells
  920. * installed on a channel.
  921. */
  922. channel_var_cell_handler_fn_ptr
  923. channel_get_var_cell_handler(channel_t *chan)
  924. {
  925. tor_assert(chan);
  926. if (CHANNEL_CAN_HANDLE_CELLS(chan))
  927. return chan->var_cell_handler;
  928. return NULL;
  929. }
  930. /**
  931. * Set both cell handlers for a channel
  932. *
  933. * This function sets both the fixed-length and variable length cell handlers
  934. * for a channel and processes any incoming cells that had been blocked in the
  935. * queue because none were available.
  936. */
  937. void
  938. channel_set_cell_handlers(channel_t *chan,
  939. channel_cell_handler_fn_ptr cell_handler,
  940. channel_var_cell_handler_fn_ptr
  941. var_cell_handler)
  942. {
  943. int try_again = 0;
  944. tor_assert(chan);
  945. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  946. log_debug(LD_CHANNEL,
  947. "Setting cell_handler callback for channel %p to %p",
  948. chan, cell_handler);
  949. log_debug(LD_CHANNEL,
  950. "Setting var_cell_handler callback for channel %p to %p",
  951. chan, var_cell_handler);
  952. /* Should we try the queue? */
  953. if (cell_handler &&
  954. cell_handler != chan->cell_handler) try_again = 1;
  955. if (var_cell_handler &&
  956. var_cell_handler != chan->var_cell_handler) try_again = 1;
  957. /* Change them */
  958. chan->cell_handler = cell_handler;
  959. chan->var_cell_handler = var_cell_handler;
  960. /* Re-run the queue if we have one and there's any reason to */
  961. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue) &&
  962. try_again &&
  963. (chan->cell_handler ||
  964. chan->var_cell_handler)) channel_process_cells(chan);
  965. }
  966. /*
  967. * On closing channels
  968. *
  969. * There are three functions that close channels, for use in
  970. * different circumstances:
  971. *
  972. * - Use channel_mark_for_close() for most cases
  973. * - Use channel_close_from_lower_layer() if you are connection_or.c
  974. * and the other end closes the underlying connection.
  975. * - Use channel_close_for_error() if you are connection_or.c and
  976. * some sort of error has occurred.
  977. */
  978. /**
  979. * Mark a channel for closure
  980. *
  981. * This function tries to close a channel_t; it will go into the CLOSING
  982. * state, and eventually the lower layer should put it into the CLOSED or
  983. * ERROR state. Then, channel_run_cleanup() will eventually free it.
  984. */
  985. void
  986. channel_mark_for_close(channel_t *chan)
  987. {
  988. tor_assert(chan != NULL);
  989. tor_assert(chan->close != NULL);
  990. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  991. if (CHANNEL_CONDEMNED(chan))
  992. return;
  993. log_debug(LD_CHANNEL,
  994. "Closing channel %p (global ID " U64_FORMAT ") "
  995. "by request",
  996. chan, U64_PRINTF_ARG(chan->global_identifier));
  997. /* Note closing by request from above */
  998. chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
  999. /* Change state to CLOSING */
  1000. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1001. /* Tell the lower layer */
  1002. chan->close(chan);
  1003. /*
  1004. * It's up to the lower layer to change state to CLOSED or ERROR when we're
  1005. * ready; we'll try to free channels that are in the finished list from
  1006. * channel_run_cleanup(). The lower layer should do this by calling
  1007. * channel_closed().
  1008. */
  1009. }
  1010. /**
  1011. * Mark a channel listener for closure
  1012. *
  1013. * This function tries to close a channel_listener_t; it will go into the
  1014. * CLOSING state, and eventually the lower layer should put it into the CLOSED
  1015. * or ERROR state. Then, channel_run_cleanup() will eventually free it.
  1016. */
  1017. void
  1018. channel_listener_mark_for_close(channel_listener_t *chan_l)
  1019. {
  1020. tor_assert(chan_l != NULL);
  1021. tor_assert(chan_l->close != NULL);
  1022. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1023. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1024. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1025. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1026. log_debug(LD_CHANNEL,
  1027. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1028. "by request",
  1029. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1030. /* Note closing by request from above */
  1031. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
  1032. /* Change state to CLOSING */
  1033. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1034. /* Tell the lower layer */
  1035. chan_l->close(chan_l);
  1036. /*
  1037. * It's up to the lower layer to change state to CLOSED or ERROR when we're
  1038. * ready; we'll try to free channels that are in the finished list from
  1039. * channel_run_cleanup(). The lower layer should do this by calling
  1040. * channel_listener_closed().
  1041. */
  1042. }
  1043. /**
  1044. * Close a channel from the lower layer
  1045. *
  1046. * Notify the channel code that the channel is being closed due to a non-error
  1047. * condition in the lower layer. This does not call the close() method, since
  1048. * the lower layer already knows.
  1049. */
  1050. void
  1051. channel_close_from_lower_layer(channel_t *chan)
  1052. {
  1053. tor_assert(chan != NULL);
  1054. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1055. if (CHANNEL_CONDEMNED(chan))
  1056. return;
  1057. log_debug(LD_CHANNEL,
  1058. "Closing channel %p (global ID " U64_FORMAT ") "
  1059. "due to lower-layer event",
  1060. chan, U64_PRINTF_ARG(chan->global_identifier));
  1061. /* Note closing by event from below */
  1062. chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
  1063. /* Change state to CLOSING */
  1064. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1065. }
  1066. /**
  1067. * Close a channel listener from the lower layer
  1068. *
  1069. * Notify the channel code that the channel listener is being closed due to a
  1070. * non-error condition in the lower layer. This does not call the close()
  1071. * method, since the lower layer already knows.
  1072. */
  1073. void
  1074. channel_listener_close_from_lower_layer(channel_listener_t *chan_l)
  1075. {
  1076. tor_assert(chan_l != NULL);
  1077. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1078. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1079. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1080. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1081. log_debug(LD_CHANNEL,
  1082. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1083. "due to lower-layer event",
  1084. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1085. /* Note closing by event from below */
  1086. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FROM_BELOW;
  1087. /* Change state to CLOSING */
  1088. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1089. }
  1090. /**
  1091. * Notify that the channel is being closed due to an error condition
  1092. *
  1093. * This function is called by the lower layer implementing the transport
  1094. * when a channel must be closed due to an error condition. This does not
  1095. * call the channel's close method, since the lower layer already knows.
  1096. */
  1097. void
  1098. channel_close_for_error(channel_t *chan)
  1099. {
  1100. tor_assert(chan != NULL);
  1101. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1102. if (CHANNEL_CONDEMNED(chan))
  1103. return;
  1104. log_debug(LD_CHANNEL,
  1105. "Closing channel %p due to lower-layer error",
  1106. chan);
  1107. /* Note closing by event from below */
  1108. chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
  1109. /* Change state to CLOSING */
  1110. channel_change_state(chan, CHANNEL_STATE_CLOSING);
  1111. }
  1112. /**
  1113. * Notify that the channel listener is being closed due to an error condition
  1114. *
  1115. * This function is called by the lower layer implementing the transport
  1116. * when a channel listener must be closed due to an error condition. This
  1117. * does not call the channel listener's close method, since the lower layer
  1118. * already knows.
  1119. */
  1120. void
  1121. channel_listener_close_for_error(channel_listener_t *chan_l)
  1122. {
  1123. tor_assert(chan_l != NULL);
  1124. /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
  1125. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1126. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1127. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1128. log_debug(LD_CHANNEL,
  1129. "Closing channel listener %p (global ID " U64_FORMAT ") "
  1130. "due to lower-layer error",
  1131. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1132. /* Note closing by event from below */
  1133. chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FOR_ERROR;
  1134. /* Change state to CLOSING */
  1135. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
  1136. }
  1137. /**
  1138. * Notify that the lower layer is finished closing the channel
  1139. *
  1140. * This function should be called by the lower layer when a channel
  1141. * is finished closing and it should be regarded as inactive and
  1142. * freed by the channel code.
  1143. */
  1144. void
  1145. channel_closed(channel_t *chan)
  1146. {
  1147. tor_assert(chan);
  1148. tor_assert(CHANNEL_CONDEMNED(chan));
  1149. /* No-op if already inactive */
  1150. if (CHANNEL_FINISHED(chan))
  1151. return;
  1152. /* Inform any pending (not attached) circs that they should
  1153. * give up. */
  1154. if (! chan->has_been_open)
  1155. circuit_n_chan_done(chan, 0, 0);
  1156. /* Now close all the attached circuits on it. */
  1157. circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
  1158. if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
  1159. channel_change_state(chan, CHANNEL_STATE_CLOSED);
  1160. } else {
  1161. channel_change_state(chan, CHANNEL_STATE_ERROR);
  1162. }
  1163. }
  1164. /**
  1165. * Notify that the lower layer is finished closing the channel listener
  1166. *
  1167. * This function should be called by the lower layer when a channel listener
  1168. * is finished closing and it should be regarded as inactive and
  1169. * freed by the channel code.
  1170. */
  1171. void
  1172. channel_listener_closed(channel_listener_t *chan_l)
  1173. {
  1174. tor_assert(chan_l);
  1175. tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
  1176. chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1177. chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
  1178. /* No-op if already inactive */
  1179. if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
  1180. chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
  1181. if (chan_l->reason_for_closing != CHANNEL_LISTENER_CLOSE_FOR_ERROR) {
  1182. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
  1183. } else {
  1184. channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_ERROR);
  1185. }
  1186. }
  1187. /**
  1188. * Clear the identity_digest of a channel
  1189. *
  1190. * This function clears the identity digest of the remote endpoint for a
  1191. * channel; this is intended for use by the lower layer.
  1192. */
  1193. void
  1194. channel_clear_identity_digest(channel_t *chan)
  1195. {
  1196. int state_not_in_map;
  1197. tor_assert(chan);
  1198. log_debug(LD_CHANNEL,
  1199. "Clearing remote endpoint digest on channel %p with "
  1200. "global ID " U64_FORMAT,
  1201. chan, U64_PRINTF_ARG(chan->global_identifier));
  1202. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1203. if (!state_not_in_map && chan->registered &&
  1204. !tor_digest_is_zero(chan->identity_digest))
  1205. /* if it's registered get it out of the digest map */
  1206. channel_remove_from_digest_map(chan);
  1207. memset(chan->identity_digest, 0,
  1208. sizeof(chan->identity_digest));
  1209. }
  1210. /**
  1211. * Set the identity_digest of a channel
  1212. *
  1213. * This function sets the identity digest of the remote endpoint for a
  1214. * channel; this is intended for use by the lower layer.
  1215. */
  1216. void
  1217. channel_set_identity_digest(channel_t *chan,
  1218. const char *identity_digest,
  1219. const ed25519_public_key_t *ed_identity)
  1220. {
  1221. int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
  1222. tor_assert(chan);
  1223. log_debug(LD_CHANNEL,
  1224. "Setting remote endpoint digest on channel %p with "
  1225. "global ID " U64_FORMAT " to digest %s",
  1226. chan, U64_PRINTF_ARG(chan->global_identifier),
  1227. identity_digest ?
  1228. hex_str(identity_digest, DIGEST_LEN) : "(null)");
  1229. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1230. was_in_digest_map =
  1231. !state_not_in_map &&
  1232. chan->registered &&
  1233. !tor_digest_is_zero(chan->identity_digest);
  1234. should_be_in_digest_map =
  1235. !state_not_in_map &&
  1236. chan->registered &&
  1237. (identity_digest &&
  1238. !tor_digest_is_zero(identity_digest));
  1239. if (was_in_digest_map)
  1240. /* We should always remove it; we'll add it back if we're writing
  1241. * in a new digest.
  1242. */
  1243. channel_remove_from_digest_map(chan);
  1244. if (identity_digest) {
  1245. memcpy(chan->identity_digest,
  1246. identity_digest,
  1247. sizeof(chan->identity_digest));
  1248. } else {
  1249. memset(chan->identity_digest, 0,
  1250. sizeof(chan->identity_digest));
  1251. }
  1252. if (ed_identity) {
  1253. memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
  1254. } else {
  1255. memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
  1256. }
  1257. /* Put it in the digest map if we should */
  1258. if (should_be_in_digest_map)
  1259. channel_add_to_digest_map(chan);
  1260. }
  1261. /**
  1262. * Clear the remote end metadata (identity_digest/nickname) of a channel
  1263. *
  1264. * This function clears all the remote end info from a channel; this is
  1265. * intended for use by the lower layer.
  1266. */
  1267. void
  1268. channel_clear_remote_end(channel_t *chan)
  1269. {
  1270. int state_not_in_map;
  1271. tor_assert(chan);
  1272. log_debug(LD_CHANNEL,
  1273. "Clearing remote endpoint identity on channel %p with "
  1274. "global ID " U64_FORMAT,
  1275. chan, U64_PRINTF_ARG(chan->global_identifier));
  1276. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1277. if (!state_not_in_map && chan->registered &&
  1278. !tor_digest_is_zero(chan->identity_digest))
  1279. /* if it's registered get it out of the digest map */
  1280. channel_remove_from_digest_map(chan);
  1281. memset(chan->identity_digest, 0,
  1282. sizeof(chan->identity_digest));
  1283. tor_free(chan->nickname);
  1284. }
  1285. /**
  1286. * Set the remote end metadata (identity_digest/nickname) of a channel
  1287. *
  1288. * This function sets new remote end info on a channel; this is intended
  1289. * for use by the lower layer.
  1290. */
  1291. void
  1292. channel_set_remote_end(channel_t *chan,
  1293. const char *identity_digest,
  1294. const char *nickname)
  1295. {
  1296. int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
  1297. tor_assert(chan);
  1298. log_debug(LD_CHANNEL,
  1299. "Setting remote endpoint identity on channel %p with "
  1300. "global ID " U64_FORMAT " to nickname %s, digest %s",
  1301. chan, U64_PRINTF_ARG(chan->global_identifier),
  1302. nickname ? nickname : "(null)",
  1303. identity_digest ?
  1304. hex_str(identity_digest, DIGEST_LEN) : "(null)");
  1305. state_not_in_map = CHANNEL_CONDEMNED(chan);
  1306. was_in_digest_map =
  1307. !state_not_in_map &&
  1308. chan->registered &&
  1309. !tor_digest_is_zero(chan->identity_digest);
  1310. should_be_in_digest_map =
  1311. !state_not_in_map &&
  1312. chan->registered &&
  1313. (identity_digest &&
  1314. !tor_digest_is_zero(identity_digest));
  1315. if (was_in_digest_map)
  1316. /* We should always remove it; we'll add it back if we're writing
  1317. * in a new digest.
  1318. */
  1319. channel_remove_from_digest_map(chan);
  1320. if (identity_digest) {
  1321. memcpy(chan->identity_digest,
  1322. identity_digest,
  1323. sizeof(chan->identity_digest));
  1324. } else {
  1325. memset(chan->identity_digest, 0,
  1326. sizeof(chan->identity_digest));
  1327. }
  1328. tor_free(chan->nickname);
  1329. if (nickname)
  1330. chan->nickname = tor_strdup(nickname);
  1331. /* Put it in the digest map if we should */
  1332. if (should_be_in_digest_map)
  1333. channel_add_to_digest_map(chan);
  1334. }
  1335. /**
  1336. * Duplicate a cell queue entry; this is a shallow copy intended for use
  1337. * in channel_write_cell_queue_entry().
  1338. */
  1339. static cell_queue_entry_t *
  1340. cell_queue_entry_dup(cell_queue_entry_t *q)
  1341. {
  1342. cell_queue_entry_t *rv = NULL;
  1343. tor_assert(q);
  1344. rv = tor_malloc(sizeof(*rv));
  1345. memcpy(rv, q, sizeof(*rv));
  1346. return rv;
  1347. }
  1348. /**
  1349. * Free a cell_queue_entry_t; the handed_off parameter indicates whether
  1350. * the contents were passed to the lower layer (it is responsible for
  1351. * them) or not (we should free).
  1352. */
  1353. STATIC void
  1354. cell_queue_entry_free(cell_queue_entry_t *q, int handed_off)
  1355. {
  1356. if (!q) return;
  1357. if (!handed_off) {
  1358. /*
  1359. * If we handed it off, the recipient becomes responsible (or
  1360. * with packed cells the channel_t subclass calls packed_cell
  1361. * free after writing out its contents; see, e.g.,
  1362. * channel_tls_write_packed_cell_method(). Otherwise, we have
  1363. * to take care of it here if possible.
  1364. */
  1365. switch (q->type) {
  1366. case CELL_QUEUE_FIXED:
  1367. if (q->u.fixed.cell) {
  1368. /*
  1369. * There doesn't seem to be a cell_free() function anywhere in the
  1370. * pre-channel code; just use tor_free()
  1371. */
  1372. tor_free(q->u.fixed.cell);
  1373. }
  1374. break;
  1375. case CELL_QUEUE_PACKED:
  1376. if (q->u.packed.packed_cell) {
  1377. packed_cell_free(q->u.packed.packed_cell);
  1378. }
  1379. break;
  1380. case CELL_QUEUE_VAR:
  1381. if (q->u.var.var_cell) {
  1382. /*
  1383. * This one's in connection_or.c; it'd be nice to figure out the
  1384. * whole flow of cells from one end to the other and factor the
  1385. * cell memory management functions like this out of the specific
  1386. * TLS lower layer.
  1387. */
  1388. var_cell_free(q->u.var.var_cell);
  1389. }
  1390. break;
  1391. default:
  1392. /*
  1393. * Nothing we can do if we don't know the type; this will
  1394. * have been warned about elsewhere.
  1395. */
  1396. break;
  1397. }
  1398. }
  1399. tor_free(q);
  1400. }
  1401. #if 0
  1402. /**
  1403. * Check whether a cell queue entry is padding; this is a helper function
  1404. * for channel_write_cell_queue_entry()
  1405. */
  1406. static int
  1407. cell_queue_entry_is_padding(cell_queue_entry_t *q)
  1408. {
  1409. tor_assert(q);
  1410. if (q->type == CELL_QUEUE_FIXED) {
  1411. if (q->u.fixed.cell) {
  1412. if (q->u.fixed.cell->command == CELL_PADDING ||
  1413. q->u.fixed.cell->command == CELL_VPADDING) {
  1414. return 1;
  1415. }
  1416. }
  1417. } else if (q->type == CELL_QUEUE_VAR) {
  1418. if (q->u.var.var_cell) {
  1419. if (q->u.var.var_cell->command == CELL_PADDING ||
  1420. q->u.var.var_cell->command == CELL_VPADDING) {
  1421. return 1;
  1422. }
  1423. }
  1424. }
  1425. return 0;
  1426. }
  1427. #endif
  1428. /**
  1429. * Allocate a new cell queue entry for a fixed-size cell
  1430. */
  1431. static cell_queue_entry_t *
  1432. cell_queue_entry_new_fixed(cell_t *cell)
  1433. {
  1434. cell_queue_entry_t *q = NULL;
  1435. tor_assert(cell);
  1436. q = tor_malloc(sizeof(*q));
  1437. q->type = CELL_QUEUE_FIXED;
  1438. q->u.fixed.cell = cell;
  1439. return q;
  1440. }
  1441. /**
  1442. * Allocate a new cell queue entry for a variable-size cell
  1443. */
  1444. static cell_queue_entry_t *
  1445. cell_queue_entry_new_var(var_cell_t *var_cell)
  1446. {
  1447. cell_queue_entry_t *q = NULL;
  1448. tor_assert(var_cell);
  1449. q = tor_malloc(sizeof(*q));
  1450. q->type = CELL_QUEUE_VAR;
  1451. q->u.var.var_cell = var_cell;
  1452. return q;
  1453. }
  1454. /**
  1455. * Ask how big the cell contained in a cell_queue_entry_t is
  1456. */
  1457. static size_t
  1458. channel_get_cell_queue_entry_size(channel_t *chan, cell_queue_entry_t *q)
  1459. {
  1460. size_t rv = 0;
  1461. tor_assert(chan);
  1462. tor_assert(q);
  1463. switch (q->type) {
  1464. case CELL_QUEUE_FIXED:
  1465. rv = get_cell_network_size(chan->wide_circ_ids);
  1466. break;
  1467. case CELL_QUEUE_VAR:
  1468. rv = get_var_cell_header_size(chan->wide_circ_ids) +
  1469. (q->u.var.var_cell ? q->u.var.var_cell->payload_len : 0);
  1470. break;
  1471. case CELL_QUEUE_PACKED:
  1472. rv = get_cell_network_size(chan->wide_circ_ids);
  1473. break;
  1474. default:
  1475. tor_assert_nonfatal_unreached_once();
  1476. }
  1477. return rv;
  1478. }
  1479. /**
  1480. * Write to a channel based on a cell_queue_entry_t
  1481. *
  1482. * Given a cell_queue_entry_t filled out by the caller, try to send the cell
  1483. * and queue it if we can't.
  1484. */
  1485. static void
  1486. channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q)
  1487. {
  1488. int result = 0, sent = 0;
  1489. cell_queue_entry_t *tmp = NULL;
  1490. size_t cell_bytes;
  1491. tor_assert(chan);
  1492. tor_assert(q);
  1493. /* Assert that the state makes sense for a cell write */
  1494. tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
  1495. {
  1496. circid_t circ_id;
  1497. if (is_destroy_cell(chan, q, &circ_id)) {
  1498. channel_note_destroy_not_pending(chan, circ_id);
  1499. }
  1500. }
  1501. /* For statistical purposes, figure out how big this cell is */
  1502. cell_bytes = channel_get_cell_queue_entry_size(chan, q);
  1503. /* Can we send it right out? If so, try */
  1504. if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue) &&
  1505. CHANNEL_IS_OPEN(chan)) {
  1506. /* Pick the right write function for this cell type and save the result */
  1507. switch (q->type) {
  1508. case CELL_QUEUE_FIXED:
  1509. tor_assert(chan->write_cell);
  1510. tor_assert(q->u.fixed.cell);
  1511. result = chan->write_cell(chan, q->u.fixed.cell);
  1512. break;
  1513. case CELL_QUEUE_PACKED:
  1514. tor_assert(chan->write_packed_cell);
  1515. tor_assert(q->u.packed.packed_cell);
  1516. result = chan->write_packed_cell(chan, q->u.packed.packed_cell);
  1517. break;
  1518. case CELL_QUEUE_VAR:
  1519. tor_assert(chan->write_var_cell);
  1520. tor_assert(q->u.var.var_cell);
  1521. result = chan->write_var_cell(chan, q->u.var.var_cell);
  1522. break;
  1523. default:
  1524. tor_assert(1);
  1525. }
  1526. /* Check if we got it out */
  1527. if (result > 0) {
  1528. sent = 1;
  1529. /* Timestamp for transmission */
  1530. channel_timestamp_xmit(chan);
  1531. /* If we're here the queue is empty, so it's drained too */
  1532. channel_timestamp_drained(chan);
  1533. /* Update the counter */
  1534. ++(chan->n_cells_xmitted);
  1535. chan->n_bytes_xmitted += cell_bytes;
  1536. /* Update global counters */
  1537. ++n_channel_cells_queued;
  1538. ++n_channel_cells_passed_to_lower_layer;
  1539. n_channel_bytes_queued += cell_bytes;
  1540. n_channel_bytes_passed_to_lower_layer += cell_bytes;
  1541. channel_assert_counter_consistency();
  1542. }
  1543. }
  1544. if (!sent) {
  1545. /* Not sent, queue it */
  1546. /*
  1547. * We have to copy the queue entry passed in, since the caller probably
  1548. * used the stack.
  1549. */
  1550. tmp = cell_queue_entry_dup(q);
  1551. TOR_SIMPLEQ_INSERT_TAIL(&chan->outgoing_queue, tmp, next);
  1552. /* Update global counters */
  1553. ++n_channel_cells_queued;
  1554. ++n_channel_cells_in_queues;
  1555. n_channel_bytes_queued += cell_bytes;
  1556. n_channel_bytes_in_queues += cell_bytes;
  1557. channel_assert_counter_consistency();
  1558. /* Update channel queue size */
  1559. chan->bytes_in_queue += cell_bytes;
  1560. /* Try to process the queue? */
  1561. if (CHANNEL_IS_OPEN(chan)) channel_flush_cells(chan);
  1562. }
  1563. }
  1564. /** Write a generic cell type to a channel
  1565. *
  1566. * Write a generic cell to a channel. It is called by channel_write_cell(),
  1567. * channel_write_var_cell() and channel_write_packed_cell() in order to reduce
  1568. * code duplication. Notice that it takes cell as pointer of type void,
  1569. * this can be dangerous because no type check is performed.
  1570. */
  1571. void
  1572. channel_write_cell_generic_(channel_t *chan, const char *cell_type,
  1573. void *cell, cell_queue_entry_t *q)
  1574. {
  1575. tor_assert(chan);
  1576. tor_assert(cell);
  1577. if (CHANNEL_IS_CLOSING(chan)) {
  1578. log_debug(LD_CHANNEL, "Discarding %c %p on closing channel %p with "
  1579. "global ID "U64_FORMAT, *cell_type, cell, chan,
  1580. U64_PRINTF_ARG(chan->global_identifier));
  1581. tor_free(cell);
  1582. return;
  1583. }
  1584. log_debug(LD_CHANNEL,
  1585. "Writing %c %p to channel %p with global ID "
  1586. U64_FORMAT, *cell_type,
  1587. cell, chan, U64_PRINTF_ARG(chan->global_identifier));
  1588. channel_write_cell_queue_entry(chan, q);
  1589. /* Update the queue size estimate */
  1590. channel_update_xmit_queue_size(chan);
  1591. }
  1592. /**
  1593. * Write a cell to a channel
  1594. *
  1595. * Write a fixed-length cell to a channel using the write_cell() method.
  1596. * This is equivalent to the pre-channels connection_or_write_cell_to_buf();
  1597. * it is called by the transport-independent code to deliver a cell to a
  1598. * channel for transmission.
  1599. */
  1600. void
  1601. channel_write_cell(channel_t *chan, cell_t *cell)
  1602. {
  1603. cell_queue_entry_t q;
  1604. q.type = CELL_QUEUE_FIXED;
  1605. q.u.fixed.cell = cell;
  1606. channel_write_cell_generic_(chan, "cell_t", cell, &q);
  1607. }
  1608. /**
  1609. * Write a packed cell to a channel
  1610. *
  1611. * Write a packed cell to a channel using the write_cell() method. This is
  1612. * called by the transport-independent code to deliver a packed cell to a
  1613. * channel for transmission.
  1614. */
  1615. void
  1616. channel_write_packed_cell(channel_t *chan, packed_cell_t *packed_cell)
  1617. {
  1618. cell_queue_entry_t q;
  1619. q.type = CELL_QUEUE_PACKED;
  1620. q.u.packed.packed_cell = packed_cell;
  1621. channel_write_cell_generic_(chan, "packed_cell_t", packed_cell, &q);
  1622. }
  1623. /**
  1624. * Write a variable-length cell to a channel
  1625. *
  1626. * Write a variable-length cell to a channel using the write_cell() method.
  1627. * This is equivalent to the pre-channels
  1628. * connection_or_write_var_cell_to_buf(); it's called by the transport-
  1629. * independent code to deliver a var_cell to a channel for transmission.
  1630. */
  1631. void
  1632. channel_write_var_cell(channel_t *chan, var_cell_t *var_cell)
  1633. {
  1634. cell_queue_entry_t q;
  1635. q.type = CELL_QUEUE_VAR;
  1636. q.u.var.var_cell = var_cell;
  1637. channel_write_cell_generic_(chan, "var_cell_t", var_cell, &q);
  1638. }
  1639. /**
  1640. * Change channel state
  1641. *
  1642. * This internal and subclass use only function is used to change channel
  1643. * state, performing all transition validity checks and whatever actions
  1644. * are appropriate to the state transition in question.
  1645. */
  1646. void
  1647. channel_change_state(channel_t *chan, channel_state_t to_state)
  1648. {
  1649. channel_state_t from_state;
  1650. unsigned char was_active, is_active;
  1651. unsigned char was_in_id_map, is_in_id_map;
  1652. tor_assert(chan);
  1653. from_state = chan->state;
  1654. tor_assert(channel_state_is_valid(from_state));
  1655. tor_assert(channel_state_is_valid(to_state));
  1656. tor_assert(channel_state_can_transition(chan->state, to_state));
  1657. /* Check for no-op transitions */
  1658. if (from_state == to_state) {
  1659. log_debug(LD_CHANNEL,
  1660. "Got no-op transition from \"%s\" to itself on channel %p"
  1661. "(global ID " U64_FORMAT ")",
  1662. channel_state_to_string(to_state),
  1663. chan, U64_PRINTF_ARG(chan->global_identifier));
  1664. return;
  1665. }
  1666. /* If we're going to a closing or closed state, we must have a reason set */
  1667. if (to_state == CHANNEL_STATE_CLOSING ||
  1668. to_state == CHANNEL_STATE_CLOSED ||
  1669. to_state == CHANNEL_STATE_ERROR) {
  1670. tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
  1671. }
  1672. /*
  1673. * We need to maintain the queues here for some transitions:
  1674. * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
  1675. * we may have a backlog of cells to transmit, so drain the queues in
  1676. * that case, and when going to CHANNEL_STATE_CLOSED the subclass
  1677. * should have made sure to finish sending things (or gone to
  1678. * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
  1679. */
  1680. log_debug(LD_CHANNEL,
  1681. "Changing state of channel %p (global ID " U64_FORMAT
  1682. ") from \"%s\" to \"%s\"",
  1683. chan,
  1684. U64_PRINTF_ARG(chan->global_identifier),
  1685. channel_state_to_string(chan->state),
  1686. channel_state_to_string(to_state));
  1687. chan->state = to_state;
  1688. /* Need to add to the right lists if the channel is registered */
  1689. if (chan->registered) {
  1690. was_active = !(from_state == CHANNEL_STATE_CLOSED ||
  1691. from_state == CHANNEL_STATE_ERROR);
  1692. is_active = !(to_state == CHANNEL_STATE_CLOSED ||
  1693. to_state == CHANNEL_STATE_ERROR);
  1694. /* Need to take off active list and put on finished list? */
  1695. if (was_active && !is_active) {
  1696. if (active_channels) smartlist_remove(active_channels, chan);
  1697. if (!finished_channels) finished_channels = smartlist_new();
  1698. smartlist_add(finished_channels, chan);
  1699. }
  1700. /* Need to put on active list? */
  1701. else if (!was_active && is_active) {
  1702. if (finished_channels) smartlist_remove(finished_channels, chan);
  1703. if (!active_channels) active_channels = smartlist_new();
  1704. smartlist_add(active_channels, chan);
  1705. }
  1706. if (!tor_digest_is_zero(chan->identity_digest)) {
  1707. /* Now we need to handle the identity map */
  1708. was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
  1709. from_state == CHANNEL_STATE_CLOSED ||
  1710. from_state == CHANNEL_STATE_ERROR);
  1711. is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
  1712. to_state == CHANNEL_STATE_CLOSED ||
  1713. to_state == CHANNEL_STATE_ERROR);
  1714. if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
  1715. else if (was_in_id_map && !is_in_id_map)
  1716. channel_remove_from_digest_map(chan);
  1717. }
  1718. }
  1719. /*
  1720. * If we're going to a closed/closing state, we don't need scheduling any
  1721. * more; in CHANNEL_STATE_MAINT we can't accept writes.
  1722. */
  1723. if (to_state == CHANNEL_STATE_CLOSING ||
  1724. to_state == CHANNEL_STATE_CLOSED ||
  1725. to_state == CHANNEL_STATE_ERROR) {
  1726. scheduler_release_channel(chan);
  1727. } else if (to_state == CHANNEL_STATE_MAINT) {
  1728. scheduler_channel_doesnt_want_writes(chan);
  1729. }
  1730. /*
  1731. * If we're closing, this channel no longer counts toward the global
  1732. * estimated queue size; if we're open, it now does.
  1733. */
  1734. if ((to_state == CHANNEL_STATE_CLOSING ||
  1735. to_state == CHANNEL_STATE_CLOSED ||
  1736. to_state == CHANNEL_STATE_ERROR) &&
  1737. (from_state == CHANNEL_STATE_OPEN ||
  1738. from_state == CHANNEL_STATE_MAINT)) {
  1739. estimated_total_queue_size -= chan->bytes_in_queue;
  1740. }
  1741. /*
  1742. * If we're opening, this channel now does count toward the global
  1743. * estimated queue size.
  1744. */
  1745. if ((to_state == CHANNEL_STATE_OPEN ||
  1746. to_state == CHANNEL_STATE_MAINT) &&
  1747. !(from_state == CHANNEL_STATE_OPEN ||
  1748. from_state == CHANNEL_STATE_MAINT)) {
  1749. estimated_total_queue_size += chan->bytes_in_queue;
  1750. }
  1751. /* Tell circuits if we opened and stuff */
  1752. if (to_state == CHANNEL_STATE_OPEN) {
  1753. channel_do_open_actions(chan);
  1754. chan->has_been_open = 1;
  1755. /* Check for queued cells to process */
  1756. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  1757. channel_process_cells(chan);
  1758. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
  1759. channel_flush_cells(chan);
  1760. } else if (to_state == CHANNEL_STATE_CLOSED ||
  1761. to_state == CHANNEL_STATE_ERROR) {
  1762. /* Assert that all queues are empty */
  1763. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
  1764. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
  1765. }
  1766. }
  1767. /**
  1768. * Change channel listener state
  1769. *
  1770. * This internal and subclass use only function is used to change channel
  1771. * listener state, performing all transition validity checks and whatever
  1772. * actions are appropriate to the state transition in question.
  1773. */
  1774. void
  1775. channel_listener_change_state(channel_listener_t *chan_l,
  1776. channel_listener_state_t to_state)
  1777. {
  1778. channel_listener_state_t from_state;
  1779. unsigned char was_active, is_active;
  1780. tor_assert(chan_l);
  1781. from_state = chan_l->state;
  1782. tor_assert(channel_listener_state_is_valid(from_state));
  1783. tor_assert(channel_listener_state_is_valid(to_state));
  1784. tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
  1785. /* Check for no-op transitions */
  1786. if (from_state == to_state) {
  1787. log_debug(LD_CHANNEL,
  1788. "Got no-op transition from \"%s\" to itself on channel "
  1789. "listener %p (global ID " U64_FORMAT ")",
  1790. channel_listener_state_to_string(to_state),
  1791. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1792. return;
  1793. }
  1794. /* If we're going to a closing or closed state, we must have a reason set */
  1795. if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
  1796. to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1797. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1798. tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
  1799. }
  1800. /*
  1801. * We need to maintain the queues here for some transitions:
  1802. * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
  1803. * we may have a backlog of cells to transmit, so drain the queues in
  1804. * that case, and when going to CHANNEL_STATE_CLOSED the subclass
  1805. * should have made sure to finish sending things (or gone to
  1806. * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
  1807. */
  1808. log_debug(LD_CHANNEL,
  1809. "Changing state of channel listener %p (global ID " U64_FORMAT
  1810. "from \"%s\" to \"%s\"",
  1811. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  1812. channel_listener_state_to_string(chan_l->state),
  1813. channel_listener_state_to_string(to_state));
  1814. chan_l->state = to_state;
  1815. /* Need to add to the right lists if the channel listener is registered */
  1816. if (chan_l->registered) {
  1817. was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1818. from_state == CHANNEL_LISTENER_STATE_ERROR);
  1819. is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1820. to_state == CHANNEL_LISTENER_STATE_ERROR);
  1821. /* Need to take off active list and put on finished list? */
  1822. if (was_active && !is_active) {
  1823. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  1824. if (!finished_listeners) finished_listeners = smartlist_new();
  1825. smartlist_add(finished_listeners, chan_l);
  1826. }
  1827. /* Need to put on active list? */
  1828. else if (!was_active && is_active) {
  1829. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  1830. if (!active_listeners) active_listeners = smartlist_new();
  1831. smartlist_add(active_listeners, chan_l);
  1832. }
  1833. }
  1834. if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1835. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1836. /* Assert that the queue is empty */
  1837. tor_assert(!(chan_l->incoming_list) ||
  1838. smartlist_len(chan_l->incoming_list) == 0);
  1839. }
  1840. }
  1841. /**
  1842. * Try to flush cells to the lower layer
  1843. *
  1844. * this is called by the lower layer to indicate that it wants more cells;
  1845. * it will try to write up to num_cells cells from the channel's cell queue or
  1846. * from circuits active on that channel, or as many as it has available if
  1847. * num_cells == -1.
  1848. */
  1849. #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
  1850. MOCK_IMPL(ssize_t,
  1851. channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
  1852. {
  1853. unsigned int unlimited = 0;
  1854. ssize_t flushed = 0;
  1855. int num_cells_from_circs, clamped_num_cells;
  1856. int q_len_before, q_len_after;
  1857. tor_assert(chan);
  1858. if (num_cells < 0) unlimited = 1;
  1859. if (!unlimited && num_cells <= flushed) goto done;
  1860. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1861. if (CHANNEL_IS_OPEN(chan)) {
  1862. /* Try to flush as much as we can that's already queued */
  1863. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  1864. (unlimited ? -1 : num_cells - flushed));
  1865. if (!unlimited && num_cells <= flushed) goto done;
  1866. if (circuitmux_num_cells(chan->cmux) > 0) {
  1867. /* Calculate number of cells, including clamp */
  1868. if (unlimited) {
  1869. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1870. } else {
  1871. if (num_cells - flushed >
  1872. MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
  1873. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1874. } else {
  1875. clamped_num_cells = (int)(num_cells - flushed);
  1876. }
  1877. }
  1878. /*
  1879. * Keep track of the change in queue size; we have to count cells
  1880. * channel_flush_from_first_active_circuit() writes out directly,
  1881. * but not double-count ones we might get later in
  1882. * channel_flush_some_cells_from_outgoing_queue()
  1883. */
  1884. q_len_before = chan_cell_queue_len(&(chan->outgoing_queue));
  1885. /* Try to get more cells from any active circuits */
  1886. num_cells_from_circs = channel_flush_from_first_active_circuit(
  1887. chan, clamped_num_cells);
  1888. q_len_after = chan_cell_queue_len(&(chan->outgoing_queue));
  1889. /*
  1890. * If it claims we got some, adjust the flushed counter and consider
  1891. * processing the queue again
  1892. */
  1893. if (num_cells_from_circs > 0) {
  1894. /*
  1895. * Adjust flushed by the number of cells counted in
  1896. * num_cells_from_circs that didn't go to the cell queue.
  1897. */
  1898. if (q_len_after > q_len_before) {
  1899. num_cells_from_circs -= (q_len_after - q_len_before);
  1900. if (num_cells_from_circs < 0) num_cells_from_circs = 0;
  1901. }
  1902. flushed += num_cells_from_circs;
  1903. /* Now process the queue if necessary */
  1904. if ((q_len_after > q_len_before) &&
  1905. (unlimited || (flushed < num_cells))) {
  1906. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  1907. (unlimited ? -1 : num_cells - flushed));
  1908. }
  1909. }
  1910. }
  1911. }
  1912. done:
  1913. return flushed;
  1914. }
  1915. /**
  1916. * Flush cells from just the channel's outgoing cell queue
  1917. *
  1918. * This gets called from channel_flush_some_cells() above to flush cells
  1919. * just from the queue without trying for active_circuits.
  1920. */
  1921. static ssize_t
  1922. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  1923. ssize_t num_cells)
  1924. {
  1925. unsigned int unlimited = 0;
  1926. ssize_t flushed = 0;
  1927. cell_queue_entry_t *q = NULL;
  1928. size_t cell_size;
  1929. int free_q = 0, handed_off = 0;
  1930. tor_assert(chan);
  1931. tor_assert(chan->write_cell);
  1932. tor_assert(chan->write_packed_cell);
  1933. tor_assert(chan->write_var_cell);
  1934. if (num_cells < 0) unlimited = 1;
  1935. if (!unlimited && num_cells <= flushed) return 0;
  1936. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1937. if (CHANNEL_IS_OPEN(chan)) {
  1938. while ((unlimited || num_cells > flushed) &&
  1939. NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
  1940. free_q = 0;
  1941. handed_off = 0;
  1942. /* Figure out how big it is for statistical purposes */
  1943. cell_size = channel_get_cell_queue_entry_size(chan, q);
  1944. /*
  1945. * Okay, we have a good queue entry, try to give it to the lower
  1946. * layer.
  1947. */
  1948. switch (q->type) {
  1949. case CELL_QUEUE_FIXED:
  1950. if (q->u.fixed.cell) {
  1951. if (chan->write_cell(chan,
  1952. q->u.fixed.cell)) {
  1953. ++flushed;
  1954. channel_timestamp_xmit(chan);
  1955. ++(chan->n_cells_xmitted);
  1956. chan->n_bytes_xmitted += cell_size;
  1957. free_q = 1;
  1958. handed_off = 1;
  1959. }
  1960. /* Else couldn't write it; leave it on the queue */
  1961. } else {
  1962. /* This shouldn't happen */
  1963. log_info(LD_CHANNEL,
  1964. "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
  1965. "with no cell on channel %p "
  1966. "(global ID " U64_FORMAT ").",
  1967. chan, U64_PRINTF_ARG(chan->global_identifier));
  1968. /* Throw it away */
  1969. free_q = 1;
  1970. handed_off = 0;
  1971. }
  1972. break;
  1973. case CELL_QUEUE_PACKED:
  1974. if (q->u.packed.packed_cell) {
  1975. if (chan->write_packed_cell(chan,
  1976. q->u.packed.packed_cell)) {
  1977. ++flushed;
  1978. channel_timestamp_xmit(chan);
  1979. ++(chan->n_cells_xmitted);
  1980. chan->n_bytes_xmitted += cell_size;
  1981. free_q = 1;
  1982. handed_off = 1;
  1983. }
  1984. /* Else couldn't write it; leave it on the queue */
  1985. } else {
  1986. /* This shouldn't happen */
  1987. log_info(LD_CHANNEL,
  1988. "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
  1989. "with no cell on channel %p "
  1990. "(global ID " U64_FORMAT ").",
  1991. chan, U64_PRINTF_ARG(chan->global_identifier));
  1992. /* Throw it away */
  1993. free_q = 1;
  1994. handed_off = 0;
  1995. }
  1996. break;
  1997. case CELL_QUEUE_VAR:
  1998. if (q->u.var.var_cell) {
  1999. if (chan->write_var_cell(chan,
  2000. q->u.var.var_cell)) {
  2001. ++flushed;
  2002. channel_timestamp_xmit(chan);
  2003. ++(chan->n_cells_xmitted);
  2004. chan->n_bytes_xmitted += cell_size;
  2005. free_q = 1;
  2006. handed_off = 1;
  2007. }
  2008. /* Else couldn't write it; leave it on the queue */
  2009. } else {
  2010. /* This shouldn't happen */
  2011. log_info(LD_CHANNEL,
  2012. "Saw broken cell queue entry of type CELL_QUEUE_VAR "
  2013. "with no cell on channel %p "
  2014. "(global ID " U64_FORMAT ").",
  2015. chan, U64_PRINTF_ARG(chan->global_identifier));
  2016. /* Throw it away */
  2017. free_q = 1;
  2018. handed_off = 0;
  2019. }
  2020. break;
  2021. default:
  2022. /* Unknown type, log and free it */
  2023. log_info(LD_CHANNEL,
  2024. "Saw an unknown cell queue entry type %d on channel %p "
  2025. "(global ID " U64_FORMAT "; ignoring it."
  2026. " Someone should fix this.",
  2027. q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
  2028. free_q = 1;
  2029. handed_off = 0;
  2030. }
  2031. /*
  2032. * if free_q is set, we used it and should remove the queue entry;
  2033. * we have to do the free down here so TOR_SIMPLEQ_REMOVE_HEAD isn't
  2034. * accessing freed memory
  2035. */
  2036. if (free_q) {
  2037. TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
  2038. /*
  2039. * ...and we handed a cell off to the lower layer, so we should
  2040. * update the counters.
  2041. */
  2042. ++n_channel_cells_passed_to_lower_layer;
  2043. --n_channel_cells_in_queues;
  2044. n_channel_bytes_passed_to_lower_layer += cell_size;
  2045. n_channel_bytes_in_queues -= cell_size;
  2046. channel_assert_counter_consistency();
  2047. /* Update the channel's queue size too */
  2048. chan->bytes_in_queue -= cell_size;
  2049. /* Finally, free q */
  2050. cell_queue_entry_free(q, handed_off);
  2051. q = NULL;
  2052. } else {
  2053. /* No cell removed from list, so we can't go on any further */
  2054. break;
  2055. }
  2056. }
  2057. }
  2058. /* Did we drain the queue? */
  2059. if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  2060. channel_timestamp_drained(chan);
  2061. }
  2062. /* Update the estimate queue size */
  2063. channel_update_xmit_queue_size(chan);
  2064. return flushed;
  2065. }
  2066. /**
  2067. * Flush as many cells as we possibly can from the queue
  2068. *
  2069. * This tries to flush as many cells from the queue as the lower layer
  2070. * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
  2071. * in unlimited mode.
  2072. */
  2073. void
  2074. channel_flush_cells(channel_t *chan)
  2075. {
  2076. channel_flush_some_cells_from_outgoing_queue(chan, -1);
  2077. }
  2078. /**
  2079. * Check if any cells are available
  2080. *
  2081. * This gets used from the lower layer to check if any more cells are
  2082. * available.
  2083. */
  2084. int
  2085. channel_more_to_flush(channel_t *chan)
  2086. {
  2087. tor_assert(chan);
  2088. /* Check if we have any queued */
  2089. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2090. return 1;
  2091. /* Check if any circuits would like to queue some */
  2092. if (circuitmux_num_cells(chan->cmux) > 0) return 1;
  2093. /* Else no */
  2094. return 0;
  2095. }
  2096. /**
  2097. * Notify the channel we're done flushing the output in the lower layer
  2098. *
  2099. * Connection.c will call this when we've flushed the output; there's some
  2100. * dirreq-related maintenance to do.
  2101. */
  2102. void
  2103. channel_notify_flushed(channel_t *chan)
  2104. {
  2105. tor_assert(chan);
  2106. if (chan->dirreq_id != 0)
  2107. geoip_change_dirreq_state(chan->dirreq_id,
  2108. DIRREQ_TUNNELED,
  2109. DIRREQ_CHANNEL_BUFFER_FLUSHED);
  2110. }
  2111. /**
  2112. * Process the queue of incoming channels on a listener
  2113. *
  2114. * Use a listener's registered callback to process as many entries in the
  2115. * queue of incoming channels as possible.
  2116. */
  2117. void
  2118. channel_listener_process_incoming(channel_listener_t *listener)
  2119. {
  2120. tor_assert(listener);
  2121. /*
  2122. * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
  2123. * while closing a listener.
  2124. */
  2125. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
  2126. listener->state == CHANNEL_LISTENER_STATE_CLOSING);
  2127. tor_assert(listener->listener);
  2128. log_debug(LD_CHANNEL,
  2129. "Processing queue of incoming connections for channel "
  2130. "listener %p (global ID " U64_FORMAT ")",
  2131. listener, U64_PRINTF_ARG(listener->global_identifier));
  2132. if (!(listener->incoming_list)) return;
  2133. SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
  2134. channel_t *, chan) {
  2135. tor_assert(chan);
  2136. log_debug(LD_CHANNEL,
  2137. "Handling incoming channel %p (" U64_FORMAT ") "
  2138. "for listener %p (" U64_FORMAT ")",
  2139. chan,
  2140. U64_PRINTF_ARG(chan->global_identifier),
  2141. listener,
  2142. U64_PRINTF_ARG(listener->global_identifier));
  2143. /* Make sure this is set correctly */
  2144. channel_mark_incoming(chan);
  2145. listener->listener(listener, chan);
  2146. } SMARTLIST_FOREACH_END(chan);
  2147. smartlist_free(listener->incoming_list);
  2148. listener->incoming_list = NULL;
  2149. }
  2150. /**
  2151. * Take actions required when a channel becomes open
  2152. *
  2153. * Handle actions we should do when we know a channel is open; a lot of
  2154. * this comes from the old connection_or_set_state_open() of connection_or.c.
  2155. *
  2156. * Because of this mechanism, future channel_t subclasses should take care
  2157. * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
  2158. * until there is positive confirmation that the network is operational.
  2159. * In particular, anything UDP-based should not make this transition until a
  2160. * packet is received from the other side.
  2161. */
  2162. void
  2163. channel_do_open_actions(channel_t *chan)
  2164. {
  2165. tor_addr_t remote_addr;
  2166. int started_here;
  2167. time_t now = time(NULL);
  2168. int close_origin_circuits = 0;
  2169. tor_assert(chan);
  2170. started_here = channel_is_outgoing(chan);
  2171. if (started_here) {
  2172. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2173. rep_hist_note_connect_succeeded(chan->identity_digest, now);
  2174. router_set_status(chan->identity_digest, 1);
  2175. } else {
  2176. /* only report it to the geoip module if it's not a known router */
  2177. if (!router_get_by_id_digest(chan->identity_digest)) {
  2178. if (channel_get_addr_if_possible(chan, &remote_addr)) {
  2179. char *transport_name = NULL;
  2180. if (chan->get_transport_name(chan, &transport_name) < 0)
  2181. transport_name = NULL;
  2182. geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
  2183. &remote_addr, transport_name,
  2184. now);
  2185. tor_free(transport_name);
  2186. }
  2187. /* Otherwise the underlying transport can't tell us this, so skip it */
  2188. }
  2189. }
  2190. circuit_n_chan_done(chan, 1, close_origin_circuits);
  2191. }
  2192. /**
  2193. * Queue an incoming channel on a listener
  2194. *
  2195. * Internal and subclass use only function to queue an incoming channel from
  2196. * a listener. A subclass of channel_listener_t should call this when a new
  2197. * incoming channel is created.
  2198. */
  2199. void
  2200. channel_listener_queue_incoming(channel_listener_t *listener,
  2201. channel_t *incoming)
  2202. {
  2203. int need_to_queue = 0;
  2204. tor_assert(listener);
  2205. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  2206. tor_assert(incoming);
  2207. log_debug(LD_CHANNEL,
  2208. "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
  2209. "channel listener %p (global ID " U64_FORMAT ")",
  2210. incoming, U64_PRINTF_ARG(incoming->global_identifier),
  2211. listener, U64_PRINTF_ARG(listener->global_identifier));
  2212. /* Do we need to queue it, or can we just call the listener right away? */
  2213. if (!(listener->listener)) need_to_queue = 1;
  2214. if (listener->incoming_list &&
  2215. (smartlist_len(listener->incoming_list) > 0))
  2216. need_to_queue = 1;
  2217. /* If we need to queue and have no queue, create one */
  2218. if (need_to_queue && !(listener->incoming_list)) {
  2219. listener->incoming_list = smartlist_new();
  2220. }
  2221. /* Bump the counter and timestamp it */
  2222. channel_listener_timestamp_active(listener);
  2223. channel_listener_timestamp_accepted(listener);
  2224. ++(listener->n_accepted);
  2225. /* If we don't need to queue, process it right away */
  2226. if (!need_to_queue) {
  2227. tor_assert(listener->listener);
  2228. listener->listener(listener, incoming);
  2229. }
  2230. /*
  2231. * Otherwise, we need to queue; queue and then process the queue if
  2232. * we can.
  2233. */
  2234. else {
  2235. tor_assert(listener->incoming_list);
  2236. smartlist_add(listener->incoming_list, incoming);
  2237. if (listener->listener) channel_listener_process_incoming(listener);
  2238. }
  2239. }
  2240. /**
  2241. * Process queued incoming cells
  2242. *
  2243. * Process as many queued cells as we can from the incoming
  2244. * cell queue.
  2245. */
  2246. void
  2247. channel_process_cells(channel_t *chan)
  2248. {
  2249. cell_queue_entry_t *q;
  2250. tor_assert(chan);
  2251. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  2252. CHANNEL_IS_OPEN(chan));
  2253. log_debug(LD_CHANNEL,
  2254. "Processing as many incoming cells as we can for channel %p",
  2255. chan);
  2256. /* Nothing we can do if we have no registered cell handlers */
  2257. if (!(chan->cell_handler ||
  2258. chan->var_cell_handler)) return;
  2259. /* Nothing we can do if we have no cells */
  2260. if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
  2261. /*
  2262. * Process cells until we're done or find one we have no current handler
  2263. * for.
  2264. *
  2265. * We must free the cells here after calling the handler, since custody
  2266. * of the buffer was given to the channel layer when they were queued;
  2267. * see comments on memory management in channel_queue_cell() and in
  2268. * channel_queue_var_cell() below.
  2269. */
  2270. while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
  2271. tor_assert(q);
  2272. tor_assert(q->type == CELL_QUEUE_FIXED ||
  2273. q->type == CELL_QUEUE_VAR);
  2274. if (q->type == CELL_QUEUE_FIXED &&
  2275. chan->cell_handler) {
  2276. /* Handle a fixed-length cell */
  2277. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2278. tor_assert(q->u.fixed.cell);
  2279. log_debug(LD_CHANNEL,
  2280. "Processing incoming cell_t %p for channel %p (global ID "
  2281. U64_FORMAT ")",
  2282. q->u.fixed.cell, chan,
  2283. U64_PRINTF_ARG(chan->global_identifier));
  2284. chan->cell_handler(chan, q->u.fixed.cell);
  2285. tor_free(q->u.fixed.cell);
  2286. tor_free(q);
  2287. } else if (q->type == CELL_QUEUE_VAR &&
  2288. chan->var_cell_handler) {
  2289. /* Handle a variable-length cell */
  2290. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2291. tor_assert(q->u.var.var_cell);
  2292. log_debug(LD_CHANNEL,
  2293. "Processing incoming var_cell_t %p for channel %p (global ID "
  2294. U64_FORMAT ")",
  2295. q->u.var.var_cell, chan,
  2296. U64_PRINTF_ARG(chan->global_identifier));
  2297. chan->var_cell_handler(chan, q->u.var.var_cell);
  2298. tor_free(q->u.var.var_cell);
  2299. tor_free(q);
  2300. } else {
  2301. /* Can't handle this one */
  2302. break;
  2303. }
  2304. }
  2305. }
  2306. /**
  2307. * Queue incoming cell
  2308. *
  2309. * This should be called by a channel_t subclass to queue an incoming fixed-
  2310. * length cell for processing, and process it if possible.
  2311. */
  2312. void
  2313. channel_queue_cell(channel_t *chan, cell_t *cell)
  2314. {
  2315. int need_to_queue = 0;
  2316. cell_queue_entry_t *q;
  2317. cell_t *cell_copy = NULL;
  2318. tor_assert(chan);
  2319. tor_assert(cell);
  2320. tor_assert(CHANNEL_IS_OPEN(chan));
  2321. /* Do we need to queue it, or can we just call the handler right away? */
  2322. if (!(chan->cell_handler)) need_to_queue = 1;
  2323. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2324. need_to_queue = 1;
  2325. /* Timestamp for receiving */
  2326. channel_timestamp_recv(chan);
  2327. /* Update the counters */
  2328. ++(chan->n_cells_recved);
  2329. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  2330. /* If we don't need to queue we can just call cell_handler */
  2331. if (!need_to_queue) {
  2332. tor_assert(chan->cell_handler);
  2333. log_debug(LD_CHANNEL,
  2334. "Directly handling incoming cell_t %p for channel %p "
  2335. "(global ID " U64_FORMAT ")",
  2336. cell, chan,
  2337. U64_PRINTF_ARG(chan->global_identifier));
  2338. chan->cell_handler(chan, cell);
  2339. } else {
  2340. /*
  2341. * Otherwise queue it and then process the queue if possible.
  2342. *
  2343. * We queue a copy, not the original pointer - it might have been on the
  2344. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2345. * if we ever have a subclass other than channel_tls_t), or be freed
  2346. * there after we return. This is the uncommon case; the non-copying
  2347. * fast path occurs in the if (!need_to_queue) case above when the
  2348. * upper layer has installed cell handlers.
  2349. */
  2350. cell_copy = tor_malloc_zero(sizeof(cell_t));
  2351. memcpy(cell_copy, cell, sizeof(cell_t));
  2352. q = cell_queue_entry_new_fixed(cell_copy);
  2353. log_debug(LD_CHANNEL,
  2354. "Queueing incoming cell_t %p for channel %p "
  2355. "(global ID " U64_FORMAT ")",
  2356. cell, chan,
  2357. U64_PRINTF_ARG(chan->global_identifier));
  2358. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2359. if (chan->cell_handler ||
  2360. chan->var_cell_handler) {
  2361. channel_process_cells(chan);
  2362. }
  2363. }
  2364. }
  2365. /**
  2366. * Queue incoming variable-length cell
  2367. *
  2368. * This should be called by a channel_t subclass to queue an incoming
  2369. * variable-length cell for processing, and process it if possible.
  2370. */
  2371. void
  2372. channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
  2373. {
  2374. int need_to_queue = 0;
  2375. cell_queue_entry_t *q;
  2376. var_cell_t *cell_copy = NULL;
  2377. tor_assert(chan);
  2378. tor_assert(var_cell);
  2379. tor_assert(CHANNEL_IS_OPEN(chan));
  2380. /* Do we need to queue it, or can we just call the handler right away? */
  2381. if (!(chan->var_cell_handler)) need_to_queue = 1;
  2382. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2383. need_to_queue = 1;
  2384. /* Timestamp for receiving */
  2385. channel_timestamp_recv(chan);
  2386. /* Update the counter */
  2387. ++(chan->n_cells_recved);
  2388. chan->n_bytes_recved += get_var_cell_header_size(chan->wide_circ_ids) +
  2389. var_cell->payload_len;
  2390. /* If we don't need to queue we can just call cell_handler */
  2391. if (!need_to_queue) {
  2392. tor_assert(chan->var_cell_handler);
  2393. log_debug(LD_CHANNEL,
  2394. "Directly handling incoming var_cell_t %p for channel %p "
  2395. "(global ID " U64_FORMAT ")",
  2396. var_cell, chan,
  2397. U64_PRINTF_ARG(chan->global_identifier));
  2398. chan->var_cell_handler(chan, var_cell);
  2399. } else {
  2400. /*
  2401. * Otherwise queue it and then process the queue if possible.
  2402. *
  2403. * We queue a copy, not the original pointer - it might have been on the
  2404. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2405. * if we ever have a subclass other than channel_tls_t), or be freed
  2406. * there after we return. This is the uncommon case; the non-copying
  2407. * fast path occurs in the if (!need_to_queue) case above when the
  2408. * upper layer has installed cell handlers.
  2409. */
  2410. cell_copy = var_cell_copy(var_cell);
  2411. q = cell_queue_entry_new_var(cell_copy);
  2412. log_debug(LD_CHANNEL,
  2413. "Queueing incoming var_cell_t %p for channel %p "
  2414. "(global ID " U64_FORMAT ")",
  2415. var_cell, chan,
  2416. U64_PRINTF_ARG(chan->global_identifier));
  2417. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2418. if (chan->cell_handler ||
  2419. chan->var_cell_handler) {
  2420. channel_process_cells(chan);
  2421. }
  2422. }
  2423. }
  2424. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  2425. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  2426. * false. */
  2427. /* XXXX Move this function. */
  2428. int
  2429. packed_cell_is_destroy(channel_t *chan,
  2430. const packed_cell_t *packed_cell,
  2431. circid_t *circid_out)
  2432. {
  2433. if (chan->wide_circ_ids) {
  2434. if (packed_cell->body[4] == CELL_DESTROY) {
  2435. *circid_out = ntohl(get_uint32(packed_cell->body));
  2436. return 1;
  2437. }
  2438. } else {
  2439. if (packed_cell->body[2] == CELL_DESTROY) {
  2440. *circid_out = ntohs(get_uint16(packed_cell->body));
  2441. return 1;
  2442. }
  2443. }
  2444. return 0;
  2445. }
  2446. /**
  2447. * Assert that the global channel stats counters are internally consistent
  2448. */
  2449. static void
  2450. channel_assert_counter_consistency(void)
  2451. {
  2452. tor_assert(n_channel_cells_queued ==
  2453. (n_channel_cells_in_queues + n_channel_cells_passed_to_lower_layer));
  2454. tor_assert(n_channel_bytes_queued ==
  2455. (n_channel_bytes_in_queues + n_channel_bytes_passed_to_lower_layer));
  2456. }
  2457. /* DOCDOC */
  2458. static int
  2459. is_destroy_cell(channel_t *chan,
  2460. const cell_queue_entry_t *q, circid_t *circid_out)
  2461. {
  2462. *circid_out = 0;
  2463. switch (q->type) {
  2464. case CELL_QUEUE_FIXED:
  2465. if (q->u.fixed.cell->command == CELL_DESTROY) {
  2466. *circid_out = q->u.fixed.cell->circ_id;
  2467. return 1;
  2468. }
  2469. break;
  2470. case CELL_QUEUE_VAR:
  2471. if (q->u.var.var_cell->command == CELL_DESTROY) {
  2472. *circid_out = q->u.var.var_cell->circ_id;
  2473. return 1;
  2474. }
  2475. break;
  2476. case CELL_QUEUE_PACKED:
  2477. return packed_cell_is_destroy(chan, q->u.packed.packed_cell, circid_out);
  2478. }
  2479. return 0;
  2480. }
  2481. /**
  2482. * Send destroy cell on a channel
  2483. *
  2484. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  2485. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  2486. * we may want to propagate reasons from other cells.
  2487. */
  2488. int
  2489. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  2490. {
  2491. tor_assert(chan);
  2492. if (circ_id == 0) {
  2493. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  2494. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2495. U64_PRINTF_ARG(chan->global_identifier),
  2496. chan, channel_state_to_string(chan->state),
  2497. chan->state);
  2498. return 0;
  2499. }
  2500. /* Check to make sure we can send on this channel first */
  2501. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  2502. channel_note_destroy_pending(chan, circ_id);
  2503. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  2504. log_debug(LD_OR,
  2505. "Sending destroy (circID %u) on channel %p "
  2506. "(global ID " U64_FORMAT ")",
  2507. (unsigned)circ_id, chan,
  2508. U64_PRINTF_ARG(chan->global_identifier));
  2509. } else {
  2510. log_warn(LD_BUG,
  2511. "Someone called channel_send_destroy() for circID %u "
  2512. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2513. (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
  2514. chan, channel_state_to_string(chan->state),
  2515. chan->state);
  2516. }
  2517. return 0;
  2518. }
  2519. /**
  2520. * Dump channel statistics to the log
  2521. *
  2522. * This is called from dumpstats() in main.c and spams the log with
  2523. * statistics on channels.
  2524. */
  2525. void
  2526. channel_dumpstats(int severity)
  2527. {
  2528. if (all_channels && smartlist_len(all_channels) > 0) {
  2529. tor_log(severity, LD_GENERAL,
  2530. "Channels have queued " U64_FORMAT " bytes in " U64_FORMAT " cells, "
  2531. "and handed " U64_FORMAT " bytes in " U64_FORMAT " cells to the lower"
  2532. " layer.",
  2533. U64_PRINTF_ARG(n_channel_bytes_queued),
  2534. U64_PRINTF_ARG(n_channel_cells_queued),
  2535. U64_PRINTF_ARG(n_channel_bytes_passed_to_lower_layer),
  2536. U64_PRINTF_ARG(n_channel_cells_passed_to_lower_layer));
  2537. tor_log(severity, LD_GENERAL,
  2538. "There are currently " U64_FORMAT " bytes in " U64_FORMAT " cells "
  2539. "in channel queues.",
  2540. U64_PRINTF_ARG(n_channel_bytes_in_queues),
  2541. U64_PRINTF_ARG(n_channel_cells_in_queues));
  2542. tor_log(severity, LD_GENERAL,
  2543. "Dumping statistics about %d channels:",
  2544. smartlist_len(all_channels));
  2545. tor_log(severity, LD_GENERAL,
  2546. "%d are active, and %d are done and waiting for cleanup",
  2547. (active_channels != NULL) ?
  2548. smartlist_len(active_channels) : 0,
  2549. (finished_channels != NULL) ?
  2550. smartlist_len(finished_channels) : 0);
  2551. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  2552. channel_dump_statistics(chan, severity));
  2553. tor_log(severity, LD_GENERAL,
  2554. "Done spamming about channels now");
  2555. } else {
  2556. tor_log(severity, LD_GENERAL,
  2557. "No channels to dump");
  2558. }
  2559. }
  2560. /**
  2561. * Dump channel listener statistics to the log
  2562. *
  2563. * This is called from dumpstats() in main.c and spams the log with
  2564. * statistics on channel listeners.
  2565. */
  2566. void
  2567. channel_listener_dumpstats(int severity)
  2568. {
  2569. if (all_listeners && smartlist_len(all_listeners) > 0) {
  2570. tor_log(severity, LD_GENERAL,
  2571. "Dumping statistics about %d channel listeners:",
  2572. smartlist_len(all_listeners));
  2573. tor_log(severity, LD_GENERAL,
  2574. "%d are active and %d are done and waiting for cleanup",
  2575. (active_listeners != NULL) ?
  2576. smartlist_len(active_listeners) : 0,
  2577. (finished_listeners != NULL) ?
  2578. smartlist_len(finished_listeners) : 0);
  2579. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  2580. channel_listener_dump_statistics(chan_l, severity));
  2581. tor_log(severity, LD_GENERAL,
  2582. "Done spamming about channel listeners now");
  2583. } else {
  2584. tor_log(severity, LD_GENERAL,
  2585. "No channel listeners to dump");
  2586. }
  2587. }
  2588. /**
  2589. * Set the cmux policy on all active channels
  2590. */
  2591. void
  2592. channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
  2593. {
  2594. if (!active_channels) return;
  2595. SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
  2596. if (curr->cmux) {
  2597. circuitmux_set_policy(curr->cmux, pol);
  2598. }
  2599. } SMARTLIST_FOREACH_END(curr);
  2600. }
  2601. /**
  2602. * Clean up channels
  2603. *
  2604. * This gets called periodically from run_scheduled_events() in main.c;
  2605. * it cleans up after closed channels.
  2606. */
  2607. void
  2608. channel_run_cleanup(void)
  2609. {
  2610. channel_t *tmp = NULL;
  2611. /* Check if we need to do anything */
  2612. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  2613. /* Iterate through finished_channels and get rid of them */
  2614. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  2615. tmp = curr;
  2616. /* Remove it from the list */
  2617. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  2618. /* Also unregister it */
  2619. channel_unregister(tmp);
  2620. /* ... and free it */
  2621. channel_free(tmp);
  2622. } SMARTLIST_FOREACH_END(curr);
  2623. }
  2624. /**
  2625. * Clean up channel listeners
  2626. *
  2627. * This gets called periodically from run_scheduled_events() in main.c;
  2628. * it cleans up after closed channel listeners.
  2629. */
  2630. void
  2631. channel_listener_run_cleanup(void)
  2632. {
  2633. channel_listener_t *tmp = NULL;
  2634. /* Check if we need to do anything */
  2635. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  2636. /* Iterate through finished_channels and get rid of them */
  2637. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  2638. tmp = curr;
  2639. /* Remove it from the list */
  2640. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  2641. /* Also unregister it */
  2642. channel_listener_unregister(tmp);
  2643. /* ... and free it */
  2644. channel_listener_free(tmp);
  2645. } SMARTLIST_FOREACH_END(curr);
  2646. }
  2647. /**
  2648. * Free a list of channels for channel_free_all()
  2649. */
  2650. static void
  2651. channel_free_list(smartlist_t *channels, int mark_for_close)
  2652. {
  2653. if (!channels) return;
  2654. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  2655. /* Deregister and free it */
  2656. tor_assert(curr);
  2657. log_debug(LD_CHANNEL,
  2658. "Cleaning up channel %p (global ID " U64_FORMAT ") "
  2659. "in state %s (%d)",
  2660. curr, U64_PRINTF_ARG(curr->global_identifier),
  2661. channel_state_to_string(curr->state), curr->state);
  2662. /* Detach circuits early so they can find the channel */
  2663. if (curr->cmux) {
  2664. circuitmux_detach_all_circuits(curr->cmux, NULL);
  2665. }
  2666. SMARTLIST_DEL_CURRENT(channels, curr);
  2667. channel_unregister(curr);
  2668. if (mark_for_close) {
  2669. if (!CHANNEL_CONDEMNED(curr)) {
  2670. channel_mark_for_close(curr);
  2671. }
  2672. channel_force_free(curr);
  2673. } else channel_free(curr);
  2674. } SMARTLIST_FOREACH_END(curr);
  2675. }
  2676. /**
  2677. * Free a list of channel listeners for channel_free_all()
  2678. */
  2679. static void
  2680. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  2681. {
  2682. if (!listeners) return;
  2683. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  2684. /* Deregister and free it */
  2685. tor_assert(curr);
  2686. log_debug(LD_CHANNEL,
  2687. "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
  2688. "in state %s (%d)",
  2689. curr, U64_PRINTF_ARG(curr->global_identifier),
  2690. channel_listener_state_to_string(curr->state), curr->state);
  2691. channel_listener_unregister(curr);
  2692. if (mark_for_close) {
  2693. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  2694. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  2695. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  2696. channel_listener_mark_for_close(curr);
  2697. }
  2698. channel_listener_force_free(curr);
  2699. } else channel_listener_free(curr);
  2700. } SMARTLIST_FOREACH_END(curr);
  2701. }
  2702. /**
  2703. * Close all channels and free everything
  2704. *
  2705. * This gets called from tor_free_all() in main.c to clean up on exit.
  2706. * It will close all registered channels and free associated storage,
  2707. * then free the all_channels, active_channels, listening_channels and
  2708. * finished_channels lists and also channel_identity_map.
  2709. */
  2710. void
  2711. channel_free_all(void)
  2712. {
  2713. log_debug(LD_CHANNEL,
  2714. "Shutting down channels...");
  2715. /* First, let's go for finished channels */
  2716. if (finished_channels) {
  2717. channel_free_list(finished_channels, 0);
  2718. smartlist_free(finished_channels);
  2719. finished_channels = NULL;
  2720. }
  2721. /* Now the finished listeners */
  2722. if (finished_listeners) {
  2723. channel_listener_free_list(finished_listeners, 0);
  2724. smartlist_free(finished_listeners);
  2725. finished_listeners = NULL;
  2726. }
  2727. /* Now all active channels */
  2728. if (active_channels) {
  2729. channel_free_list(active_channels, 1);
  2730. smartlist_free(active_channels);
  2731. active_channels = NULL;
  2732. }
  2733. /* Now all active listeners */
  2734. if (active_listeners) {
  2735. channel_listener_free_list(active_listeners, 1);
  2736. smartlist_free(active_listeners);
  2737. active_listeners = NULL;
  2738. }
  2739. /* Now all channels, in case any are left over */
  2740. if (all_channels) {
  2741. channel_free_list(all_channels, 1);
  2742. smartlist_free(all_channels);
  2743. all_channels = NULL;
  2744. }
  2745. /* Now all listeners, in case any are left over */
  2746. if (all_listeners) {
  2747. channel_listener_free_list(all_listeners, 1);
  2748. smartlist_free(all_listeners);
  2749. all_listeners = NULL;
  2750. }
  2751. /* Now free channel_identity_map */
  2752. log_debug(LD_CHANNEL,
  2753. "Freeing channel_identity_map");
  2754. /* Geez, anything still left over just won't die ... let it leak then */
  2755. HT_CLEAR(channel_idmap, &channel_identity_map);
  2756. log_debug(LD_CHANNEL,
  2757. "Done cleaning up after channels");
  2758. }
  2759. /**
  2760. * Connect to a given addr/port/digest
  2761. *
  2762. * This sets up a new outgoing channel; in the future if multiple
  2763. * channel_t subclasses are available, this is where the selection policy
  2764. * should go. It may also be desirable to fold port into tor_addr_t
  2765. * or make a new type including a tor_addr_t and port, so we have a
  2766. * single abstract object encapsulating all the protocol details of
  2767. * how to contact an OR.
  2768. */
  2769. channel_t *
  2770. channel_connect(const tor_addr_t *addr, uint16_t port,
  2771. const char *id_digest,
  2772. const ed25519_public_key_t *ed_id)
  2773. {
  2774. return channel_tls_connect(addr, port, id_digest, ed_id);
  2775. }
  2776. /**
  2777. * Decide which of two channels to prefer for extending a circuit
  2778. *
  2779. * This function is called while extending a circuit and returns true iff
  2780. * a is 'better' than b. The most important criterion here is that a
  2781. * canonical channel is always better than a non-canonical one, but the
  2782. * number of circuits and the age are used as tie-breakers.
  2783. *
  2784. * This is based on the former connection_or_is_better() of connection_or.c
  2785. */
  2786. int
  2787. channel_is_better(time_t now, channel_t *a, channel_t *b,
  2788. int forgive_new_connections)
  2789. {
  2790. int a_grace, b_grace;
  2791. int a_is_canonical, b_is_canonical;
  2792. int a_has_circs, b_has_circs;
  2793. /*
  2794. * Do not definitively deprecate a new channel with no circuits on it
  2795. * until this much time has passed.
  2796. */
  2797. #define NEW_CHAN_GRACE_PERIOD (15*60)
  2798. tor_assert(a);
  2799. tor_assert(b);
  2800. /* Check if one is canonical and the other isn't first */
  2801. a_is_canonical = channel_is_canonical(a);
  2802. b_is_canonical = channel_is_canonical(b);
  2803. if (a_is_canonical && !b_is_canonical) return 1;
  2804. if (!a_is_canonical && b_is_canonical) return 0;
  2805. /*
  2806. * Okay, if we're here they tied on canonicity. Next we check if
  2807. * they have any circuits, and if one does and the other doesn't,
  2808. * we prefer the one that does, unless we are forgiving and the
  2809. * one that has no circuits is in its grace period.
  2810. */
  2811. a_has_circs = (channel_num_circuits(a) > 0);
  2812. b_has_circs = (channel_num_circuits(b) > 0);
  2813. a_grace = (forgive_new_connections &&
  2814. (now < channel_when_created(a) + NEW_CHAN_GRACE_PERIOD));
  2815. b_grace = (forgive_new_connections &&
  2816. (now < channel_when_created(b) + NEW_CHAN_GRACE_PERIOD));
  2817. if (a_has_circs && !b_has_circs && !b_grace) return 1;
  2818. if (!a_has_circs && b_has_circs && !a_grace) return 0;
  2819. /* They tied on circuits too; just prefer whichever is newer */
  2820. if (channel_when_created(a) > channel_when_created(b)) return 1;
  2821. else return 0;
  2822. }
  2823. /**
  2824. * Get a channel to extend a circuit
  2825. *
  2826. * Pick a suitable channel to extend a circuit to given the desired digest
  2827. * the address we believe is correct for that digest; this tries to see
  2828. * if we already have one for the requested endpoint, but if there is no good
  2829. * channel, set *msg_out to a message describing the channel's state
  2830. * and our next action, and set *launch_out to a boolean indicated whether
  2831. * the caller should try to launch a new channel with channel_connect().
  2832. */
  2833. channel_t *
  2834. channel_get_for_extend(const char *rsa_id_digest,
  2835. const ed25519_public_key_t *ed_id,
  2836. const tor_addr_t *target_addr,
  2837. const char **msg_out,
  2838. int *launch_out)
  2839. {
  2840. channel_t *chan, *best = NULL;
  2841. int n_inprogress_goodaddr = 0, n_old = 0;
  2842. int n_noncanonical = 0, n_possible = 0;
  2843. time_t now = approx_time();
  2844. tor_assert(msg_out);
  2845. tor_assert(launch_out);
  2846. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2847. /* Walk the list, unrefing the old one and refing the new at each
  2848. * iteration.
  2849. */
  2850. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2851. tor_assert(tor_memeq(chan->identity_digest,
  2852. rsa_id_digest, DIGEST_LEN));
  2853. if (CHANNEL_CONDEMNED(chan))
  2854. continue;
  2855. /* Never return a channel on which the other end appears to be
  2856. * a client. */
  2857. if (channel_is_client(chan)) {
  2858. continue;
  2859. }
  2860. /* The Ed25519 key has to match too */
  2861. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  2862. continue;
  2863. }
  2864. /* Never return a non-open connection. */
  2865. if (!CHANNEL_IS_OPEN(chan)) {
  2866. /* If the address matches, don't launch a new connection for this
  2867. * circuit. */
  2868. if (channel_matches_target_addr_for_extend(chan, target_addr))
  2869. ++n_inprogress_goodaddr;
  2870. continue;
  2871. }
  2872. /* Never return a connection that shouldn't be used for circs. */
  2873. if (channel_is_bad_for_new_circs(chan)) {
  2874. ++n_old;
  2875. continue;
  2876. }
  2877. /* Never return a non-canonical connection using a recent link protocol
  2878. * if the address is not what we wanted.
  2879. *
  2880. * The channel_is_canonical_is_reliable() function asks the lower layer
  2881. * if we should trust channel_is_canonical(). The below is from the
  2882. * comments of the old circuit_or_get_for_extend() and applies when
  2883. * the lower-layer transport is channel_tls_t.
  2884. *
  2885. * (For old link protocols, we can't rely on is_canonical getting
  2886. * set properly if we're talking to the right address, since we might
  2887. * have an out-of-date descriptor, and we will get no NETINFO cell to
  2888. * tell us about the right address.)
  2889. */
  2890. if (!channel_is_canonical(chan) &&
  2891. channel_is_canonical_is_reliable(chan) &&
  2892. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  2893. ++n_noncanonical;
  2894. continue;
  2895. }
  2896. ++n_possible;
  2897. if (!best) {
  2898. best = chan; /* If we have no 'best' so far, this one is good enough. */
  2899. continue;
  2900. }
  2901. if (channel_is_better(now, chan, best, 0))
  2902. best = chan;
  2903. }
  2904. if (best) {
  2905. *msg_out = "Connection is fine; using it.";
  2906. *launch_out = 0;
  2907. return best;
  2908. } else if (n_inprogress_goodaddr) {
  2909. *msg_out = "Connection in progress; waiting.";
  2910. *launch_out = 0;
  2911. return NULL;
  2912. } else if (n_old || n_noncanonical) {
  2913. *msg_out = "Connections all too old, or too non-canonical. "
  2914. " Launching a new one.";
  2915. *launch_out = 1;
  2916. return NULL;
  2917. } else {
  2918. *msg_out = "Not connected. Connecting.";
  2919. *launch_out = 1;
  2920. return NULL;
  2921. }
  2922. }
  2923. /**
  2924. * Describe the transport subclass for a channel
  2925. *
  2926. * Invoke a method to get a string description of the lower-layer
  2927. * transport for this channel.
  2928. */
  2929. const char *
  2930. channel_describe_transport(channel_t *chan)
  2931. {
  2932. tor_assert(chan);
  2933. tor_assert(chan->describe_transport);
  2934. return chan->describe_transport(chan);
  2935. }
  2936. /**
  2937. * Describe the transport subclass for a channel listener
  2938. *
  2939. * Invoke a method to get a string description of the lower-layer
  2940. * transport for this channel listener.
  2941. */
  2942. const char *
  2943. channel_listener_describe_transport(channel_listener_t *chan_l)
  2944. {
  2945. tor_assert(chan_l);
  2946. tor_assert(chan_l->describe_transport);
  2947. return chan_l->describe_transport(chan_l);
  2948. }
  2949. /**
  2950. * Return the number of entries in <b>queue</b>
  2951. */
  2952. STATIC int
  2953. chan_cell_queue_len(const chan_cell_queue_t *queue)
  2954. {
  2955. int r = 0;
  2956. cell_queue_entry_t *cell;
  2957. TOR_SIMPLEQ_FOREACH(cell, queue, next)
  2958. ++r;
  2959. return r;
  2960. }
  2961. /**
  2962. * Dump channel statistics
  2963. *
  2964. * Dump statistics for one channel to the log
  2965. */
  2966. MOCK_IMPL(void,
  2967. channel_dump_statistics, (channel_t *chan, int severity))
  2968. {
  2969. double avg, interval, age;
  2970. time_t now = time(NULL);
  2971. tor_addr_t remote_addr;
  2972. int have_remote_addr;
  2973. char *remote_addr_str;
  2974. tor_assert(chan);
  2975. age = (double)(now - chan->timestamp_created);
  2976. tor_log(severity, LD_GENERAL,
  2977. "Channel " U64_FORMAT " (at %p) with transport %s is in state "
  2978. "%s (%d)",
  2979. U64_PRINTF_ARG(chan->global_identifier), chan,
  2980. channel_describe_transport(chan),
  2981. channel_state_to_string(chan->state), chan->state);
  2982. tor_log(severity, LD_GENERAL,
  2983. " * Channel " U64_FORMAT " was created at " U64_FORMAT
  2984. " (" U64_FORMAT " seconds ago) "
  2985. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  2986. U64_PRINTF_ARG(chan->global_identifier),
  2987. U64_PRINTF_ARG(chan->timestamp_created),
  2988. U64_PRINTF_ARG(now - chan->timestamp_created),
  2989. U64_PRINTF_ARG(chan->timestamp_active),
  2990. U64_PRINTF_ARG(now - chan->timestamp_active));
  2991. /* Handle digest and nickname */
  2992. if (!tor_digest_is_zero(chan->identity_digest)) {
  2993. if (chan->nickname) {
  2994. tor_log(severity, LD_GENERAL,
  2995. " * Channel " U64_FORMAT " says it is connected "
  2996. "to an OR with digest %s and nickname %s",
  2997. U64_PRINTF_ARG(chan->global_identifier),
  2998. hex_str(chan->identity_digest, DIGEST_LEN),
  2999. chan->nickname);
  3000. } else {
  3001. tor_log(severity, LD_GENERAL,
  3002. " * Channel " U64_FORMAT " says it is connected "
  3003. "to an OR with digest %s and no known nickname",
  3004. U64_PRINTF_ARG(chan->global_identifier),
  3005. hex_str(chan->identity_digest, DIGEST_LEN));
  3006. }
  3007. } else {
  3008. if (chan->nickname) {
  3009. tor_log(severity, LD_GENERAL,
  3010. " * Channel " U64_FORMAT " does not know the digest"
  3011. " of the OR it is connected to, but reports its nickname is %s",
  3012. U64_PRINTF_ARG(chan->global_identifier),
  3013. chan->nickname);
  3014. } else {
  3015. tor_log(severity, LD_GENERAL,
  3016. " * Channel " U64_FORMAT " does not know the digest"
  3017. " or the nickname of the OR it is connected to",
  3018. U64_PRINTF_ARG(chan->global_identifier));
  3019. }
  3020. }
  3021. /* Handle remote address and descriptions */
  3022. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  3023. if (have_remote_addr) {
  3024. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3025. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  3026. tor_log(severity, LD_GENERAL,
  3027. " * Channel " U64_FORMAT " says its remote address"
  3028. " is %s, and gives a canonical description of \"%s\" and an "
  3029. "actual description of \"%s\"",
  3030. U64_PRINTF_ARG(chan->global_identifier),
  3031. safe_str(remote_addr_str),
  3032. safe_str(channel_get_canonical_remote_descr(chan)),
  3033. safe_str(actual));
  3034. tor_free(remote_addr_str);
  3035. tor_free(actual);
  3036. } else {
  3037. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3038. tor_log(severity, LD_GENERAL,
  3039. " * Channel " U64_FORMAT " does not know its remote "
  3040. "address, but gives a canonical description of \"%s\" and an "
  3041. "actual description of \"%s\"",
  3042. U64_PRINTF_ARG(chan->global_identifier),
  3043. channel_get_canonical_remote_descr(chan),
  3044. actual);
  3045. tor_free(actual);
  3046. }
  3047. /* Handle marks */
  3048. tor_log(severity, LD_GENERAL,
  3049. " * Channel " U64_FORMAT " has these marks: %s %s %s "
  3050. "%s %s %s",
  3051. U64_PRINTF_ARG(chan->global_identifier),
  3052. channel_is_bad_for_new_circs(chan) ?
  3053. "bad_for_new_circs" : "!bad_for_new_circs",
  3054. channel_is_canonical(chan) ?
  3055. "canonical" : "!canonical",
  3056. channel_is_canonical_is_reliable(chan) ?
  3057. "is_canonical_is_reliable" :
  3058. "!is_canonical_is_reliable",
  3059. channel_is_client(chan) ?
  3060. "client" : "!client",
  3061. channel_is_local(chan) ?
  3062. "local" : "!local",
  3063. channel_is_incoming(chan) ?
  3064. "incoming" : "outgoing");
  3065. /* Describe queues */
  3066. tor_log(severity, LD_GENERAL,
  3067. " * Channel " U64_FORMAT " has %d queued incoming cells"
  3068. " and %d queued outgoing cells",
  3069. U64_PRINTF_ARG(chan->global_identifier),
  3070. chan_cell_queue_len(&chan->incoming_queue),
  3071. chan_cell_queue_len(&chan->outgoing_queue));
  3072. /* Describe circuits */
  3073. tor_log(severity, LD_GENERAL,
  3074. " * Channel " U64_FORMAT " has %d active circuits out of"
  3075. " %d in total",
  3076. U64_PRINTF_ARG(chan->global_identifier),
  3077. (chan->cmux != NULL) ?
  3078. circuitmux_num_active_circuits(chan->cmux) : 0,
  3079. (chan->cmux != NULL) ?
  3080. circuitmux_num_circuits(chan->cmux) : 0);
  3081. /* Describe timestamps */
  3082. tor_log(severity, LD_GENERAL,
  3083. " * Channel " U64_FORMAT " was last used by a "
  3084. "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3085. U64_PRINTF_ARG(chan->global_identifier),
  3086. U64_PRINTF_ARG(chan->timestamp_client),
  3087. U64_PRINTF_ARG(now - chan->timestamp_client));
  3088. tor_log(severity, LD_GENERAL,
  3089. " * Channel " U64_FORMAT " was last drained at "
  3090. U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3091. U64_PRINTF_ARG(chan->global_identifier),
  3092. U64_PRINTF_ARG(chan->timestamp_drained),
  3093. U64_PRINTF_ARG(now - chan->timestamp_drained));
  3094. tor_log(severity, LD_GENERAL,
  3095. " * Channel " U64_FORMAT " last received a cell "
  3096. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3097. U64_PRINTF_ARG(chan->global_identifier),
  3098. U64_PRINTF_ARG(chan->timestamp_recv),
  3099. U64_PRINTF_ARG(now - chan->timestamp_recv));
  3100. tor_log(severity, LD_GENERAL,
  3101. " * Channel " U64_FORMAT " last transmitted a cell "
  3102. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3103. U64_PRINTF_ARG(chan->global_identifier),
  3104. U64_PRINTF_ARG(chan->timestamp_xmit),
  3105. U64_PRINTF_ARG(now - chan->timestamp_xmit));
  3106. /* Describe counters and rates */
  3107. tor_log(severity, LD_GENERAL,
  3108. " * Channel " U64_FORMAT " has received "
  3109. U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
  3110. U64_FORMAT " bytes in " U64_FORMAT " cells",
  3111. U64_PRINTF_ARG(chan->global_identifier),
  3112. U64_PRINTF_ARG(chan->n_bytes_recved),
  3113. U64_PRINTF_ARG(chan->n_cells_recved),
  3114. U64_PRINTF_ARG(chan->n_bytes_xmitted),
  3115. U64_PRINTF_ARG(chan->n_cells_xmitted));
  3116. if (now > chan->timestamp_created &&
  3117. chan->timestamp_created > 0) {
  3118. if (chan->n_bytes_recved > 0) {
  3119. avg = (double)(chan->n_bytes_recved) / age;
  3120. tor_log(severity, LD_GENERAL,
  3121. " * Channel " U64_FORMAT " has averaged %f "
  3122. "bytes received per second",
  3123. U64_PRINTF_ARG(chan->global_identifier), avg);
  3124. }
  3125. if (chan->n_cells_recved > 0) {
  3126. avg = (double)(chan->n_cells_recved) / age;
  3127. if (avg >= 1.0) {
  3128. tor_log(severity, LD_GENERAL,
  3129. " * Channel " U64_FORMAT " has averaged %f "
  3130. "cells received per second",
  3131. U64_PRINTF_ARG(chan->global_identifier), avg);
  3132. } else if (avg >= 0.0) {
  3133. interval = 1.0 / avg;
  3134. tor_log(severity, LD_GENERAL,
  3135. " * Channel " U64_FORMAT " has averaged %f "
  3136. "seconds between received cells",
  3137. U64_PRINTF_ARG(chan->global_identifier), interval);
  3138. }
  3139. }
  3140. if (chan->n_bytes_xmitted > 0) {
  3141. avg = (double)(chan->n_bytes_xmitted) / age;
  3142. tor_log(severity, LD_GENERAL,
  3143. " * Channel " U64_FORMAT " has averaged %f "
  3144. "bytes transmitted per second",
  3145. U64_PRINTF_ARG(chan->global_identifier), avg);
  3146. }
  3147. if (chan->n_cells_xmitted > 0) {
  3148. avg = (double)(chan->n_cells_xmitted) / age;
  3149. if (avg >= 1.0) {
  3150. tor_log(severity, LD_GENERAL,
  3151. " * Channel " U64_FORMAT " has averaged %f "
  3152. "cells transmitted per second",
  3153. U64_PRINTF_ARG(chan->global_identifier), avg);
  3154. } else if (avg >= 0.0) {
  3155. interval = 1.0 / avg;
  3156. tor_log(severity, LD_GENERAL,
  3157. " * Channel " U64_FORMAT " has averaged %f "
  3158. "seconds between transmitted cells",
  3159. U64_PRINTF_ARG(chan->global_identifier), interval);
  3160. }
  3161. }
  3162. }
  3163. /* Dump anything the lower layer has to say */
  3164. channel_dump_transport_statistics(chan, severity);
  3165. }
  3166. /**
  3167. * Dump channel listener statistics
  3168. *
  3169. * Dump statistics for one channel listener to the log
  3170. */
  3171. void
  3172. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  3173. {
  3174. double avg, interval, age;
  3175. time_t now = time(NULL);
  3176. tor_assert(chan_l);
  3177. age = (double)(now - chan_l->timestamp_created);
  3178. tor_log(severity, LD_GENERAL,
  3179. "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
  3180. "state %s (%d)",
  3181. U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
  3182. channel_listener_describe_transport(chan_l),
  3183. channel_listener_state_to_string(chan_l->state), chan_l->state);
  3184. tor_log(severity, LD_GENERAL,
  3185. " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
  3186. " (" U64_FORMAT " seconds ago) "
  3187. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3188. U64_PRINTF_ARG(chan_l->global_identifier),
  3189. U64_PRINTF_ARG(chan_l->timestamp_created),
  3190. U64_PRINTF_ARG(now - chan_l->timestamp_created),
  3191. U64_PRINTF_ARG(chan_l->timestamp_active),
  3192. U64_PRINTF_ARG(now - chan_l->timestamp_active));
  3193. tor_log(severity, LD_GENERAL,
  3194. " * Channel listener " U64_FORMAT " last accepted an incoming "
  3195. "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
  3196. "and has accepted " U64_FORMAT " channels in total",
  3197. U64_PRINTF_ARG(chan_l->global_identifier),
  3198. U64_PRINTF_ARG(chan_l->timestamp_accepted),
  3199. U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
  3200. U64_PRINTF_ARG(chan_l->n_accepted));
  3201. /*
  3202. * If it's sensible to do so, get the rate of incoming channels on this
  3203. * listener
  3204. */
  3205. if (now > chan_l->timestamp_created &&
  3206. chan_l->timestamp_created > 0 &&
  3207. chan_l->n_accepted > 0) {
  3208. avg = (double)(chan_l->n_accepted) / age;
  3209. if (avg >= 1.0) {
  3210. tor_log(severity, LD_GENERAL,
  3211. " * Channel listener " U64_FORMAT " has averaged %f incoming "
  3212. "channels per second",
  3213. U64_PRINTF_ARG(chan_l->global_identifier), avg);
  3214. } else if (avg >= 0.0) {
  3215. interval = 1.0 / avg;
  3216. tor_log(severity, LD_GENERAL,
  3217. " * Channel listener " U64_FORMAT " has averaged %f seconds "
  3218. "between incoming channels",
  3219. U64_PRINTF_ARG(chan_l->global_identifier), interval);
  3220. }
  3221. }
  3222. /* Dump anything the lower layer has to say */
  3223. channel_listener_dump_transport_statistics(chan_l, severity);
  3224. }
  3225. /**
  3226. * Invoke transport-specific stats dump for channel
  3227. *
  3228. * If there is a lower-layer statistics dump method, invoke it
  3229. */
  3230. void
  3231. channel_dump_transport_statistics(channel_t *chan, int severity)
  3232. {
  3233. tor_assert(chan);
  3234. if (chan->dumpstats) chan->dumpstats(chan, severity);
  3235. }
  3236. /**
  3237. * Invoke transport-specific stats dump for channel listener
  3238. *
  3239. * If there is a lower-layer statistics dump method, invoke it
  3240. */
  3241. void
  3242. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  3243. int severity)
  3244. {
  3245. tor_assert(chan_l);
  3246. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  3247. }
  3248. /**
  3249. * Return text description of the remote endpoint
  3250. *
  3251. * This function return a test provided by the lower layer of the remote
  3252. * endpoint for this channel; it should specify the actual address connected
  3253. * to/from.
  3254. *
  3255. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3256. * may invalidate the return value from this function.
  3257. */
  3258. const char *
  3259. channel_get_actual_remote_descr(channel_t *chan)
  3260. {
  3261. tor_assert(chan);
  3262. tor_assert(chan->get_remote_descr);
  3263. /* Param 1 indicates the actual description */
  3264. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  3265. }
  3266. /**
  3267. * Return the text address of the remote endpoint.
  3268. *
  3269. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3270. * may invalidate the return value from this function.
  3271. */
  3272. const char *
  3273. channel_get_actual_remote_address(channel_t *chan)
  3274. {
  3275. /* Param 1 indicates the actual description */
  3276. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  3277. }
  3278. /**
  3279. * Return text description of the remote endpoint canonical address
  3280. *
  3281. * This function return a test provided by the lower layer of the remote
  3282. * endpoint for this channel; it should use the known canonical address for
  3283. * this OR's identity digest if possible.
  3284. *
  3285. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3286. * may invalidate the return value from this function.
  3287. */
  3288. const char *
  3289. channel_get_canonical_remote_descr(channel_t *chan)
  3290. {
  3291. tor_assert(chan);
  3292. tor_assert(chan->get_remote_descr);
  3293. /* Param 0 indicates the canonicalized description */
  3294. return chan->get_remote_descr(chan, 0);
  3295. }
  3296. /**
  3297. * Get remote address if possible.
  3298. *
  3299. * Write the remote address out to a tor_addr_t if the underlying transport
  3300. * supports this operation, and return 1. Return 0 if the underlying transport
  3301. * doesn't let us do this.
  3302. */
  3303. int
  3304. channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
  3305. {
  3306. tor_assert(chan);
  3307. tor_assert(addr_out);
  3308. if (chan->get_remote_addr)
  3309. return chan->get_remote_addr(chan, addr_out);
  3310. /* Else no support, method not implemented */
  3311. else return 0;
  3312. }
  3313. /**
  3314. * Check if there are outgoing queue writes on this channel
  3315. *
  3316. * Indicate if either we have queued cells, or if not, whether the underlying
  3317. * lower-layer transport thinks it has an output queue.
  3318. */
  3319. int
  3320. channel_has_queued_writes(channel_t *chan)
  3321. {
  3322. int has_writes = 0;
  3323. tor_assert(chan);
  3324. tor_assert(chan->has_queued_writes);
  3325. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  3326. has_writes = 1;
  3327. } else {
  3328. /* Check with the lower layer */
  3329. has_writes = chan->has_queued_writes(chan);
  3330. }
  3331. return has_writes;
  3332. }
  3333. /**
  3334. * Check the is_bad_for_new_circs flag
  3335. *
  3336. * This function returns the is_bad_for_new_circs flag of the specified
  3337. * channel.
  3338. */
  3339. int
  3340. channel_is_bad_for_new_circs(channel_t *chan)
  3341. {
  3342. tor_assert(chan);
  3343. return chan->is_bad_for_new_circs;
  3344. }
  3345. /**
  3346. * Mark a channel as bad for new circuits
  3347. *
  3348. * Set the is_bad_for_new_circs_flag on chan.
  3349. */
  3350. void
  3351. channel_mark_bad_for_new_circs(channel_t *chan)
  3352. {
  3353. tor_assert(chan);
  3354. chan->is_bad_for_new_circs = 1;
  3355. }
  3356. /**
  3357. * Get the client flag
  3358. *
  3359. * This returns the client flag of a channel, which will be set if
  3360. * command_process_create_cell() in command.c thinks this is a connection
  3361. * from a client.
  3362. */
  3363. int
  3364. channel_is_client(channel_t *chan)
  3365. {
  3366. tor_assert(chan);
  3367. return chan->is_client;
  3368. }
  3369. /**
  3370. * Set the client flag
  3371. *
  3372. * Mark a channel as being from a client
  3373. */
  3374. void
  3375. channel_mark_client(channel_t *chan)
  3376. {
  3377. tor_assert(chan);
  3378. chan->is_client = 1;
  3379. }
  3380. /**
  3381. * Get the canonical flag for a channel
  3382. *
  3383. * This returns the is_canonical for a channel; this flag is determined by
  3384. * the lower layer and can't be set in a transport-independent way.
  3385. */
  3386. int
  3387. channel_is_canonical(channel_t *chan)
  3388. {
  3389. tor_assert(chan);
  3390. tor_assert(chan->is_canonical);
  3391. return chan->is_canonical(chan, 0);
  3392. }
  3393. /**
  3394. * Test if the canonical flag is reliable
  3395. *
  3396. * This function asks if the lower layer thinks it's safe to trust the
  3397. * result of channel_is_canonical()
  3398. */
  3399. int
  3400. channel_is_canonical_is_reliable(channel_t *chan)
  3401. {
  3402. tor_assert(chan);
  3403. tor_assert(chan->is_canonical);
  3404. return chan->is_canonical(chan, 1);
  3405. }
  3406. /**
  3407. * Test incoming flag
  3408. *
  3409. * This function gets the incoming flag; this is set when a listener spawns
  3410. * a channel. If this returns true the channel was remotely initiated.
  3411. */
  3412. int
  3413. channel_is_incoming(channel_t *chan)
  3414. {
  3415. tor_assert(chan);
  3416. return chan->is_incoming;
  3417. }
  3418. /**
  3419. * Set the incoming flag
  3420. *
  3421. * This function is called when a channel arrives on a listening channel
  3422. * to mark it as incoming.
  3423. */
  3424. void
  3425. channel_mark_incoming(channel_t *chan)
  3426. {
  3427. tor_assert(chan);
  3428. chan->is_incoming = 1;
  3429. }
  3430. /**
  3431. * Test local flag
  3432. *
  3433. * This function gets the local flag; the lower layer should set this when
  3434. * setting up the channel if is_local_addr() is true for all of the
  3435. * destinations it will communicate with on behalf of this channel. It's
  3436. * used to decide whether to declare the network reachable when seeing incoming
  3437. * traffic on the channel.
  3438. */
  3439. int
  3440. channel_is_local(channel_t *chan)
  3441. {
  3442. tor_assert(chan);
  3443. return chan->is_local;
  3444. }
  3445. /**
  3446. * Set the local flag
  3447. *
  3448. * This internal-only function should be called by the lower layer if the
  3449. * channel is to a local address. See channel_is_local() above or the
  3450. * description of the is_local bit in channel.h
  3451. */
  3452. void
  3453. channel_mark_local(channel_t *chan)
  3454. {
  3455. tor_assert(chan);
  3456. chan->is_local = 1;
  3457. }
  3458. /**
  3459. * Mark a channel as remote
  3460. *
  3461. * This internal-only function should be called by the lower layer if the
  3462. * channel is not to a local address but has previously been marked local.
  3463. * See channel_is_local() above or the description of the is_local bit in
  3464. * channel.h
  3465. */
  3466. void
  3467. channel_mark_remote(channel_t *chan)
  3468. {
  3469. tor_assert(chan);
  3470. chan->is_local = 0;
  3471. }
  3472. /**
  3473. * Test outgoing flag
  3474. *
  3475. * This function gets the outgoing flag; this is the inverse of the incoming
  3476. * bit set when a listener spawns a channel. If this returns true the channel
  3477. * was locally initiated.
  3478. */
  3479. int
  3480. channel_is_outgoing(channel_t *chan)
  3481. {
  3482. tor_assert(chan);
  3483. return !(chan->is_incoming);
  3484. }
  3485. /**
  3486. * Mark a channel as outgoing
  3487. *
  3488. * This function clears the incoming flag and thus marks a channel as
  3489. * outgoing.
  3490. */
  3491. void
  3492. channel_mark_outgoing(channel_t *chan)
  3493. {
  3494. tor_assert(chan);
  3495. chan->is_incoming = 0;
  3496. }
  3497. /************************
  3498. * Flow control queries *
  3499. ***********************/
  3500. /*
  3501. * Get the latest estimate for the total queue size of all open channels
  3502. */
  3503. uint64_t
  3504. channel_get_global_queue_estimate(void)
  3505. {
  3506. return estimated_total_queue_size;
  3507. }
  3508. /*
  3509. * Estimate the number of writeable cells
  3510. *
  3511. * Ask the lower layer for an estimate of how many cells it can accept, and
  3512. * then subtract the length of our outgoing_queue, if any, to produce an
  3513. * estimate of the number of cells this channel can accept for writes.
  3514. */
  3515. int
  3516. channel_num_cells_writeable(channel_t *chan)
  3517. {
  3518. int result;
  3519. tor_assert(chan);
  3520. tor_assert(chan->num_cells_writeable);
  3521. if (chan->state == CHANNEL_STATE_OPEN) {
  3522. /* Query lower layer */
  3523. result = chan->num_cells_writeable(chan);
  3524. /* Subtract cell queue length, if any */
  3525. result -= chan_cell_queue_len(&chan->outgoing_queue);
  3526. if (result < 0) result = 0;
  3527. } else {
  3528. /* No cells are writeable in any other state */
  3529. result = 0;
  3530. }
  3531. return result;
  3532. }
  3533. /*********************
  3534. * Timestamp updates *
  3535. ********************/
  3536. /**
  3537. * Update the created timestamp for a channel
  3538. *
  3539. * This updates the channel's created timestamp and should only be called
  3540. * from channel_init().
  3541. */
  3542. void
  3543. channel_timestamp_created(channel_t *chan)
  3544. {
  3545. time_t now = time(NULL);
  3546. tor_assert(chan);
  3547. chan->timestamp_created = now;
  3548. }
  3549. /**
  3550. * Update the created timestamp for a channel listener
  3551. *
  3552. * This updates the channel listener's created timestamp and should only be
  3553. * called from channel_init_listener().
  3554. */
  3555. void
  3556. channel_listener_timestamp_created(channel_listener_t *chan_l)
  3557. {
  3558. time_t now = time(NULL);
  3559. tor_assert(chan_l);
  3560. chan_l->timestamp_created = now;
  3561. }
  3562. /**
  3563. * Update the last active timestamp for a channel
  3564. *
  3565. * This function updates the channel's last active timestamp; it should be
  3566. * called by the lower layer whenever there is activity on the channel which
  3567. * does not lead to a cell being transmitted or received; the active timestamp
  3568. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  3569. * but it should be updated for things like the v3 handshake and stuff that
  3570. * produce activity only visible to the lower layer.
  3571. */
  3572. void
  3573. channel_timestamp_active(channel_t *chan)
  3574. {
  3575. time_t now = time(NULL);
  3576. tor_assert(chan);
  3577. chan->timestamp_active = now;
  3578. }
  3579. /**
  3580. * Update the last active timestamp for a channel listener
  3581. */
  3582. void
  3583. channel_listener_timestamp_active(channel_listener_t *chan_l)
  3584. {
  3585. time_t now = time(NULL);
  3586. tor_assert(chan_l);
  3587. chan_l->timestamp_active = now;
  3588. }
  3589. /**
  3590. * Update the last accepted timestamp.
  3591. *
  3592. * This function updates the channel listener's last accepted timestamp; it
  3593. * should be called whenever a new incoming channel is accepted on a
  3594. * listener.
  3595. */
  3596. void
  3597. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  3598. {
  3599. time_t now = time(NULL);
  3600. tor_assert(chan_l);
  3601. chan_l->timestamp_active = now;
  3602. chan_l->timestamp_accepted = now;
  3603. }
  3604. /**
  3605. * Update client timestamp
  3606. *
  3607. * This function is called by relay.c to timestamp a channel that appears to
  3608. * be used as a client.
  3609. */
  3610. void
  3611. channel_timestamp_client(channel_t *chan)
  3612. {
  3613. time_t now = time(NULL);
  3614. tor_assert(chan);
  3615. chan->timestamp_client = now;
  3616. }
  3617. /**
  3618. * Update the last drained timestamp
  3619. *
  3620. * This is called whenever we transmit a cell which leaves the outgoing cell
  3621. * queue completely empty. It also updates the xmit time and the active time.
  3622. */
  3623. void
  3624. channel_timestamp_drained(channel_t *chan)
  3625. {
  3626. time_t now = time(NULL);
  3627. tor_assert(chan);
  3628. chan->timestamp_active = now;
  3629. chan->timestamp_drained = now;
  3630. chan->timestamp_xmit = now;
  3631. }
  3632. /**
  3633. * Update the recv timestamp
  3634. *
  3635. * This is called whenever we get an incoming cell from the lower layer.
  3636. * This also updates the active timestamp.
  3637. */
  3638. void
  3639. channel_timestamp_recv(channel_t *chan)
  3640. {
  3641. time_t now = time(NULL);
  3642. tor_assert(chan);
  3643. chan->timestamp_active = now;
  3644. chan->timestamp_recv = now;
  3645. }
  3646. /**
  3647. * Update the xmit timestamp
  3648. * This is called whenever we pass an outgoing cell to the lower layer. This
  3649. * also updates the active timestamp.
  3650. */
  3651. void
  3652. channel_timestamp_xmit(channel_t *chan)
  3653. {
  3654. time_t now = time(NULL);
  3655. tor_assert(chan);
  3656. chan->timestamp_active = now;
  3657. chan->timestamp_xmit = now;
  3658. }
  3659. /***************************************************************
  3660. * Timestamp queries - see above for definitions of timestamps *
  3661. **************************************************************/
  3662. /**
  3663. * Query created timestamp for a channel
  3664. */
  3665. time_t
  3666. channel_when_created(channel_t *chan)
  3667. {
  3668. tor_assert(chan);
  3669. return chan->timestamp_created;
  3670. }
  3671. /**
  3672. * Query created timestamp for a channel listener
  3673. */
  3674. time_t
  3675. channel_listener_when_created(channel_listener_t *chan_l)
  3676. {
  3677. tor_assert(chan_l);
  3678. return chan_l->timestamp_created;
  3679. }
  3680. /**
  3681. * Query last active timestamp for a channel
  3682. */
  3683. time_t
  3684. channel_when_last_active(channel_t *chan)
  3685. {
  3686. tor_assert(chan);
  3687. return chan->timestamp_active;
  3688. }
  3689. /**
  3690. * Query last active timestamp for a channel listener
  3691. */
  3692. time_t
  3693. channel_listener_when_last_active(channel_listener_t *chan_l)
  3694. {
  3695. tor_assert(chan_l);
  3696. return chan_l->timestamp_active;
  3697. }
  3698. /**
  3699. * Query last accepted timestamp for a channel listener
  3700. */
  3701. time_t
  3702. channel_listener_when_last_accepted(channel_listener_t *chan_l)
  3703. {
  3704. tor_assert(chan_l);
  3705. return chan_l->timestamp_accepted;
  3706. }
  3707. /**
  3708. * Query client timestamp
  3709. */
  3710. time_t
  3711. channel_when_last_client(channel_t *chan)
  3712. {
  3713. tor_assert(chan);
  3714. return chan->timestamp_client;
  3715. }
  3716. /**
  3717. * Query drained timestamp
  3718. */
  3719. time_t
  3720. channel_when_last_drained(channel_t *chan)
  3721. {
  3722. tor_assert(chan);
  3723. return chan->timestamp_drained;
  3724. }
  3725. /**
  3726. * Query recv timestamp
  3727. */
  3728. time_t
  3729. channel_when_last_recv(channel_t *chan)
  3730. {
  3731. tor_assert(chan);
  3732. return chan->timestamp_recv;
  3733. }
  3734. /**
  3735. * Query xmit timestamp
  3736. */
  3737. time_t
  3738. channel_when_last_xmit(channel_t *chan)
  3739. {
  3740. tor_assert(chan);
  3741. return chan->timestamp_xmit;
  3742. }
  3743. /**
  3744. * Query accepted counter
  3745. */
  3746. uint64_t
  3747. channel_listener_count_accepted(channel_listener_t *chan_l)
  3748. {
  3749. tor_assert(chan_l);
  3750. return chan_l->n_accepted;
  3751. }
  3752. /**
  3753. * Query received cell counter
  3754. */
  3755. uint64_t
  3756. channel_count_recved(channel_t *chan)
  3757. {
  3758. tor_assert(chan);
  3759. return chan->n_cells_recved;
  3760. }
  3761. /**
  3762. * Query transmitted cell counter
  3763. */
  3764. uint64_t
  3765. channel_count_xmitted(channel_t *chan)
  3766. {
  3767. tor_assert(chan);
  3768. return chan->n_cells_xmitted;
  3769. }
  3770. /**
  3771. * Check if a channel matches an extend_info_t
  3772. *
  3773. * This function calls the lower layer and asks if this channel matches a
  3774. * given extend_info_t.
  3775. */
  3776. int
  3777. channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
  3778. {
  3779. tor_assert(chan);
  3780. tor_assert(chan->matches_extend_info);
  3781. tor_assert(extend_info);
  3782. return chan->matches_extend_info(chan, extend_info);
  3783. }
  3784. /**
  3785. * Check if a channel matches a given target address; return true iff we do.
  3786. *
  3787. * This function calls into the lower layer and asks if this channel thinks
  3788. * it matches a given target address for circuit extension purposes.
  3789. */
  3790. int
  3791. channel_matches_target_addr_for_extend(channel_t *chan,
  3792. const tor_addr_t *target)
  3793. {
  3794. tor_assert(chan);
  3795. tor_assert(chan->matches_target);
  3796. tor_assert(target);
  3797. return chan->matches_target(chan, target);
  3798. }
  3799. /**
  3800. * Return the total number of circuits used by a channel
  3801. *
  3802. * @param chan Channel to query
  3803. * @return Number of circuits using this as n_chan or p_chan
  3804. */
  3805. unsigned int
  3806. channel_num_circuits(channel_t *chan)
  3807. {
  3808. tor_assert(chan);
  3809. return chan->num_n_circuits +
  3810. chan->num_p_circuits;
  3811. }
  3812. /**
  3813. * Set up circuit ID generation
  3814. *
  3815. * This is called when setting up a channel and replaces the old
  3816. * connection_or_set_circid_type()
  3817. */
  3818. MOCK_IMPL(void,
  3819. channel_set_circid_type,(channel_t *chan,
  3820. crypto_pk_t *identity_rcvd,
  3821. int consider_identity))
  3822. {
  3823. int started_here;
  3824. crypto_pk_t *our_identity;
  3825. tor_assert(chan);
  3826. started_here = channel_is_outgoing(chan);
  3827. if (! consider_identity) {
  3828. if (started_here)
  3829. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3830. else
  3831. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3832. return;
  3833. }
  3834. our_identity = started_here ?
  3835. get_tlsclient_identity_key() : get_server_identity_key();
  3836. if (identity_rcvd) {
  3837. if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
  3838. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3839. } else {
  3840. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3841. }
  3842. } else {
  3843. chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
  3844. }
  3845. }
  3846. /** Helper for channel_update_bad_for_new_circs(): Perform the
  3847. * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
  3848. * all of which MUST have the same RSA ID. (They MAY have different
  3849. * Ed25519 IDs.) */
  3850. static void
  3851. channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
  3852. {
  3853. /*XXXX This function should really be about channels. 15056 */
  3854. channel_t *chan;
  3855. /* First, get a minimal list of the ed25519 identites */
  3856. smartlist_t *ed_identities = smartlist_new();
  3857. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  3858. uint8_t *id_copy =
  3859. tor_memdup(&chan->ed25519_identity.pubkey, DIGEST256_LEN);
  3860. smartlist_add(ed_identities, id_copy);
  3861. }
  3862. smartlist_sort_digests256(ed_identities);
  3863. smartlist_uniq_digests256(ed_identities);
  3864. /* Now, for each Ed identity, build a smartlist and find the best entry on
  3865. * it. */
  3866. smartlist_t *or_conns = smartlist_new();
  3867. SMARTLIST_FOREACH_BEGIN(ed_identities, const uint8_t *, ed_id) {
  3868. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  3869. channel_tls_t *chantls = BASE_CHAN_TO_TLS(chan);
  3870. if (tor_memneq(ed_id, &chan->ed25519_identity.pubkey, DIGEST256_LEN))
  3871. continue;
  3872. or_connection_t *orconn = chantls->conn;
  3873. if (orconn) {
  3874. tor_assert(orconn->chan == chantls);
  3875. smartlist_add(or_conns, orconn);
  3876. }
  3877. }
  3878. connection_or_group_set_badness_(or_conns, force);
  3879. smartlist_clear(or_conns);
  3880. } SMARTLIST_FOREACH_END(ed_id);
  3881. /* XXXX 15056 we may want to do something special with connections that have
  3882. * no set Ed25519 identity! */
  3883. smartlist_free(or_conns);
  3884. SMARTLIST_FOREACH(ed_identities, uint8_t *, ed_id, tor_free(ed_id));
  3885. smartlist_free(ed_identities);
  3886. }
  3887. /** Go through all the channels (or if <b>digest</b> is non-NULL, just
  3888. * the OR connections with that digest), and set the is_bad_for_new_circs
  3889. * flag based on the rules in connection_or_group_set_badness() (or just
  3890. * always set it if <b>force</b> is true).
  3891. */
  3892. void
  3893. channel_update_bad_for_new_circs(const char *digest, int force)
  3894. {
  3895. if (digest) {
  3896. channel_idmap_entry_t *ent;
  3897. channel_idmap_entry_t search;
  3898. memset(&search, 0, sizeof(search));
  3899. memcpy(search.digest, digest, DIGEST_LEN);
  3900. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  3901. if (ent) {
  3902. channel_rsa_id_group_set_badness(&ent->channel_list, force);
  3903. }
  3904. return;
  3905. }
  3906. /* no digest; just look at everything. */
  3907. channel_idmap_entry_t **iter;
  3908. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  3909. channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
  3910. }
  3911. }
  3912. /**
  3913. * Update the estimated number of bytes queued to transmit for this channel,
  3914. * and notify the scheduler. The estimate includes both the channel queue and
  3915. * the queue size reported by the lower layer, and an overhead estimate
  3916. * optionally provided by the lower layer.
  3917. */
  3918. void
  3919. channel_update_xmit_queue_size(channel_t *chan)
  3920. {
  3921. uint64_t queued, adj;
  3922. double overhead;
  3923. tor_assert(chan);
  3924. tor_assert(chan->num_bytes_queued);
  3925. /*
  3926. * First, get the number of bytes we have queued without factoring in
  3927. * lower-layer overhead.
  3928. */
  3929. queued = chan->num_bytes_queued(chan) + chan->bytes_in_queue;
  3930. /* Next, adjust by the overhead factor, if any is available */
  3931. if (chan->get_overhead_estimate) {
  3932. overhead = chan->get_overhead_estimate(chan);
  3933. if (overhead >= 1.0) {
  3934. queued = (uint64_t)(queued * overhead);
  3935. } else {
  3936. /* Ignore silly overhead factors */
  3937. log_notice(LD_CHANNEL, "Ignoring silly overhead factor %f", overhead);
  3938. }
  3939. }
  3940. /* Now, compare to the previous estimate */
  3941. if (queued > chan->bytes_queued_for_xmit) {
  3942. adj = queued - chan->bytes_queued_for_xmit;
  3943. log_debug(LD_CHANNEL,
  3944. "Increasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  3945. " from " U64_FORMAT " to " U64_FORMAT,
  3946. U64_PRINTF_ARG(chan->global_identifier),
  3947. U64_PRINTF_ARG(adj),
  3948. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  3949. U64_PRINTF_ARG(queued));
  3950. /* Update the channel's estimate */
  3951. chan->bytes_queued_for_xmit = queued;
  3952. /* Update the global queue size estimate if appropriate */
  3953. if (chan->state == CHANNEL_STATE_OPEN ||
  3954. chan->state == CHANNEL_STATE_MAINT) {
  3955. estimated_total_queue_size += adj;
  3956. log_debug(LD_CHANNEL,
  3957. "Increasing global queue size by " U64_FORMAT " for channel "
  3958. U64_FORMAT ", new size is " U64_FORMAT,
  3959. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  3960. U64_PRINTF_ARG(estimated_total_queue_size));
  3961. /* Tell the scheduler we're increasing the queue size */
  3962. scheduler_adjust_queue_size(chan, 1, adj);
  3963. }
  3964. } else if (queued < chan->bytes_queued_for_xmit) {
  3965. adj = chan->bytes_queued_for_xmit - queued;
  3966. log_debug(LD_CHANNEL,
  3967. "Decreasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  3968. " from " U64_FORMAT " to " U64_FORMAT,
  3969. U64_PRINTF_ARG(chan->global_identifier),
  3970. U64_PRINTF_ARG(adj),
  3971. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  3972. U64_PRINTF_ARG(queued));
  3973. /* Update the channel's estimate */
  3974. chan->bytes_queued_for_xmit = queued;
  3975. /* Update the global queue size estimate if appropriate */
  3976. if (chan->state == CHANNEL_STATE_OPEN ||
  3977. chan->state == CHANNEL_STATE_MAINT) {
  3978. estimated_total_queue_size -= adj;
  3979. log_debug(LD_CHANNEL,
  3980. "Decreasing global queue size by " U64_FORMAT " for channel "
  3981. U64_FORMAT ", new size is " U64_FORMAT,
  3982. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  3983. U64_PRINTF_ARG(estimated_total_queue_size));
  3984. /* Tell the scheduler we're decreasing the queue size */
  3985. scheduler_adjust_queue_size(chan, -1, adj);
  3986. }
  3987. }
  3988. }