channel.c 131 KB

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