channel.c 114 KB

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