channel.c 127 KB

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