channel.c 129 KB

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