channel.c 127 KB

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