channel.c 140 KB

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