channel.c 129 KB

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