SecuritySessionClientSettings.cs 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614
  1. //----------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IdentityModel.Claims;
  9. using System.IdentityModel.Selectors;
  10. using System.IdentityModel.Tokens;
  11. using System.Runtime;
  12. using System.ServiceModel.Channels;
  13. using System.ServiceModel.Diagnostics;
  14. using System.ServiceModel.Dispatcher;
  15. using System.ServiceModel.Security.Tokens;
  16. using System.Net;
  17. using System.Threading;
  18. using System.Xml;
  19. using System.Globalization;
  20. using System.ServiceModel.Diagnostics.Application;
  21. // Please use 'sdv //depot/devdiv/private/indigo_xws/ndp/indigo/src/ServiceModel/System/ServiceModel/Security/SecuritySessionChannelFactory.cs'
  22. // to see version history before the file was renamed
  23. // This class is named Settings since the only public APIs are for
  24. // settings; however, this class also manages all functionality
  25. // for session channels through internal APIs
  26. static class SecuritySessionClientSettings
  27. {
  28. internal const string defaultKeyRenewalIntervalString = "10:00:00";
  29. internal const string defaultKeyRolloverIntervalString = "00:05:00";
  30. internal static readonly TimeSpan defaultKeyRenewalInterval = TimeSpan.Parse(defaultKeyRenewalIntervalString, CultureInfo.InvariantCulture);
  31. internal static readonly TimeSpan defaultKeyRolloverInterval = TimeSpan.Parse(defaultKeyRolloverIntervalString, CultureInfo.InvariantCulture);
  32. internal const bool defaultTolerateTransportFailures = true;
  33. }
  34. sealed class SecuritySessionClientSettings<TChannel> : IChannelSecureConversationSessionSettings, ISecurityCommunicationObject
  35. {
  36. SecurityProtocolFactory sessionProtocolFactory;
  37. TimeSpan keyRenewalInterval;
  38. TimeSpan keyRolloverInterval;
  39. bool tolerateTransportFailures;
  40. SecurityChannelFactory<TChannel> securityChannelFactory;
  41. IChannelFactory innerChannelFactory;
  42. ChannelBuilder channelBuilder;
  43. WrapperSecurityCommunicationObject communicationObject;
  44. SecurityStandardsManager standardsManager;
  45. SecurityTokenParameters issuedTokenParameters;
  46. int issuedTokenRenewalThreshold;
  47. bool canRenewSession = true;
  48. object thisLock = new object();
  49. public SecuritySessionClientSettings()
  50. {
  51. this.keyRenewalInterval = SecuritySessionClientSettings.defaultKeyRenewalInterval;
  52. this.keyRolloverInterval = SecuritySessionClientSettings.defaultKeyRolloverInterval;
  53. this.tolerateTransportFailures = SecuritySessionClientSettings.defaultTolerateTransportFailures;
  54. this.communicationObject = new WrapperSecurityCommunicationObject(this);
  55. }
  56. IChannelFactory InnerChannelFactory
  57. {
  58. get
  59. {
  60. return this.innerChannelFactory;
  61. }
  62. }
  63. internal ChannelBuilder ChannelBuilder
  64. {
  65. get
  66. {
  67. return this.channelBuilder;
  68. }
  69. set
  70. {
  71. this.channelBuilder = value;
  72. }
  73. }
  74. SecurityChannelFactory<TChannel> SecurityChannelFactory
  75. {
  76. get
  77. {
  78. return this.securityChannelFactory;
  79. }
  80. }
  81. public SecurityProtocolFactory SessionProtocolFactory
  82. {
  83. get
  84. {
  85. return this.sessionProtocolFactory;
  86. }
  87. set
  88. {
  89. this.communicationObject.ThrowIfDisposedOrImmutable();
  90. this.sessionProtocolFactory = value;
  91. }
  92. }
  93. public TimeSpan KeyRenewalInterval
  94. {
  95. get
  96. {
  97. return this.keyRenewalInterval;
  98. }
  99. set
  100. {
  101. if (value <= TimeSpan.Zero)
  102. {
  103. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
  104. }
  105. this.communicationObject.ThrowIfDisposedOrImmutable();
  106. this.keyRenewalInterval = value;
  107. }
  108. }
  109. public TimeSpan KeyRolloverInterval
  110. {
  111. get
  112. {
  113. return this.keyRolloverInterval;
  114. }
  115. set
  116. {
  117. if (value <= TimeSpan.Zero)
  118. {
  119. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
  120. }
  121. this.communicationObject.ThrowIfDisposedOrImmutable();
  122. this.keyRolloverInterval = value;
  123. }
  124. }
  125. public bool TolerateTransportFailures
  126. {
  127. get
  128. {
  129. return this.tolerateTransportFailures;
  130. }
  131. set
  132. {
  133. this.communicationObject.ThrowIfDisposedOrImmutable();
  134. this.tolerateTransportFailures = value;
  135. }
  136. }
  137. public bool CanRenewSession
  138. {
  139. get
  140. {
  141. return this.canRenewSession;
  142. }
  143. set
  144. {
  145. this.canRenewSession = value;
  146. }
  147. }
  148. public SecurityTokenParameters IssuedSecurityTokenParameters
  149. {
  150. get
  151. {
  152. return this.issuedTokenParameters;
  153. }
  154. set
  155. {
  156. this.communicationObject.ThrowIfDisposedOrImmutable();
  157. this.issuedTokenParameters = value;
  158. }
  159. }
  160. public SecurityStandardsManager SecurityStandardsManager
  161. {
  162. get
  163. {
  164. return this.standardsManager;
  165. }
  166. set
  167. {
  168. this.communicationObject.ThrowIfDisposedOrImmutable();
  169. this.standardsManager = value;
  170. }
  171. }
  172. // ISecurityCommunicationObject members
  173. public TimeSpan DefaultOpenTimeout
  174. {
  175. get { return ServiceDefaults.OpenTimeout; }
  176. }
  177. public TimeSpan DefaultCloseTimeout
  178. {
  179. get { return ServiceDefaults.CloseTimeout; }
  180. }
  181. internal IChannelFactory CreateInnerChannelFactory()
  182. {
  183. if (this.ChannelBuilder.CanBuildChannelFactory<IDuplexSessionChannel>())
  184. {
  185. return this.ChannelBuilder.BuildChannelFactory<IDuplexSessionChannel>();
  186. }
  187. else if (this.ChannelBuilder.CanBuildChannelFactory<IDuplexChannel>())
  188. {
  189. return this.ChannelBuilder.BuildChannelFactory<IDuplexChannel>();
  190. }
  191. else if (this.ChannelBuilder.CanBuildChannelFactory<IRequestChannel>())
  192. {
  193. return this.ChannelBuilder.BuildChannelFactory<IRequestChannel>();
  194. }
  195. else
  196. {
  197. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  198. }
  199. }
  200. public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  201. {
  202. return this.communicationObject.BeginClose(timeout, callback, state);
  203. }
  204. public void EndClose(IAsyncResult result)
  205. {
  206. this.communicationObject.EndClose(result);
  207. }
  208. IAsyncResult ISecurityCommunicationObject.OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  209. {
  210. return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnClose), timeout, callback, state);
  211. }
  212. IAsyncResult ISecurityCommunicationObject.OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  213. {
  214. return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnOpen), timeout, callback, state);
  215. }
  216. public void OnClosed()
  217. {
  218. }
  219. public void OnClosing()
  220. {
  221. }
  222. void ISecurityCommunicationObject.OnEndClose(IAsyncResult result)
  223. {
  224. OperationWithTimeoutAsyncResult.End(result);
  225. }
  226. void ISecurityCommunicationObject.OnEndOpen(IAsyncResult result)
  227. {
  228. OperationWithTimeoutAsyncResult.End(result);
  229. }
  230. public void OnFaulted()
  231. {
  232. }
  233. public void OnOpened()
  234. {
  235. }
  236. public void OnOpening()
  237. {
  238. }
  239. public void OnClose(TimeSpan timeout)
  240. {
  241. if (this.sessionProtocolFactory != null)
  242. {
  243. this.sessionProtocolFactory.Close(false, timeout);
  244. }
  245. }
  246. public void OnAbort()
  247. {
  248. if (this.sessionProtocolFactory != null)
  249. {
  250. this.sessionProtocolFactory.Close(true, TimeSpan.Zero);
  251. }
  252. }
  253. public void OnOpen(TimeSpan timeout)
  254. {
  255. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  256. if (this.sessionProtocolFactory == null)
  257. {
  258. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecuritySessionProtocolFactoryShouldBeSetBeforeThisOperation)));
  259. }
  260. if (this.standardsManager == null)
  261. {
  262. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecurityStandardsManagerNotSet, this.GetType().ToString())));
  263. }
  264. if (this.issuedTokenParameters == null)
  265. {
  266. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuedSecurityTokenParametersNotSet, this.GetType())));
  267. }
  268. if (this.keyRenewalInterval < this.keyRolloverInterval)
  269. {
  270. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.KeyRolloverGreaterThanKeyRenewal)));
  271. }
  272. this.issuedTokenRenewalThreshold = this.sessionProtocolFactory.SecurityBindingElement.LocalClientSettings.CookieRenewalThresholdPercentage;
  273. this.ConfigureSessionProtocolFactory();
  274. this.sessionProtocolFactory.Open(true, timeoutHelper.RemainingTime());
  275. }
  276. internal void Close(TimeSpan timeout)
  277. {
  278. this.communicationObject.Close(timeout);
  279. }
  280. internal void Abort()
  281. {
  282. this.communicationObject.Abort();
  283. }
  284. internal void Open(SecurityChannelFactory<TChannel> securityChannelFactory,
  285. IChannelFactory innerChannelFactory, ChannelBuilder channelBuilder, TimeSpan timeout)
  286. {
  287. this.securityChannelFactory = securityChannelFactory;
  288. this.innerChannelFactory = innerChannelFactory;
  289. this.channelBuilder = channelBuilder;
  290. this.communicationObject.Open(timeout);
  291. }
  292. internal TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
  293. {
  294. return OnCreateChannel(remoteAddress, via, null);
  295. }
  296. internal TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via, MessageFilter filter)
  297. {
  298. this.communicationObject.ThrowIfClosed();
  299. if (filter != null)
  300. {
  301. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  302. }
  303. if (typeof(TChannel) == typeof(IRequestSessionChannel))
  304. {
  305. return (TChannel)((object)(new SecurityRequestSessionChannel(this, remoteAddress, via)));
  306. }
  307. else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
  308. {
  309. // typeof(TChannel) == typeof(IDuplexSessionChannel)
  310. return (TChannel)((object)(new ClientSecurityDuplexSessionChannel(this, remoteAddress, via)));
  311. }
  312. else
  313. {
  314. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)), "TChannel"));
  315. }
  316. }
  317. void ConfigureSessionProtocolFactory()
  318. {
  319. if (this.sessionProtocolFactory is SessionSymmetricMessageSecurityProtocolFactory)
  320. {
  321. AddressingVersion addressing = MessageVersion.Default.Addressing;
  322. if (this.channelBuilder != null)
  323. {
  324. MessageEncodingBindingElement encoding = this.channelBuilder.Binding.Elements.Find<MessageEncodingBindingElement>();
  325. if (encoding != null)
  326. {
  327. addressing = encoding.MessageVersion.Addressing;
  328. }
  329. }
  330. if (addressing != AddressingVersion.WSAddressing10 && addressing != AddressingVersion.WSAddressingAugust2004)
  331. {
  332. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  333. new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, addressing)));
  334. }
  335. SessionSymmetricMessageSecurityProtocolFactory symmetric = (SessionSymmetricMessageSecurityProtocolFactory)this.sessionProtocolFactory;
  336. if (!symmetric.ApplyIntegrity || !symmetric.RequireIntegrity)
  337. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecuritySessionRequiresMessageIntegrity)));
  338. MessagePartSpecification bodyPart = new MessagePartSpecification(true);
  339. symmetric.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction);
  340. symmetric.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManager.SecureConversationDriver.CloseAction);
  341. symmetric.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, addressing.FaultAction);
  342. symmetric.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, addressing.DefaultFaultAction);
  343. symmetric.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, DotNetSecurityStrings.SecuritySessionFaultAction);
  344. symmetric.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManager.SecureConversationDriver.CloseAction);
  345. symmetric.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction);
  346. if (symmetric.ApplyConfidentiality)
  347. {
  348. symmetric.ProtectionRequirements.IncomingEncryptionParts.AddParts(MessagePartSpecification.NoParts, this.SecurityStandardsManager.SecureConversationDriver.CloseAction);
  349. symmetric.ProtectionRequirements.IncomingEncryptionParts.AddParts(MessagePartSpecification.NoParts, this.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction);
  350. }
  351. if (symmetric.RequireConfidentiality)
  352. {
  353. symmetric.ProtectionRequirements.OutgoingEncryptionParts.AddParts(MessagePartSpecification.NoParts, this.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction);
  354. symmetric.ProtectionRequirements.OutgoingEncryptionParts.AddParts(MessagePartSpecification.NoParts, this.SecurityStandardsManager.SecureConversationDriver.CloseAction);
  355. symmetric.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, addressing.FaultAction);
  356. symmetric.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, addressing.DefaultFaultAction);
  357. symmetric.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, DotNetSecurityStrings.SecuritySessionFaultAction);
  358. }
  359. }
  360. else if (this.sessionProtocolFactory is SessionSymmetricTransportSecurityProtocolFactory)
  361. {
  362. SessionSymmetricTransportSecurityProtocolFactory transport = (SessionSymmetricTransportSecurityProtocolFactory)this.sessionProtocolFactory;
  363. transport.AddTimestamp = true;
  364. transport.SecurityTokenParameters.RequireDerivedKeys = false;
  365. }
  366. else
  367. {
  368. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  369. }
  370. }
  371. abstract class ClientSecuritySessionChannel : ChannelBase
  372. {
  373. EndpointAddress to;
  374. Uri via;
  375. IClientReliableChannelBinder channelBinder;
  376. ChannelParameterCollection channelParameters;
  377. SecurityToken currentSessionToken;
  378. SecurityToken previousSessionToken;
  379. DateTime keyRenewalTime;
  380. DateTime keyRolloverTime;
  381. SecurityProtocol securityProtocol;
  382. SecuritySessionClientSettings<TChannel> settings;
  383. SecurityTokenProvider sessionTokenProvider;
  384. bool isKeyRenewalOngoing = false;
  385. InterruptibleWaitObject keyRenewalCompletedEvent;
  386. bool sentClose;
  387. bool receivedClose;
  388. volatile bool isOutputClosed;
  389. volatile bool isInputClosed;
  390. InterruptibleWaitObject inputSessionClosedHandle = new InterruptibleWaitObject(false);
  391. bool sendCloseHandshake = false;
  392. MessageVersion messageVersion;
  393. bool isCompositeDuplexConnection;
  394. Message closeResponse;
  395. InterruptibleWaitObject outputSessionCloseHandle = new InterruptibleWaitObject(true);
  396. WebHeaderCollection webHeaderCollection;
  397. protected ClientSecuritySessionChannel(SecuritySessionClientSettings<TChannel> settings, EndpointAddress to, Uri via)
  398. : base(settings.SecurityChannelFactory)
  399. {
  400. this.settings = settings;
  401. this.to = to;
  402. this.via = via;
  403. this.keyRenewalCompletedEvent = new InterruptibleWaitObject(false);
  404. this.messageVersion = settings.SecurityChannelFactory.MessageVersion;
  405. this.channelParameters = new ChannelParameterCollection(this);
  406. this.InitializeChannelBinder();
  407. this.webHeaderCollection = new WebHeaderCollection();
  408. }
  409. protected SecuritySessionClientSettings<TChannel> Settings
  410. {
  411. get
  412. {
  413. return this.settings;
  414. }
  415. }
  416. protected IClientReliableChannelBinder ChannelBinder
  417. {
  418. get
  419. {
  420. return this.channelBinder;
  421. }
  422. }
  423. public EndpointAddress RemoteAddress
  424. {
  425. get
  426. {
  427. return this.to;
  428. }
  429. }
  430. public Uri Via
  431. {
  432. get
  433. {
  434. return this.via;
  435. }
  436. }
  437. protected bool SendCloseHandshake
  438. {
  439. get
  440. {
  441. return this.sendCloseHandshake;
  442. }
  443. }
  444. protected EndpointAddress InternalLocalAddress
  445. {
  446. get
  447. {
  448. if (this.channelBinder != null)
  449. return this.channelBinder.LocalAddress;
  450. return null;
  451. }
  452. }
  453. protected virtual bool CanDoSecurityCorrelation
  454. {
  455. get
  456. {
  457. return false;
  458. }
  459. }
  460. public MessageVersion MessageVersion
  461. {
  462. get { return this.messageVersion; }
  463. }
  464. protected bool IsInputClosed
  465. {
  466. get { return isInputClosed; }
  467. }
  468. protected bool IsOutputClosed
  469. {
  470. get { return isOutputClosed; }
  471. }
  472. protected abstract bool ExpectClose
  473. {
  474. get;
  475. }
  476. protected abstract string SessionId
  477. {
  478. get;
  479. }
  480. public override T GetProperty<T>()
  481. {
  482. if (typeof(T) == typeof(ChannelParameterCollection))
  483. {
  484. return this.channelParameters as T;
  485. }
  486. if (typeof(T) == typeof(FaultConverter) && (this.channelBinder != null))
  487. {
  488. return new SecurityChannelFaultConverter(this.channelBinder.Channel) as T;
  489. }
  490. else if (typeof(T) == typeof(WebHeaderCollection))
  491. {
  492. return (T)(object)this.webHeaderCollection;
  493. }
  494. T result = base.GetProperty<T>();
  495. if ((result == null) && (channelBinder != null) && (channelBinder.Channel != null))
  496. {
  497. result = channelBinder.Channel.GetProperty<T>();
  498. }
  499. return result;
  500. }
  501. protected abstract void InitializeSession(SecurityToken sessionToken);
  502. void InitializeSecurityState(SecurityToken sessionToken)
  503. {
  504. InitializeSession(sessionToken);
  505. this.currentSessionToken = sessionToken;
  506. this.previousSessionToken = null;
  507. List<SecurityToken> incomingSessionTokens = new List<SecurityToken>(1);
  508. incomingSessionTokens.Add(sessionToken);
  509. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).SetIdentityCheckAuthenticator(new GenericXmlSecurityTokenAuthenticator());
  510. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).SetIncomingSessionTokens(incomingSessionTokens);
  511. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).SetOutgoingSessionToken(sessionToken);
  512. if (this.CanDoSecurityCorrelation)
  513. {
  514. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).ReturnCorrelationState = true;
  515. }
  516. this.keyRenewalTime = GetKeyRenewalTime(sessionToken);
  517. }
  518. void SetupSessionTokenProvider()
  519. {
  520. InitiatorServiceModelSecurityTokenRequirement requirement = new InitiatorServiceModelSecurityTokenRequirement();
  521. this.Settings.IssuedSecurityTokenParameters.InitializeSecurityTokenRequirement(requirement);
  522. requirement.KeyUsage = SecurityKeyUsage.Signature;
  523. requirement.SupportSecurityContextCancellation = true;
  524. requirement.SecurityAlgorithmSuite = this.Settings.SessionProtocolFactory.OutgoingAlgorithmSuite;
  525. requirement.SecurityBindingElement = this.Settings.SessionProtocolFactory.SecurityBindingElement;
  526. requirement.TargetAddress = this.to;
  527. requirement.Via = this.Via;
  528. requirement.MessageSecurityVersion = this.Settings.SessionProtocolFactory.MessageSecurityVersion.SecurityTokenVersion;
  529. requirement.Properties[ServiceModelSecurityTokenRequirement.PrivacyNoticeUriProperty] = this.Settings.SessionProtocolFactory.PrivacyNoticeUri;
  530. requirement.WebHeaders = this.webHeaderCollection;
  531. if (this.channelParameters != null)
  532. {
  533. requirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = this.channelParameters;
  534. }
  535. requirement.Properties[ServiceModelSecurityTokenRequirement.PrivacyNoticeVersionProperty] = this.Settings.SessionProtocolFactory.PrivacyNoticeVersion;
  536. if (this.channelBinder.LocalAddress != null)
  537. {
  538. requirement.DuplexClientLocalAddress = this.channelBinder.LocalAddress;
  539. }
  540. this.sessionTokenProvider = this.Settings.SessionProtocolFactory.SecurityTokenManager.CreateSecurityTokenProvider(requirement);
  541. }
  542. void OpenCore(SecurityToken sessionToken, TimeSpan timeout)
  543. {
  544. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  545. this.securityProtocol = this.Settings.SessionProtocolFactory.CreateSecurityProtocol(this.to, this.Via, null, true, timeoutHelper.RemainingTime());
  546. if (!(this.securityProtocol is IInitiatorSecuritySessionProtocol))
  547. {
  548. Fx.Assert("Security protocol must be IInitiatorSecuritySessionProtocol.");
  549. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ProtocolMisMatch, "IInitiatorSecuritySessionProtocol", this.GetType().ToString())));
  550. }
  551. this.securityProtocol.Open(timeoutHelper.RemainingTime());
  552. this.channelBinder.Open(timeoutHelper.RemainingTime());
  553. this.InitializeSecurityState(sessionToken);
  554. }
  555. protected override void OnFaulted()
  556. {
  557. this.AbortCore();
  558. this.inputSessionClosedHandle.Fault(this);
  559. this.keyRenewalCompletedEvent.Fault(this);
  560. this.outputSessionCloseHandle.Fault(this);
  561. base.OnFaulted();
  562. }
  563. protected override void OnOpen(TimeSpan timeout)
  564. {
  565. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  566. SetupSessionTokenProvider();
  567. SecurityUtils.OpenTokenProviderIfRequired(this.sessionTokenProvider, timeoutHelper.RemainingTime());
  568. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ?
  569. ServiceModelActivity.CreateBoundedActivity() : null)
  570. {
  571. if (DiagnosticUtility.ShouldUseActivity)
  572. {
  573. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivitySecuritySetup), ActivityType.SecuritySetup);
  574. }
  575. SecurityToken sessionToken = this.sessionTokenProvider.GetToken(timeoutHelper.RemainingTime());
  576. // Token was issued, do send cancel on close;
  577. this.sendCloseHandshake = true;
  578. this.OpenCore(sessionToken, timeoutHelper.RemainingTime());
  579. }
  580. }
  581. protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  582. {
  583. ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ?
  584. ServiceModelActivity.CreateAsyncActivity() : null;
  585. using (ServiceModelActivity.BoundOperation(activity, true))
  586. {
  587. if (DiagnosticUtility.ShouldUseActivity)
  588. {
  589. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivitySecuritySetup), ActivityType.SecuritySetup);
  590. }
  591. return new OpenAsyncResult(this, timeout, callback, state);
  592. }
  593. }
  594. protected override void OnEndOpen(IAsyncResult result)
  595. {
  596. OpenAsyncResult.End(result);
  597. }
  598. void InitializeChannelBinder()
  599. {
  600. ChannelBuilder channelBuilder = this.Settings.ChannelBuilder;
  601. TolerateFaultsMode faultMode = this.Settings.TolerateTransportFailures ? TolerateFaultsMode.Always : TolerateFaultsMode.Never;
  602. if (channelBuilder.CanBuildChannelFactory<IDuplexSessionChannel>())
  603. {
  604. this.channelBinder = ClientReliableChannelBinder<IDuplexSessionChannel>.CreateBinder(this.RemoteAddress, this.Via, (IChannelFactory<IDuplexSessionChannel>)(object)this.Settings.InnerChannelFactory,
  605. MaskingMode.None, faultMode, this.channelParameters, this.DefaultCloseTimeout, this.DefaultSendTimeout);
  606. }
  607. else if (channelBuilder.CanBuildChannelFactory<IDuplexChannel>())
  608. {
  609. this.channelBinder = ClientReliableChannelBinder<IDuplexChannel>.CreateBinder(this.RemoteAddress, this.Via, (IChannelFactory<IDuplexChannel>)(object)this.Settings.InnerChannelFactory,
  610. MaskingMode.None, faultMode, this.channelParameters, this.DefaultCloseTimeout, this.DefaultSendTimeout);
  611. this.isCompositeDuplexConnection = true;
  612. }
  613. else if (channelBuilder.CanBuildChannelFactory<IRequestChannel>())
  614. {
  615. this.channelBinder = ClientReliableChannelBinder<IRequestChannel>.CreateBinder(this.RemoteAddress, this.Via, (IChannelFactory<IRequestChannel>)(object)this.Settings.InnerChannelFactory,
  616. MaskingMode.None, faultMode, this.channelParameters, this.DefaultCloseTimeout, this.DefaultSendTimeout);
  617. }
  618. else if (channelBuilder.CanBuildChannelFactory<IRequestSessionChannel>())
  619. {
  620. this.channelBinder = ClientReliableChannelBinder<IRequestSessionChannel>.CreateBinder(this.RemoteAddress, this.Via, (IChannelFactory<IRequestSessionChannel>)(object)this.Settings.InnerChannelFactory,
  621. MaskingMode.None, faultMode, this.channelParameters, this.DefaultCloseTimeout, this.DefaultSendTimeout);
  622. }
  623. this.channelBinder.Faulted += this.OnInnerFaulted;
  624. }
  625. void OnInnerFaulted(IReliableChannelBinder sender, Exception exception)
  626. {
  627. this.Fault(exception);
  628. }
  629. protected virtual bool OnCloseResponseReceived()
  630. {
  631. bool setInputSessionClosedHandle = false;
  632. bool isCloseResponseExpected = false;
  633. lock (ThisLock)
  634. {
  635. isCloseResponseExpected = this.sentClose;
  636. if (isCloseResponseExpected && !this.isInputClosed)
  637. {
  638. this.isInputClosed = true;
  639. setInputSessionClosedHandle = true;
  640. }
  641. }
  642. if (!isCloseResponseExpected)
  643. {
  644. this.Fault(new ProtocolException(SR.GetString(SR.UnexpectedSecuritySessionCloseResponse)));
  645. return false;
  646. }
  647. if (setInputSessionClosedHandle)
  648. {
  649. this.inputSessionClosedHandle.Set();
  650. }
  651. return true;
  652. }
  653. protected virtual bool OnCloseReceived()
  654. {
  655. if (!ExpectClose)
  656. {
  657. this.Fault(new ProtocolException(SR.GetString(SR.UnexpectedSecuritySessionClose)));
  658. return false;
  659. }
  660. bool setInputSessionClosedHandle = false;
  661. lock (ThisLock)
  662. {
  663. if (!this.isInputClosed)
  664. {
  665. this.isInputClosed = true;
  666. this.receivedClose = true;
  667. setInputSessionClosedHandle = true;
  668. }
  669. }
  670. if (setInputSessionClosedHandle)
  671. {
  672. this.inputSessionClosedHandle.Set();
  673. }
  674. return true;
  675. }
  676. Message PrepareCloseMessage()
  677. {
  678. SecurityToken tokenToClose;
  679. lock (ThisLock)
  680. {
  681. tokenToClose = this.currentSessionToken;
  682. }
  683. RequestSecurityToken rst = new RequestSecurityToken(this.Settings.SecurityStandardsManager);
  684. rst.RequestType = this.Settings.SecurityStandardsManager.TrustDriver.RequestTypeClose;
  685. rst.CloseTarget = this.Settings.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(tokenToClose, SecurityTokenReferenceStyle.External);
  686. rst.MakeReadOnly();
  687. Message closeMessage = Message.CreateMessage(this.MessageVersion, ActionHeader.Create(this.Settings.SecurityStandardsManager.SecureConversationDriver.CloseAction, this.MessageVersion.Addressing), rst);
  688. RequestReplyCorrelator.PrepareRequest(closeMessage);
  689. if (this.webHeaderCollection != null && this.webHeaderCollection.Count > 0)
  690. {
  691. object prop = null;
  692. HttpRequestMessageProperty rmp = null;
  693. if (closeMessage.Properties.TryGetValue(HttpRequestMessageProperty.Name, out prop))
  694. {
  695. rmp = prop as HttpRequestMessageProperty;
  696. }
  697. else
  698. {
  699. rmp = new HttpRequestMessageProperty();
  700. closeMessage.Properties.Add(HttpRequestMessageProperty.Name, rmp);
  701. }
  702. if (rmp != null && rmp.Headers != null)
  703. {
  704. rmp.Headers.Add(this.webHeaderCollection);
  705. }
  706. }
  707. if (this.InternalLocalAddress != null)
  708. {
  709. closeMessage.Headers.ReplyTo = this.InternalLocalAddress;
  710. }
  711. else
  712. {
  713. if (closeMessage.Version.Addressing == AddressingVersion.WSAddressing10)
  714. {
  715. closeMessage.Headers.ReplyTo = null;
  716. }
  717. else if (closeMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
  718. {
  719. closeMessage.Headers.ReplyTo = EndpointAddress.AnonymousAddress;
  720. }
  721. else
  722. {
  723. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  724. new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, closeMessage.Version.Addressing)));
  725. }
  726. }
  727. if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
  728. {
  729. TraceUtility.AddAmbientActivityToMessage(closeMessage);
  730. }
  731. return closeMessage;
  732. }
  733. protected SecurityProtocolCorrelationState SendCloseMessage(TimeSpan timeout)
  734. {
  735. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  736. SecurityProtocolCorrelationState closeCorrelationState;
  737. Message closeMessage = PrepareCloseMessage();
  738. try
  739. {
  740. closeCorrelationState = this.securityProtocol.SecureOutgoingMessage(ref closeMessage, timeoutHelper.RemainingTime(), null);
  741. this.ChannelBinder.Send(closeMessage, timeoutHelper.RemainingTime());
  742. }
  743. finally
  744. {
  745. closeMessage.Close();
  746. }
  747. SecurityTraceRecordHelper.TraceCloseMessageSent(this.currentSessionToken, this.RemoteAddress);
  748. return closeCorrelationState;
  749. }
  750. protected void SendCloseResponseMessage(TimeSpan timeout)
  751. {
  752. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  753. Message message = null;
  754. try
  755. {
  756. message = this.closeResponse;
  757. this.securityProtocol.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime(), null);
  758. this.ChannelBinder.Send(message, timeoutHelper.RemainingTime());
  759. SecurityTraceRecordHelper.TraceCloseResponseMessageSent(this.currentSessionToken, this.RemoteAddress);
  760. }
  761. finally
  762. {
  763. message.Close();
  764. }
  765. }
  766. IAsyncResult BeginSendCloseMessage(TimeSpan timeout, AsyncCallback callback, object state)
  767. {
  768. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ?
  769. ServiceModelActivity.CreateBoundedActivity() : null)
  770. {
  771. if (DiagnosticUtility.ShouldUseActivity)
  772. {
  773. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivitySecurityClose), ActivityType.SecuritySetup);
  774. }
  775. Message closeMessage = PrepareCloseMessage();
  776. return new SecureSendAsyncResult(closeMessage, this, timeout, callback, state, true);
  777. }
  778. }
  779. SecurityProtocolCorrelationState EndSendCloseMessage(IAsyncResult result)
  780. {
  781. SecurityProtocolCorrelationState correlationState = SecureSendAsyncResult.End(result);
  782. SecurityTraceRecordHelper.TraceCloseMessageSent(this.currentSessionToken, this.RemoteAddress);
  783. return correlationState;
  784. }
  785. IAsyncResult BeginSendCloseResponseMessage(TimeSpan timeout, AsyncCallback callback, object state)
  786. {
  787. return new SecureSendAsyncResult(this.closeResponse, this, timeout, callback, state, true);
  788. }
  789. void EndSendCloseResponseMessage(IAsyncResult result)
  790. {
  791. SecureSendAsyncResult.End(result);
  792. SecurityTraceRecordHelper.TraceCloseResponseMessageSent(this.currentSessionToken, this.RemoteAddress);
  793. }
  794. MessageFault GetProtocolFault(ref Message message, out bool isKeyRenewalFault, out bool isSessionAbortedFault)
  795. {
  796. isKeyRenewalFault = false;
  797. isSessionAbortedFault = false;
  798. MessageFault result = null;
  799. using (MessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue))
  800. {
  801. message = buffer.CreateMessage();
  802. Message copy = buffer.CreateMessage();
  803. MessageFault fault = MessageFault.CreateFault(copy, TransportDefaults.MaxSecurityFaultSize);
  804. if (fault.Code.IsSenderFault)
  805. {
  806. FaultCode subCode = fault.Code.SubCode;
  807. if (subCode != null)
  808. {
  809. SecurityStandardsManager standardsManager = this.securityProtocol.SecurityProtocolFactory.StandardsManager;
  810. SecureConversationDriver scDriver = standardsManager.SecureConversationDriver;
  811. if (subCode.Namespace == scDriver.Namespace.Value && subCode.Name == scDriver.RenewNeededFaultCode.Value)
  812. {
  813. result = fault;
  814. isKeyRenewalFault = true;
  815. }
  816. else if (subCode.Namespace == DotNetSecurityStrings.Namespace && subCode.Name == DotNetSecurityStrings.SecuritySessionAbortedFault)
  817. {
  818. result = fault;
  819. isSessionAbortedFault = true;
  820. }
  821. }
  822. }
  823. }
  824. return result;
  825. }
  826. void ProcessKeyRenewalFault()
  827. {
  828. SecurityTraceRecordHelper.TraceSessionKeyRenewalFault(this.currentSessionToken, this.RemoteAddress);
  829. lock (ThisLock)
  830. {
  831. this.keyRenewalTime = DateTime.UtcNow;
  832. }
  833. }
  834. void ProcessSessionAbortedFault(MessageFault sessionAbortedFault)
  835. {
  836. SecurityTraceRecordHelper.TraceRemoteSessionAbortedFault(this.currentSessionToken, this.RemoteAddress);
  837. this.Fault(new FaultException(sessionAbortedFault));
  838. }
  839. void ProcessCloseResponse(Message response)
  840. {
  841. // the close message may have been received by the channel after the channel factory has been closed
  842. if (response.Headers.Action != this.Settings.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction.Value)
  843. {
  844. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.InvalidCloseResponseAction, response.Headers.Action)), response);
  845. }
  846. RequestSecurityTokenResponse rstr = null;
  847. XmlDictionaryReader bodyReader = response.GetReaderAtBodyContents();
  848. using (bodyReader)
  849. {
  850. if (this.Settings.SecurityStandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
  851. rstr = this.Settings.SecurityStandardsManager.TrustDriver.CreateRequestSecurityTokenResponse(bodyReader);
  852. else if (this.Settings.SecurityStandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
  853. {
  854. RequestSecurityTokenResponseCollection rstrc = this.Settings.SecurityStandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);
  855. foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
  856. {
  857. if (rstr != null)
  858. {
  859. // More than one RSTR is found. So throw an exception.
  860. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MoreThanOneRSTRInRSTRC)));
  861. }
  862. rstr = rstrItem;
  863. }
  864. }
  865. else
  866. {
  867. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  868. }
  869. response.ReadFromBodyContentsToEnd(bodyReader);
  870. }
  871. if (!rstr.IsRequestedTokenClosed)
  872. {
  873. throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SessionTokenWasNotClosed)), response);
  874. }
  875. }
  876. void PrepareReply(Message request, Message reply)
  877. {
  878. if (request.Headers.ReplyTo != null)
  879. {
  880. request.Headers.ReplyTo.ApplyTo(reply);
  881. }
  882. else if (request.Headers.From != null)
  883. {
  884. request.Headers.From.ApplyTo(reply);
  885. }
  886. if (request.Headers.MessageId != null)
  887. {
  888. reply.Headers.RelatesTo = request.Headers.MessageId;
  889. }
  890. TraceUtility.CopyActivity(request, reply);
  891. if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
  892. {
  893. TraceUtility.AddActivityHeader(reply);
  894. }
  895. }
  896. bool DoesSkiClauseMatchSigningToken(SecurityContextKeyIdentifierClause skiClause, Message request)
  897. {
  898. if (this.SessionId == null)
  899. {
  900. return false;
  901. }
  902. return (skiClause.ContextId.ToString() == this.SessionId);
  903. }
  904. void ProcessCloseMessage(Message message)
  905. {
  906. RequestSecurityToken rst;
  907. XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
  908. using (bodyReader)
  909. {
  910. rst = this.Settings.SecurityStandardsManager.TrustDriver.CreateRequestSecurityToken(bodyReader);
  911. message.ReadFromBodyContentsToEnd(bodyReader);
  912. }
  913. if (rst.RequestType != null && rst.RequestType != this.Settings.SecurityStandardsManager.TrustDriver.RequestTypeClose)
  914. {
  915. throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.InvalidRstRequestType, rst.RequestType)), message);
  916. }
  917. if (rst.CloseTarget == null)
  918. {
  919. throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.NoCloseTargetSpecified)), message);
  920. }
  921. SecurityContextKeyIdentifierClause sctSkiClause = rst.CloseTarget as SecurityContextKeyIdentifierClause;
  922. if (sctSkiClause == null || !DoesSkiClauseMatchSigningToken(sctSkiClause, message))
  923. {
  924. throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.BadCloseTarget, rst.CloseTarget)), message);
  925. }
  926. // prepare the close response
  927. RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.Settings.SecurityStandardsManager);
  928. rstr.Context = rst.Context;
  929. rstr.IsRequestedTokenClosed = true;
  930. rstr.MakeReadOnly();
  931. Message response = null;
  932. if (this.Settings.SecurityStandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
  933. response = Message.CreateMessage(message.Version, ActionHeader.Create(this.Settings.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction, message.Version.Addressing), rstr);
  934. else if (this.Settings.SecurityStandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
  935. {
  936. List<RequestSecurityTokenResponse> rstrList = new List<RequestSecurityTokenResponse>();
  937. rstrList.Add(rstr);
  938. RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(rstrList, this.Settings.SecurityStandardsManager);
  939. response = Message.CreateMessage(message.Version, ActionHeader.Create(this.Settings.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction, message.Version.Addressing), rstrCollection);
  940. }
  941. else
  942. {
  943. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  944. }
  945. PrepareReply(message, response);
  946. this.closeResponse = response;
  947. }
  948. bool ShouldWrapException(Exception e)
  949. {
  950. return ((e is FormatException) || (e is XmlException));
  951. }
  952. protected Message ProcessIncomingMessage(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, out MessageFault protocolFault)
  953. {
  954. protocolFault = null;
  955. lock (ThisLock)
  956. {
  957. DoKeyRolloverIfNeeded();
  958. }
  959. try
  960. {
  961. VerifyIncomingMessage(ref message, timeout, correlationState);
  962. string action = message.Headers.Action;
  963. if (action == this.Settings.SecurityStandardsManager.SecureConversationDriver.CloseResponseAction.Value)
  964. {
  965. SecurityTraceRecordHelper.TraceCloseResponseReceived(this.currentSessionToken, this.RemoteAddress);
  966. this.ProcessCloseResponse(message);
  967. this.OnCloseResponseReceived();
  968. }
  969. else if (action == this.Settings.SecurityStandardsManager.SecureConversationDriver.CloseAction.Value)
  970. {
  971. SecurityTraceRecordHelper.TraceCloseMessageReceived(this.currentSessionToken, this.RemoteAddress);
  972. this.ProcessCloseMessage(message);
  973. this.OnCloseReceived();
  974. }
  975. else if (action == DotNetSecurityStrings.SecuritySessionFaultAction)
  976. {
  977. bool isKeyRenewalFault;
  978. bool isSessionAbortedFault;
  979. protocolFault = GetProtocolFault(ref message, out isKeyRenewalFault, out isSessionAbortedFault);
  980. if (isKeyRenewalFault)
  981. {
  982. ProcessKeyRenewalFault();
  983. }
  984. else if (isSessionAbortedFault)
  985. {
  986. ProcessSessionAbortedFault(protocolFault);
  987. }
  988. else
  989. {
  990. return message;
  991. }
  992. }
  993. else
  994. {
  995. return message;
  996. }
  997. }
  998. #pragma warning suppress 56500 // covered by FxCOP
  999. catch (Exception e)
  1000. {
  1001. if ((e is CommunicationException) || (e is TimeoutException) || (Fx.IsFatal(e)) || !ShouldWrapException(e))
  1002. {
  1003. throw;
  1004. }
  1005. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MessageSecurityVerificationFailed), e));
  1006. }
  1007. message.Close();
  1008. return null;
  1009. }
  1010. protected Message ProcessRequestContext(RequestContext requestContext, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
  1011. {
  1012. if (requestContext == null)
  1013. {
  1014. return null;
  1015. }
  1016. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1017. Message message = requestContext.RequestMessage;
  1018. Message unverifiedMessage = message;
  1019. try
  1020. {
  1021. Exception faultException = null;
  1022. try
  1023. {
  1024. MessageFault dummyProtocolFault;
  1025. return ProcessIncomingMessage(message, timeoutHelper.RemainingTime(), correlationState, out dummyProtocolFault);
  1026. }
  1027. catch (MessageSecurityException e)
  1028. {
  1029. // if the message is an unsecured security fault from the other party over the same connection then fault the session
  1030. if (!isCompositeDuplexConnection)
  1031. {
  1032. if (unverifiedMessage.IsFault)
  1033. {
  1034. MessageFault fault = MessageFault.CreateFault(unverifiedMessage, TransportDefaults.MaxSecurityFaultSize);
  1035. if (SecurityUtils.IsSecurityFault(fault, this.settings.sessionProtocolFactory.StandardsManager))
  1036. {
  1037. faultException = SecurityUtils.CreateSecurityFaultException(fault);
  1038. }
  1039. }
  1040. else
  1041. {
  1042. faultException = e;
  1043. }
  1044. }
  1045. }
  1046. if (faultException != null)
  1047. {
  1048. this.Fault(faultException);
  1049. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(faultException);
  1050. }
  1051. return null;
  1052. }
  1053. finally
  1054. {
  1055. requestContext.Close(timeoutHelper.RemainingTime());
  1056. }
  1057. }
  1058. /// <summary>
  1059. /// This method removes the previous session key when the key rollover time is past.
  1060. /// It must be called within a lock
  1061. /// </summary>
  1062. void DoKeyRolloverIfNeeded()
  1063. {
  1064. if (DateTime.UtcNow >= this.keyRolloverTime && this.previousSessionToken != null)
  1065. {
  1066. SecurityTraceRecordHelper.TracePreviousSessionKeyDiscarded(this.previousSessionToken, this.currentSessionToken, this.RemoteAddress);
  1067. // forget the previous session token
  1068. this.previousSessionToken = null;
  1069. List<SecurityToken> incomingTokens = new List<SecurityToken>(1);
  1070. incomingTokens.Add(this.currentSessionToken);
  1071. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).SetIncomingSessionTokens(incomingTokens);
  1072. }
  1073. }
  1074. DateTime GetKeyRenewalTime(SecurityToken token)
  1075. {
  1076. TimeSpan tokenValidityInterval = TimeSpan.FromTicks((long)(((token.ValidTo.Ticks - token.ValidFrom.Ticks) * this.settings.issuedTokenRenewalThreshold) / 100));
  1077. DateTime keyRenewalTime1 = TimeoutHelper.Add(token.ValidFrom, tokenValidityInterval);
  1078. DateTime keyRenewalTime2 = TimeoutHelper.Add(token.ValidFrom, this.settings.keyRenewalInterval);
  1079. if (keyRenewalTime1 < keyRenewalTime2)
  1080. {
  1081. return keyRenewalTime1;
  1082. }
  1083. else
  1084. {
  1085. return keyRenewalTime2;
  1086. }
  1087. }
  1088. /// <summary>
  1089. /// This method returns true if key renewal is needed.
  1090. /// It must be called within a lock
  1091. /// </summary>
  1092. bool IsKeyRenewalNeeded()
  1093. {
  1094. return DateTime.UtcNow >= this.keyRenewalTime;
  1095. }
  1096. /// <summary>
  1097. /// When the new session token is obtained, mark the current token as previous and remove it
  1098. /// after KeyRolloverTime. Mark the new current as pending and update the next key renewal time
  1099. /// </summary>
  1100. void UpdateSessionTokens(SecurityToken newToken)
  1101. {
  1102. lock (ThisLock)
  1103. {
  1104. this.previousSessionToken = this.currentSessionToken;
  1105. this.keyRolloverTime = TimeoutHelper.Add(DateTime.UtcNow, this.Settings.KeyRolloverInterval);
  1106. this.currentSessionToken = newToken;
  1107. this.keyRenewalTime = GetKeyRenewalTime(newToken);
  1108. List<SecurityToken> incomingTokens = new List<SecurityToken>(2);
  1109. incomingTokens.Add(this.previousSessionToken);
  1110. incomingTokens.Add(this.currentSessionToken);
  1111. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).SetIncomingSessionTokens(incomingTokens);
  1112. ((IInitiatorSecuritySessionProtocol)this.securityProtocol).SetOutgoingSessionToken(this.currentSessionToken);
  1113. SecurityTraceRecordHelper.TraceSessionKeyRenewed(this.currentSessionToken, this.previousSessionToken, this.RemoteAddress);
  1114. }
  1115. }
  1116. void RenewKey(TimeSpan timeout)
  1117. {
  1118. if (!this.settings.CanRenewSession)
  1119. {
  1120. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SessionKeyExpiredException(SR.GetString(SR.SessionKeyRenewalNotSupported)));
  1121. }
  1122. bool startKeyRenewal;
  1123. lock (ThisLock)
  1124. {
  1125. if (!this.isKeyRenewalOngoing)
  1126. {
  1127. this.isKeyRenewalOngoing = true;
  1128. this.keyRenewalCompletedEvent.Reset();
  1129. startKeyRenewal = true;
  1130. }
  1131. else
  1132. {
  1133. startKeyRenewal = false;
  1134. }
  1135. }
  1136. if (startKeyRenewal == true)
  1137. {
  1138. try
  1139. {
  1140. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ?
  1141. ServiceModelActivity.CreateBoundedActivity() : null)
  1142. {
  1143. if (DiagnosticUtility.ShouldUseActivity)
  1144. {
  1145. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivitySecurityRenew), ActivityType.SecuritySetup);
  1146. }
  1147. SecurityToken renewedToken = this.sessionTokenProvider.RenewToken(timeout, this.currentSessionToken);
  1148. UpdateSessionTokens(renewedToken);
  1149. }
  1150. }
  1151. finally
  1152. {
  1153. lock (ThisLock)
  1154. {
  1155. this.isKeyRenewalOngoing = false;
  1156. this.keyRenewalCompletedEvent.Set();
  1157. }
  1158. }
  1159. }
  1160. else
  1161. {
  1162. this.keyRenewalCompletedEvent.Wait(timeout);
  1163. lock (ThisLock)
  1164. {
  1165. if (IsKeyRenewalNeeded())
  1166. {
  1167. // the key renewal attempt failed. Throw an exception to the user
  1168. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SessionKeyExpiredException(SR.GetString(SR.UnableToRenewSessionKey)));
  1169. }
  1170. }
  1171. }
  1172. }
  1173. bool CheckIfKeyRenewalNeeded()
  1174. {
  1175. bool doKeyRenewal = false;
  1176. lock (ThisLock)
  1177. {
  1178. doKeyRenewal = IsKeyRenewalNeeded();
  1179. DoKeyRolloverIfNeeded();
  1180. }
  1181. return doKeyRenewal;
  1182. }
  1183. protected IAsyncResult BeginSecureOutgoingMessage(Message message, TimeSpan timeout, AsyncCallback callback, object state)
  1184. {
  1185. bool doKeyRenewal = CheckIfKeyRenewalNeeded();
  1186. if (!doKeyRenewal)
  1187. {
  1188. SecurityProtocolCorrelationState correlationState = this.securityProtocol.SecureOutgoingMessage(ref message, timeout, null);
  1189. return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, correlationState, callback, state);
  1190. }
  1191. else
  1192. {
  1193. return new KeyRenewalAsyncResult(message, this, timeout, callback, state);
  1194. }
  1195. }
  1196. protected Message EndSecureOutgoingMessage(IAsyncResult result, out SecurityProtocolCorrelationState correlationState)
  1197. {
  1198. if (result is CompletedAsyncResult<Message, SecurityProtocolCorrelationState>)
  1199. {
  1200. return CompletedAsyncResult<Message, SecurityProtocolCorrelationState>.End(result, out correlationState);
  1201. }
  1202. else
  1203. {
  1204. TimeSpan remainingTime;
  1205. Message message = KeyRenewalAsyncResult.End(result, out remainingTime);
  1206. correlationState = this.securityProtocol.SecureOutgoingMessage(ref message, remainingTime, null);
  1207. return message;
  1208. }
  1209. }
  1210. protected SecurityProtocolCorrelationState SecureOutgoingMessage(ref Message message, TimeSpan timeout)
  1211. {
  1212. bool doKeyRenewal = CheckIfKeyRenewalNeeded();
  1213. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1214. if (doKeyRenewal)
  1215. {
  1216. RenewKey(timeoutHelper.RemainingTime());
  1217. }
  1218. return this.securityProtocol.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime(), null);
  1219. }
  1220. protected void VerifyIncomingMessage(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
  1221. {
  1222. this.securityProtocol.VerifyIncomingMessage(ref message, timeout, correlationState);
  1223. }
  1224. protected virtual void AbortCore()
  1225. {
  1226. if (this.channelBinder != null)
  1227. {
  1228. this.channelBinder.Abort();
  1229. }
  1230. if (this.sessionTokenProvider != null)
  1231. {
  1232. SecurityUtils.AbortTokenProviderIfRequired(this.sessionTokenProvider);
  1233. }
  1234. }
  1235. protected virtual void CloseCore(TimeSpan timeout)
  1236. {
  1237. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1238. try
  1239. {
  1240. if (this.channelBinder != null)
  1241. {
  1242. this.channelBinder.Close(timeoutHelper.RemainingTime());
  1243. }
  1244. if (this.sessionTokenProvider != null)
  1245. {
  1246. SecurityUtils.CloseTokenProviderIfRequired(this.sessionTokenProvider, timeoutHelper.RemainingTime());
  1247. }
  1248. this.keyRenewalCompletedEvent.Abort(this);
  1249. this.inputSessionClosedHandle.Abort(this);
  1250. }
  1251. catch (CommunicationObjectAbortedException)
  1252. {
  1253. if (this.State != CommunicationState.Closed)
  1254. {
  1255. throw;
  1256. }
  1257. }
  1258. }
  1259. protected virtual IAsyncResult BeginCloseCore(TimeSpan timeout, AsyncCallback callback, object state)
  1260. {
  1261. return new CloseCoreAsyncResult(this, timeout, callback, state);
  1262. }
  1263. protected virtual void EndCloseCore(IAsyncResult result)
  1264. {
  1265. CloseCoreAsyncResult.End(result);
  1266. }
  1267. protected IAsyncResult BeginReceiveInternal(TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
  1268. {
  1269. return new ReceiveAsyncResult(this, timeout, correlationState, callback, state);
  1270. }
  1271. protected Message EndReceiveInternal(IAsyncResult result)
  1272. {
  1273. return ReceiveAsyncResult.End(result);
  1274. }
  1275. protected Message ReceiveInternal(TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
  1276. {
  1277. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1278. while (!this.isInputClosed)
  1279. {
  1280. RequestContext requestContext;
  1281. if (this.ChannelBinder.TryReceive(timeoutHelper.RemainingTime(), out requestContext))
  1282. {
  1283. if (requestContext == null)
  1284. {
  1285. return null;
  1286. }
  1287. Message message = ProcessRequestContext(requestContext, timeoutHelper.RemainingTime(), correlationState);
  1288. if (message != null)
  1289. {
  1290. return message;
  1291. }
  1292. }
  1293. if (timeoutHelper.RemainingTime() == TimeSpan.Zero)
  1294. {
  1295. // we timed out
  1296. break;
  1297. }
  1298. }
  1299. return null;
  1300. }
  1301. protected bool CloseSession(TimeSpan timeout, out bool wasAborted)
  1302. {
  1303. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ?
  1304. ServiceModelActivity.CreateBoundedActivity() : null)
  1305. {
  1306. if (DiagnosticUtility.ShouldUseActivity)
  1307. {
  1308. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivitySecurityClose), ActivityType.SecuritySetup);
  1309. }
  1310. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1311. wasAborted = false;
  1312. try
  1313. {
  1314. this.CloseOutputSession(timeoutHelper.RemainingTime());
  1315. return this.inputSessionClosedHandle.Wait(timeoutHelper.RemainingTime(), false);
  1316. }
  1317. catch (CommunicationObjectAbortedException)
  1318. {
  1319. if (this.State != CommunicationState.Closed)
  1320. {
  1321. throw;
  1322. }
  1323. wasAborted = true;
  1324. }
  1325. return false;
  1326. }
  1327. }
  1328. protected IAsyncResult BeginCloseSession(TimeSpan timeout, AsyncCallback callback, object state)
  1329. {
  1330. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ?
  1331. ServiceModelActivity.CreateAsyncActivity() : null)
  1332. {
  1333. if (DiagnosticUtility.ShouldUseActivity)
  1334. {
  1335. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivitySecurityClose), ActivityType.SecuritySetup);
  1336. }
  1337. return new CloseSessionAsyncResult(timeout, this, callback, state);
  1338. }
  1339. }
  1340. protected bool EndCloseSession(IAsyncResult result, out bool wasAborted)
  1341. {
  1342. return CloseSessionAsyncResult.End(result, out wasAborted);
  1343. }
  1344. void DetermineCloseMessageToSend(out bool sendClose, out bool sendCloseResponse)
  1345. {
  1346. sendClose = false;
  1347. sendCloseResponse = false;
  1348. lock (ThisLock)
  1349. {
  1350. if (!this.isOutputClosed)
  1351. {
  1352. this.isOutputClosed = true;
  1353. if (this.receivedClose)
  1354. {
  1355. sendCloseResponse = true;
  1356. }
  1357. else
  1358. {
  1359. sendClose = true;
  1360. this.sentClose = true;
  1361. }
  1362. this.outputSessionCloseHandle.Reset();
  1363. }
  1364. }
  1365. }
  1366. protected virtual SecurityProtocolCorrelationState CloseOutputSession(TimeSpan timeout)
  1367. {
  1368. ThrowIfFaulted();
  1369. if (!this.SendCloseHandshake)
  1370. {
  1371. return null;
  1372. }
  1373. bool sendClose;
  1374. bool sendCloseResponse;
  1375. DetermineCloseMessageToSend(out sendClose, out sendCloseResponse);
  1376. if (sendClose || sendCloseResponse)
  1377. {
  1378. try
  1379. {
  1380. if (sendClose)
  1381. {
  1382. return this.SendCloseMessage(timeout);
  1383. }
  1384. else
  1385. {
  1386. this.SendCloseResponseMessage(timeout);
  1387. return null;
  1388. }
  1389. }
  1390. finally
  1391. {
  1392. this.outputSessionCloseHandle.Set();
  1393. }
  1394. }
  1395. else
  1396. {
  1397. return null;
  1398. }
  1399. }
  1400. protected virtual IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state)
  1401. {
  1402. ThrowIfFaulted();
  1403. if (!this.SendCloseHandshake)
  1404. {
  1405. return new CompletedAsyncResult(callback, state);
  1406. }
  1407. bool sendClose;
  1408. bool sendCloseResponse;
  1409. DetermineCloseMessageToSend(out sendClose, out sendCloseResponse);
  1410. if (sendClose || sendCloseResponse)
  1411. {
  1412. bool setOutputSessionCloseHandle = true;
  1413. try
  1414. {
  1415. IAsyncResult result;
  1416. if (sendClose)
  1417. {
  1418. result = this.BeginSendCloseMessage(timeout, callback, state);
  1419. }
  1420. else
  1421. {
  1422. result = this.BeginSendCloseResponseMessage(timeout, callback, state);
  1423. }
  1424. setOutputSessionCloseHandle = false;
  1425. return result;
  1426. }
  1427. finally
  1428. {
  1429. if (setOutputSessionCloseHandle)
  1430. {
  1431. this.outputSessionCloseHandle.Set();
  1432. }
  1433. }
  1434. }
  1435. else
  1436. {
  1437. return new CompletedAsyncResult(callback, state);
  1438. }
  1439. }
  1440. protected virtual SecurityProtocolCorrelationState EndCloseOutputSession(IAsyncResult result)
  1441. {
  1442. if (result is CompletedAsyncResult)
  1443. {
  1444. CompletedAsyncResult.End(result);
  1445. return null;
  1446. }
  1447. bool sentCloseLocal;
  1448. lock (ThisLock)
  1449. {
  1450. sentCloseLocal = this.sentClose;
  1451. }
  1452. try
  1453. {
  1454. if (sentCloseLocal)
  1455. {
  1456. return this.EndSendCloseMessage(result);
  1457. }
  1458. else
  1459. {
  1460. this.EndSendCloseResponseMessage(result);
  1461. return null;
  1462. }
  1463. }
  1464. finally
  1465. {
  1466. this.outputSessionCloseHandle.Set();
  1467. }
  1468. }
  1469. protected void CheckOutputOpen()
  1470. {
  1471. ThrowIfClosedOrNotOpen();
  1472. lock (ThisLock)
  1473. {
  1474. if (isOutputClosed)
  1475. {
  1476. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new CommunicationException(SR.GetString(SR.OutputNotExpected)));
  1477. }
  1478. }
  1479. }
  1480. protected override void OnAbort()
  1481. {
  1482. this.AbortCore();
  1483. this.inputSessionClosedHandle.Abort(this);
  1484. this.keyRenewalCompletedEvent.Abort(this);
  1485. this.outputSessionCloseHandle.Abort(this);
  1486. }
  1487. protected override void OnClose(TimeSpan timeout)
  1488. {
  1489. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1490. if (this.SendCloseHandshake)
  1491. {
  1492. bool wasAborted;
  1493. bool wasSessionClosed = this.CloseSession(timeout, out wasAborted);
  1494. if (wasAborted)
  1495. {
  1496. return;
  1497. }
  1498. if (!wasSessionClosed)
  1499. {
  1500. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.GetString(SR.ClientSecurityCloseTimeout, timeout)));
  1501. }
  1502. // wait for any concurrent output session close to finish
  1503. try
  1504. {
  1505. if (!this.outputSessionCloseHandle.Wait(timeoutHelper.RemainingTime(), false))
  1506. {
  1507. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.GetString(SR.ClientSecurityOutputSessionCloseTimeout, timeoutHelper.OriginalTimeout)));
  1508. }
  1509. }
  1510. catch (CommunicationObjectAbortedException)
  1511. {
  1512. if (this.State == CommunicationState.Closed)
  1513. {
  1514. return;
  1515. }
  1516. else
  1517. {
  1518. throw;
  1519. }
  1520. }
  1521. }
  1522. this.CloseCore(timeoutHelper.RemainingTime());
  1523. }
  1524. protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  1525. {
  1526. return new CloseAsyncResult(this, timeout, callback, state);
  1527. }
  1528. protected override void OnEndClose(IAsyncResult result)
  1529. {
  1530. CloseAsyncResult.End(result);
  1531. }
  1532. class CloseCoreAsyncResult : TraceAsyncResult
  1533. {
  1534. static AsyncCallback closeChannelBinderCallback = Fx.ThunkCallback(new AsyncCallback(ChannelBinderCloseCallback));
  1535. static AsyncCallback closeTokenProviderCallback = Fx.ThunkCallback(new AsyncCallback(CloseTokenProviderCallback));
  1536. TimeoutHelper timeoutHelper;
  1537. ClientSecuritySessionChannel channel;
  1538. public CloseCoreAsyncResult(ClientSecuritySessionChannel channel, TimeSpan timeout, AsyncCallback callback, object state)
  1539. : base(callback, state)
  1540. {
  1541. this.channel = channel;
  1542. this.timeoutHelper = new TimeoutHelper(timeout);
  1543. bool completeSelf = false;
  1544. if (channel.channelBinder != null)
  1545. {
  1546. try
  1547. {
  1548. IAsyncResult result = this.channel.channelBinder.BeginClose(timeoutHelper.RemainingTime(), closeChannelBinderCallback, this);
  1549. if (!result.CompletedSynchronously)
  1550. {
  1551. return;
  1552. }
  1553. this.channel.channelBinder.EndClose(result);
  1554. }
  1555. catch (CommunicationObjectAbortedException)
  1556. {
  1557. if (this.channel.State != CommunicationState.Closed)
  1558. {
  1559. throw;
  1560. }
  1561. completeSelf = true;
  1562. }
  1563. }
  1564. if (!completeSelf)
  1565. {
  1566. completeSelf = this.OnChannelBinderClosed();
  1567. }
  1568. if (completeSelf)
  1569. {
  1570. Complete(true);
  1571. }
  1572. }
  1573. static void ChannelBinderCloseCallback(IAsyncResult result)
  1574. {
  1575. if (result.CompletedSynchronously)
  1576. {
  1577. return;
  1578. }
  1579. CloseCoreAsyncResult self = (CloseCoreAsyncResult)(result.AsyncState);
  1580. Exception completionException = null;
  1581. bool completeSelf = false;
  1582. try
  1583. {
  1584. try
  1585. {
  1586. self.channel.channelBinder.EndClose(result);
  1587. }
  1588. catch (CommunicationObjectAbortedException)
  1589. {
  1590. if (self.channel.State != CommunicationState.Closed)
  1591. {
  1592. throw;
  1593. }
  1594. completeSelf = true;
  1595. }
  1596. if (!completeSelf)
  1597. {
  1598. completeSelf = self.OnChannelBinderClosed();
  1599. }
  1600. }
  1601. #pragma warning suppress 56500 // covered by FxCOP
  1602. catch (Exception e)
  1603. {
  1604. if (Fx.IsFatal(e))
  1605. {
  1606. throw;
  1607. }
  1608. completeSelf = true;
  1609. completionException = e;
  1610. }
  1611. if (completeSelf)
  1612. {
  1613. self.Complete(false, completionException);
  1614. }
  1615. }
  1616. bool OnChannelBinderClosed()
  1617. {
  1618. if (channel.sessionTokenProvider != null)
  1619. {
  1620. try
  1621. {
  1622. IAsyncResult result = SecurityUtils.BeginCloseTokenProviderIfRequired(this.channel.sessionTokenProvider, timeoutHelper.RemainingTime(), closeTokenProviderCallback, this);
  1623. if (!result.CompletedSynchronously)
  1624. {
  1625. return false;
  1626. }
  1627. SecurityUtils.EndCloseTokenProviderIfRequired(result);
  1628. }
  1629. catch (CommunicationObjectAbortedException)
  1630. {
  1631. if (channel.State != CommunicationState.Closed)
  1632. {
  1633. throw;
  1634. }
  1635. return true;
  1636. }
  1637. }
  1638. return this.OnTokenProviderClosed();
  1639. }
  1640. static void CloseTokenProviderCallback(IAsyncResult result)
  1641. {
  1642. if (result.CompletedSynchronously)
  1643. {
  1644. return;
  1645. }
  1646. CloseCoreAsyncResult self = (CloseCoreAsyncResult)(result.AsyncState);
  1647. Exception completionException = null;
  1648. bool completeSelf = false;
  1649. try
  1650. {
  1651. try
  1652. {
  1653. SecurityUtils.EndCloseTokenProviderIfRequired(result);
  1654. }
  1655. catch (CommunicationObjectAbortedException)
  1656. {
  1657. if (self.channel.State != CommunicationState.Closed)
  1658. {
  1659. throw;
  1660. }
  1661. completeSelf = true;
  1662. }
  1663. if (!completeSelf)
  1664. {
  1665. completeSelf = self.OnTokenProviderClosed();
  1666. }
  1667. }
  1668. #pragma warning suppress 56500 // covered by FxCOP
  1669. catch (Exception e)
  1670. {
  1671. if (Fx.IsFatal(e))
  1672. {
  1673. throw;
  1674. }
  1675. completeSelf = true;
  1676. completionException = e;
  1677. }
  1678. if (completeSelf)
  1679. {
  1680. self.Complete(false, completionException);
  1681. }
  1682. }
  1683. bool OnTokenProviderClosed()
  1684. {
  1685. this.channel.keyRenewalCompletedEvent.Abort(this.channel);
  1686. this.channel.inputSessionClosedHandle.Abort(this.channel);
  1687. return true;
  1688. }
  1689. public static void End(IAsyncResult result)
  1690. {
  1691. AsyncResult.End<CloseCoreAsyncResult>(result);
  1692. }
  1693. }
  1694. class ReceiveAsyncResult : TraceAsyncResult
  1695. {
  1696. static AsyncCallback onReceive = Fx.ThunkCallback(new AsyncCallback(OnReceive));
  1697. ClientSecuritySessionChannel channel;
  1698. Message message;
  1699. SecurityProtocolCorrelationState correlationState;
  1700. TimeoutHelper timeoutHelper;
  1701. public ReceiveAsyncResult(ClientSecuritySessionChannel channel, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
  1702. : base(callback, state)
  1703. {
  1704. this.channel = channel;
  1705. this.correlationState = correlationState;
  1706. this.timeoutHelper = new TimeoutHelper(timeout);
  1707. IAsyncResult result = channel.ChannelBinder.BeginTryReceive(timeoutHelper.RemainingTime(), onReceive, this);
  1708. if (!result.CompletedSynchronously)
  1709. return;
  1710. bool completedSynchronously = CompleteReceive(result);
  1711. if (completedSynchronously)
  1712. {
  1713. Complete(true);
  1714. }
  1715. }
  1716. bool CompleteReceive(IAsyncResult result)
  1717. {
  1718. while (!channel.isInputClosed)
  1719. {
  1720. RequestContext requestContext;
  1721. if (channel.ChannelBinder.EndTryReceive(result, out requestContext))
  1722. {
  1723. if (requestContext == null)
  1724. break;
  1725. message = channel.ProcessRequestContext(requestContext, timeoutHelper.RemainingTime(), this.correlationState);
  1726. if (message != null || channel.isInputClosed)
  1727. break;
  1728. }
  1729. TimeSpan timeout = timeoutHelper.RemainingTime();
  1730. if (timeout == TimeSpan.Zero)
  1731. {
  1732. // we timed out
  1733. break;
  1734. }
  1735. result = channel.ChannelBinder.BeginTryReceive(timeoutHelper.RemainingTime(), onReceive, this);
  1736. if (!result.CompletedSynchronously)
  1737. return false;
  1738. }
  1739. return true;
  1740. }
  1741. public static Message End(IAsyncResult result)
  1742. {
  1743. ReceiveAsyncResult receiveResult = AsyncResult.End<ReceiveAsyncResult>(result);
  1744. return receiveResult.message;
  1745. }
  1746. static void OnReceive(IAsyncResult result)
  1747. {
  1748. if (result.CompletedSynchronously)
  1749. return;
  1750. ReceiveAsyncResult self = (ReceiveAsyncResult)result.AsyncState;
  1751. bool completeSelf = false;
  1752. Exception completionException = null;
  1753. try
  1754. {
  1755. completeSelf = self.CompleteReceive(result);
  1756. }
  1757. #pragma warning suppress 56500 // covered by FxCOP
  1758. catch (Exception e)
  1759. {
  1760. if (Fx.IsFatal(e))
  1761. {
  1762. throw;
  1763. }
  1764. completeSelf = true;
  1765. completionException = e;
  1766. }
  1767. if (completeSelf)
  1768. {
  1769. self.Complete(false, completionException);
  1770. }
  1771. }
  1772. }
  1773. class OpenAsyncResult : TraceAsyncResult
  1774. {
  1775. static readonly AsyncCallback getTokenCallback = Fx.ThunkCallback(new AsyncCallback(GetTokenCallback));
  1776. static readonly AsyncCallback openTokenProviderCallback = Fx.ThunkCallback(new AsyncCallback(OpenTokenProviderCallback));
  1777. ClientSecuritySessionChannel sessionChannel;
  1778. TimeoutHelper timeoutHelper;
  1779. public OpenAsyncResult(ClientSecuritySessionChannel sessionChannel, TimeSpan timeout, AsyncCallback callback, object state)
  1780. : base(callback, state)
  1781. {
  1782. this.timeoutHelper = new TimeoutHelper(timeout);
  1783. this.sessionChannel = sessionChannel;
  1784. this.sessionChannel.SetupSessionTokenProvider();
  1785. IAsyncResult result = SecurityUtils.BeginOpenTokenProviderIfRequired(this.sessionChannel.sessionTokenProvider, timeoutHelper.RemainingTime(), openTokenProviderCallback, this);
  1786. if (!result.CompletedSynchronously)
  1787. {
  1788. return;
  1789. }
  1790. SecurityUtils.EndOpenTokenProviderIfRequired(result);
  1791. bool completeSelf = this.OnTokenProviderOpened();
  1792. if (completeSelf)
  1793. {
  1794. Complete(true);
  1795. }
  1796. }
  1797. static void OpenTokenProviderCallback(IAsyncResult result)
  1798. {
  1799. if (result.CompletedSynchronously)
  1800. {
  1801. return;
  1802. }
  1803. OpenAsyncResult thisAsyncResult = (OpenAsyncResult)result.AsyncState;
  1804. bool completeSelf = false;
  1805. Exception completionException = null;
  1806. try
  1807. {
  1808. SecurityUtils.EndOpenTokenProviderIfRequired(result);
  1809. completeSelf = thisAsyncResult.OnTokenProviderOpened();
  1810. }
  1811. #pragma warning suppress 56500 // covered by FxCOP
  1812. catch (Exception e)
  1813. {
  1814. if (Fx.IsFatal(e))
  1815. {
  1816. throw;
  1817. }
  1818. completeSelf = true;
  1819. completionException = e;
  1820. }
  1821. if (completeSelf)
  1822. {
  1823. thisAsyncResult.Complete(false, completionException);
  1824. }
  1825. }
  1826. bool OnTokenProviderOpened()
  1827. {
  1828. IAsyncResult result = this.sessionChannel.sessionTokenProvider.BeginGetToken(timeoutHelper.RemainingTime(), getTokenCallback, this);
  1829. if (!result.CompletedSynchronously)
  1830. {
  1831. return false;
  1832. }
  1833. SecurityToken sessionToken = this.sessionChannel.sessionTokenProvider.EndGetToken(result);
  1834. return this.OnTokenObtained(sessionToken);
  1835. }
  1836. bool OnTokenObtained(SecurityToken sessionToken)
  1837. {
  1838. // Token was issued, do send cancel on close;
  1839. this.sessionChannel.sendCloseHandshake = true;
  1840. this.sessionChannel.OpenCore(sessionToken, timeoutHelper.RemainingTime());
  1841. return true;
  1842. }
  1843. static void GetTokenCallback(IAsyncResult result)
  1844. {
  1845. if (result.CompletedSynchronously)
  1846. {
  1847. return;
  1848. }
  1849. OpenAsyncResult thisAsyncResult = (OpenAsyncResult)result.AsyncState;
  1850. try
  1851. {
  1852. using (ServiceModelActivity.BoundOperation(thisAsyncResult.CallbackActivity))
  1853. {
  1854. bool completeSelf = false;
  1855. Exception completionException = null;
  1856. try
  1857. {
  1858. SecurityToken sessionToken = thisAsyncResult.sessionChannel.sessionTokenProvider.EndGetToken(result);
  1859. completeSelf = thisAsyncResult.OnTokenObtained(sessionToken);
  1860. }
  1861. #pragma warning suppress 56500 // covered by FxCOP
  1862. catch (Exception e)
  1863. {
  1864. if (Fx.IsFatal(e))
  1865. {
  1866. throw;
  1867. }
  1868. completeSelf = true;
  1869. completionException = e;
  1870. }
  1871. if (completeSelf)
  1872. {
  1873. thisAsyncResult.Complete(false, completionException);
  1874. }
  1875. }
  1876. }
  1877. finally
  1878. {
  1879. if (thisAsyncResult.CallbackActivity != null)
  1880. {
  1881. thisAsyncResult.CallbackActivity.Dispose();
  1882. }
  1883. }
  1884. }
  1885. public static void End(IAsyncResult result)
  1886. {
  1887. AsyncResult.End<OpenAsyncResult>(result);
  1888. ServiceModelActivity.Stop(((OpenAsyncResult)result).CallbackActivity);
  1889. }
  1890. }
  1891. class CloseSessionAsyncResult : TraceAsyncResult
  1892. {
  1893. static readonly AsyncCallback closeOutputSessionCallback = Fx.ThunkCallback(new AsyncCallback(CloseOutputSessionCallback));
  1894. static readonly AsyncCallback shutdownWaitCallback = Fx.ThunkCallback(new AsyncCallback(ShutdownWaitCallback));
  1895. ClientSecuritySessionChannel sessionChannel;
  1896. bool closeCompleted;
  1897. bool wasAborted;
  1898. TimeoutHelper timeoutHelper;
  1899. public CloseSessionAsyncResult(TimeSpan timeout, ClientSecuritySessionChannel sessionChannel, AsyncCallback callback, object state)
  1900. : base(callback, state)
  1901. {
  1902. this.timeoutHelper = new TimeoutHelper(timeout);
  1903. this.sessionChannel = sessionChannel;
  1904. bool completeSelf = false;
  1905. try
  1906. {
  1907. IAsyncResult result = this.sessionChannel.BeginCloseOutputSession(timeoutHelper.RemainingTime(), closeOutputSessionCallback, this);
  1908. if (!result.CompletedSynchronously)
  1909. {
  1910. return;
  1911. }
  1912. this.sessionChannel.EndCloseOutputSession(result);
  1913. }
  1914. catch (CommunicationObjectAbortedException)
  1915. {
  1916. if (this.sessionChannel.State != CommunicationState.Closed)
  1917. {
  1918. throw;
  1919. }
  1920. completeSelf = true;
  1921. wasAborted = true;
  1922. }
  1923. if (!wasAborted)
  1924. {
  1925. completeSelf = this.OnOutputSessionClosed();
  1926. }
  1927. if (completeSelf)
  1928. {
  1929. Complete(true);
  1930. }
  1931. }
  1932. static void CloseOutputSessionCallback(IAsyncResult result)
  1933. {
  1934. if (result.CompletedSynchronously)
  1935. {
  1936. return;
  1937. }
  1938. CloseSessionAsyncResult thisResult = (CloseSessionAsyncResult)result.AsyncState;
  1939. bool completeSelf = false;
  1940. Exception completionException = null;
  1941. try
  1942. {
  1943. try
  1944. {
  1945. thisResult.sessionChannel.EndCloseOutputSession(result);
  1946. }
  1947. catch (CommunicationObjectAbortedException)
  1948. {
  1949. if (thisResult.sessionChannel.State != CommunicationState.Closed)
  1950. {
  1951. throw;
  1952. }
  1953. thisResult.wasAborted = true;
  1954. completeSelf = true;
  1955. }
  1956. if (!thisResult.wasAborted)
  1957. {
  1958. completeSelf = thisResult.OnOutputSessionClosed();
  1959. }
  1960. }
  1961. #pragma warning suppress 56500 // covered by FxCOP
  1962. catch (Exception e)
  1963. {
  1964. if (Fx.IsFatal(e))
  1965. {
  1966. throw;
  1967. }
  1968. completeSelf = true;
  1969. completionException = e;
  1970. }
  1971. if (completeSelf)
  1972. {
  1973. thisResult.Complete(false, completionException);
  1974. }
  1975. }
  1976. bool OnOutputSessionClosed()
  1977. {
  1978. try
  1979. {
  1980. IAsyncResult result = this.sessionChannel.inputSessionClosedHandle.BeginWait(this.timeoutHelper.RemainingTime(), true, shutdownWaitCallback, this);
  1981. if (!result.CompletedSynchronously)
  1982. {
  1983. return false;
  1984. }
  1985. this.sessionChannel.inputSessionClosedHandle.EndWait(result);
  1986. this.closeCompleted = true;
  1987. }
  1988. catch (CommunicationObjectAbortedException)
  1989. {
  1990. if (this.sessionChannel.State != CommunicationState.Closed)
  1991. {
  1992. throw;
  1993. }
  1994. // if the channel was aborted by a parallel thread, allow the Close to
  1995. // complete cleanly
  1996. this.wasAborted = true;
  1997. }
  1998. catch (TimeoutException)
  1999. {
  2000. this.closeCompleted = false;
  2001. }
  2002. return true;
  2003. }
  2004. static void ShutdownWaitCallback(IAsyncResult result)
  2005. {
  2006. if (result.CompletedSynchronously)
  2007. {
  2008. return;
  2009. }
  2010. CloseSessionAsyncResult thisResult = (CloseSessionAsyncResult)result.AsyncState;
  2011. Exception completionException = null;
  2012. try
  2013. {
  2014. thisResult.sessionChannel.inputSessionClosedHandle.EndWait(result);
  2015. thisResult.closeCompleted = true;
  2016. }
  2017. catch (CommunicationObjectAbortedException)
  2018. {
  2019. if (thisResult.sessionChannel.State != CommunicationState.Closed)
  2020. {
  2021. throw;
  2022. }
  2023. thisResult.wasAborted = true;
  2024. }
  2025. catch (TimeoutException)
  2026. {
  2027. thisResult.closeCompleted = false;
  2028. }
  2029. #pragma warning suppress 56500 // covered by FxCOP
  2030. catch (Exception e)
  2031. {
  2032. if (Fx.IsFatal(e))
  2033. {
  2034. throw;
  2035. }
  2036. completionException = e;
  2037. }
  2038. thisResult.Complete(false, completionException);
  2039. }
  2040. public static bool End(IAsyncResult result, out bool wasAborted)
  2041. {
  2042. CloseSessionAsyncResult thisResult = AsyncResult.End<CloseSessionAsyncResult>(result);
  2043. wasAborted = thisResult.wasAborted;
  2044. ServiceModelActivity.Stop(thisResult.CallbackActivity);
  2045. return thisResult.closeCompleted;
  2046. }
  2047. }
  2048. class CloseAsyncResult : TraceAsyncResult
  2049. {
  2050. static readonly AsyncCallback closeSessionCallback = Fx.ThunkCallback(new AsyncCallback(CloseSessionCallback));
  2051. static readonly AsyncCallback outputSessionClosedCallback = Fx.ThunkCallback(new AsyncCallback(OutputSessionClosedCallback));
  2052. static readonly AsyncCallback closeCoreCallback = Fx.ThunkCallback(new AsyncCallback(CloseCoreCallback));
  2053. ClientSecuritySessionChannel sessionChannel;
  2054. TimeoutHelper timeoutHelper;
  2055. public CloseAsyncResult(ClientSecuritySessionChannel sessionChannel, TimeSpan timeout, AsyncCallback callback, object state)
  2056. : base(callback, state)
  2057. {
  2058. sessionChannel.ThrowIfFaulted();
  2059. this.timeoutHelper = new TimeoutHelper(timeout);
  2060. this.sessionChannel = sessionChannel;
  2061. if (!sessionChannel.SendCloseHandshake)
  2062. {
  2063. if (this.CloseCore())
  2064. {
  2065. Complete(true);
  2066. }
  2067. return;
  2068. }
  2069. bool wasClosed;
  2070. bool wasAborted = false;
  2071. IAsyncResult result = this.sessionChannel.BeginCloseSession(this.timeoutHelper.RemainingTime(), closeSessionCallback, this);
  2072. if (!result.CompletedSynchronously)
  2073. {
  2074. return;
  2075. }
  2076. wasClosed = this.sessionChannel.EndCloseSession(result, out wasAborted);
  2077. if (wasAborted)
  2078. {
  2079. Complete(true);
  2080. return;
  2081. }
  2082. if (!wasClosed)
  2083. {
  2084. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.GetString(SR.ClientSecurityCloseTimeout, timeout)));
  2085. }
  2086. bool completeSelf = this.OnWaitForOutputSessionClose(out wasAborted);
  2087. if (wasAborted || completeSelf)
  2088. {
  2089. Complete(true);
  2090. }
  2091. }
  2092. static void CloseSessionCallback(IAsyncResult result)
  2093. {
  2094. if (result.CompletedSynchronously)
  2095. {
  2096. return;
  2097. }
  2098. CloseAsyncResult thisResult = (CloseAsyncResult)result.AsyncState;
  2099. bool completeSelf = false;
  2100. Exception completionException = null;
  2101. try
  2102. {
  2103. bool wasAborted;
  2104. bool wasClosed = thisResult.sessionChannel.EndCloseSession(result, out wasAborted);
  2105. if (wasAborted)
  2106. {
  2107. completeSelf = true;
  2108. }
  2109. else
  2110. {
  2111. if (!wasClosed)
  2112. {
  2113. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.GetString(SR.ClientSecurityCloseTimeout, thisResult.timeoutHelper.OriginalTimeout)));
  2114. }
  2115. completeSelf = thisResult.OnWaitForOutputSessionClose(out wasAborted);
  2116. if (wasAborted)
  2117. {
  2118. completeSelf = true;
  2119. }
  2120. }
  2121. }
  2122. #pragma warning suppress 56500 // covered by FxCOP
  2123. catch (Exception e)
  2124. {
  2125. if (Fx.IsFatal(e))
  2126. {
  2127. throw;
  2128. }
  2129. completeSelf = true;
  2130. completionException = e;
  2131. }
  2132. if (completeSelf)
  2133. {
  2134. thisResult.Complete(false, completionException);
  2135. }
  2136. }
  2137. bool OnWaitForOutputSessionClose(out bool wasAborted)
  2138. {
  2139. wasAborted = false;
  2140. bool wasOutputSessionClosed = false;
  2141. // wait for pending output sessions to finish
  2142. try
  2143. {
  2144. IAsyncResult result = this.sessionChannel.outputSessionCloseHandle.BeginWait(timeoutHelper.RemainingTime(), true, outputSessionClosedCallback, this);
  2145. if (!result.CompletedSynchronously)
  2146. {
  2147. return false;
  2148. }
  2149. this.sessionChannel.outputSessionCloseHandle.EndWait(result);
  2150. wasOutputSessionClosed = true;
  2151. }
  2152. catch (TimeoutException)
  2153. {
  2154. wasOutputSessionClosed = false;
  2155. }
  2156. catch (CommunicationObjectAbortedException)
  2157. {
  2158. if (this.sessionChannel.State == CommunicationState.Closed)
  2159. {
  2160. wasAborted = true;
  2161. }
  2162. else
  2163. {
  2164. throw;
  2165. }
  2166. }
  2167. if (wasAborted)
  2168. {
  2169. return true;
  2170. }
  2171. if (!wasOutputSessionClosed)
  2172. {
  2173. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.GetString(SR.ClientSecurityOutputSessionCloseTimeout, timeoutHelper.OriginalTimeout)));
  2174. }
  2175. else
  2176. {
  2177. return this.CloseCore();
  2178. }
  2179. }
  2180. static void OutputSessionClosedCallback(IAsyncResult result)
  2181. {
  2182. if (result.CompletedSynchronously)
  2183. {
  2184. return;
  2185. }
  2186. CloseAsyncResult self = (CloseAsyncResult)(result.AsyncState);
  2187. Exception completionException = null;
  2188. bool completeSelf = false;
  2189. try
  2190. {
  2191. bool wasOutputSessionClosed = false;
  2192. bool wasAborted = false;
  2193. try
  2194. {
  2195. self.sessionChannel.outputSessionCloseHandle.EndWait(result);
  2196. wasOutputSessionClosed = true;
  2197. }
  2198. catch (TimeoutException)
  2199. {
  2200. wasOutputSessionClosed = false;
  2201. }
  2202. catch (CommunicationObjectFaultedException)
  2203. {
  2204. if (self.sessionChannel.State == CommunicationState.Closed)
  2205. {
  2206. wasAborted = true;
  2207. }
  2208. else
  2209. {
  2210. throw;
  2211. }
  2212. }
  2213. if (!wasAborted)
  2214. {
  2215. if (!wasOutputSessionClosed)
  2216. {
  2217. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.GetString(SR.ClientSecurityOutputSessionCloseTimeout, self.timeoutHelper.OriginalTimeout)));
  2218. }
  2219. completeSelf = self.CloseCore();
  2220. }
  2221. else
  2222. {
  2223. completeSelf = true;
  2224. }
  2225. }
  2226. #pragma warning suppress 56500 // covered by FxCOP
  2227. catch (Exception e)
  2228. {
  2229. if (Fx.IsFatal(e))
  2230. {
  2231. throw;
  2232. }
  2233. completionException = e;
  2234. completeSelf = true;
  2235. }
  2236. if (completeSelf)
  2237. {
  2238. self.Complete(false, completionException);
  2239. }
  2240. }
  2241. bool CloseCore()
  2242. {
  2243. IAsyncResult result = this.sessionChannel.BeginCloseCore(timeoutHelper.RemainingTime(), closeCoreCallback, this);
  2244. if (!result.CompletedSynchronously)
  2245. {
  2246. return false;
  2247. }
  2248. this.sessionChannel.EndCloseCore(result);
  2249. return true;
  2250. }
  2251. static void CloseCoreCallback(IAsyncResult result)
  2252. {
  2253. if (result.CompletedSynchronously)
  2254. {
  2255. return;
  2256. }
  2257. CloseAsyncResult self = (CloseAsyncResult)(result.AsyncState);
  2258. Exception completionException = null;
  2259. try
  2260. {
  2261. self.sessionChannel.EndCloseCore(result);
  2262. }
  2263. #pragma warning suppress 56500 // covered by FxCOP
  2264. catch (Exception e)
  2265. {
  2266. if (Fx.IsFatal(e))
  2267. {
  2268. throw;
  2269. }
  2270. completionException = e;
  2271. }
  2272. self.Complete(false, completionException);
  2273. }
  2274. public static void End(IAsyncResult result)
  2275. {
  2276. AsyncResult.End<CloseAsyncResult>(result);
  2277. }
  2278. }
  2279. class KeyRenewalAsyncResult : TraceAsyncResult
  2280. {
  2281. static readonly Action<object> renewKeyCallback = new Action<object>(RenewKeyCallback);
  2282. Message message;
  2283. ClientSecuritySessionChannel sessionChannel;
  2284. TimeoutHelper timeoutHelper;
  2285. public KeyRenewalAsyncResult(Message message, ClientSecuritySessionChannel sessionChannel, TimeSpan timeout, AsyncCallback callback, object state)
  2286. : base(callback, state)
  2287. {
  2288. timeoutHelper = new TimeoutHelper(timeout);
  2289. this.message = message;
  2290. this.sessionChannel = sessionChannel;
  2291. // its ok to start up a separate thread for this since this is a very rare event.
  2292. ActionItem.Schedule(renewKeyCallback, this);
  2293. }
  2294. static void RenewKeyCallback(object state)
  2295. {
  2296. KeyRenewalAsyncResult thisResult = (KeyRenewalAsyncResult)state;
  2297. Exception completionException = null;
  2298. try
  2299. {
  2300. using (thisResult.CallbackActivity == null ? null : ServiceModelActivity.BoundOperation(thisResult.CallbackActivity))
  2301. {
  2302. thisResult.sessionChannel.RenewKey(thisResult.timeoutHelper.RemainingTime());
  2303. }
  2304. }
  2305. #pragma warning suppress 56500 // covered by FxCOP
  2306. catch (Exception e)
  2307. {
  2308. if (Fx.IsFatal(e))
  2309. {
  2310. throw;
  2311. }
  2312. completionException = e;
  2313. }
  2314. thisResult.Complete(false, completionException);
  2315. }
  2316. public static Message End(IAsyncResult result, out TimeSpan remainingTime)
  2317. {
  2318. KeyRenewalAsyncResult thisResult = AsyncResult.End<KeyRenewalAsyncResult>(result);
  2319. remainingTime = thisResult.timeoutHelper.RemainingTime();
  2320. return thisResult.message;
  2321. }
  2322. }
  2323. internal abstract class SecureSendAsyncResultBase : TraceAsyncResult
  2324. {
  2325. static readonly AsyncCallback secureOutgoingMessageCallback = Fx.ThunkCallback(new AsyncCallback(SecureOutgoingMessageCallback));
  2326. Message message;
  2327. SecurityProtocolCorrelationState correlationState;
  2328. ClientSecuritySessionChannel sessionChannel;
  2329. bool didSecureOutgoingMessageCompleteSynchronously = false;
  2330. TimeoutHelper timeoutHelper;
  2331. protected SecureSendAsyncResultBase(Message message, ClientSecuritySessionChannel sessionChannel, TimeSpan timeout, AsyncCallback callback, object state)
  2332. : base(callback, state)
  2333. {
  2334. this.message = message;
  2335. this.sessionChannel = sessionChannel;
  2336. this.timeoutHelper = new TimeoutHelper(timeout);
  2337. IAsyncResult result = this.sessionChannel.BeginSecureOutgoingMessage(message, timeoutHelper.RemainingTime(), secureOutgoingMessageCallback, this);
  2338. if (!result.CompletedSynchronously)
  2339. {
  2340. return;
  2341. }
  2342. this.message = this.sessionChannel.EndSecureOutgoingMessage(result, out this.correlationState);
  2343. this.didSecureOutgoingMessageCompleteSynchronously = true;
  2344. }
  2345. protected bool DidSecureOutgoingMessageCompleteSynchronously
  2346. {
  2347. get
  2348. {
  2349. return this.didSecureOutgoingMessageCompleteSynchronously;
  2350. }
  2351. }
  2352. protected TimeoutHelper TimeoutHelper
  2353. {
  2354. get
  2355. {
  2356. return this.timeoutHelper;
  2357. }
  2358. }
  2359. protected IClientReliableChannelBinder ChannelBinder
  2360. {
  2361. get
  2362. {
  2363. return this.sessionChannel.ChannelBinder;
  2364. }
  2365. }
  2366. protected Message Message
  2367. {
  2368. get
  2369. {
  2370. return this.message;
  2371. }
  2372. }
  2373. protected SecurityProtocolCorrelationState SecurityCorrelationState
  2374. {
  2375. get
  2376. {
  2377. return this.correlationState;
  2378. }
  2379. }
  2380. protected abstract bool OnMessageSecured();
  2381. static void SecureOutgoingMessageCallback(IAsyncResult result)
  2382. {
  2383. if (result.CompletedSynchronously)
  2384. {
  2385. return;
  2386. }
  2387. SecureSendAsyncResultBase thisResult = (SecureSendAsyncResultBase)result.AsyncState;
  2388. bool completeSelf = false;
  2389. Exception completionException = null;
  2390. try
  2391. {
  2392. thisResult.message = thisResult.sessionChannel.EndSecureOutgoingMessage(result, out thisResult.correlationState);
  2393. completeSelf = thisResult.OnMessageSecured();
  2394. }
  2395. #pragma warning suppress 56500 // covered by FxCOP
  2396. catch (Exception e)
  2397. {
  2398. if (Fx.IsFatal(e))
  2399. {
  2400. throw;
  2401. }
  2402. completeSelf = true;
  2403. completionException = e;
  2404. }
  2405. if (completeSelf)
  2406. {
  2407. thisResult.Complete(false, completionException);
  2408. }
  2409. }
  2410. }
  2411. internal sealed class SecureSendAsyncResult : SecureSendAsyncResultBase
  2412. {
  2413. static readonly AsyncCallback sendCallback = Fx.ThunkCallback(new AsyncCallback(SendCallback));
  2414. bool autoCloseMessage;
  2415. public SecureSendAsyncResult(Message message, ClientSecuritySessionChannel sessionChannel, TimeSpan timeout, AsyncCallback callback, object state, bool autoCloseMessage)
  2416. : base(message, sessionChannel, timeout, callback, state)
  2417. {
  2418. this.autoCloseMessage = autoCloseMessage;
  2419. if (!this.DidSecureOutgoingMessageCompleteSynchronously)
  2420. {
  2421. return;
  2422. }
  2423. bool completeSelf = this.OnMessageSecured();
  2424. if (completeSelf)
  2425. {
  2426. Complete(true);
  2427. }
  2428. }
  2429. protected override bool OnMessageSecured()
  2430. {
  2431. bool closeMessage = true;
  2432. try
  2433. {
  2434. IAsyncResult result = this.ChannelBinder.BeginSend(this.Message, this.TimeoutHelper.RemainingTime(), sendCallback, this);
  2435. if (!result.CompletedSynchronously)
  2436. {
  2437. closeMessage = false;
  2438. return false;
  2439. }
  2440. this.ChannelBinder.EndSend(result);
  2441. return true;
  2442. }
  2443. finally
  2444. {
  2445. if (closeMessage && this.autoCloseMessage && this.Message != null)
  2446. {
  2447. this.Message.Close();
  2448. }
  2449. }
  2450. }
  2451. static void SendCallback(IAsyncResult result)
  2452. {
  2453. if (result.CompletedSynchronously)
  2454. {
  2455. return;
  2456. }
  2457. SecureSendAsyncResult thisResult = (SecureSendAsyncResult)result.AsyncState;
  2458. Exception completionException = null;
  2459. try
  2460. {
  2461. thisResult.ChannelBinder.EndSend(result);
  2462. }
  2463. #pragma warning suppress 56500 // covered by FxCOP
  2464. catch (Exception e)
  2465. {
  2466. if (Fx.IsFatal(e))
  2467. {
  2468. throw;
  2469. }
  2470. completionException = e;
  2471. }
  2472. finally
  2473. {
  2474. if (thisResult.autoCloseMessage && thisResult.Message != null)
  2475. {
  2476. thisResult.Message.Close();
  2477. }
  2478. if (thisResult.CallbackActivity != null && DiagnosticUtility.ShouldUseActivity)
  2479. {
  2480. thisResult.CallbackActivity.Stop();
  2481. }
  2482. }
  2483. thisResult.Complete(false, completionException);
  2484. }
  2485. public static SecurityProtocolCorrelationState End(IAsyncResult result)
  2486. {
  2487. SecureSendAsyncResult thisResult = AsyncResult.End<SecureSendAsyncResult>(result);
  2488. return thisResult.SecurityCorrelationState;
  2489. }
  2490. }
  2491. protected class SoapSecurityOutputSession : ISecureConversationSession, IOutputSession
  2492. {
  2493. ClientSecuritySessionChannel channel;
  2494. EndpointIdentity remoteIdentity;
  2495. UniqueId sessionId;
  2496. SecurityKeyIdentifierClause sessionTokenIdentifier;
  2497. SecurityStandardsManager standardsManager;
  2498. public SoapSecurityOutputSession(ClientSecuritySessionChannel channel)
  2499. {
  2500. this.channel = channel;
  2501. }
  2502. internal void Initialize(SecurityToken sessionToken, SecuritySessionClientSettings<TChannel> settings)
  2503. {
  2504. if (sessionToken == null)
  2505. {
  2506. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sessionToken");
  2507. }
  2508. if (settings == null)
  2509. {
  2510. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("settings");
  2511. }
  2512. Claim identityClaim = SecurityUtils.GetPrimaryIdentityClaim(((GenericXmlSecurityToken)sessionToken).AuthorizationPolicies);
  2513. if (identityClaim != null)
  2514. {
  2515. this.remoteIdentity = EndpointIdentity.CreateIdentity(identityClaim);
  2516. }
  2517. this.standardsManager = settings.SessionProtocolFactory.StandardsManager;
  2518. this.sessionId = GetSessionId(sessionToken, this.standardsManager);
  2519. this.sessionTokenIdentifier = settings.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(sessionToken,
  2520. SecurityTokenReferenceStyle.External);
  2521. }
  2522. UniqueId GetSessionId(SecurityToken sessionToken, SecurityStandardsManager standardsManager)
  2523. {
  2524. GenericXmlSecurityToken gxt = sessionToken as GenericXmlSecurityToken;
  2525. if (gxt == null)
  2526. {
  2527. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SessionTokenIsNotGenericXmlToken, sessionToken, typeof(GenericXmlSecurityToken))));
  2528. }
  2529. return standardsManager.SecureConversationDriver.GetSecurityContextTokenId(XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(gxt.TokenXml)));
  2530. }
  2531. public string Id
  2532. {
  2533. get
  2534. {
  2535. if (this.sessionId == null)
  2536. {
  2537. // PreSharp Bug: Property get methods should not throw exceptions.
  2538. #pragma warning suppress 56503
  2539. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ChannelMustBeOpenedToGetSessionId)));
  2540. }
  2541. return this.sessionId.ToString();
  2542. }
  2543. }
  2544. public EndpointIdentity RemoteIdentity
  2545. {
  2546. get
  2547. {
  2548. return this.remoteIdentity;
  2549. }
  2550. }
  2551. public void WriteSessionTokenIdentifier(XmlDictionaryWriter writer)
  2552. {
  2553. this.channel.ThrowIfDisposedOrNotOpen();
  2554. this.standardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(writer, this.sessionTokenIdentifier);
  2555. }
  2556. public bool TryReadSessionTokenIdentifier(XmlReader reader)
  2557. {
  2558. this.channel.ThrowIfDisposedOrNotOpen();
  2559. if (!this.standardsManager.SecurityTokenSerializer.CanReadKeyIdentifierClause(reader))
  2560. {
  2561. return false;
  2562. }
  2563. SecurityContextKeyIdentifierClause incomingTokenIdentifier =
  2564. this.standardsManager.SecurityTokenSerializer.ReadKeyIdentifierClause(reader) as SecurityContextKeyIdentifierClause;
  2565. return incomingTokenIdentifier != null && incomingTokenIdentifier.Matches(sessionId, null);
  2566. }
  2567. }
  2568. }
  2569. abstract class ClientSecuritySimplexSessionChannel : ClientSecuritySessionChannel
  2570. {
  2571. SoapSecurityOutputSession outputSession;
  2572. protected ClientSecuritySimplexSessionChannel(SecuritySessionClientSettings<TChannel> settings, EndpointAddress to, Uri via)
  2573. : base(settings, to, via)
  2574. {
  2575. this.outputSession = new SoapSecurityOutputSession(this);
  2576. }
  2577. public IOutputSession Session
  2578. {
  2579. get
  2580. {
  2581. return this.outputSession;
  2582. }
  2583. }
  2584. protected override bool ExpectClose
  2585. {
  2586. get { return false; }
  2587. }
  2588. protected override string SessionId
  2589. {
  2590. get { return this.Session.Id; }
  2591. }
  2592. protected override void InitializeSession(SecurityToken sessionToken)
  2593. {
  2594. this.outputSession.Initialize(sessionToken, this.Settings);
  2595. }
  2596. }
  2597. sealed class SecurityRequestSessionChannel : ClientSecuritySimplexSessionChannel, IRequestSessionChannel
  2598. {
  2599. public SecurityRequestSessionChannel(SecuritySessionClientSettings<TChannel> settings, EndpointAddress to, Uri via)
  2600. : base(settings, to, via)
  2601. {
  2602. }
  2603. protected override bool CanDoSecurityCorrelation
  2604. {
  2605. get
  2606. {
  2607. return true;
  2608. }
  2609. }
  2610. protected override SecurityProtocolCorrelationState CloseOutputSession(TimeSpan timeout)
  2611. {
  2612. ThrowIfFaulted();
  2613. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  2614. SecurityProtocolCorrelationState correlationState = base.CloseOutputSession(timeoutHelper.RemainingTime());
  2615. Message message = ReceiveInternal(timeoutHelper.RemainingTime(), correlationState);
  2616. if (message != null)
  2617. {
  2618. using (message)
  2619. {
  2620. ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message);
  2621. throw TraceUtility.ThrowHelperWarning(error, message);
  2622. }
  2623. }
  2624. return null;
  2625. }
  2626. protected override IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state)
  2627. {
  2628. ThrowIfFaulted();
  2629. return new CloseOutputSessionAsyncResult(this, timeout, callback, state);
  2630. }
  2631. protected override SecurityProtocolCorrelationState EndCloseOutputSession(IAsyncResult result)
  2632. {
  2633. CloseOutputSessionAsyncResult.End(result);
  2634. return null;
  2635. }
  2636. IAsyncResult BeginBaseCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state)
  2637. {
  2638. return base.BeginCloseOutputSession(timeout, callback, state);
  2639. }
  2640. SecurityProtocolCorrelationState EndBaseCloseOutputSession(IAsyncResult result)
  2641. {
  2642. return base.EndCloseOutputSession(result);
  2643. }
  2644. public Message Request(Message message)
  2645. {
  2646. return this.Request(message, this.DefaultSendTimeout);
  2647. }
  2648. Message ProcessReply(Message reply, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
  2649. {
  2650. if (reply == null)
  2651. {
  2652. return null;
  2653. }
  2654. Message unverifiedReply = reply;
  2655. Message processedReply = null;
  2656. MessageFault protocolFault = null;
  2657. Exception faultException = null;
  2658. try
  2659. {
  2660. processedReply = this.ProcessIncomingMessage(reply, timeout, correlationState, out protocolFault);
  2661. }
  2662. catch (MessageSecurityException)
  2663. {
  2664. if (unverifiedReply.IsFault)
  2665. {
  2666. MessageFault fault = MessageFault.CreateFault(unverifiedReply, TransportDefaults.MaxSecurityFaultSize);
  2667. if (SecurityUtils.IsSecurityFault(fault, this.Settings.standardsManager))
  2668. {
  2669. faultException = SecurityUtils.CreateSecurityFaultException(fault);
  2670. }
  2671. }
  2672. if (faultException == null)
  2673. {
  2674. throw;
  2675. }
  2676. }
  2677. if (faultException != null)
  2678. {
  2679. Fault(faultException);
  2680. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(faultException);
  2681. }
  2682. if (processedReply == null && protocolFault != null)
  2683. {
  2684. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SecuritySessionFaultReplyWasSent), new FaultException(protocolFault)));
  2685. }
  2686. return processedReply;
  2687. }
  2688. public Message Request(Message message, TimeSpan timeout)
  2689. {
  2690. ThrowIfFaulted();
  2691. CheckOutputOpen();
  2692. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  2693. SecurityProtocolCorrelationState correlationState = this.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime());
  2694. Message reply = this.ChannelBinder.Request(message, timeoutHelper.RemainingTime());
  2695. return ProcessReply(reply, timeoutHelper.RemainingTime(), correlationState);
  2696. }
  2697. public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
  2698. {
  2699. return this.BeginRequest(message, this.DefaultSendTimeout, callback, state);
  2700. }
  2701. public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
  2702. {
  2703. ThrowIfFaulted();
  2704. CheckOutputOpen();
  2705. return new SecureRequestAsyncResult(message, this, timeout, callback, state);
  2706. }
  2707. public Message EndRequest(IAsyncResult result)
  2708. {
  2709. SecurityProtocolCorrelationState requestCorrelationState;
  2710. TimeSpan remainingTime;
  2711. Message reply = SecureRequestAsyncResult.EndAsReply(result, out requestCorrelationState, out remainingTime);
  2712. return ProcessReply(reply, remainingTime, requestCorrelationState);
  2713. }
  2714. sealed class SecureRequestAsyncResult : SecureSendAsyncResultBase
  2715. {
  2716. static readonly AsyncCallback requestCallback = Fx.ThunkCallback(new AsyncCallback(RequestCallback));
  2717. Message reply;
  2718. public SecureRequestAsyncResult(Message request, ClientSecuritySessionChannel sessionChannel, TimeSpan timeout, AsyncCallback callback, object state)
  2719. : base(request, sessionChannel, timeout, callback, state)
  2720. {
  2721. if (!this.DidSecureOutgoingMessageCompleteSynchronously)
  2722. {
  2723. return;
  2724. }
  2725. bool completeSelf = OnMessageSecured();
  2726. if (completeSelf)
  2727. {
  2728. Complete(true);
  2729. }
  2730. }
  2731. protected override bool OnMessageSecured()
  2732. {
  2733. IAsyncResult result = this.ChannelBinder.BeginRequest(this.Message, this.TimeoutHelper.RemainingTime(), requestCallback, this);
  2734. if (!result.CompletedSynchronously)
  2735. {
  2736. return false;
  2737. }
  2738. this.reply = this.ChannelBinder.EndRequest(result);
  2739. return true;
  2740. }
  2741. static void RequestCallback(IAsyncResult result)
  2742. {
  2743. if (result.CompletedSynchronously)
  2744. {
  2745. return;
  2746. }
  2747. SecureRequestAsyncResult thisAsyncResult = (SecureRequestAsyncResult)result.AsyncState;
  2748. Exception completionException = null;
  2749. try
  2750. {
  2751. thisAsyncResult.reply = thisAsyncResult.ChannelBinder.EndRequest(result);
  2752. }
  2753. #pragma warning suppress 56500 // covered by FxCOP
  2754. catch (Exception e)
  2755. {
  2756. if (Fx.IsFatal(e))
  2757. {
  2758. throw;
  2759. }
  2760. completionException = e;
  2761. }
  2762. thisAsyncResult.Complete(false, completionException);
  2763. }
  2764. public static Message EndAsReply(IAsyncResult result, out SecurityProtocolCorrelationState correlationState, out TimeSpan remainingTime)
  2765. {
  2766. SecureRequestAsyncResult thisResult = AsyncResult.End<SecureRequestAsyncResult>(result);
  2767. correlationState = thisResult.SecurityCorrelationState;
  2768. remainingTime = thisResult.TimeoutHelper.RemainingTime();
  2769. return thisResult.reply;
  2770. }
  2771. }
  2772. class CloseOutputSessionAsyncResult : TraceAsyncResult
  2773. {
  2774. static readonly AsyncCallback baseCloseOutputSessionCallback = Fx.ThunkCallback(new AsyncCallback(BaseCloseOutputSessionCallback));
  2775. static readonly AsyncCallback receiveInternalCallback = Fx.ThunkCallback(new AsyncCallback(ReceiveInternalCallback));
  2776. SecurityRequestSessionChannel requestChannel;
  2777. SecurityProtocolCorrelationState correlationState;
  2778. TimeoutHelper timeoutHelper;
  2779. public CloseOutputSessionAsyncResult(SecurityRequestSessionChannel requestChannel, TimeSpan timeout, AsyncCallback callback, object state)
  2780. : base(callback, state)
  2781. {
  2782. this.timeoutHelper = new TimeoutHelper(timeout);
  2783. this.requestChannel = requestChannel;
  2784. IAsyncResult result = this.requestChannel.BeginBaseCloseOutputSession(timeoutHelper.RemainingTime(), baseCloseOutputSessionCallback, this);
  2785. if (!result.CompletedSynchronously)
  2786. {
  2787. return;
  2788. }
  2789. this.correlationState = this.requestChannel.EndBaseCloseOutputSession(result);
  2790. bool completeSelf = this.OnBaseOutputSessionClosed();
  2791. if (completeSelf)
  2792. {
  2793. Complete(true);
  2794. }
  2795. }
  2796. static void BaseCloseOutputSessionCallback(IAsyncResult result)
  2797. {
  2798. if (result.CompletedSynchronously)
  2799. {
  2800. return;
  2801. }
  2802. CloseOutputSessionAsyncResult thisAsyncResult = (CloseOutputSessionAsyncResult)result.AsyncState;
  2803. bool completeSelf = false;
  2804. Exception completionException = null;
  2805. try
  2806. {
  2807. thisAsyncResult.correlationState = thisAsyncResult.requestChannel.EndBaseCloseOutputSession(result);
  2808. completeSelf = thisAsyncResult.OnBaseOutputSessionClosed();
  2809. }
  2810. #pragma warning suppress 56500 // covered by FxCOP
  2811. catch (Exception e)
  2812. {
  2813. if (Fx.IsFatal(e))
  2814. {
  2815. throw;
  2816. }
  2817. completeSelf = true;
  2818. completionException = e;
  2819. }
  2820. if (completeSelf)
  2821. {
  2822. thisAsyncResult.Complete(false, completionException);
  2823. }
  2824. }
  2825. bool OnBaseOutputSessionClosed()
  2826. {
  2827. IAsyncResult result = this.requestChannel.BeginReceiveInternal(this.timeoutHelper.RemainingTime(), this.correlationState, receiveInternalCallback, this);
  2828. if (!result.CompletedSynchronously)
  2829. {
  2830. return false;
  2831. }
  2832. Message message = this.requestChannel.EndReceiveInternal(result);
  2833. return this.OnMessageReceived(message);
  2834. }
  2835. static void ReceiveInternalCallback(IAsyncResult result)
  2836. {
  2837. if (result.CompletedSynchronously)
  2838. {
  2839. return;
  2840. }
  2841. CloseOutputSessionAsyncResult thisAsyncResult = (CloseOutputSessionAsyncResult)result.AsyncState;
  2842. bool completeSelf = false;
  2843. Exception completionException = null;
  2844. try
  2845. {
  2846. Message message = thisAsyncResult.requestChannel.EndReceiveInternal(result);
  2847. completeSelf = thisAsyncResult.OnMessageReceived(message);
  2848. }
  2849. #pragma warning suppress 56500 // covered by FxCOP
  2850. catch (Exception e)
  2851. {
  2852. if (Fx.IsFatal(e))
  2853. {
  2854. throw;
  2855. }
  2856. completeSelf = true;
  2857. completionException = e;
  2858. }
  2859. if (completeSelf)
  2860. {
  2861. thisAsyncResult.Complete(false, completionException);
  2862. }
  2863. }
  2864. bool OnMessageReceived(Message message)
  2865. {
  2866. if (message != null)
  2867. {
  2868. using (message)
  2869. {
  2870. ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message);
  2871. throw TraceUtility.ThrowHelperWarning(error, message);
  2872. }
  2873. }
  2874. return true;
  2875. }
  2876. public static void End(IAsyncResult result)
  2877. {
  2878. AsyncResult.End<CloseOutputSessionAsyncResult>(result);
  2879. }
  2880. }
  2881. }
  2882. class ClientSecurityDuplexSessionChannel : ClientSecuritySessionChannel, IDuplexSessionChannel
  2883. {
  2884. static AsyncCallback onReceive = Fx.ThunkCallback(new AsyncCallback(OnReceive));
  2885. SoapSecurityClientDuplexSession session;
  2886. InputQueue<Message> queue;
  2887. Action startReceiving;
  2888. Action<object> completeLater;
  2889. public ClientSecurityDuplexSessionChannel(SecuritySessionClientSettings<TChannel> settings, EndpointAddress to, Uri via)
  2890. : base(settings, to, via)
  2891. {
  2892. this.session = new SoapSecurityClientDuplexSession(this);
  2893. this.queue = TraceUtility.CreateInputQueue<Message>();
  2894. this.startReceiving = new Action(StartReceiving);
  2895. this.completeLater = new Action<object>(CompleteLater);
  2896. }
  2897. public EndpointAddress LocalAddress
  2898. {
  2899. get
  2900. {
  2901. return base.InternalLocalAddress;
  2902. }
  2903. }
  2904. public IDuplexSession Session
  2905. {
  2906. get
  2907. {
  2908. return this.session;
  2909. }
  2910. }
  2911. protected override bool ExpectClose
  2912. {
  2913. get { return true; }
  2914. }
  2915. protected override string SessionId
  2916. {
  2917. get { return this.session.Id; }
  2918. }
  2919. public Message Receive()
  2920. {
  2921. return this.Receive(this.DefaultReceiveTimeout);
  2922. }
  2923. public Message Receive(TimeSpan timeout)
  2924. {
  2925. return InputChannel.HelpReceive(this, timeout);
  2926. }
  2927. public IAsyncResult BeginReceive(AsyncCallback callback, object state)
  2928. {
  2929. return this.BeginReceive(this.DefaultReceiveTimeout, callback, state);
  2930. }
  2931. public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
  2932. {
  2933. return InputChannel.HelpBeginReceive(this, timeout, callback, state);
  2934. }
  2935. public Message EndReceive(IAsyncResult result)
  2936. {
  2937. return InputChannel.HelpEndReceive(result);
  2938. }
  2939. public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state)
  2940. {
  2941. ThrowIfFaulted();
  2942. return queue.BeginDequeue(timeout, callback, state);
  2943. }
  2944. public bool EndTryReceive(IAsyncResult result, out Message message)
  2945. {
  2946. bool wasDequeued = queue.EndDequeue(result, out message);
  2947. if (message == null)
  2948. {
  2949. // the channel could have faulted, shutting down the input queue
  2950. ThrowIfFaulted();
  2951. }
  2952. return wasDequeued;
  2953. }
  2954. protected override void OnOpened()
  2955. {
  2956. base.OnOpened();
  2957. StartReceiving();
  2958. }
  2959. public bool TryReceive(TimeSpan timeout, out Message message)
  2960. {
  2961. ThrowIfFaulted();
  2962. bool wasDequeued = queue.Dequeue(timeout, out message);
  2963. if (message == null)
  2964. {
  2965. // the channel could have faulted, shutting down the input queue
  2966. ThrowIfFaulted();
  2967. }
  2968. return wasDequeued;
  2969. }
  2970. public void Send(Message message)
  2971. {
  2972. this.Send(message, this.DefaultSendTimeout);
  2973. }
  2974. public void Send(Message message, TimeSpan timeout)
  2975. {
  2976. ThrowIfFaulted();
  2977. CheckOutputOpen();
  2978. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  2979. this.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime());
  2980. this.ChannelBinder.Send(message, timeoutHelper.RemainingTime());
  2981. }
  2982. public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
  2983. {
  2984. return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
  2985. }
  2986. public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
  2987. {
  2988. ThrowIfFaulted();
  2989. CheckOutputOpen();
  2990. return new SecureSendAsyncResult(message, this, timeout, callback, state, false);
  2991. }
  2992. public void EndSend(IAsyncResult result)
  2993. {
  2994. SecureSendAsyncResult.End(result);
  2995. }
  2996. protected override void InitializeSession(SecurityToken sessionToken)
  2997. {
  2998. this.session.Initialize(sessionToken, this.Settings);
  2999. }
  3000. void StartReceiving()
  3001. {
  3002. IAsyncResult result = this.IssueReceive();
  3003. if (result != null && result.CompletedSynchronously)
  3004. {
  3005. ActionItem.Schedule(completeLater, result);
  3006. }
  3007. }
  3008. IAsyncResult IssueReceive()
  3009. {
  3010. while (true)
  3011. {
  3012. // no need to receive anymore if in the closed state
  3013. if (this.State == CommunicationState.Closed || this.State == CommunicationState.Faulted || this.IsInputClosed)
  3014. {
  3015. return null;
  3016. }
  3017. try
  3018. {
  3019. return this.BeginReceiveInternal(TimeSpan.MaxValue, null, onReceive, this);
  3020. }
  3021. catch (CommunicationException e)
  3022. {
  3023. // BeginReceive failed. ignore the exception and start another receive
  3024. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  3025. }
  3026. catch (TimeoutException e)
  3027. {
  3028. // BeginReceive failed. ignore the exception and start another receive
  3029. if (TD.ReceiveTimeoutIsEnabled())
  3030. {
  3031. TD.ReceiveTimeout(e.Message);
  3032. }
  3033. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  3034. }
  3035. }
  3036. }
  3037. void CompleteLater(object obj)
  3038. {
  3039. CompleteReceive((IAsyncResult)obj);
  3040. }
  3041. static void OnReceive(IAsyncResult result)
  3042. {
  3043. if (result.CompletedSynchronously)
  3044. return;
  3045. ((ClientSecurityDuplexSessionChannel)result.AsyncState).CompleteReceive(result);
  3046. }
  3047. void CompleteReceive(IAsyncResult result)
  3048. {
  3049. Message message = null;
  3050. bool issueAnotherReceive = false;
  3051. try
  3052. {
  3053. message = this.EndReceiveInternal(result);
  3054. issueAnotherReceive = true;
  3055. }
  3056. catch (MessageSecurityException)
  3057. {
  3058. // a messagesecurityexception will only be thrown if the channel received a fault
  3059. // from the other side, in which case the channel would have faulted
  3060. issueAnotherReceive = false;
  3061. }
  3062. catch (CommunicationException e)
  3063. {
  3064. issueAnotherReceive = true;
  3065. // EndReceive failed. ignore the exception and start another receive
  3066. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  3067. }
  3068. catch (TimeoutException e)
  3069. {
  3070. issueAnotherReceive = true;
  3071. // EndReceive failed. ignore the exception and start another receive
  3072. if (TD.ReceiveTimeoutIsEnabled())
  3073. {
  3074. TD.ReceiveTimeout(e.Message);
  3075. }
  3076. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  3077. }
  3078. IAsyncResult nextReceiveResult = null;
  3079. if (issueAnotherReceive)
  3080. {
  3081. nextReceiveResult = this.IssueReceive();
  3082. if (nextReceiveResult != null && nextReceiveResult.CompletedSynchronously)
  3083. {
  3084. ActionItem.Schedule(completeLater, nextReceiveResult);
  3085. }
  3086. }
  3087. if (message != null)
  3088. {
  3089. // since we may be dispatching to user code ---- non-fatal exceptions
  3090. try
  3091. {
  3092. this.queue.EnqueueAndDispatch(message);
  3093. }
  3094. #pragma warning suppress 56500 // covered by FxCOP
  3095. catch (Exception e)
  3096. {
  3097. if (Fx.IsFatal(e)) throw;
  3098. DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
  3099. }
  3100. }
  3101. }
  3102. protected override void AbortCore()
  3103. {
  3104. try
  3105. {
  3106. this.queue.Dispose();
  3107. }
  3108. catch (CommunicationException e)
  3109. {
  3110. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  3111. }
  3112. catch (TimeoutException e)
  3113. {
  3114. if (TD.CloseTimeoutIsEnabled())
  3115. {
  3116. TD.CloseTimeout(e.Message);
  3117. }
  3118. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  3119. }
  3120. base.AbortCore();
  3121. }
  3122. public bool WaitForMessage(TimeSpan timeout)
  3123. {
  3124. return this.queue.WaitForItem(timeout);
  3125. }
  3126. public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
  3127. {
  3128. return this.queue.BeginWaitForItem(timeout, callback, state);
  3129. }
  3130. public bool EndWaitForMessage(IAsyncResult result)
  3131. {
  3132. return this.queue.EndWaitForItem(result);
  3133. }
  3134. protected override void OnFaulted()
  3135. {
  3136. queue.Shutdown(() => this.GetPendingException());
  3137. base.OnFaulted();
  3138. }
  3139. protected override bool OnCloseResponseReceived()
  3140. {
  3141. if (base.OnCloseResponseReceived())
  3142. {
  3143. this.queue.Shutdown();
  3144. return true;
  3145. }
  3146. else
  3147. {
  3148. return false;
  3149. }
  3150. }
  3151. protected override bool OnCloseReceived()
  3152. {
  3153. if (base.OnCloseReceived())
  3154. {
  3155. this.queue.Shutdown();
  3156. return true;
  3157. }
  3158. else
  3159. {
  3160. return false;
  3161. }
  3162. }
  3163. class SoapSecurityClientDuplexSession : SoapSecurityOutputSession, IDuplexSession
  3164. {
  3165. ClientSecurityDuplexSessionChannel channel;
  3166. bool initialized = false;
  3167. public SoapSecurityClientDuplexSession(ClientSecurityDuplexSessionChannel channel)
  3168. : base(channel)
  3169. {
  3170. this.channel = channel;
  3171. }
  3172. internal new void Initialize(SecurityToken sessionToken, SecuritySessionClientSettings<TChannel> settings)
  3173. {
  3174. base.Initialize(sessionToken, settings);
  3175. this.initialized = true;
  3176. }
  3177. void CheckInitialized()
  3178. {
  3179. if (!this.initialized)
  3180. {
  3181. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ChannelNotOpen)));
  3182. }
  3183. }
  3184. public void CloseOutputSession()
  3185. {
  3186. this.CloseOutputSession(this.channel.DefaultCloseTimeout);
  3187. }
  3188. public void CloseOutputSession(TimeSpan timeout)
  3189. {
  3190. CheckInitialized();
  3191. this.channel.ThrowIfFaulted();
  3192. this.channel.ThrowIfNotOpened();
  3193. Exception pendingException = null;
  3194. try
  3195. {
  3196. this.channel.CloseOutputSession(timeout);
  3197. }
  3198. catch (CommunicationObjectAbortedException)
  3199. {
  3200. if (this.channel.State != CommunicationState.Closed)
  3201. {
  3202. throw;
  3203. }
  3204. }
  3205. #pragma warning suppress 56500 // covered by FxCOP
  3206. catch (Exception e)
  3207. {
  3208. if (Fx.IsFatal(e)) throw;
  3209. pendingException = e;
  3210. }
  3211. if (pendingException != null)
  3212. {
  3213. this.channel.Fault(pendingException);
  3214. throw pendingException;
  3215. }
  3216. }
  3217. public IAsyncResult BeginCloseOutputSession(AsyncCallback callback, object state)
  3218. {
  3219. return this.BeginCloseOutputSession(this.channel.DefaultCloseTimeout, callback, state);
  3220. }
  3221. public IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state)
  3222. {
  3223. CheckInitialized();
  3224. this.channel.ThrowIfFaulted();
  3225. this.channel.ThrowIfNotOpened();
  3226. Exception pendingException = null;
  3227. try
  3228. {
  3229. return this.channel.BeginCloseOutputSession(timeout, callback, state);
  3230. }
  3231. catch (CommunicationObjectAbortedException)
  3232. {
  3233. if (this.channel.State != CommunicationState.Closed)
  3234. {
  3235. throw;
  3236. }
  3237. // another thread must have aborted the channel. Allow the close to complete
  3238. // gracefully
  3239. return new CompletedAsyncResult(callback, state);
  3240. }
  3241. #pragma warning suppress 56500 // covered by FxCOP
  3242. catch (Exception e)
  3243. {
  3244. if (Fx.IsFatal(e)) throw;
  3245. pendingException = e;
  3246. }
  3247. if (pendingException != null)
  3248. {
  3249. this.channel.Fault(pendingException);
  3250. if (pendingException is CommunicationException)
  3251. {
  3252. throw pendingException;
  3253. }
  3254. else
  3255. {
  3256. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(pendingException);
  3257. }
  3258. }
  3259. // we should never reach here
  3260. Fx.Assert("Unexpected control flow");
  3261. return null;
  3262. }
  3263. public void EndCloseOutputSession(IAsyncResult result)
  3264. {
  3265. if (result is CompletedAsyncResult)
  3266. {
  3267. CompletedAsyncResult.End(result);
  3268. return;
  3269. }
  3270. Exception pendingException = null;
  3271. try
  3272. {
  3273. this.channel.EndCloseOutputSession(result);
  3274. }
  3275. catch (CommunicationObjectAbortedException)
  3276. {
  3277. if (this.channel.State != CommunicationState.Closed)
  3278. {
  3279. throw;
  3280. }
  3281. // another thread must have aborted the channel. Allow the close to complete
  3282. // gracefully
  3283. }
  3284. #pragma warning suppress 56500 // covered by FxCOP
  3285. catch (Exception e)
  3286. {
  3287. if (Fx.IsFatal(e)) throw;
  3288. pendingException = e;
  3289. }
  3290. if (pendingException != null)
  3291. {
  3292. this.channel.Fault(pendingException);
  3293. if (pendingException is CommunicationException)
  3294. {
  3295. throw pendingException;
  3296. }
  3297. else
  3298. {
  3299. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(pendingException);
  3300. }
  3301. }
  3302. }
  3303. }
  3304. }
  3305. }
  3306. }