channel.c 116 KB

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