channel.c 114 KB

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