channel.c 139 KB

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