channel.c 140 KB

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