channel.c 129 KB

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