channel.c 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883
  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. #include "rendservice.h"
  65. /* Global lists of channels */
  66. /* All channel_t instances */
  67. static smartlist_t *all_channels = NULL;
  68. /* All channel_t instances not in ERROR or CLOSED states */
  69. static smartlist_t *active_channels = NULL;
  70. /* All channel_t instances in ERROR or CLOSED states */
  71. static smartlist_t *finished_channels = NULL;
  72. /* All channel_listener_t instances */
  73. static smartlist_t *all_listeners = NULL;
  74. /* All channel_listener_t instances in LISTENING state */
  75. static smartlist_t *active_listeners = NULL;
  76. /* All channel_listener_t instances in LISTENING state */
  77. static smartlist_t *finished_listeners = NULL;
  78. /** Map from channel->global_identifier to channel. Contains the same
  79. * elements as all_channels. */
  80. static HT_HEAD(channel_gid_map, channel_s) channel_gid_map = HT_INITIALIZER();
  81. static unsigned
  82. channel_id_hash(const channel_t *chan)
  83. {
  84. return (unsigned) chan->global_identifier;
  85. }
  86. static int
  87. channel_id_eq(const channel_t *a, const channel_t *b)
  88. {
  89. return a->global_identifier == b->global_identifier;
  90. }
  91. HT_PROTOTYPE(channel_gid_map, channel_s, gidmap_node,
  92. channel_id_hash, channel_id_eq)
  93. HT_GENERATE2(channel_gid_map, channel_s, gidmap_node,
  94. channel_id_hash, channel_id_eq,
  95. 0.6, tor_reallocarray_, tor_free_)
  96. HANDLE_IMPL(channel, channel_s,)
  97. /* Counter for ID numbers */
  98. static uint64_t n_channels_allocated = 0;
  99. /*
  100. * Channel global byte/cell counters, for statistics and for scheduler high
  101. * /low-water marks.
  102. */
  103. /*
  104. * Total number of cells ever given to any channel with the
  105. * channel_write_*_cell() functions.
  106. */
  107. static uint64_t n_channel_cells_queued = 0;
  108. /*
  109. * Total number of cells ever passed to a channel lower layer with the
  110. * write_*_cell() methods.
  111. */
  112. static uint64_t n_channel_cells_passed_to_lower_layer = 0;
  113. /*
  114. * Current number of cells in all channel queues; should be
  115. * n_channel_cells_queued - n_channel_cells_passed_to_lower_layer.
  116. */
  117. static uint64_t n_channel_cells_in_queues = 0;
  118. /*
  119. * Total number of bytes for all cells ever queued to a channel and
  120. * counted in n_channel_cells_queued.
  121. */
  122. static uint64_t n_channel_bytes_queued = 0;
  123. /*
  124. * Total number of bytes for all cells ever passed to a channel lower layer
  125. * and counted in n_channel_cells_passed_to_lower_layer.
  126. */
  127. static uint64_t n_channel_bytes_passed_to_lower_layer = 0;
  128. /*
  129. * Current number of bytes in all channel queues; should be
  130. * n_channel_bytes_queued - n_channel_bytes_passed_to_lower_layer.
  131. */
  132. static uint64_t n_channel_bytes_in_queues = 0;
  133. /*
  134. * Current total estimated queue size *including lower layer queues and
  135. * transmit overhead*
  136. */
  137. STATIC uint64_t estimated_total_queue_size = 0;
  138. /* Digest->channel map
  139. *
  140. * Similar to the one used in connection_or.c, this maps from the identity
  141. * digest of a remote endpoint to a channel_t to that endpoint. Channels
  142. * should be placed here when registered and removed when they close or error.
  143. * If more than one channel exists, follow the next_with_same_id pointer
  144. * as a linked list.
  145. */
  146. static HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
  147. HT_INITIALIZER();
  148. typedef struct channel_idmap_entry_s {
  149. HT_ENTRY(channel_idmap_entry_s) node;
  150. uint8_t digest[DIGEST_LEN];
  151. TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
  152. } channel_idmap_entry_t;
  153. static inline unsigned
  154. channel_idmap_hash(const channel_idmap_entry_t *ent)
  155. {
  156. return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
  157. }
  158. static inline int
  159. channel_idmap_eq(const channel_idmap_entry_t *a,
  160. const channel_idmap_entry_t *b)
  161. {
  162. return tor_memeq(a->digest, b->digest, DIGEST_LEN);
  163. }
  164. HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
  165. channel_idmap_eq)
  166. HT_GENERATE2(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
  167. channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_)
  168. static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
  169. #if 0
  170. static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
  171. #endif
  172. static cell_queue_entry_t *
  173. cell_queue_entry_new_fixed(cell_t *cell);
  174. static cell_queue_entry_t *
  175. cell_queue_entry_new_var(var_cell_t *var_cell);
  176. static int is_destroy_cell(channel_t *chan,
  177. const cell_queue_entry_t *q, circid_t *circid_out);
  178. static void channel_assert_counter_consistency(void);
  179. /* Functions to maintain the digest map */
  180. static void channel_add_to_digest_map(channel_t *chan);
  181. static void channel_remove_from_digest_map(channel_t *chan);
  182. /*
  183. * Flush cells from just the outgoing queue without trying to get them
  184. * from circuits; used internall by channel_flush_some_cells().
  185. */
  186. static ssize_t
  187. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  188. ssize_t num_cells);
  189. static void channel_force_xfree(channel_t *chan);
  190. static void channel_free_list(smartlist_t *channels, int mark_for_close);
  191. static void channel_listener_free_list(smartlist_t *channels,
  192. int mark_for_close);
  193. static void channel_listener_force_xfree(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 /* 0 */
  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_xfree(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_xfree(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_xfree(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_xfree(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_xfree(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 /* 0 */
  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. static 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. if (to_state == CHANNEL_STATE_CLOSED ||
  1850. to_state == CHANNEL_STATE_ERROR) {
  1851. /* Assert that all queues are empty */
  1852. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
  1853. tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
  1854. }
  1855. }
  1856. /**
  1857. * As channel_change_state_, but change the state to any state but open.
  1858. */
  1859. void
  1860. channel_change_state(channel_t *chan, channel_state_t to_state)
  1861. {
  1862. tor_assert(to_state != CHANNEL_STATE_OPEN);
  1863. channel_change_state_(chan, to_state);
  1864. }
  1865. /**
  1866. * As channel_change_state, but change the state to open.
  1867. */
  1868. void
  1869. channel_change_state_open(channel_t *chan)
  1870. {
  1871. channel_change_state_(chan, CHANNEL_STATE_OPEN);
  1872. /* Tell circuits if we opened and stuff */
  1873. channel_do_open_actions(chan);
  1874. chan->has_been_open = 1;
  1875. /* Check for queued cells to process */
  1876. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  1877. channel_process_cells(chan);
  1878. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
  1879. channel_flush_cells(chan);
  1880. }
  1881. /**
  1882. * Change channel listener state
  1883. *
  1884. * This internal and subclass use only function is used to change channel
  1885. * listener state, performing all transition validity checks and whatever
  1886. * actions are appropriate to the state transition in question.
  1887. */
  1888. void
  1889. channel_listener_change_state(channel_listener_t *chan_l,
  1890. channel_listener_state_t to_state)
  1891. {
  1892. channel_listener_state_t from_state;
  1893. unsigned char was_active, is_active;
  1894. tor_assert(chan_l);
  1895. from_state = chan_l->state;
  1896. tor_assert(channel_listener_state_is_valid(from_state));
  1897. tor_assert(channel_listener_state_is_valid(to_state));
  1898. tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
  1899. /* Check for no-op transitions */
  1900. if (from_state == to_state) {
  1901. log_debug(LD_CHANNEL,
  1902. "Got no-op transition from \"%s\" to itself on channel "
  1903. "listener %p (global ID " U64_FORMAT ")",
  1904. channel_listener_state_to_string(to_state),
  1905. chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
  1906. return;
  1907. }
  1908. /* If we're going to a closing or closed state, we must have a reason set */
  1909. if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
  1910. to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1911. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1912. tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
  1913. }
  1914. /*
  1915. * We need to maintain the queues here for some transitions:
  1916. * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
  1917. * we may have a backlog of cells to transmit, so drain the queues in
  1918. * that case, and when going to CHANNEL_STATE_CLOSED the subclass
  1919. * should have made sure to finish sending things (or gone to
  1920. * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
  1921. */
  1922. log_debug(LD_CHANNEL,
  1923. "Changing state of channel listener %p (global ID " U64_FORMAT
  1924. "from \"%s\" to \"%s\"",
  1925. chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
  1926. channel_listener_state_to_string(chan_l->state),
  1927. channel_listener_state_to_string(to_state));
  1928. chan_l->state = to_state;
  1929. /* Need to add to the right lists if the channel listener is registered */
  1930. if (chan_l->registered) {
  1931. was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1932. from_state == CHANNEL_LISTENER_STATE_ERROR);
  1933. is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1934. to_state == CHANNEL_LISTENER_STATE_ERROR);
  1935. /* Need to take off active list and put on finished list? */
  1936. if (was_active && !is_active) {
  1937. if (active_listeners) smartlist_remove(active_listeners, chan_l);
  1938. if (!finished_listeners) finished_listeners = smartlist_new();
  1939. smartlist_add(finished_listeners, chan_l);
  1940. }
  1941. /* Need to put on active list? */
  1942. else if (!was_active && is_active) {
  1943. if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
  1944. if (!active_listeners) active_listeners = smartlist_new();
  1945. smartlist_add(active_listeners, chan_l);
  1946. }
  1947. }
  1948. if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
  1949. to_state == CHANNEL_LISTENER_STATE_ERROR) {
  1950. /* Assert that the queue is empty */
  1951. tor_assert(!(chan_l->incoming_list) ||
  1952. smartlist_len(chan_l->incoming_list) == 0);
  1953. }
  1954. }
  1955. /**
  1956. * Try to flush cells to the lower layer
  1957. *
  1958. * this is called by the lower layer to indicate that it wants more cells;
  1959. * it will try to write up to num_cells cells from the channel's cell queue or
  1960. * from circuits active on that channel, or as many as it has available if
  1961. * num_cells == -1.
  1962. */
  1963. #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
  1964. MOCK_IMPL(ssize_t,
  1965. channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
  1966. {
  1967. unsigned int unlimited = 0;
  1968. ssize_t flushed = 0;
  1969. int num_cells_from_circs, clamped_num_cells;
  1970. int q_len_before, q_len_after;
  1971. tor_assert(chan);
  1972. if (num_cells < 0) unlimited = 1;
  1973. if (!unlimited && num_cells <= flushed) goto done;
  1974. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  1975. if (CHANNEL_IS_OPEN(chan)) {
  1976. /* Try to flush as much as we can that's already queued */
  1977. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  1978. (unlimited ? -1 : num_cells - flushed));
  1979. if (!unlimited && num_cells <= flushed) goto done;
  1980. if (circuitmux_num_cells(chan->cmux) > 0) {
  1981. /* Calculate number of cells, including clamp */
  1982. if (unlimited) {
  1983. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1984. } else {
  1985. if (num_cells - flushed >
  1986. MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
  1987. clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
  1988. } else {
  1989. clamped_num_cells = (int)(num_cells - flushed);
  1990. }
  1991. }
  1992. /*
  1993. * Keep track of the change in queue size; we have to count cells
  1994. * channel_flush_from_first_active_circuit() writes out directly,
  1995. * but not double-count ones we might get later in
  1996. * channel_flush_some_cells_from_outgoing_queue()
  1997. */
  1998. q_len_before = chan_cell_queue_len(&(chan->outgoing_queue));
  1999. /* Try to get more cells from any active circuits */
  2000. num_cells_from_circs = channel_flush_from_first_active_circuit(
  2001. chan, clamped_num_cells);
  2002. q_len_after = chan_cell_queue_len(&(chan->outgoing_queue));
  2003. /*
  2004. * If it claims we got some, adjust the flushed counter and consider
  2005. * processing the queue again
  2006. */
  2007. if (num_cells_from_circs > 0) {
  2008. /*
  2009. * Adjust flushed by the number of cells counted in
  2010. * num_cells_from_circs that didn't go to the cell queue.
  2011. */
  2012. if (q_len_after > q_len_before) {
  2013. num_cells_from_circs -= (q_len_after - q_len_before);
  2014. if (num_cells_from_circs < 0) num_cells_from_circs = 0;
  2015. }
  2016. flushed += num_cells_from_circs;
  2017. /* Now process the queue if necessary */
  2018. if ((q_len_after > q_len_before) &&
  2019. (unlimited || (flushed < num_cells))) {
  2020. flushed += channel_flush_some_cells_from_outgoing_queue(chan,
  2021. (unlimited ? -1 : num_cells - flushed));
  2022. }
  2023. }
  2024. }
  2025. }
  2026. done:
  2027. return flushed;
  2028. }
  2029. /**
  2030. * Flush cells from just the channel's outgoing cell queue
  2031. *
  2032. * This gets called from channel_flush_some_cells() above to flush cells
  2033. * just from the queue without trying for active_circuits.
  2034. */
  2035. static ssize_t
  2036. channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
  2037. ssize_t num_cells)
  2038. {
  2039. unsigned int unlimited = 0;
  2040. ssize_t flushed = 0;
  2041. cell_queue_entry_t *q = NULL;
  2042. size_t cell_size;
  2043. int free_q = 0, handed_off = 0;
  2044. tor_assert(chan);
  2045. tor_assert(chan->write_cell);
  2046. tor_assert(chan->write_packed_cell);
  2047. tor_assert(chan->write_var_cell);
  2048. if (num_cells < 0) unlimited = 1;
  2049. if (!unlimited && num_cells <= flushed) return 0;
  2050. /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
  2051. if (CHANNEL_IS_OPEN(chan)) {
  2052. while ((unlimited || num_cells > flushed) &&
  2053. NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
  2054. free_q = 0;
  2055. handed_off = 0;
  2056. /* Figure out how big it is for statistical purposes */
  2057. cell_size = channel_get_cell_queue_entry_size(chan, q);
  2058. /*
  2059. * Okay, we have a good queue entry, try to give it to the lower
  2060. * layer.
  2061. */
  2062. switch (q->type) {
  2063. case CELL_QUEUE_FIXED:
  2064. if (q->u.fixed.cell) {
  2065. if (chan->write_cell(chan,
  2066. q->u.fixed.cell)) {
  2067. ++flushed;
  2068. channel_timestamp_xmit(chan);
  2069. ++(chan->n_cells_xmitted);
  2070. chan->n_bytes_xmitted += cell_size;
  2071. free_q = 1;
  2072. handed_off = 1;
  2073. }
  2074. /* Else couldn't write it; leave it on the queue */
  2075. } else {
  2076. /* This shouldn't happen */
  2077. log_info(LD_CHANNEL,
  2078. "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
  2079. "with no cell on channel %p "
  2080. "(global ID " U64_FORMAT ").",
  2081. chan, U64_PRINTF_ARG(chan->global_identifier));
  2082. /* Throw it away */
  2083. free_q = 1;
  2084. handed_off = 0;
  2085. }
  2086. break;
  2087. case CELL_QUEUE_PACKED:
  2088. if (q->u.packed.packed_cell) {
  2089. if (chan->write_packed_cell(chan,
  2090. q->u.packed.packed_cell)) {
  2091. ++flushed;
  2092. channel_timestamp_xmit(chan);
  2093. ++(chan->n_cells_xmitted);
  2094. chan->n_bytes_xmitted += cell_size;
  2095. free_q = 1;
  2096. handed_off = 1;
  2097. }
  2098. /* Else couldn't write it; leave it on the queue */
  2099. } else {
  2100. /* This shouldn't happen */
  2101. log_info(LD_CHANNEL,
  2102. "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
  2103. "with no cell on channel %p "
  2104. "(global ID " U64_FORMAT ").",
  2105. chan, U64_PRINTF_ARG(chan->global_identifier));
  2106. /* Throw it away */
  2107. free_q = 1;
  2108. handed_off = 0;
  2109. }
  2110. break;
  2111. case CELL_QUEUE_VAR:
  2112. if (q->u.var.var_cell) {
  2113. if (chan->write_var_cell(chan,
  2114. q->u.var.var_cell)) {
  2115. ++flushed;
  2116. channel_timestamp_xmit(chan);
  2117. ++(chan->n_cells_xmitted);
  2118. chan->n_bytes_xmitted += cell_size;
  2119. free_q = 1;
  2120. handed_off = 1;
  2121. }
  2122. /* Else couldn't write it; leave it on the queue */
  2123. } else {
  2124. /* This shouldn't happen */
  2125. log_info(LD_CHANNEL,
  2126. "Saw broken cell queue entry of type CELL_QUEUE_VAR "
  2127. "with no cell on channel %p "
  2128. "(global ID " U64_FORMAT ").",
  2129. chan, U64_PRINTF_ARG(chan->global_identifier));
  2130. /* Throw it away */
  2131. free_q = 1;
  2132. handed_off = 0;
  2133. }
  2134. break;
  2135. default:
  2136. /* Unknown type, log and free it */
  2137. log_info(LD_CHANNEL,
  2138. "Saw an unknown cell queue entry type %d on channel %p "
  2139. "(global ID " U64_FORMAT "; ignoring it."
  2140. " Someone should fix this.",
  2141. q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
  2142. free_q = 1;
  2143. handed_off = 0;
  2144. }
  2145. /*
  2146. * if free_q is set, we used it and should remove the queue entry;
  2147. * we have to do the free down here so TOR_SIMPLEQ_REMOVE_HEAD isn't
  2148. * accessing freed memory
  2149. */
  2150. if (free_q) {
  2151. TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
  2152. /*
  2153. * ...and we handed a cell off to the lower layer, so we should
  2154. * update the counters.
  2155. */
  2156. ++n_channel_cells_passed_to_lower_layer;
  2157. --n_channel_cells_in_queues;
  2158. n_channel_bytes_passed_to_lower_layer += cell_size;
  2159. n_channel_bytes_in_queues -= cell_size;
  2160. channel_assert_counter_consistency();
  2161. /* Update the channel's queue size too */
  2162. chan->bytes_in_queue -= cell_size;
  2163. /* Finally, free q */
  2164. cell_queue_entry_xfree(q, handed_off);
  2165. q = NULL;
  2166. } else {
  2167. /* No cell removed from list, so we can't go on any further */
  2168. break;
  2169. }
  2170. }
  2171. }
  2172. /* Did we drain the queue? */
  2173. if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  2174. channel_timestamp_drained(chan);
  2175. }
  2176. /* Update the estimate queue size */
  2177. channel_update_xmit_queue_size(chan);
  2178. return flushed;
  2179. }
  2180. /**
  2181. * Flush as many cells as we possibly can from the queue
  2182. *
  2183. * This tries to flush as many cells from the queue as the lower layer
  2184. * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
  2185. * in unlimited mode.
  2186. */
  2187. void
  2188. channel_flush_cells(channel_t *chan)
  2189. {
  2190. channel_flush_some_cells_from_outgoing_queue(chan, -1);
  2191. }
  2192. /**
  2193. * Check if any cells are available
  2194. *
  2195. * This gets used from the lower layer to check if any more cells are
  2196. * available.
  2197. */
  2198. MOCK_IMPL(int,
  2199. channel_more_to_flush, (channel_t *chan))
  2200. {
  2201. tor_assert(chan);
  2202. /* Check if we have any queued */
  2203. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2204. return 1;
  2205. /* Check if any circuits would like to queue some */
  2206. if (circuitmux_num_cells(chan->cmux) > 0) return 1;
  2207. /* Else no */
  2208. return 0;
  2209. }
  2210. /**
  2211. * Notify the channel we're done flushing the output in the lower layer
  2212. *
  2213. * Connection.c will call this when we've flushed the output; there's some
  2214. * dirreq-related maintenance to do.
  2215. */
  2216. void
  2217. channel_notify_flushed(channel_t *chan)
  2218. {
  2219. tor_assert(chan);
  2220. if (chan->dirreq_id != 0)
  2221. geoip_change_dirreq_state(chan->dirreq_id,
  2222. DIRREQ_TUNNELED,
  2223. DIRREQ_CHANNEL_BUFFER_FLUSHED);
  2224. }
  2225. /**
  2226. * Process the queue of incoming channels on a listener
  2227. *
  2228. * Use a listener's registered callback to process as many entries in the
  2229. * queue of incoming channels as possible.
  2230. */
  2231. void
  2232. channel_listener_process_incoming(channel_listener_t *listener)
  2233. {
  2234. tor_assert(listener);
  2235. /*
  2236. * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
  2237. * while closing a listener.
  2238. */
  2239. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
  2240. listener->state == CHANNEL_LISTENER_STATE_CLOSING);
  2241. tor_assert(listener->listener);
  2242. log_debug(LD_CHANNEL,
  2243. "Processing queue of incoming connections for channel "
  2244. "listener %p (global ID " U64_FORMAT ")",
  2245. listener, U64_PRINTF_ARG(listener->global_identifier));
  2246. if (!(listener->incoming_list)) return;
  2247. SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
  2248. channel_t *, chan) {
  2249. tor_assert(chan);
  2250. log_debug(LD_CHANNEL,
  2251. "Handling incoming channel %p (" U64_FORMAT ") "
  2252. "for listener %p (" U64_FORMAT ")",
  2253. chan,
  2254. U64_PRINTF_ARG(chan->global_identifier),
  2255. listener,
  2256. U64_PRINTF_ARG(listener->global_identifier));
  2257. /* Make sure this is set correctly */
  2258. channel_mark_incoming(chan);
  2259. listener->listener(listener, chan);
  2260. } SMARTLIST_FOREACH_END(chan);
  2261. smartlist_free(listener->incoming_list);
  2262. listener->incoming_list = NULL;
  2263. }
  2264. /**
  2265. * Take actions required when a channel becomes open
  2266. *
  2267. * Handle actions we should do when we know a channel is open; a lot of
  2268. * this comes from the old connection_or_set_state_open() of connection_or.c.
  2269. *
  2270. * Because of this mechanism, future channel_t subclasses should take care
  2271. * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
  2272. * until there is positive confirmation that the network is operational.
  2273. * In particular, anything UDP-based should not make this transition until a
  2274. * packet is received from the other side.
  2275. */
  2276. void
  2277. channel_do_open_actions(channel_t *chan)
  2278. {
  2279. tor_addr_t remote_addr;
  2280. int started_here;
  2281. time_t now = time(NULL);
  2282. int close_origin_circuits = 0;
  2283. tor_assert(chan);
  2284. started_here = channel_is_outgoing(chan);
  2285. if (started_here) {
  2286. circuit_build_times_network_is_live(get_circuit_build_times_mutable());
  2287. rep_hist_note_connect_succeeded(chan->identity_digest, now);
  2288. router_set_status(chan->identity_digest, 1);
  2289. } else {
  2290. /* only report it to the geoip module if it's not a known router */
  2291. if (!connection_or_digest_is_known_relay(chan->identity_digest)) {
  2292. if (channel_get_addr_if_possible(chan, &remote_addr)) {
  2293. char *transport_name = NULL;
  2294. if (chan->get_transport_name(chan, &transport_name) < 0)
  2295. transport_name = NULL;
  2296. geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
  2297. &remote_addr, transport_name,
  2298. now);
  2299. tor_free(transport_name);
  2300. }
  2301. /* Otherwise the underlying transport can't tell us this, so skip it */
  2302. }
  2303. }
  2304. /* Disable or reduce padding according to user prefs. */
  2305. if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
  2306. if (!get_options()->ConnectionPadding) {
  2307. /* Disable if torrc disabled */
  2308. channelpadding_disable_padding_on_channel(chan);
  2309. } else if (get_options()->Tor2webMode &&
  2310. !networkstatus_get_param(NULL,
  2311. CHANNELPADDING_TOR2WEB_PARAM,
  2312. CHANNELPADDING_TOR2WEB_DEFAULT, 0, 1)) {
  2313. /* Disable if we're using tor2web and the consensus disabled padding
  2314. * for tor2web */
  2315. channelpadding_disable_padding_on_channel(chan);
  2316. } else if (rend_service_allow_non_anonymous_connection(get_options()) &&
  2317. !networkstatus_get_param(NULL,
  2318. CHANNELPADDING_SOS_PARAM,
  2319. CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
  2320. /* Disable if we're using RSOS and the consensus disabled padding
  2321. * for RSOS*/
  2322. channelpadding_disable_padding_on_channel(chan);
  2323. } else if (get_options()->ReducedConnectionPadding) {
  2324. /* Padding can be forced and/or reduced by clients, regardless of if
  2325. * the channel supports it */
  2326. channelpadding_reduce_padding_on_channel(chan);
  2327. }
  2328. }
  2329. circuit_n_chan_done(chan, 1, close_origin_circuits);
  2330. }
  2331. /**
  2332. * Queue an incoming channel on a listener
  2333. *
  2334. * Internal and subclass use only function to queue an incoming channel from
  2335. * a listener. A subclass of channel_listener_t should call this when a new
  2336. * incoming channel is created.
  2337. */
  2338. void
  2339. channel_listener_queue_incoming(channel_listener_t *listener,
  2340. channel_t *incoming)
  2341. {
  2342. int need_to_queue = 0;
  2343. tor_assert(listener);
  2344. tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  2345. tor_assert(incoming);
  2346. log_debug(LD_CHANNEL,
  2347. "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
  2348. "channel listener %p (global ID " U64_FORMAT ")",
  2349. incoming, U64_PRINTF_ARG(incoming->global_identifier),
  2350. listener, U64_PRINTF_ARG(listener->global_identifier));
  2351. /* Do we need to queue it, or can we just call the listener right away? */
  2352. if (!(listener->listener)) need_to_queue = 1;
  2353. if (listener->incoming_list &&
  2354. (smartlist_len(listener->incoming_list) > 0))
  2355. need_to_queue = 1;
  2356. /* If we need to queue and have no queue, create one */
  2357. if (need_to_queue && !(listener->incoming_list)) {
  2358. listener->incoming_list = smartlist_new();
  2359. }
  2360. /* Bump the counter and timestamp it */
  2361. channel_listener_timestamp_active(listener);
  2362. channel_listener_timestamp_accepted(listener);
  2363. ++(listener->n_accepted);
  2364. /* If we don't need to queue, process it right away */
  2365. if (!need_to_queue) {
  2366. tor_assert(listener->listener);
  2367. listener->listener(listener, incoming);
  2368. }
  2369. /*
  2370. * Otherwise, we need to queue; queue and then process the queue if
  2371. * we can.
  2372. */
  2373. else {
  2374. tor_assert(listener->incoming_list);
  2375. smartlist_add(listener->incoming_list, incoming);
  2376. if (listener->listener) channel_listener_process_incoming(listener);
  2377. }
  2378. }
  2379. /**
  2380. * Process queued incoming cells
  2381. *
  2382. * Process as many queued cells as we can from the incoming
  2383. * cell queue.
  2384. */
  2385. void
  2386. channel_process_cells(channel_t *chan)
  2387. {
  2388. cell_queue_entry_t *q;
  2389. tor_assert(chan);
  2390. tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
  2391. CHANNEL_IS_OPEN(chan));
  2392. log_debug(LD_CHANNEL,
  2393. "Processing as many incoming cells as we can for channel %p",
  2394. chan);
  2395. /* Nothing we can do if we have no registered cell handlers */
  2396. if (!(chan->cell_handler ||
  2397. chan->var_cell_handler)) return;
  2398. /* Nothing we can do if we have no cells */
  2399. if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
  2400. /*
  2401. * Process cells until we're done or find one we have no current handler
  2402. * for.
  2403. *
  2404. * We must free the cells here after calling the handler, since custody
  2405. * of the buffer was given to the channel layer when they were queued;
  2406. * see comments on memory management in channel_queue_cell() and in
  2407. * channel_queue_var_cell() below.
  2408. */
  2409. while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
  2410. tor_assert(q);
  2411. tor_assert(q->type == CELL_QUEUE_FIXED ||
  2412. q->type == CELL_QUEUE_VAR);
  2413. if (q->type == CELL_QUEUE_FIXED &&
  2414. chan->cell_handler) {
  2415. /* Handle a fixed-length cell */
  2416. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2417. tor_assert(q->u.fixed.cell);
  2418. log_debug(LD_CHANNEL,
  2419. "Processing incoming cell_t %p for channel %p (global ID "
  2420. U64_FORMAT ")",
  2421. q->u.fixed.cell, chan,
  2422. U64_PRINTF_ARG(chan->global_identifier));
  2423. chan->cell_handler(chan, q->u.fixed.cell);
  2424. tor_free(q->u.fixed.cell);
  2425. tor_free(q);
  2426. } else if (q->type == CELL_QUEUE_VAR &&
  2427. chan->var_cell_handler) {
  2428. /* Handle a variable-length cell */
  2429. TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
  2430. tor_assert(q->u.var.var_cell);
  2431. log_debug(LD_CHANNEL,
  2432. "Processing incoming var_cell_t %p for channel %p (global ID "
  2433. U64_FORMAT ")",
  2434. q->u.var.var_cell, chan,
  2435. U64_PRINTF_ARG(chan->global_identifier));
  2436. chan->var_cell_handler(chan, q->u.var.var_cell);
  2437. tor_free(q->u.var.var_cell);
  2438. tor_free(q);
  2439. } else {
  2440. /* Can't handle this one */
  2441. break;
  2442. }
  2443. }
  2444. }
  2445. /**
  2446. * Queue incoming cell
  2447. *
  2448. * This should be called by a channel_t subclass to queue an incoming fixed-
  2449. * length cell for processing, and process it if possible.
  2450. */
  2451. void
  2452. channel_queue_cell(channel_t *chan, cell_t *cell)
  2453. {
  2454. int need_to_queue = 0;
  2455. cell_queue_entry_t *q;
  2456. cell_t *cell_copy = NULL;
  2457. tor_assert(chan);
  2458. tor_assert(cell);
  2459. tor_assert(CHANNEL_IS_OPEN(chan));
  2460. /* Do we need to queue it, or can we just call the handler right away? */
  2461. if (!(chan->cell_handler)) need_to_queue = 1;
  2462. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2463. need_to_queue = 1;
  2464. /* Timestamp for receiving */
  2465. channel_timestamp_recv(chan);
  2466. /* Update the counters */
  2467. ++(chan->n_cells_recved);
  2468. chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
  2469. /* If we don't need to queue we can just call cell_handler */
  2470. if (!need_to_queue) {
  2471. tor_assert(chan->cell_handler);
  2472. log_debug(LD_CHANNEL,
  2473. "Directly handling incoming cell_t %p for channel %p "
  2474. "(global ID " U64_FORMAT ")",
  2475. cell, chan,
  2476. U64_PRINTF_ARG(chan->global_identifier));
  2477. chan->cell_handler(chan, cell);
  2478. } else {
  2479. /*
  2480. * Otherwise queue it and then process the queue if possible.
  2481. *
  2482. * We queue a copy, not the original pointer - it might have been on the
  2483. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2484. * if we ever have a subclass other than channel_tls_t), or be freed
  2485. * there after we return. This is the uncommon case; the non-copying
  2486. * fast path occurs in the if (!need_to_queue) case above when the
  2487. * upper layer has installed cell handlers.
  2488. */
  2489. cell_copy = tor_malloc_zero(sizeof(cell_t));
  2490. memcpy(cell_copy, cell, sizeof(cell_t));
  2491. q = cell_queue_entry_new_fixed(cell_copy);
  2492. log_debug(LD_CHANNEL,
  2493. "Queueing incoming cell_t %p for channel %p "
  2494. "(global ID " U64_FORMAT ")",
  2495. cell, chan,
  2496. U64_PRINTF_ARG(chan->global_identifier));
  2497. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2498. if (chan->cell_handler ||
  2499. chan->var_cell_handler) {
  2500. channel_process_cells(chan);
  2501. }
  2502. }
  2503. }
  2504. /**
  2505. * Queue incoming variable-length cell
  2506. *
  2507. * This should be called by a channel_t subclass to queue an incoming
  2508. * variable-length cell for processing, and process it if possible.
  2509. */
  2510. void
  2511. channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
  2512. {
  2513. int need_to_queue = 0;
  2514. cell_queue_entry_t *q;
  2515. var_cell_t *cell_copy = NULL;
  2516. tor_assert(chan);
  2517. tor_assert(var_cell);
  2518. tor_assert(CHANNEL_IS_OPEN(chan));
  2519. /* Do we need to queue it, or can we just call the handler right away? */
  2520. if (!(chan->var_cell_handler)) need_to_queue = 1;
  2521. if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
  2522. need_to_queue = 1;
  2523. /* Timestamp for receiving */
  2524. channel_timestamp_recv(chan);
  2525. /* Update the counter */
  2526. ++(chan->n_cells_recved);
  2527. chan->n_bytes_recved += get_var_cell_header_size(chan->wide_circ_ids) +
  2528. var_cell->payload_len;
  2529. /* If we don't need to queue we can just call cell_handler */
  2530. if (!need_to_queue) {
  2531. tor_assert(chan->var_cell_handler);
  2532. log_debug(LD_CHANNEL,
  2533. "Directly handling incoming var_cell_t %p for channel %p "
  2534. "(global ID " U64_FORMAT ")",
  2535. var_cell, chan,
  2536. U64_PRINTF_ARG(chan->global_identifier));
  2537. chan->var_cell_handler(chan, var_cell);
  2538. } else {
  2539. /*
  2540. * Otherwise queue it and then process the queue if possible.
  2541. *
  2542. * We queue a copy, not the original pointer - it might have been on the
  2543. * stack in connection_or_process_cells_from_inbuf() (or another caller
  2544. * if we ever have a subclass other than channel_tls_t), or be freed
  2545. * there after we return. This is the uncommon case; the non-copying
  2546. * fast path occurs in the if (!need_to_queue) case above when the
  2547. * upper layer has installed cell handlers.
  2548. */
  2549. cell_copy = var_cell_copy(var_cell);
  2550. q = cell_queue_entry_new_var(cell_copy);
  2551. log_debug(LD_CHANNEL,
  2552. "Queueing incoming var_cell_t %p for channel %p "
  2553. "(global ID " U64_FORMAT ")",
  2554. var_cell, chan,
  2555. U64_PRINTF_ARG(chan->global_identifier));
  2556. TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
  2557. if (chan->cell_handler ||
  2558. chan->var_cell_handler) {
  2559. channel_process_cells(chan);
  2560. }
  2561. }
  2562. }
  2563. /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
  2564. * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
  2565. * false. */
  2566. /* XXXX Move this function. */
  2567. int
  2568. packed_cell_is_destroy(channel_t *chan,
  2569. const packed_cell_t *packed_cell,
  2570. circid_t *circid_out)
  2571. {
  2572. if (chan->wide_circ_ids) {
  2573. if (packed_cell->body[4] == CELL_DESTROY) {
  2574. *circid_out = ntohl(get_uint32(packed_cell->body));
  2575. return 1;
  2576. }
  2577. } else {
  2578. if (packed_cell->body[2] == CELL_DESTROY) {
  2579. *circid_out = ntohs(get_uint16(packed_cell->body));
  2580. return 1;
  2581. }
  2582. }
  2583. return 0;
  2584. }
  2585. /**
  2586. * Assert that the global channel stats counters are internally consistent
  2587. */
  2588. static void
  2589. channel_assert_counter_consistency(void)
  2590. {
  2591. tor_assert(n_channel_cells_queued ==
  2592. (n_channel_cells_in_queues + n_channel_cells_passed_to_lower_layer));
  2593. tor_assert(n_channel_bytes_queued ==
  2594. (n_channel_bytes_in_queues + n_channel_bytes_passed_to_lower_layer));
  2595. }
  2596. /* DOCDOC */
  2597. static int
  2598. is_destroy_cell(channel_t *chan,
  2599. const cell_queue_entry_t *q, circid_t *circid_out)
  2600. {
  2601. *circid_out = 0;
  2602. switch (q->type) {
  2603. case CELL_QUEUE_FIXED:
  2604. if (q->u.fixed.cell->command == CELL_DESTROY) {
  2605. *circid_out = q->u.fixed.cell->circ_id;
  2606. return 1;
  2607. }
  2608. break;
  2609. case CELL_QUEUE_VAR:
  2610. if (q->u.var.var_cell->command == CELL_DESTROY) {
  2611. *circid_out = q->u.var.var_cell->circ_id;
  2612. return 1;
  2613. }
  2614. break;
  2615. case CELL_QUEUE_PACKED:
  2616. return packed_cell_is_destroy(chan, q->u.packed.packed_cell, circid_out);
  2617. }
  2618. return 0;
  2619. }
  2620. /**
  2621. * Send destroy cell on a channel
  2622. *
  2623. * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
  2624. * onto channel <b>chan</b>. Don't perform range-checking on reason:
  2625. * we may want to propagate reasons from other cells.
  2626. */
  2627. int
  2628. channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
  2629. {
  2630. tor_assert(chan);
  2631. if (circ_id == 0) {
  2632. log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
  2633. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2634. U64_PRINTF_ARG(chan->global_identifier),
  2635. chan, channel_state_to_string(chan->state),
  2636. chan->state);
  2637. return 0;
  2638. }
  2639. /* Check to make sure we can send on this channel first */
  2640. if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
  2641. channel_note_destroy_pending(chan, circ_id);
  2642. circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
  2643. log_debug(LD_OR,
  2644. "Sending destroy (circID %u) on channel %p "
  2645. "(global ID " U64_FORMAT ")",
  2646. (unsigned)circ_id, chan,
  2647. U64_PRINTF_ARG(chan->global_identifier));
  2648. } else {
  2649. log_warn(LD_BUG,
  2650. "Someone called channel_send_destroy() for circID %u "
  2651. "on a channel " U64_FORMAT " at %p in state %s (%d)",
  2652. (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
  2653. chan, channel_state_to_string(chan->state),
  2654. chan->state);
  2655. }
  2656. return 0;
  2657. }
  2658. /**
  2659. * Dump channel statistics to the log
  2660. *
  2661. * This is called from dumpstats() in main.c and spams the log with
  2662. * statistics on channels.
  2663. */
  2664. void
  2665. channel_dumpstats(int severity)
  2666. {
  2667. if (all_channels && smartlist_len(all_channels) > 0) {
  2668. tor_log(severity, LD_GENERAL,
  2669. "Channels have queued " U64_FORMAT " bytes in " U64_FORMAT " cells, "
  2670. "and handed " U64_FORMAT " bytes in " U64_FORMAT " cells to the lower"
  2671. " layer.",
  2672. U64_PRINTF_ARG(n_channel_bytes_queued),
  2673. U64_PRINTF_ARG(n_channel_cells_queued),
  2674. U64_PRINTF_ARG(n_channel_bytes_passed_to_lower_layer),
  2675. U64_PRINTF_ARG(n_channel_cells_passed_to_lower_layer));
  2676. tor_log(severity, LD_GENERAL,
  2677. "There are currently " U64_FORMAT " bytes in " U64_FORMAT " cells "
  2678. "in channel queues.",
  2679. U64_PRINTF_ARG(n_channel_bytes_in_queues),
  2680. U64_PRINTF_ARG(n_channel_cells_in_queues));
  2681. tor_log(severity, LD_GENERAL,
  2682. "Dumping statistics about %d channels:",
  2683. smartlist_len(all_channels));
  2684. tor_log(severity, LD_GENERAL,
  2685. "%d are active, and %d are done and waiting for cleanup",
  2686. (active_channels != NULL) ?
  2687. smartlist_len(active_channels) : 0,
  2688. (finished_channels != NULL) ?
  2689. smartlist_len(finished_channels) : 0);
  2690. SMARTLIST_FOREACH(all_channels, channel_t *, chan,
  2691. channel_dump_statistics(chan, severity));
  2692. tor_log(severity, LD_GENERAL,
  2693. "Done spamming about channels now");
  2694. } else {
  2695. tor_log(severity, LD_GENERAL,
  2696. "No channels to dump");
  2697. }
  2698. }
  2699. /**
  2700. * Dump channel listener statistics to the log
  2701. *
  2702. * This is called from dumpstats() in main.c and spams the log with
  2703. * statistics on channel listeners.
  2704. */
  2705. void
  2706. channel_listener_dumpstats(int severity)
  2707. {
  2708. if (all_listeners && smartlist_len(all_listeners) > 0) {
  2709. tor_log(severity, LD_GENERAL,
  2710. "Dumping statistics about %d channel listeners:",
  2711. smartlist_len(all_listeners));
  2712. tor_log(severity, LD_GENERAL,
  2713. "%d are active and %d are done and waiting for cleanup",
  2714. (active_listeners != NULL) ?
  2715. smartlist_len(active_listeners) : 0,
  2716. (finished_listeners != NULL) ?
  2717. smartlist_len(finished_listeners) : 0);
  2718. SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
  2719. channel_listener_dump_statistics(chan_l, severity));
  2720. tor_log(severity, LD_GENERAL,
  2721. "Done spamming about channel listeners now");
  2722. } else {
  2723. tor_log(severity, LD_GENERAL,
  2724. "No channel listeners to dump");
  2725. }
  2726. }
  2727. /**
  2728. * Set the cmux policy on all active channels
  2729. */
  2730. void
  2731. channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
  2732. {
  2733. if (!active_channels) return;
  2734. SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
  2735. if (curr->cmux) {
  2736. circuitmux_set_policy(curr->cmux, pol);
  2737. }
  2738. } SMARTLIST_FOREACH_END(curr);
  2739. }
  2740. /**
  2741. * Clean up channels
  2742. *
  2743. * This gets called periodically from run_scheduled_events() in main.c;
  2744. * it cleans up after closed channels.
  2745. */
  2746. void
  2747. channel_run_cleanup(void)
  2748. {
  2749. channel_t *tmp = NULL;
  2750. /* Check if we need to do anything */
  2751. if (!finished_channels || smartlist_len(finished_channels) == 0) return;
  2752. /* Iterate through finished_channels and get rid of them */
  2753. SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
  2754. tmp = curr;
  2755. /* Remove it from the list */
  2756. SMARTLIST_DEL_CURRENT(finished_channels, curr);
  2757. /* Also unregister it */
  2758. channel_unregister(tmp);
  2759. /* ... and free it */
  2760. channel_free(tmp);
  2761. } SMARTLIST_FOREACH_END(curr);
  2762. }
  2763. /**
  2764. * Clean up channel listeners
  2765. *
  2766. * This gets called periodically from run_scheduled_events() in main.c;
  2767. * it cleans up after closed channel listeners.
  2768. */
  2769. void
  2770. channel_listener_run_cleanup(void)
  2771. {
  2772. channel_listener_t *tmp = NULL;
  2773. /* Check if we need to do anything */
  2774. if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
  2775. /* Iterate through finished_channels and get rid of them */
  2776. SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
  2777. tmp = curr;
  2778. /* Remove it from the list */
  2779. SMARTLIST_DEL_CURRENT(finished_listeners, curr);
  2780. /* Also unregister it */
  2781. channel_listener_unregister(tmp);
  2782. /* ... and free it */
  2783. channel_listener_free(tmp);
  2784. } SMARTLIST_FOREACH_END(curr);
  2785. }
  2786. /**
  2787. * Free a list of channels for channel_free_all()
  2788. */
  2789. static void
  2790. channel_free_list(smartlist_t *channels, int mark_for_close)
  2791. {
  2792. if (!channels) return;
  2793. SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
  2794. /* Deregister and free it */
  2795. tor_assert(curr);
  2796. log_debug(LD_CHANNEL,
  2797. "Cleaning up channel %p (global ID " U64_FORMAT ") "
  2798. "in state %s (%d)",
  2799. curr, U64_PRINTF_ARG(curr->global_identifier),
  2800. channel_state_to_string(curr->state), curr->state);
  2801. /* Detach circuits early so they can find the channel */
  2802. if (curr->cmux) {
  2803. circuitmux_detach_all_circuits(curr->cmux, NULL);
  2804. }
  2805. SMARTLIST_DEL_CURRENT(channels, curr);
  2806. channel_unregister(curr);
  2807. if (mark_for_close) {
  2808. if (!CHANNEL_CONDEMNED(curr)) {
  2809. channel_mark_for_close(curr);
  2810. }
  2811. channel_force_xfree(curr);
  2812. } else channel_free(curr);
  2813. } SMARTLIST_FOREACH_END(curr);
  2814. }
  2815. /**
  2816. * Free a list of channel listeners for channel_free_all()
  2817. */
  2818. static void
  2819. channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
  2820. {
  2821. if (!listeners) return;
  2822. SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
  2823. /* Deregister and free it */
  2824. tor_assert(curr);
  2825. log_debug(LD_CHANNEL,
  2826. "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
  2827. "in state %s (%d)",
  2828. curr, U64_PRINTF_ARG(curr->global_identifier),
  2829. channel_listener_state_to_string(curr->state), curr->state);
  2830. channel_listener_unregister(curr);
  2831. if (mark_for_close) {
  2832. if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
  2833. curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
  2834. curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
  2835. channel_listener_mark_for_close(curr);
  2836. }
  2837. channel_listener_force_xfree(curr);
  2838. } else channel_listener_free(curr);
  2839. } SMARTLIST_FOREACH_END(curr);
  2840. }
  2841. /**
  2842. * Close all channels and free everything
  2843. *
  2844. * This gets called from tor_free_all() in main.c to clean up on exit.
  2845. * It will close all registered channels and free associated storage,
  2846. * then free the all_channels, active_channels, listening_channels and
  2847. * finished_channels lists and also channel_identity_map.
  2848. */
  2849. void
  2850. channel_free_all(void)
  2851. {
  2852. log_debug(LD_CHANNEL,
  2853. "Shutting down channels...");
  2854. /* First, let's go for finished channels */
  2855. if (finished_channels) {
  2856. channel_free_list(finished_channels, 0);
  2857. smartlist_free(finished_channels);
  2858. finished_channels = NULL;
  2859. }
  2860. /* Now the finished listeners */
  2861. if (finished_listeners) {
  2862. channel_listener_free_list(finished_listeners, 0);
  2863. smartlist_free(finished_listeners);
  2864. finished_listeners = NULL;
  2865. }
  2866. /* Now all active channels */
  2867. if (active_channels) {
  2868. channel_free_list(active_channels, 1);
  2869. smartlist_free(active_channels);
  2870. active_channels = NULL;
  2871. }
  2872. /* Now all active listeners */
  2873. if (active_listeners) {
  2874. channel_listener_free_list(active_listeners, 1);
  2875. smartlist_free(active_listeners);
  2876. active_listeners = NULL;
  2877. }
  2878. /* Now all channels, in case any are left over */
  2879. if (all_channels) {
  2880. channel_free_list(all_channels, 1);
  2881. smartlist_free(all_channels);
  2882. all_channels = NULL;
  2883. }
  2884. /* Now all listeners, in case any are left over */
  2885. if (all_listeners) {
  2886. channel_listener_free_list(all_listeners, 1);
  2887. smartlist_free(all_listeners);
  2888. all_listeners = NULL;
  2889. }
  2890. /* Now free channel_identity_map */
  2891. log_debug(LD_CHANNEL,
  2892. "Freeing channel_identity_map");
  2893. /* Geez, anything still left over just won't die ... let it leak then */
  2894. HT_CLEAR(channel_idmap, &channel_identity_map);
  2895. /* Same with channel_gid_map */
  2896. log_debug(LD_CHANNEL,
  2897. "Freeing channel_gid_map");
  2898. HT_CLEAR(channel_gid_map, &channel_gid_map);
  2899. log_debug(LD_CHANNEL,
  2900. "Done cleaning up after channels");
  2901. }
  2902. /**
  2903. * Connect to a given addr/port/digest
  2904. *
  2905. * This sets up a new outgoing channel; in the future if multiple
  2906. * channel_t subclasses are available, this is where the selection policy
  2907. * should go. It may also be desirable to fold port into tor_addr_t
  2908. * or make a new type including a tor_addr_t and port, so we have a
  2909. * single abstract object encapsulating all the protocol details of
  2910. * how to contact an OR.
  2911. */
  2912. channel_t *
  2913. channel_connect(const tor_addr_t *addr, uint16_t port,
  2914. const char *id_digest,
  2915. const ed25519_public_key_t *ed_id)
  2916. {
  2917. return channel_tls_connect(addr, port, id_digest, ed_id);
  2918. }
  2919. /**
  2920. * Decide which of two channels to prefer for extending a circuit
  2921. *
  2922. * This function is called while extending a circuit and returns true iff
  2923. * a is 'better' than b. The most important criterion here is that a
  2924. * canonical channel is always better than a non-canonical one, but the
  2925. * number of circuits and the age are used as tie-breakers.
  2926. *
  2927. * This is based on the former connection_or_is_better() of connection_or.c
  2928. */
  2929. int
  2930. channel_is_better(channel_t *a, channel_t *b)
  2931. {
  2932. int a_is_canonical, b_is_canonical;
  2933. tor_assert(a);
  2934. tor_assert(b);
  2935. /* If one channel is bad for new circuits, and the other isn't,
  2936. * use the one that is still good. */
  2937. if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
  2938. return 1;
  2939. if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
  2940. return 0;
  2941. /* Check if one is canonical and the other isn't first */
  2942. a_is_canonical = channel_is_canonical(a);
  2943. b_is_canonical = channel_is_canonical(b);
  2944. if (a_is_canonical && !b_is_canonical) return 1;
  2945. if (!a_is_canonical && b_is_canonical) return 0;
  2946. /* Check if we suspect that one of the channels will be preferred
  2947. * by the peer */
  2948. if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
  2949. if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
  2950. /*
  2951. * Okay, if we're here they tied on canonicity, the prefer the older
  2952. * connection, so that the adversary can't create a new connection
  2953. * and try to switch us over to it (which will leak information
  2954. * about long-lived circuits). Additionally, switching connections
  2955. * too often makes us more vulnerable to attacks like Torscan and
  2956. * passive netflow-based equivalents.
  2957. *
  2958. * Connections will still only live for at most a week, due to
  2959. * the check in connection_or_group_set_badness() against
  2960. * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
  2961. * unusable for new circuits after 1 week. That check sets
  2962. * is_bad_for_new_circs, which is checked in channel_get_for_extend().
  2963. *
  2964. * We check channel_is_bad_for_new_circs() above here anyway, for safety.
  2965. */
  2966. if (channel_when_created(a) < channel_when_created(b)) return 1;
  2967. else if (channel_when_created(a) > channel_when_created(b)) return 0;
  2968. if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
  2969. else return 0;
  2970. }
  2971. /**
  2972. * Get a channel to extend a circuit
  2973. *
  2974. * Pick a suitable channel to extend a circuit to given the desired digest
  2975. * the address we believe is correct for that digest; this tries to see
  2976. * if we already have one for the requested endpoint, but if there is no good
  2977. * channel, set *msg_out to a message describing the channel's state
  2978. * and our next action, and set *launch_out to a boolean indicated whether
  2979. * the caller should try to launch a new channel with channel_connect().
  2980. */
  2981. channel_t *
  2982. channel_get_for_extend(const char *rsa_id_digest,
  2983. const ed25519_public_key_t *ed_id,
  2984. const tor_addr_t *target_addr,
  2985. const char **msg_out,
  2986. int *launch_out)
  2987. {
  2988. channel_t *chan, *best = NULL;
  2989. int n_inprogress_goodaddr = 0, n_old = 0;
  2990. int n_noncanonical = 0, n_possible = 0;
  2991. tor_assert(msg_out);
  2992. tor_assert(launch_out);
  2993. chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
  2994. /* Walk the list, unrefing the old one and refing the new at each
  2995. * iteration.
  2996. */
  2997. for (; chan; chan = channel_next_with_rsa_identity(chan)) {
  2998. tor_assert(tor_memeq(chan->identity_digest,
  2999. rsa_id_digest, DIGEST_LEN));
  3000. if (CHANNEL_CONDEMNED(chan))
  3001. continue;
  3002. /* Never return a channel on which the other end appears to be
  3003. * a client. */
  3004. if (channel_is_client(chan)) {
  3005. continue;
  3006. }
  3007. /* The Ed25519 key has to match too */
  3008. if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
  3009. continue;
  3010. }
  3011. /* Never return a non-open connection. */
  3012. if (!CHANNEL_IS_OPEN(chan)) {
  3013. /* If the address matches, don't launch a new connection for this
  3014. * circuit. */
  3015. if (channel_matches_target_addr_for_extend(chan, target_addr))
  3016. ++n_inprogress_goodaddr;
  3017. continue;
  3018. }
  3019. /* Never return a connection that shouldn't be used for circs. */
  3020. if (channel_is_bad_for_new_circs(chan)) {
  3021. ++n_old;
  3022. continue;
  3023. }
  3024. /* Never return a non-canonical connection using a recent link protocol
  3025. * if the address is not what we wanted.
  3026. *
  3027. * The channel_is_canonical_is_reliable() function asks the lower layer
  3028. * if we should trust channel_is_canonical(). The below is from the
  3029. * comments of the old circuit_or_get_for_extend() and applies when
  3030. * the lower-layer transport is channel_tls_t.
  3031. *
  3032. * (For old link protocols, we can't rely on is_canonical getting
  3033. * set properly if we're talking to the right address, since we might
  3034. * have an out-of-date descriptor, and we will get no NETINFO cell to
  3035. * tell us about the right address.)
  3036. */
  3037. if (!channel_is_canonical(chan) &&
  3038. channel_is_canonical_is_reliable(chan) &&
  3039. !channel_matches_target_addr_for_extend(chan, target_addr)) {
  3040. ++n_noncanonical;
  3041. continue;
  3042. }
  3043. ++n_possible;
  3044. if (!best) {
  3045. best = chan; /* If we have no 'best' so far, this one is good enough. */
  3046. continue;
  3047. }
  3048. if (channel_is_better(chan, best))
  3049. best = chan;
  3050. }
  3051. if (best) {
  3052. *msg_out = "Connection is fine; using it.";
  3053. *launch_out = 0;
  3054. return best;
  3055. } else if (n_inprogress_goodaddr) {
  3056. *msg_out = "Connection in progress; waiting.";
  3057. *launch_out = 0;
  3058. return NULL;
  3059. } else if (n_old || n_noncanonical) {
  3060. *msg_out = "Connections all too old, or too non-canonical. "
  3061. " Launching a new one.";
  3062. *launch_out = 1;
  3063. return NULL;
  3064. } else {
  3065. *msg_out = "Not connected. Connecting.";
  3066. *launch_out = 1;
  3067. return NULL;
  3068. }
  3069. }
  3070. /**
  3071. * Describe the transport subclass for a channel
  3072. *
  3073. * Invoke a method to get a string description of the lower-layer
  3074. * transport for this channel.
  3075. */
  3076. const char *
  3077. channel_describe_transport(channel_t *chan)
  3078. {
  3079. tor_assert(chan);
  3080. tor_assert(chan->describe_transport);
  3081. return chan->describe_transport(chan);
  3082. }
  3083. /**
  3084. * Describe the transport subclass for a channel listener
  3085. *
  3086. * Invoke a method to get a string description of the lower-layer
  3087. * transport for this channel listener.
  3088. */
  3089. const char *
  3090. channel_listener_describe_transport(channel_listener_t *chan_l)
  3091. {
  3092. tor_assert(chan_l);
  3093. tor_assert(chan_l->describe_transport);
  3094. return chan_l->describe_transport(chan_l);
  3095. }
  3096. /**
  3097. * Return the number of entries in <b>queue</b>
  3098. */
  3099. STATIC int
  3100. chan_cell_queue_len(const chan_cell_queue_t *queue)
  3101. {
  3102. int r = 0;
  3103. cell_queue_entry_t *cell;
  3104. TOR_SIMPLEQ_FOREACH(cell, queue, next)
  3105. ++r;
  3106. return r;
  3107. }
  3108. /**
  3109. * Dump channel statistics
  3110. *
  3111. * Dump statistics for one channel to the log
  3112. */
  3113. MOCK_IMPL(void,
  3114. channel_dump_statistics, (channel_t *chan, int severity))
  3115. {
  3116. double avg, interval, age;
  3117. time_t now = time(NULL);
  3118. tor_addr_t remote_addr;
  3119. int have_remote_addr;
  3120. char *remote_addr_str;
  3121. tor_assert(chan);
  3122. age = (double)(now - chan->timestamp_created);
  3123. tor_log(severity, LD_GENERAL,
  3124. "Channel " U64_FORMAT " (at %p) with transport %s is in state "
  3125. "%s (%d)",
  3126. U64_PRINTF_ARG(chan->global_identifier), chan,
  3127. channel_describe_transport(chan),
  3128. channel_state_to_string(chan->state), chan->state);
  3129. tor_log(severity, LD_GENERAL,
  3130. " * Channel " U64_FORMAT " was created at " U64_FORMAT
  3131. " (" U64_FORMAT " seconds ago) "
  3132. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3133. U64_PRINTF_ARG(chan->global_identifier),
  3134. U64_PRINTF_ARG(chan->timestamp_created),
  3135. U64_PRINTF_ARG(now - chan->timestamp_created),
  3136. U64_PRINTF_ARG(chan->timestamp_active),
  3137. U64_PRINTF_ARG(now - chan->timestamp_active));
  3138. /* Handle digest and nickname */
  3139. if (!tor_digest_is_zero(chan->identity_digest)) {
  3140. if (chan->nickname) {
  3141. tor_log(severity, LD_GENERAL,
  3142. " * Channel " U64_FORMAT " says it is connected "
  3143. "to an OR with digest %s and nickname %s",
  3144. U64_PRINTF_ARG(chan->global_identifier),
  3145. hex_str(chan->identity_digest, DIGEST_LEN),
  3146. chan->nickname);
  3147. } else {
  3148. tor_log(severity, LD_GENERAL,
  3149. " * Channel " U64_FORMAT " says it is connected "
  3150. "to an OR with digest %s and no known nickname",
  3151. U64_PRINTF_ARG(chan->global_identifier),
  3152. hex_str(chan->identity_digest, DIGEST_LEN));
  3153. }
  3154. } else {
  3155. if (chan->nickname) {
  3156. tor_log(severity, LD_GENERAL,
  3157. " * Channel " U64_FORMAT " does not know the digest"
  3158. " of the OR it is connected to, but reports its nickname is %s",
  3159. U64_PRINTF_ARG(chan->global_identifier),
  3160. chan->nickname);
  3161. } else {
  3162. tor_log(severity, LD_GENERAL,
  3163. " * Channel " U64_FORMAT " does not know the digest"
  3164. " or the nickname of the OR it is connected to",
  3165. U64_PRINTF_ARG(chan->global_identifier));
  3166. }
  3167. }
  3168. /* Handle remote address and descriptions */
  3169. have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
  3170. if (have_remote_addr) {
  3171. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3172. remote_addr_str = tor_addr_to_str_dup(&remote_addr);
  3173. tor_log(severity, LD_GENERAL,
  3174. " * Channel " U64_FORMAT " says its remote address"
  3175. " is %s, and gives a canonical description of \"%s\" and an "
  3176. "actual description of \"%s\"",
  3177. U64_PRINTF_ARG(chan->global_identifier),
  3178. safe_str(remote_addr_str),
  3179. safe_str(channel_get_canonical_remote_descr(chan)),
  3180. safe_str(actual));
  3181. tor_free(remote_addr_str);
  3182. tor_free(actual);
  3183. } else {
  3184. char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
  3185. tor_log(severity, LD_GENERAL,
  3186. " * Channel " U64_FORMAT " does not know its remote "
  3187. "address, but gives a canonical description of \"%s\" and an "
  3188. "actual description of \"%s\"",
  3189. U64_PRINTF_ARG(chan->global_identifier),
  3190. channel_get_canonical_remote_descr(chan),
  3191. actual);
  3192. tor_free(actual);
  3193. }
  3194. /* Handle marks */
  3195. tor_log(severity, LD_GENERAL,
  3196. " * Channel " U64_FORMAT " has these marks: %s %s %s "
  3197. "%s %s %s",
  3198. U64_PRINTF_ARG(chan->global_identifier),
  3199. channel_is_bad_for_new_circs(chan) ?
  3200. "bad_for_new_circs" : "!bad_for_new_circs",
  3201. channel_is_canonical(chan) ?
  3202. "canonical" : "!canonical",
  3203. channel_is_canonical_is_reliable(chan) ?
  3204. "is_canonical_is_reliable" :
  3205. "!is_canonical_is_reliable",
  3206. channel_is_client(chan) ?
  3207. "client" : "!client",
  3208. channel_is_local(chan) ?
  3209. "local" : "!local",
  3210. channel_is_incoming(chan) ?
  3211. "incoming" : "outgoing");
  3212. /* Describe queues */
  3213. tor_log(severity, LD_GENERAL,
  3214. " * Channel " U64_FORMAT " has %d queued incoming cells"
  3215. " and %d queued outgoing cells",
  3216. U64_PRINTF_ARG(chan->global_identifier),
  3217. chan_cell_queue_len(&chan->incoming_queue),
  3218. chan_cell_queue_len(&chan->outgoing_queue));
  3219. /* Describe circuits */
  3220. tor_log(severity, LD_GENERAL,
  3221. " * Channel " U64_FORMAT " has %d active circuits out of"
  3222. " %d in total",
  3223. U64_PRINTF_ARG(chan->global_identifier),
  3224. (chan->cmux != NULL) ?
  3225. circuitmux_num_active_circuits(chan->cmux) : 0,
  3226. (chan->cmux != NULL) ?
  3227. circuitmux_num_circuits(chan->cmux) : 0);
  3228. /* Describe timestamps */
  3229. tor_log(severity, LD_GENERAL,
  3230. " * Channel " U64_FORMAT " was last used by a "
  3231. "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3232. U64_PRINTF_ARG(chan->global_identifier),
  3233. U64_PRINTF_ARG(chan->timestamp_client),
  3234. U64_PRINTF_ARG(now - chan->timestamp_client));
  3235. tor_log(severity, LD_GENERAL,
  3236. " * Channel " U64_FORMAT " was last drained at "
  3237. U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3238. U64_PRINTF_ARG(chan->global_identifier),
  3239. U64_PRINTF_ARG(chan->timestamp_drained),
  3240. U64_PRINTF_ARG(now - chan->timestamp_drained));
  3241. tor_log(severity, LD_GENERAL,
  3242. " * Channel " U64_FORMAT " last received a cell "
  3243. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3244. U64_PRINTF_ARG(chan->global_identifier),
  3245. U64_PRINTF_ARG(chan->timestamp_recv),
  3246. U64_PRINTF_ARG(now - chan->timestamp_recv));
  3247. tor_log(severity, LD_GENERAL,
  3248. " * Channel " U64_FORMAT " last transmitted a cell "
  3249. "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3250. U64_PRINTF_ARG(chan->global_identifier),
  3251. U64_PRINTF_ARG(chan->timestamp_xmit),
  3252. U64_PRINTF_ARG(now - chan->timestamp_xmit));
  3253. /* Describe counters and rates */
  3254. tor_log(severity, LD_GENERAL,
  3255. " * Channel " U64_FORMAT " has received "
  3256. U64_FORMAT " bytes in " U64_FORMAT " cells and transmitted "
  3257. U64_FORMAT " bytes in " U64_FORMAT " cells",
  3258. U64_PRINTF_ARG(chan->global_identifier),
  3259. U64_PRINTF_ARG(chan->n_bytes_recved),
  3260. U64_PRINTF_ARG(chan->n_cells_recved),
  3261. U64_PRINTF_ARG(chan->n_bytes_xmitted),
  3262. U64_PRINTF_ARG(chan->n_cells_xmitted));
  3263. if (now > chan->timestamp_created &&
  3264. chan->timestamp_created > 0) {
  3265. if (chan->n_bytes_recved > 0) {
  3266. avg = (double)(chan->n_bytes_recved) / age;
  3267. tor_log(severity, LD_GENERAL,
  3268. " * Channel " U64_FORMAT " has averaged %f "
  3269. "bytes received per second",
  3270. U64_PRINTF_ARG(chan->global_identifier), avg);
  3271. }
  3272. if (chan->n_cells_recved > 0) {
  3273. avg = (double)(chan->n_cells_recved) / age;
  3274. if (avg >= 1.0) {
  3275. tor_log(severity, LD_GENERAL,
  3276. " * Channel " U64_FORMAT " has averaged %f "
  3277. "cells received per second",
  3278. U64_PRINTF_ARG(chan->global_identifier), avg);
  3279. } else if (avg >= 0.0) {
  3280. interval = 1.0 / avg;
  3281. tor_log(severity, LD_GENERAL,
  3282. " * Channel " U64_FORMAT " has averaged %f "
  3283. "seconds between received cells",
  3284. U64_PRINTF_ARG(chan->global_identifier), interval);
  3285. }
  3286. }
  3287. if (chan->n_bytes_xmitted > 0) {
  3288. avg = (double)(chan->n_bytes_xmitted) / age;
  3289. tor_log(severity, LD_GENERAL,
  3290. " * Channel " U64_FORMAT " has averaged %f "
  3291. "bytes transmitted per second",
  3292. U64_PRINTF_ARG(chan->global_identifier), avg);
  3293. }
  3294. if (chan->n_cells_xmitted > 0) {
  3295. avg = (double)(chan->n_cells_xmitted) / age;
  3296. if (avg >= 1.0) {
  3297. tor_log(severity, LD_GENERAL,
  3298. " * Channel " U64_FORMAT " has averaged %f "
  3299. "cells transmitted per second",
  3300. U64_PRINTF_ARG(chan->global_identifier), avg);
  3301. } else if (avg >= 0.0) {
  3302. interval = 1.0 / avg;
  3303. tor_log(severity, LD_GENERAL,
  3304. " * Channel " U64_FORMAT " has averaged %f "
  3305. "seconds between transmitted cells",
  3306. U64_PRINTF_ARG(chan->global_identifier), interval);
  3307. }
  3308. }
  3309. }
  3310. /* Dump anything the lower layer has to say */
  3311. channel_dump_transport_statistics(chan, severity);
  3312. }
  3313. /**
  3314. * Dump channel listener statistics
  3315. *
  3316. * Dump statistics for one channel listener to the log
  3317. */
  3318. void
  3319. channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
  3320. {
  3321. double avg, interval, age;
  3322. time_t now = time(NULL);
  3323. tor_assert(chan_l);
  3324. age = (double)(now - chan_l->timestamp_created);
  3325. tor_log(severity, LD_GENERAL,
  3326. "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
  3327. "state %s (%d)",
  3328. U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
  3329. channel_listener_describe_transport(chan_l),
  3330. channel_listener_state_to_string(chan_l->state), chan_l->state);
  3331. tor_log(severity, LD_GENERAL,
  3332. " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
  3333. " (" U64_FORMAT " seconds ago) "
  3334. "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
  3335. U64_PRINTF_ARG(chan_l->global_identifier),
  3336. U64_PRINTF_ARG(chan_l->timestamp_created),
  3337. U64_PRINTF_ARG(now - chan_l->timestamp_created),
  3338. U64_PRINTF_ARG(chan_l->timestamp_active),
  3339. U64_PRINTF_ARG(now - chan_l->timestamp_active));
  3340. tor_log(severity, LD_GENERAL,
  3341. " * Channel listener " U64_FORMAT " last accepted an incoming "
  3342. "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
  3343. "and has accepted " U64_FORMAT " channels in total",
  3344. U64_PRINTF_ARG(chan_l->global_identifier),
  3345. U64_PRINTF_ARG(chan_l->timestamp_accepted),
  3346. U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
  3347. U64_PRINTF_ARG(chan_l->n_accepted));
  3348. /*
  3349. * If it's sensible to do so, get the rate of incoming channels on this
  3350. * listener
  3351. */
  3352. if (now > chan_l->timestamp_created &&
  3353. chan_l->timestamp_created > 0 &&
  3354. chan_l->n_accepted > 0) {
  3355. avg = (double)(chan_l->n_accepted) / age;
  3356. if (avg >= 1.0) {
  3357. tor_log(severity, LD_GENERAL,
  3358. " * Channel listener " U64_FORMAT " has averaged %f incoming "
  3359. "channels per second",
  3360. U64_PRINTF_ARG(chan_l->global_identifier), avg);
  3361. } else if (avg >= 0.0) {
  3362. interval = 1.0 / avg;
  3363. tor_log(severity, LD_GENERAL,
  3364. " * Channel listener " U64_FORMAT " has averaged %f seconds "
  3365. "between incoming channels",
  3366. U64_PRINTF_ARG(chan_l->global_identifier), interval);
  3367. }
  3368. }
  3369. /* Dump anything the lower layer has to say */
  3370. channel_listener_dump_transport_statistics(chan_l, severity);
  3371. }
  3372. /**
  3373. * Invoke transport-specific stats dump for channel
  3374. *
  3375. * If there is a lower-layer statistics dump method, invoke it
  3376. */
  3377. void
  3378. channel_dump_transport_statistics(channel_t *chan, int severity)
  3379. {
  3380. tor_assert(chan);
  3381. if (chan->dumpstats) chan->dumpstats(chan, severity);
  3382. }
  3383. /**
  3384. * Invoke transport-specific stats dump for channel listener
  3385. *
  3386. * If there is a lower-layer statistics dump method, invoke it
  3387. */
  3388. void
  3389. channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
  3390. int severity)
  3391. {
  3392. tor_assert(chan_l);
  3393. if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
  3394. }
  3395. /**
  3396. * Return text description of the remote endpoint
  3397. *
  3398. * This function return a test provided by the lower layer of the remote
  3399. * endpoint for this channel; it should specify the actual address connected
  3400. * to/from.
  3401. *
  3402. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3403. * may invalidate the return value from this function.
  3404. */
  3405. const char *
  3406. channel_get_actual_remote_descr(channel_t *chan)
  3407. {
  3408. tor_assert(chan);
  3409. tor_assert(chan->get_remote_descr);
  3410. /* Param 1 indicates the actual description */
  3411. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
  3412. }
  3413. /**
  3414. * Return the text address of the remote endpoint.
  3415. *
  3416. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3417. * may invalidate the return value from this function.
  3418. */
  3419. const char *
  3420. channel_get_actual_remote_address(channel_t *chan)
  3421. {
  3422. /* Param 1 indicates the actual description */
  3423. return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
  3424. }
  3425. /**
  3426. * Return text description of the remote endpoint canonical address
  3427. *
  3428. * This function return a test provided by the lower layer of the remote
  3429. * endpoint for this channel; it should use the known canonical address for
  3430. * this OR's identity digest if possible.
  3431. *
  3432. * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
  3433. * may invalidate the return value from this function.
  3434. */
  3435. const char *
  3436. channel_get_canonical_remote_descr(channel_t *chan)
  3437. {
  3438. tor_assert(chan);
  3439. tor_assert(chan->get_remote_descr);
  3440. /* Param 0 indicates the canonicalized description */
  3441. return chan->get_remote_descr(chan, 0);
  3442. }
  3443. /**
  3444. * Get remote address if possible.
  3445. *
  3446. * Write the remote address out to a tor_addr_t if the underlying transport
  3447. * supports this operation, and return 1. Return 0 if the underlying transport
  3448. * doesn't let us do this.
  3449. */
  3450. int
  3451. channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
  3452. {
  3453. tor_assert(chan);
  3454. tor_assert(addr_out);
  3455. if (chan->get_remote_addr)
  3456. return chan->get_remote_addr(chan, addr_out);
  3457. /* Else no support, method not implemented */
  3458. else return 0;
  3459. }
  3460. /**
  3461. * Check if there are outgoing queue writes on this channel
  3462. *
  3463. * Indicate if either we have queued cells, or if not, whether the underlying
  3464. * lower-layer transport thinks it has an output queue.
  3465. */
  3466. int
  3467. channel_has_queued_writes(channel_t *chan)
  3468. {
  3469. int has_writes = 0;
  3470. tor_assert(chan);
  3471. tor_assert(chan->has_queued_writes);
  3472. if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
  3473. has_writes = 1;
  3474. } else {
  3475. /* Check with the lower layer */
  3476. has_writes = chan->has_queued_writes(chan);
  3477. }
  3478. return has_writes;
  3479. }
  3480. /**
  3481. * Check the is_bad_for_new_circs flag
  3482. *
  3483. * This function returns the is_bad_for_new_circs flag of the specified
  3484. * channel.
  3485. */
  3486. int
  3487. channel_is_bad_for_new_circs(channel_t *chan)
  3488. {
  3489. tor_assert(chan);
  3490. return chan->is_bad_for_new_circs;
  3491. }
  3492. /**
  3493. * Mark a channel as bad for new circuits
  3494. *
  3495. * Set the is_bad_for_new_circs_flag on chan.
  3496. */
  3497. void
  3498. channel_mark_bad_for_new_circs(channel_t *chan)
  3499. {
  3500. tor_assert(chan);
  3501. chan->is_bad_for_new_circs = 1;
  3502. }
  3503. /**
  3504. * Get the client flag
  3505. *
  3506. * This returns the client flag of a channel, which will be set if
  3507. * command_process_create_cell() in command.c thinks this is a connection
  3508. * from a client.
  3509. */
  3510. int
  3511. channel_is_client(const channel_t *chan)
  3512. {
  3513. tor_assert(chan);
  3514. return chan->is_client;
  3515. }
  3516. /**
  3517. * Set the client flag
  3518. *
  3519. * Mark a channel as being from a client
  3520. */
  3521. void
  3522. channel_mark_client(channel_t *chan)
  3523. {
  3524. tor_assert(chan);
  3525. chan->is_client = 1;
  3526. }
  3527. /**
  3528. * Clear the client flag
  3529. *
  3530. * Mark a channel as being _not_ from a client
  3531. */
  3532. void
  3533. channel_clear_client(channel_t *chan)
  3534. {
  3535. tor_assert(chan);
  3536. chan->is_client = 0;
  3537. }
  3538. /**
  3539. * Get the canonical flag for a channel
  3540. *
  3541. * This returns the is_canonical for a channel; this flag is determined by
  3542. * the lower layer and can't be set in a transport-independent way.
  3543. */
  3544. int
  3545. channel_is_canonical(channel_t *chan)
  3546. {
  3547. tor_assert(chan);
  3548. tor_assert(chan->is_canonical);
  3549. return chan->is_canonical(chan, 0);
  3550. }
  3551. /**
  3552. * Test if the canonical flag is reliable
  3553. *
  3554. * This function asks if the lower layer thinks it's safe to trust the
  3555. * result of channel_is_canonical()
  3556. */
  3557. int
  3558. channel_is_canonical_is_reliable(channel_t *chan)
  3559. {
  3560. tor_assert(chan);
  3561. tor_assert(chan->is_canonical);
  3562. return chan->is_canonical(chan, 1);
  3563. }
  3564. /**
  3565. * Test incoming flag
  3566. *
  3567. * This function gets the incoming flag; this is set when a listener spawns
  3568. * a channel. If this returns true the channel was remotely initiated.
  3569. */
  3570. int
  3571. channel_is_incoming(channel_t *chan)
  3572. {
  3573. tor_assert(chan);
  3574. return chan->is_incoming;
  3575. }
  3576. /**
  3577. * Set the incoming flag
  3578. *
  3579. * This function is called when a channel arrives on a listening channel
  3580. * to mark it as incoming.
  3581. */
  3582. void
  3583. channel_mark_incoming(channel_t *chan)
  3584. {
  3585. tor_assert(chan);
  3586. chan->is_incoming = 1;
  3587. }
  3588. /**
  3589. * Test local flag
  3590. *
  3591. * This function gets the local flag; the lower layer should set this when
  3592. * setting up the channel if is_local_addr() is true for all of the
  3593. * destinations it will communicate with on behalf of this channel. It's
  3594. * used to decide whether to declare the network reachable when seeing incoming
  3595. * traffic on the channel.
  3596. */
  3597. int
  3598. channel_is_local(channel_t *chan)
  3599. {
  3600. tor_assert(chan);
  3601. return chan->is_local;
  3602. }
  3603. /**
  3604. * Set the local flag
  3605. *
  3606. * This internal-only function should be called by the lower layer if the
  3607. * channel is to a local address. See channel_is_local() above or the
  3608. * description of the is_local bit in channel.h
  3609. */
  3610. void
  3611. channel_mark_local(channel_t *chan)
  3612. {
  3613. tor_assert(chan);
  3614. chan->is_local = 1;
  3615. }
  3616. /**
  3617. * Mark a channel as remote
  3618. *
  3619. * This internal-only function should be called by the lower layer if the
  3620. * channel is not to a local address but has previously been marked local.
  3621. * See channel_is_local() above or the description of the is_local bit in
  3622. * channel.h
  3623. */
  3624. void
  3625. channel_mark_remote(channel_t *chan)
  3626. {
  3627. tor_assert(chan);
  3628. chan->is_local = 0;
  3629. }
  3630. /**
  3631. * Test outgoing flag
  3632. *
  3633. * This function gets the outgoing flag; this is the inverse of the incoming
  3634. * bit set when a listener spawns a channel. If this returns true the channel
  3635. * was locally initiated.
  3636. */
  3637. int
  3638. channel_is_outgoing(channel_t *chan)
  3639. {
  3640. tor_assert(chan);
  3641. return !(chan->is_incoming);
  3642. }
  3643. /**
  3644. * Mark a channel as outgoing
  3645. *
  3646. * This function clears the incoming flag and thus marks a channel as
  3647. * outgoing.
  3648. */
  3649. void
  3650. channel_mark_outgoing(channel_t *chan)
  3651. {
  3652. tor_assert(chan);
  3653. chan->is_incoming = 0;
  3654. }
  3655. /************************
  3656. * Flow control queries *
  3657. ***********************/
  3658. /*
  3659. * Get the latest estimate for the total queue size of all open channels
  3660. */
  3661. uint64_t
  3662. channel_get_global_queue_estimate(void)
  3663. {
  3664. return estimated_total_queue_size;
  3665. }
  3666. /*
  3667. * Estimate the number of writeable cells
  3668. *
  3669. * Ask the lower layer for an estimate of how many cells it can accept, and
  3670. * then subtract the length of our outgoing_queue, if any, to produce an
  3671. * estimate of the number of cells this channel can accept for writes.
  3672. */
  3673. int
  3674. channel_num_cells_writeable(channel_t *chan)
  3675. {
  3676. int result;
  3677. tor_assert(chan);
  3678. tor_assert(chan->num_cells_writeable);
  3679. if (chan->state == CHANNEL_STATE_OPEN) {
  3680. /* Query lower layer */
  3681. result = chan->num_cells_writeable(chan);
  3682. /* Subtract cell queue length, if any */
  3683. result -= chan_cell_queue_len(&chan->outgoing_queue);
  3684. if (result < 0) result = 0;
  3685. } else {
  3686. /* No cells are writeable in any other state */
  3687. result = 0;
  3688. }
  3689. return result;
  3690. }
  3691. /*********************
  3692. * Timestamp updates *
  3693. ********************/
  3694. /**
  3695. * Update the created timestamp for a channel
  3696. *
  3697. * This updates the channel's created timestamp and should only be called
  3698. * from channel_init().
  3699. */
  3700. void
  3701. channel_timestamp_created(channel_t *chan)
  3702. {
  3703. time_t now = time(NULL);
  3704. tor_assert(chan);
  3705. chan->timestamp_created = now;
  3706. }
  3707. /**
  3708. * Update the created timestamp for a channel listener
  3709. *
  3710. * This updates the channel listener's created timestamp and should only be
  3711. * called from channel_init_listener().
  3712. */
  3713. void
  3714. channel_listener_timestamp_created(channel_listener_t *chan_l)
  3715. {
  3716. time_t now = time(NULL);
  3717. tor_assert(chan_l);
  3718. chan_l->timestamp_created = now;
  3719. }
  3720. /**
  3721. * Update the last active timestamp for a channel
  3722. *
  3723. * This function updates the channel's last active timestamp; it should be
  3724. * called by the lower layer whenever there is activity on the channel which
  3725. * does not lead to a cell being transmitted or received; the active timestamp
  3726. * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
  3727. * but it should be updated for things like the v3 handshake and stuff that
  3728. * produce activity only visible to the lower layer.
  3729. */
  3730. void
  3731. channel_timestamp_active(channel_t *chan)
  3732. {
  3733. time_t now = time(NULL);
  3734. tor_assert(chan);
  3735. chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
  3736. chan->timestamp_active = now;
  3737. /* Clear any potential netflow padding timer. We're active */
  3738. chan->next_padding_time_ms = 0;
  3739. }
  3740. /**
  3741. * Update the last active timestamp for a channel listener
  3742. */
  3743. void
  3744. channel_listener_timestamp_active(channel_listener_t *chan_l)
  3745. {
  3746. time_t now = time(NULL);
  3747. tor_assert(chan_l);
  3748. chan_l->timestamp_active = now;
  3749. }
  3750. /**
  3751. * Update the last accepted timestamp.
  3752. *
  3753. * This function updates the channel listener's last accepted timestamp; it
  3754. * should be called whenever a new incoming channel is accepted on a
  3755. * listener.
  3756. */
  3757. void
  3758. channel_listener_timestamp_accepted(channel_listener_t *chan_l)
  3759. {
  3760. time_t now = time(NULL);
  3761. tor_assert(chan_l);
  3762. chan_l->timestamp_active = now;
  3763. chan_l->timestamp_accepted = now;
  3764. }
  3765. /**
  3766. * Update client timestamp
  3767. *
  3768. * This function is called by relay.c to timestamp a channel that appears to
  3769. * be used as a client.
  3770. */
  3771. void
  3772. channel_timestamp_client(channel_t *chan)
  3773. {
  3774. time_t now = time(NULL);
  3775. tor_assert(chan);
  3776. chan->timestamp_client = now;
  3777. }
  3778. /**
  3779. * Update the last drained timestamp
  3780. *
  3781. * This is called whenever we transmit a cell which leaves the outgoing cell
  3782. * queue completely empty. It also updates the xmit time and the active time.
  3783. */
  3784. void
  3785. channel_timestamp_drained(channel_t *chan)
  3786. {
  3787. time_t now = time(NULL);
  3788. tor_assert(chan);
  3789. chan->timestamp_active = now;
  3790. chan->timestamp_drained = now;
  3791. chan->timestamp_xmit = now;
  3792. }
  3793. /**
  3794. * Update the recv timestamp
  3795. *
  3796. * This is called whenever we get an incoming cell from the lower layer.
  3797. * This also updates the active timestamp.
  3798. */
  3799. void
  3800. channel_timestamp_recv(channel_t *chan)
  3801. {
  3802. time_t now = time(NULL);
  3803. tor_assert(chan);
  3804. chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
  3805. chan->timestamp_active = now;
  3806. chan->timestamp_recv = now;
  3807. /* Clear any potential netflow padding timer. We're active */
  3808. chan->next_padding_time_ms = 0;
  3809. }
  3810. /**
  3811. * Update the xmit timestamp
  3812. * This is called whenever we pass an outgoing cell to the lower layer. This
  3813. * also updates the active timestamp.
  3814. */
  3815. void
  3816. channel_timestamp_xmit(channel_t *chan)
  3817. {
  3818. time_t now = time(NULL);
  3819. tor_assert(chan);
  3820. chan->timestamp_xfer_ms = monotime_coarse_absolute_msec();
  3821. chan->timestamp_active = now;
  3822. chan->timestamp_xmit = now;
  3823. /* Clear any potential netflow padding timer. We're active */
  3824. chan->next_padding_time_ms = 0;
  3825. }
  3826. /***************************************************************
  3827. * Timestamp queries - see above for definitions of timestamps *
  3828. **************************************************************/
  3829. /**
  3830. * Query created timestamp for a channel
  3831. */
  3832. time_t
  3833. channel_when_created(channel_t *chan)
  3834. {
  3835. tor_assert(chan);
  3836. return chan->timestamp_created;
  3837. }
  3838. /**
  3839. * Query created timestamp for a channel listener
  3840. */
  3841. time_t
  3842. channel_listener_when_created(channel_listener_t *chan_l)
  3843. {
  3844. tor_assert(chan_l);
  3845. return chan_l->timestamp_created;
  3846. }
  3847. /**
  3848. * Query last active timestamp for a channel
  3849. */
  3850. time_t
  3851. channel_when_last_active(channel_t *chan)
  3852. {
  3853. tor_assert(chan);
  3854. return chan->timestamp_active;
  3855. }
  3856. /**
  3857. * Query last active timestamp for a channel listener
  3858. */
  3859. time_t
  3860. channel_listener_when_last_active(channel_listener_t *chan_l)
  3861. {
  3862. tor_assert(chan_l);
  3863. return chan_l->timestamp_active;
  3864. }
  3865. /**
  3866. * Query last accepted timestamp for a channel listener
  3867. */
  3868. time_t
  3869. channel_listener_when_last_accepted(channel_listener_t *chan_l)
  3870. {
  3871. tor_assert(chan_l);
  3872. return chan_l->timestamp_accepted;
  3873. }
  3874. /**
  3875. * Query client timestamp
  3876. */
  3877. time_t
  3878. channel_when_last_client(channel_t *chan)
  3879. {
  3880. tor_assert(chan);
  3881. return chan->timestamp_client;
  3882. }
  3883. /**
  3884. * Query drained timestamp
  3885. */
  3886. time_t
  3887. channel_when_last_drained(channel_t *chan)
  3888. {
  3889. tor_assert(chan);
  3890. return chan->timestamp_drained;
  3891. }
  3892. /**
  3893. * Query recv timestamp
  3894. */
  3895. time_t
  3896. channel_when_last_recv(channel_t *chan)
  3897. {
  3898. tor_assert(chan);
  3899. return chan->timestamp_recv;
  3900. }
  3901. /**
  3902. * Query xmit timestamp
  3903. */
  3904. time_t
  3905. channel_when_last_xmit(channel_t *chan)
  3906. {
  3907. tor_assert(chan);
  3908. return chan->timestamp_xmit;
  3909. }
  3910. /**
  3911. * Query accepted counter
  3912. */
  3913. uint64_t
  3914. channel_listener_count_accepted(channel_listener_t *chan_l)
  3915. {
  3916. tor_assert(chan_l);
  3917. return chan_l->n_accepted;
  3918. }
  3919. /**
  3920. * Query received cell counter
  3921. */
  3922. uint64_t
  3923. channel_count_recved(channel_t *chan)
  3924. {
  3925. tor_assert(chan);
  3926. return chan->n_cells_recved;
  3927. }
  3928. /**
  3929. * Query transmitted cell counter
  3930. */
  3931. uint64_t
  3932. channel_count_xmitted(channel_t *chan)
  3933. {
  3934. tor_assert(chan);
  3935. return chan->n_cells_xmitted;
  3936. }
  3937. /**
  3938. * Check if a channel matches an extend_info_t
  3939. *
  3940. * This function calls the lower layer and asks if this channel matches a
  3941. * given extend_info_t.
  3942. */
  3943. int
  3944. channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
  3945. {
  3946. tor_assert(chan);
  3947. tor_assert(chan->matches_extend_info);
  3948. tor_assert(extend_info);
  3949. return chan->matches_extend_info(chan, extend_info);
  3950. }
  3951. /**
  3952. * Check if a channel matches a given target address; return true iff we do.
  3953. *
  3954. * This function calls into the lower layer and asks if this channel thinks
  3955. * it matches a given target address for circuit extension purposes.
  3956. */
  3957. int
  3958. channel_matches_target_addr_for_extend(channel_t *chan,
  3959. const tor_addr_t *target)
  3960. {
  3961. tor_assert(chan);
  3962. tor_assert(chan->matches_target);
  3963. tor_assert(target);
  3964. return chan->matches_target(chan, target);
  3965. }
  3966. /**
  3967. * Return the total number of circuits used by a channel
  3968. *
  3969. * @param chan Channel to query
  3970. * @return Number of circuits using this as n_chan or p_chan
  3971. */
  3972. unsigned int
  3973. channel_num_circuits(channel_t *chan)
  3974. {
  3975. tor_assert(chan);
  3976. return chan->num_n_circuits +
  3977. chan->num_p_circuits;
  3978. }
  3979. /**
  3980. * Set up circuit ID generation
  3981. *
  3982. * This is called when setting up a channel and replaces the old
  3983. * connection_or_set_circid_type()
  3984. */
  3985. MOCK_IMPL(void,
  3986. channel_set_circid_type,(channel_t *chan,
  3987. crypto_pk_t *identity_rcvd,
  3988. int consider_identity))
  3989. {
  3990. int started_here;
  3991. crypto_pk_t *our_identity;
  3992. tor_assert(chan);
  3993. started_here = channel_is_outgoing(chan);
  3994. if (! consider_identity) {
  3995. if (started_here)
  3996. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  3997. else
  3998. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  3999. return;
  4000. }
  4001. our_identity = started_here ?
  4002. get_tlsclient_identity_key() : get_server_identity_key();
  4003. if (identity_rcvd) {
  4004. if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
  4005. chan->circ_id_type = CIRC_ID_TYPE_LOWER;
  4006. } else {
  4007. chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
  4008. }
  4009. } else {
  4010. chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
  4011. }
  4012. }
  4013. /** Helper for channel_update_bad_for_new_circs(): Perform the
  4014. * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
  4015. * all of which MUST have the same RSA ID. (They MAY have different
  4016. * Ed25519 IDs.) */
  4017. static void
  4018. channel_rsa_id_group_set_badness(struct channel_list_s *lst, int force)
  4019. {
  4020. /*XXXX This function should really be about channels. 15056 */
  4021. channel_t *chan;
  4022. /* First, get a minimal list of the ed25519 identites */
  4023. smartlist_t *ed_identities = smartlist_new();
  4024. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  4025. uint8_t *id_copy =
  4026. tor_memdup(&chan->ed25519_identity.pubkey, DIGEST256_LEN);
  4027. smartlist_add(ed_identities, id_copy);
  4028. }
  4029. smartlist_sort_digests256(ed_identities);
  4030. smartlist_uniq_digests256(ed_identities);
  4031. /* Now, for each Ed identity, build a smartlist and find the best entry on
  4032. * it. */
  4033. smartlist_t *or_conns = smartlist_new();
  4034. SMARTLIST_FOREACH_BEGIN(ed_identities, const uint8_t *, ed_id) {
  4035. TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
  4036. channel_tls_t *chantls = BASE_CHAN_TO_TLS(chan);
  4037. if (tor_memneq(ed_id, &chan->ed25519_identity.pubkey, DIGEST256_LEN))
  4038. continue;
  4039. or_connection_t *orconn = chantls->conn;
  4040. if (orconn) {
  4041. tor_assert(orconn->chan == chantls);
  4042. smartlist_add(or_conns, orconn);
  4043. }
  4044. }
  4045. connection_or_group_set_badness_(or_conns, force);
  4046. smartlist_clear(or_conns);
  4047. } SMARTLIST_FOREACH_END(ed_id);
  4048. /* XXXX 15056 we may want to do something special with connections that have
  4049. * no set Ed25519 identity! */
  4050. smartlist_free(or_conns);
  4051. SMARTLIST_FOREACH(ed_identities, uint8_t *, ed_id, tor_free(ed_id));
  4052. smartlist_free(ed_identities);
  4053. }
  4054. /** Go through all the channels (or if <b>digest</b> is non-NULL, just
  4055. * the OR connections with that digest), and set the is_bad_for_new_circs
  4056. * flag based on the rules in connection_or_group_set_badness() (or just
  4057. * always set it if <b>force</b> is true).
  4058. */
  4059. void
  4060. channel_update_bad_for_new_circs(const char *digest, int force)
  4061. {
  4062. if (digest) {
  4063. channel_idmap_entry_t *ent;
  4064. channel_idmap_entry_t search;
  4065. memset(&search, 0, sizeof(search));
  4066. memcpy(search.digest, digest, DIGEST_LEN);
  4067. ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
  4068. if (ent) {
  4069. channel_rsa_id_group_set_badness(&ent->channel_list, force);
  4070. }
  4071. return;
  4072. }
  4073. /* no digest; just look at everything. */
  4074. channel_idmap_entry_t **iter;
  4075. HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
  4076. channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
  4077. }
  4078. }
  4079. /**
  4080. * Update the estimated number of bytes queued to transmit for this channel,
  4081. * and notify the scheduler. The estimate includes both the channel queue and
  4082. * the queue size reported by the lower layer, and an overhead estimate
  4083. * optionally provided by the lower layer.
  4084. */
  4085. void
  4086. channel_update_xmit_queue_size(channel_t *chan)
  4087. {
  4088. uint64_t queued, adj;
  4089. double overhead;
  4090. tor_assert(chan);
  4091. tor_assert(chan->num_bytes_queued);
  4092. /*
  4093. * First, get the number of bytes we have queued without factoring in
  4094. * lower-layer overhead.
  4095. */
  4096. queued = chan->num_bytes_queued(chan) + chan->bytes_in_queue;
  4097. /* Next, adjust by the overhead factor, if any is available */
  4098. if (chan->get_overhead_estimate) {
  4099. overhead = chan->get_overhead_estimate(chan);
  4100. if (overhead >= 1.0) {
  4101. queued = (uint64_t)(queued * overhead);
  4102. } else {
  4103. /* Ignore silly overhead factors */
  4104. log_notice(LD_CHANNEL, "Ignoring silly overhead factor %f", overhead);
  4105. }
  4106. }
  4107. /* Now, compare to the previous estimate */
  4108. if (queued > chan->bytes_queued_for_xmit) {
  4109. adj = queued - chan->bytes_queued_for_xmit;
  4110. log_debug(LD_CHANNEL,
  4111. "Increasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  4112. " from " U64_FORMAT " to " U64_FORMAT,
  4113. U64_PRINTF_ARG(chan->global_identifier),
  4114. U64_PRINTF_ARG(adj),
  4115. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  4116. U64_PRINTF_ARG(queued));
  4117. /* Update the channel's estimate */
  4118. chan->bytes_queued_for_xmit = queued;
  4119. /* Update the global queue size estimate if appropriate */
  4120. if (chan->state == CHANNEL_STATE_OPEN ||
  4121. chan->state == CHANNEL_STATE_MAINT) {
  4122. estimated_total_queue_size += adj;
  4123. log_debug(LD_CHANNEL,
  4124. "Increasing global queue size by " U64_FORMAT " for channel "
  4125. U64_FORMAT ", new size is " U64_FORMAT,
  4126. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  4127. U64_PRINTF_ARG(estimated_total_queue_size));
  4128. }
  4129. } else if (queued < chan->bytes_queued_for_xmit) {
  4130. adj = chan->bytes_queued_for_xmit - queued;
  4131. log_debug(LD_CHANNEL,
  4132. "Decreasing queue size for channel " U64_FORMAT " by " U64_FORMAT
  4133. " from " U64_FORMAT " to " U64_FORMAT,
  4134. U64_PRINTF_ARG(chan->global_identifier),
  4135. U64_PRINTF_ARG(adj),
  4136. U64_PRINTF_ARG(chan->bytes_queued_for_xmit),
  4137. U64_PRINTF_ARG(queued));
  4138. /* Update the channel's estimate */
  4139. chan->bytes_queued_for_xmit = queued;
  4140. /* Update the global queue size estimate if appropriate */
  4141. if (chan->state == CHANNEL_STATE_OPEN ||
  4142. chan->state == CHANNEL_STATE_MAINT) {
  4143. estimated_total_queue_size -= adj;
  4144. log_debug(LD_CHANNEL,
  4145. "Decreasing global queue size by " U64_FORMAT " for channel "
  4146. U64_FORMAT ", new size is " U64_FORMAT,
  4147. U64_PRINTF_ARG(adj), U64_PRINTF_ARG(chan->global_identifier),
  4148. U64_PRINTF_ARG(estimated_total_queue_size));
  4149. }
  4150. }
  4151. }