PipeConnection.cs 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Net;
  11. using System.Runtime;
  12. using System.Runtime.Diagnostics;
  13. using System.Runtime.InteropServices;
  14. using System.Runtime.Versioning;
  15. using System.Security.AccessControl;
  16. using System.ComponentModel;
  17. using System.Security;
  18. using System.Security.Cryptography;
  19. using System.Security.Permissions;
  20. using System.Security.Principal;
  21. using System.ServiceModel;
  22. using System.ServiceModel.Activation;
  23. using System.ServiceModel.Diagnostics;
  24. using System.ServiceModel.Diagnostics.Application;
  25. using System.ServiceModel.Security;
  26. using System.Text;
  27. using System.Threading;
  28. using SafeCloseHandle = System.ServiceModel.Activation.SafeCloseHandle;
  29. sealed class PipeConnection : IConnection
  30. {
  31. // common state
  32. PipeHandle pipe;
  33. CloseState closeState;
  34. bool aborted;
  35. bool isBoundToCompletionPort;
  36. bool autoBindToCompletionPort;
  37. TraceEventType exceptionEventType;
  38. static byte[] zeroBuffer;
  39. // read state
  40. object readLock = new object();
  41. bool inReadingState; // This keeps track of the state machine (IConnection interface).
  42. bool isReadOutstanding; // This tracks whether an actual I/O is pending.
  43. OverlappedContext readOverlapped;
  44. byte[] asyncReadBuffer;
  45. int readBufferSize;
  46. ManualResetEvent atEOFEvent;
  47. bool isAtEOF;
  48. OverlappedIOCompleteCallback onAsyncReadComplete;
  49. Exception asyncReadException;
  50. WaitCallback asyncReadCallback;
  51. object asyncReadCallbackState;
  52. int asyncBytesRead;
  53. // write state
  54. object writeLock = new object();
  55. bool inWritingState; // This keeps track of the state machine (IConnection interface).
  56. bool isWriteOutstanding; // This tracks whether an actual I/O is pending.
  57. OverlappedContext writeOverlapped;
  58. Exception asyncWriteException;
  59. WaitCallback asyncWriteCallback;
  60. object asyncWriteCallbackState;
  61. int asyncBytesToWrite;
  62. bool isShutdownWritten;
  63. int syncWriteSize;
  64. byte[] pendingWriteBuffer;
  65. BufferManager pendingWriteBufferManager;
  66. OverlappedIOCompleteCallback onAsyncWriteComplete;
  67. int writeBufferSize;
  68. // timeout support
  69. TimeSpan readTimeout;
  70. IOThreadTimer readTimer;
  71. static Action<object> onReadTimeout;
  72. string timeoutErrorString;
  73. TransferOperation timeoutErrorTransferOperation;
  74. TimeSpan writeTimeout;
  75. IOThreadTimer writeTimer;
  76. static Action<object> onWriteTimeout;
  77. public PipeConnection(PipeHandle pipe, int connectionBufferSize, bool isBoundToCompletionPort, bool autoBindToCompletionPort)
  78. {
  79. if (pipe == null)
  80. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("pipe");
  81. if (pipe.IsInvalid)
  82. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("pipe");
  83. this.closeState = CloseState.Open;
  84. this.exceptionEventType = TraceEventType.Error;
  85. this.isBoundToCompletionPort = isBoundToCompletionPort;
  86. this.autoBindToCompletionPort = autoBindToCompletionPort;
  87. this.pipe = pipe;
  88. this.readBufferSize = connectionBufferSize;
  89. this.writeBufferSize = connectionBufferSize;
  90. this.readOverlapped = new OverlappedContext();
  91. this.asyncReadBuffer = DiagnosticUtility.Utility.AllocateByteArray(connectionBufferSize);
  92. this.writeOverlapped = new OverlappedContext();
  93. this.atEOFEvent = new ManualResetEvent(false);
  94. this.onAsyncReadComplete = new OverlappedIOCompleteCallback(OnAsyncReadComplete);
  95. this.onAsyncWriteComplete = new OverlappedIOCompleteCallback(OnAsyncWriteComplete);
  96. }
  97. public int AsyncReadBufferSize
  98. {
  99. get
  100. {
  101. return this.readBufferSize;
  102. }
  103. }
  104. public byte[] AsyncReadBuffer
  105. {
  106. get
  107. {
  108. return this.asyncReadBuffer;
  109. }
  110. }
  111. static byte[] ZeroBuffer
  112. {
  113. get
  114. {
  115. if (PipeConnection.zeroBuffer == null)
  116. {
  117. PipeConnection.zeroBuffer = new byte[1];
  118. }
  119. return PipeConnection.zeroBuffer;
  120. }
  121. }
  122. public TraceEventType ExceptionEventType
  123. {
  124. get { return this.exceptionEventType; }
  125. set { this.exceptionEventType = value; }
  126. }
  127. public IPEndPoint RemoteIPEndPoint
  128. {
  129. get { return null; }
  130. }
  131. IOThreadTimer ReadTimer
  132. {
  133. get
  134. {
  135. if (this.readTimer == null)
  136. {
  137. if (onReadTimeout == null)
  138. {
  139. onReadTimeout = new Action<object>(OnReadTimeout);
  140. }
  141. this.readTimer = new IOThreadTimer(onReadTimeout, this, false);
  142. }
  143. return this.readTimer;
  144. }
  145. }
  146. IOThreadTimer WriteTimer
  147. {
  148. get
  149. {
  150. if (this.writeTimer == null)
  151. {
  152. if (onWriteTimeout == null)
  153. {
  154. onWriteTimeout = new Action<object>(OnWriteTimeout);
  155. }
  156. this.writeTimer = new IOThreadTimer(onWriteTimeout, this, false);
  157. }
  158. return this.writeTimer;
  159. }
  160. }
  161. static void OnReadTimeout(object state)
  162. {
  163. PipeConnection thisPtr = (PipeConnection)state;
  164. thisPtr.Abort(SR.GetString(SR.PipeConnectionAbortedReadTimedOut, thisPtr.readTimeout), TransferOperation.Read);
  165. }
  166. static void OnWriteTimeout(object state)
  167. {
  168. PipeConnection thisPtr = (PipeConnection)state;
  169. thisPtr.Abort(SR.GetString(SR.PipeConnectionAbortedWriteTimedOut, thisPtr.writeTimeout), TransferOperation.Write);
  170. }
  171. public void Abort()
  172. {
  173. Abort(null, TransferOperation.Undefined);
  174. }
  175. void Abort(string timeoutErrorString, TransferOperation transferOperation)
  176. {
  177. CloseHandle(true, timeoutErrorString, transferOperation);
  178. }
  179. Exception ConvertPipeException(PipeException pipeException, TransferOperation transferOperation)
  180. {
  181. return ConvertPipeException(pipeException.Message, pipeException, transferOperation);
  182. }
  183. Exception ConvertPipeException(string exceptionMessage, PipeException pipeException, TransferOperation transferOperation)
  184. {
  185. if (this.timeoutErrorString != null)
  186. {
  187. if (transferOperation == this.timeoutErrorTransferOperation)
  188. {
  189. return new TimeoutException(this.timeoutErrorString, pipeException);
  190. }
  191. else
  192. {
  193. return new CommunicationException(this.timeoutErrorString, pipeException);
  194. }
  195. }
  196. else if (this.aborted)
  197. {
  198. return new CommunicationObjectAbortedException(exceptionMessage, pipeException);
  199. }
  200. else
  201. {
  202. return new CommunicationException(exceptionMessage, pipeException);
  203. }
  204. }
  205. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  206. public unsafe AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout,
  207. WaitCallback callback, object state)
  208. {
  209. ConnectionUtilities.ValidateBufferBounds(AsyncReadBuffer, offset, size);
  210. lock (readLock)
  211. {
  212. try
  213. {
  214. ValidateEnterReadingState(true);
  215. if (isAtEOF)
  216. {
  217. asyncBytesRead = 0;
  218. asyncReadException = null;
  219. return AsyncCompletionResult.Completed;
  220. }
  221. if (autoBindToCompletionPort)
  222. {
  223. if (!isBoundToCompletionPort)
  224. {
  225. lock (writeLock)
  226. {
  227. // readLock, writeLock acquired in order to prevent deadlock
  228. EnsureBoundToCompletionPort();
  229. }
  230. }
  231. }
  232. if (this.isReadOutstanding)
  233. {
  234. throw Fx.AssertAndThrow("Read I/O already pending when BeginRead called.");
  235. }
  236. try
  237. {
  238. this.readTimeout = timeout;
  239. if (this.readTimeout != TimeSpan.MaxValue)
  240. {
  241. this.ReadTimer.Set(this.readTimeout);
  242. }
  243. this.asyncReadCallback = callback;
  244. this.asyncReadCallbackState = state;
  245. this.isReadOutstanding = true;
  246. this.readOverlapped.StartAsyncOperation(AsyncReadBuffer, this.onAsyncReadComplete, this.isBoundToCompletionPort);
  247. if (UnsafeNativeMethods.ReadFile(this.pipe.DangerousGetHandle(), this.readOverlapped.BufferPtr + offset, size, IntPtr.Zero, this.readOverlapped.NativeOverlapped) == 0)
  248. {
  249. int error = Marshal.GetLastWin32Error();
  250. if (error != UnsafeNativeMethods.ERROR_IO_PENDING && error != UnsafeNativeMethods.ERROR_MORE_DATA)
  251. {
  252. this.isReadOutstanding = false;
  253. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Exceptions.CreateReadException(error));
  254. }
  255. }
  256. }
  257. finally
  258. {
  259. if (!this.isReadOutstanding)
  260. {
  261. // Unbind the buffer.
  262. this.readOverlapped.CancelAsyncOperation();
  263. this.asyncReadCallback = null;
  264. this.asyncReadCallbackState = null;
  265. this.ReadTimer.Cancel();
  266. }
  267. }
  268. if (!this.isReadOutstanding)
  269. {
  270. int bytesRead;
  271. Exception readException = Exceptions.GetOverlappedReadException(this.pipe, this.readOverlapped.NativeOverlapped, out bytesRead);
  272. if (readException != null)
  273. {
  274. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(readException);
  275. }
  276. asyncBytesRead = bytesRead;
  277. HandleReadComplete(asyncBytesRead);
  278. }
  279. else
  280. {
  281. EnterReadingState();
  282. }
  283. return this.isReadOutstanding ? AsyncCompletionResult.Queued : AsyncCompletionResult.Completed;
  284. }
  285. catch (PipeException e)
  286. {
  287. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Read), ExceptionEventType);
  288. }
  289. }
  290. }
  291. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  292. public unsafe AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
  293. WaitCallback callback, object state)
  294. {
  295. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  296. FinishPendingWrite(timeout);
  297. ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
  298. if (autoBindToCompletionPort && !isBoundToCompletionPort)
  299. {
  300. // Locks must be both taken, and in this order.
  301. lock (readLock)
  302. {
  303. lock (writeLock)
  304. {
  305. ValidateEnterWritingState(true);
  306. EnsureBoundToCompletionPort();
  307. }
  308. }
  309. }
  310. lock (writeLock)
  311. {
  312. try
  313. {
  314. ValidateEnterWritingState(true);
  315. if (this.isWriteOutstanding)
  316. {
  317. throw Fx.AssertAndThrow("Write I/O already pending when BeginWrite called.");
  318. }
  319. try
  320. {
  321. this.writeTimeout = timeout;
  322. this.WriteTimer.Set(timeoutHelper.RemainingTime());
  323. this.asyncBytesToWrite = size;
  324. this.asyncWriteException = null;
  325. this.asyncWriteCallback = callback;
  326. this.asyncWriteCallbackState = state;
  327. this.isWriteOutstanding = true;
  328. this.writeOverlapped.StartAsyncOperation(buffer, this.onAsyncWriteComplete, this.isBoundToCompletionPort);
  329. if (UnsafeNativeMethods.WriteFile(this.pipe.DangerousGetHandle(), this.writeOverlapped.BufferPtr + offset, size, IntPtr.Zero, this.writeOverlapped.NativeOverlapped) == 0)
  330. {
  331. int error = Marshal.GetLastWin32Error();
  332. if (error != UnsafeNativeMethods.ERROR_IO_PENDING)
  333. {
  334. this.isWriteOutstanding = false;
  335. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Exceptions.CreateWriteException(error));
  336. }
  337. }
  338. }
  339. finally
  340. {
  341. if (!this.isWriteOutstanding)
  342. {
  343. // Unbind the buffer.
  344. this.writeOverlapped.CancelAsyncOperation();
  345. this.ResetWriteState();
  346. this.WriteTimer.Cancel();
  347. }
  348. }
  349. if (!this.isWriteOutstanding)
  350. {
  351. int bytesWritten;
  352. Exception writeException = Exceptions.GetOverlappedWriteException(this.pipe, this.writeOverlapped.NativeOverlapped, out bytesWritten);
  353. if (writeException == null && bytesWritten != size)
  354. {
  355. writeException = new PipeException(SR.GetString(SR.PipeWriteIncomplete));
  356. }
  357. if (writeException != null)
  358. {
  359. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(writeException);
  360. }
  361. }
  362. else
  363. {
  364. EnterWritingState();
  365. }
  366. return this.isWriteOutstanding ? AsyncCompletionResult.Queued : AsyncCompletionResult.Completed;
  367. }
  368. catch (PipeException e)
  369. {
  370. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Write), ExceptionEventType);
  371. }
  372. }
  373. }
  374. // CSDMain 112188: Note asyncAndLinger has no effect here. Async pooling for Tcp was
  375. // added and NamedPipes currently doesn't obey the async model.
  376. public void Close(TimeSpan timeout, bool asyncAndLinger)
  377. {
  378. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  379. FinishPendingWrite(timeout);
  380. bool shouldCloseHandle = false;
  381. try
  382. {
  383. bool existingReadIsPending = false;
  384. bool shouldReadEOF = false;
  385. bool shouldWriteEOF = false;
  386. lock (readLock)
  387. {
  388. lock (writeLock)
  389. {
  390. if (!isShutdownWritten && inWritingState)
  391. {
  392. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  393. new PipeException(SR.GetString(SR.PipeCantCloseWithPendingWrite)), ExceptionEventType);
  394. }
  395. if (closeState == CloseState.Closing || closeState == CloseState.HandleClosed)
  396. {
  397. // already closing or closed, so just return
  398. return;
  399. }
  400. closeState = CloseState.Closing;
  401. shouldCloseHandle = true;
  402. if (!isAtEOF)
  403. {
  404. if (inReadingState)
  405. {
  406. existingReadIsPending = true;
  407. }
  408. else
  409. {
  410. shouldReadEOF = true;
  411. }
  412. }
  413. if (!isShutdownWritten)
  414. {
  415. shouldWriteEOF = true;
  416. isShutdownWritten = true;
  417. }
  418. }
  419. }
  420. if (shouldWriteEOF)
  421. {
  422. StartWriteZero(timeoutHelper.RemainingTime());
  423. }
  424. if (shouldReadEOF)
  425. {
  426. StartReadZero();
  427. }
  428. // wait for shutdown write to complete
  429. try
  430. {
  431. WaitForWriteZero(timeoutHelper.RemainingTime(), true);
  432. }
  433. catch (TimeoutException e)
  434. {
  435. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  436. new TimeoutException(SR.GetString(SR.PipeShutdownWriteError), e), ExceptionEventType);
  437. }
  438. // ensure we have received EOF signal
  439. if (shouldReadEOF)
  440. {
  441. try
  442. {
  443. WaitForReadZero(timeoutHelper.RemainingTime(), true);
  444. }
  445. catch (TimeoutException e)
  446. {
  447. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  448. new TimeoutException(SR.GetString(SR.PipeShutdownReadError), e), ExceptionEventType);
  449. }
  450. }
  451. else if (existingReadIsPending)
  452. {
  453. if (!TimeoutHelper.WaitOne(atEOFEvent, timeoutHelper.RemainingTime()))
  454. {
  455. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  456. new TimeoutException(SR.GetString(SR.PipeShutdownReadError)), ExceptionEventType);
  457. }
  458. }
  459. // else we had already seen EOF.
  460. // at this point, we may get exceptions if the other side closes the handle first
  461. try
  462. {
  463. // write an ack for eof
  464. StartWriteZero(timeoutHelper.RemainingTime());
  465. // read an ack for eof
  466. StartReadZero();
  467. // wait for write to complete/fail
  468. WaitForWriteZero(timeoutHelper.RemainingTime(), false);
  469. // wait for read to complete/fail
  470. WaitForReadZero(timeoutHelper.RemainingTime(), false);
  471. }
  472. catch (PipeException e)
  473. {
  474. if (!IsBrokenPipeError(e.ErrorCode))
  475. {
  476. throw;
  477. }
  478. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  479. }
  480. catch (CommunicationException e)
  481. {
  482. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  483. }
  484. catch (TimeoutException e)
  485. {
  486. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  487. }
  488. }
  489. catch (TimeoutException e)
  490. {
  491. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  492. new TimeoutException(SR.GetString(SR.PipeCloseFailed), e), ExceptionEventType);
  493. }
  494. catch (PipeException e)
  495. {
  496. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  497. ConvertPipeException(SR.GetString(SR.PipeCloseFailed), e, TransferOperation.Undefined), ExceptionEventType);
  498. }
  499. finally
  500. {
  501. if (shouldCloseHandle)
  502. {
  503. CloseHandle(false, null, TransferOperation.Undefined);
  504. }
  505. }
  506. }
  507. void CloseHandle(bool abort, string timeoutErrorString, TransferOperation transferOperation)
  508. {
  509. lock (readLock)
  510. {
  511. lock (writeLock)
  512. {
  513. if (this.closeState == CloseState.HandleClosed)
  514. {
  515. return;
  516. }
  517. this.timeoutErrorString = timeoutErrorString;
  518. this.timeoutErrorTransferOperation = transferOperation;
  519. this.aborted = abort;
  520. this.closeState = CloseState.HandleClosed;
  521. this.pipe.Close();
  522. this.readOverlapped.FreeOrDefer();
  523. this.writeOverlapped.FreeOrDefer();
  524. if (this.atEOFEvent != null)
  525. {
  526. this.atEOFEvent.Close();
  527. }
  528. // This should only do anything in the abort case.
  529. try
  530. {
  531. FinishPendingWrite(TimeSpan.Zero);
  532. }
  533. catch (TimeoutException exception)
  534. {
  535. if (TD.CloseTimeoutIsEnabled())
  536. {
  537. TD.CloseTimeout(exception.Message);
  538. }
  539. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
  540. }
  541. catch (CommunicationException exception)
  542. {
  543. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
  544. }
  545. }
  546. }
  547. if (abort)
  548. {
  549. TraceEventType traceEventType = TraceEventType.Warning;
  550. // we could be timing out a cached connection
  551. if (this.ExceptionEventType == TraceEventType.Information)
  552. {
  553. traceEventType = this.ExceptionEventType;
  554. }
  555. if (DiagnosticUtility.ShouldTrace(traceEventType))
  556. {
  557. TraceUtility.TraceEvent(traceEventType, TraceCode.PipeConnectionAbort, SR.GetString(SR.TraceCodePipeConnectionAbort), this);
  558. }
  559. }
  560. }
  561. CommunicationException CreatePipeDuplicationFailedException(int win32Error)
  562. {
  563. Exception innerException = new PipeException(SR.GetString(SR.PipeDuplicationFailed), win32Error);
  564. return new CommunicationException(innerException.Message, innerException);
  565. }
  566. public object DuplicateAndClose(int targetProcessId)
  567. {
  568. SafeCloseHandle targetProcessHandle = ListenerUnsafeNativeMethods.OpenProcess(ListenerUnsafeNativeMethods.PROCESS_DUP_HANDLE, false, targetProcessId);
  569. if (targetProcessHandle.IsInvalid)
  570. {
  571. targetProcessHandle.SetHandleAsInvalid();
  572. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  573. CreatePipeDuplicationFailedException(Marshal.GetLastWin32Error()), ExceptionEventType);
  574. }
  575. try
  576. {
  577. // no need to close this handle, it's a pseudo handle. expected value is -1.
  578. IntPtr sourceProcessHandle = ListenerUnsafeNativeMethods.GetCurrentProcess();
  579. if (sourceProcessHandle == IntPtr.Zero)
  580. {
  581. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  582. CreatePipeDuplicationFailedException(Marshal.GetLastWin32Error()), ExceptionEventType);
  583. }
  584. IntPtr duplicatedHandle;
  585. bool success = UnsafeNativeMethods.DuplicateHandle(sourceProcessHandle, this.pipe, targetProcessHandle, out duplicatedHandle, 0, false, UnsafeNativeMethods.DUPLICATE_SAME_ACCESS);
  586. if (!success)
  587. {
  588. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(
  589. CreatePipeDuplicationFailedException(Marshal.GetLastWin32Error()), ExceptionEventType);
  590. }
  591. this.Abort();
  592. return duplicatedHandle;
  593. }
  594. finally
  595. {
  596. targetProcessHandle.Close();
  597. }
  598. }
  599. public object GetCoreTransport()
  600. {
  601. return pipe;
  602. }
  603. void EnsureBoundToCompletionPort()
  604. {
  605. // Both read and write locks must be acquired before doing this
  606. if (!isBoundToCompletionPort)
  607. {
  608. ThreadPool.BindHandle(this.pipe);
  609. isBoundToCompletionPort = true;
  610. }
  611. }
  612. public int EndRead()
  613. {
  614. if (asyncReadException != null)
  615. {
  616. Exception exceptionToThrow = asyncReadException;
  617. asyncReadException = null;
  618. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(exceptionToThrow, ExceptionEventType);
  619. }
  620. return asyncBytesRead;
  621. }
  622. public void EndWrite()
  623. {
  624. if (this.asyncWriteException != null)
  625. {
  626. Exception exceptionToThrow = this.asyncWriteException;
  627. this.asyncWriteException = null;
  628. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(exceptionToThrow, ExceptionEventType);
  629. }
  630. }
  631. void EnterReadingState()
  632. {
  633. inReadingState = true;
  634. }
  635. void EnterWritingState()
  636. {
  637. inWritingState = true;
  638. }
  639. void ExitReadingState()
  640. {
  641. inReadingState = false;
  642. }
  643. void ExitWritingState()
  644. {
  645. inWritingState = false;
  646. }
  647. void ReadIOCompleted()
  648. {
  649. this.readOverlapped.FreeIfDeferred();
  650. }
  651. void WriteIOCompleted()
  652. {
  653. this.writeOverlapped.FreeIfDeferred();
  654. }
  655. void FinishPendingWrite(TimeSpan timeout)
  656. {
  657. if (this.pendingWriteBuffer == null)
  658. {
  659. return;
  660. }
  661. byte[] buffer;
  662. BufferManager bufferManager;
  663. lock (this.writeLock)
  664. {
  665. if (this.pendingWriteBuffer == null)
  666. {
  667. return;
  668. }
  669. buffer = this.pendingWriteBuffer;
  670. this.pendingWriteBuffer = null;
  671. bufferManager = this.pendingWriteBufferManager;
  672. this.pendingWriteBufferManager = null;
  673. }
  674. try
  675. {
  676. bool success = false;
  677. try
  678. {
  679. WaitForSyncWrite(timeout, true);
  680. success = true;
  681. }
  682. finally
  683. {
  684. lock (this.writeLock)
  685. {
  686. try
  687. {
  688. if (success)
  689. {
  690. FinishSyncWrite(true);
  691. }
  692. }
  693. finally
  694. {
  695. ExitWritingState();
  696. if (!this.isWriteOutstanding)
  697. {
  698. bufferManager.ReturnBuffer(buffer);
  699. WriteIOCompleted();
  700. }
  701. }
  702. }
  703. }
  704. }
  705. catch (PipeException e)
  706. {
  707. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Write), ExceptionEventType);
  708. }
  709. }
  710. #if FUTURE
  711. ulong GetServerPid()
  712. {
  713. ulong id;
  714. #pragma warning suppress 56523 // [....], Win32Exception ctor calls Marshal.GetLastWin32Error()
  715. if (!UnsafeNativeMethods.GetNamedPipeServerProcessId(pipe, out id))
  716. {
  717. Win32Exception e = new Win32Exception();
  718. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(e.Message, e));
  719. }
  720. return id;
  721. }
  722. ulong GetClientPid()
  723. {
  724. ulong id;
  725. #pragma warning suppress 56523 // [....], Win32Exception ctor calls Marshal.GetLastWin32Error()
  726. if (!UnsafeNativeMethods.GetNamedPipeServerProcessId(pipe, out id))
  727. {
  728. Win32Exception e = new Win32Exception();
  729. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(e.Message, e));
  730. }
  731. return id;
  732. }
  733. #endif
  734. void HandleReadComplete(int bytesRead)
  735. {
  736. if (bytesRead == 0)
  737. {
  738. isAtEOF = true;
  739. atEOFEvent.Set();
  740. }
  741. }
  742. bool IsBrokenPipeError(int error)
  743. {
  744. return error == UnsafeNativeMethods.ERROR_NO_DATA ||
  745. error == UnsafeNativeMethods.ERROR_BROKEN_PIPE;
  746. }
  747. Exception CreatePipeClosedException(TransferOperation transferOperation)
  748. {
  749. return ConvertPipeException(new PipeException(SR.GetString(SR.PipeClosed)), transferOperation);
  750. }
  751. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  752. unsafe void OnAsyncReadComplete(bool haveResult, int error, int numBytes)
  753. {
  754. WaitCallback callback;
  755. object state;
  756. lock (readLock)
  757. {
  758. try
  759. {
  760. try
  761. {
  762. if (this.readTimeout != TimeSpan.MaxValue && !this.ReadTimer.Cancel())
  763. {
  764. this.Abort(SR.GetString(SR.PipeConnectionAbortedReadTimedOut, this.readTimeout), TransferOperation.Read);
  765. }
  766. if (this.closeState == CloseState.HandleClosed)
  767. {
  768. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeClosedException(TransferOperation.Read));
  769. }
  770. if (!haveResult)
  771. {
  772. if (UnsafeNativeMethods.GetOverlappedResult(this.pipe.DangerousGetHandle(), this.readOverlapped.NativeOverlapped, out numBytes, 0) == 0)
  773. {
  774. error = Marshal.GetLastWin32Error();
  775. }
  776. else
  777. {
  778. error = 0;
  779. }
  780. }
  781. if (error != 0 && error != UnsafeNativeMethods.ERROR_MORE_DATA)
  782. {
  783. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Exceptions.CreateReadException((int)error));
  784. }
  785. this.asyncBytesRead = numBytes;
  786. HandleReadComplete(this.asyncBytesRead);
  787. }
  788. catch (PipeException e)
  789. {
  790. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertPipeException(e, TransferOperation.Read));
  791. }
  792. }
  793. #pragma warning suppress 56500 // [....], transferring exception to caller
  794. catch (Exception e)
  795. {
  796. if (Fx.IsFatal(e))
  797. {
  798. throw;
  799. }
  800. this.asyncReadException = e;
  801. }
  802. finally
  803. {
  804. this.isReadOutstanding = false;
  805. ReadIOCompleted();
  806. ExitReadingState();
  807. callback = this.asyncReadCallback;
  808. this.asyncReadCallback = null;
  809. state = this.asyncReadCallbackState;
  810. this.asyncReadCallbackState = null;
  811. }
  812. }
  813. callback(state);
  814. }
  815. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  816. unsafe void OnAsyncWriteComplete(bool haveResult, int error, int numBytes)
  817. {
  818. WaitCallback callback;
  819. object state;
  820. Exception writeException = null;
  821. this.WriteTimer.Cancel();
  822. lock (writeLock)
  823. {
  824. try
  825. {
  826. try
  827. {
  828. if (this.closeState == CloseState.HandleClosed)
  829. {
  830. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeClosedException(TransferOperation.Write));
  831. }
  832. if (!haveResult)
  833. {
  834. if (UnsafeNativeMethods.GetOverlappedResult(this.pipe.DangerousGetHandle(), this.writeOverlapped.NativeOverlapped, out numBytes, 0) == 0)
  835. {
  836. error = Marshal.GetLastWin32Error();
  837. }
  838. else
  839. {
  840. error = 0;
  841. }
  842. }
  843. if (error != 0)
  844. {
  845. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Exceptions.CreateWriteException(error));
  846. }
  847. else if (numBytes != this.asyncBytesToWrite)
  848. {
  849. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new PipeException(SR.GetString(SR.PipeWriteIncomplete)));
  850. }
  851. }
  852. catch (PipeException e)
  853. {
  854. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Write), ExceptionEventType);
  855. }
  856. }
  857. #pragma warning suppress 56500 // [....], transferring exception to another thread
  858. catch (Exception e)
  859. {
  860. if (Fx.IsFatal(e))
  861. {
  862. throw;
  863. }
  864. writeException = e;
  865. }
  866. finally
  867. {
  868. this.isWriteOutstanding = false;
  869. WriteIOCompleted();
  870. ExitWritingState();
  871. this.asyncWriteException = writeException;
  872. callback = this.asyncWriteCallback;
  873. state = this.asyncWriteCallbackState;
  874. this.ResetWriteState();
  875. }
  876. }
  877. if (callback != null)
  878. {
  879. callback(state);
  880. }
  881. }
  882. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  883. unsafe public int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
  884. {
  885. ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
  886. try
  887. {
  888. lock (readLock)
  889. {
  890. ValidateEnterReadingState(true);
  891. if (isAtEOF)
  892. {
  893. return 0;
  894. }
  895. StartSyncRead(buffer, offset, size);
  896. EnterReadingState();
  897. }
  898. int bytesRead = -1;
  899. bool success = false;
  900. try
  901. {
  902. WaitForSyncRead(timeout, true);
  903. success = true;
  904. }
  905. finally
  906. {
  907. lock (this.readLock)
  908. {
  909. try
  910. {
  911. if (success)
  912. {
  913. bytesRead = FinishSyncRead(true);
  914. HandleReadComplete(bytesRead);
  915. }
  916. }
  917. finally
  918. {
  919. ExitReadingState();
  920. if (!this.isReadOutstanding)
  921. {
  922. ReadIOCompleted();
  923. }
  924. }
  925. }
  926. }
  927. Fx.Assert(bytesRead >= 0, "Logic error in Read - bytesRead not set.");
  928. return bytesRead;
  929. }
  930. catch (PipeException e)
  931. {
  932. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Read), ExceptionEventType);
  933. }
  934. }
  935. public void Shutdown(TimeSpan timeout)
  936. {
  937. try
  938. {
  939. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  940. FinishPendingWrite(timeoutHelper.RemainingTime());
  941. lock (writeLock)
  942. {
  943. ValidateEnterWritingState(true);
  944. StartWriteZero(timeoutHelper.RemainingTime());
  945. isShutdownWritten = true;
  946. }
  947. }
  948. catch (PipeException e)
  949. {
  950. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Undefined), ExceptionEventType);
  951. }
  952. }
  953. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  954. unsafe void StartReadZero()
  955. {
  956. lock (this.readLock)
  957. {
  958. ValidateEnterReadingState(false);
  959. StartSyncRead(ZeroBuffer, 0, 1);
  960. EnterReadingState();
  961. }
  962. }
  963. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  964. unsafe void StartWriteZero(TimeSpan timeout)
  965. {
  966. FinishPendingWrite(timeout);
  967. lock (this.writeLock)
  968. {
  969. ValidateEnterWritingState(false);
  970. StartSyncWrite(ZeroBuffer, 0, 0);
  971. EnterWritingState();
  972. }
  973. }
  974. void ResetWriteState()
  975. {
  976. this.asyncBytesToWrite = -1;
  977. this.asyncWriteCallback = null;
  978. this.asyncWriteCallbackState = null;
  979. }
  980. public IAsyncResult BeginValidate(Uri uri, AsyncCallback callback, object state)
  981. {
  982. return new CompletedAsyncResult<bool>(true, callback, state);
  983. }
  984. public bool EndValidate(IAsyncResult result)
  985. {
  986. return CompletedAsyncResult<bool>.End(result);
  987. }
  988. void WaitForReadZero(TimeSpan timeout, bool traceExceptionsAsErrors)
  989. {
  990. bool success = false;
  991. try
  992. {
  993. WaitForSyncRead(timeout, traceExceptionsAsErrors);
  994. success = true;
  995. }
  996. finally
  997. {
  998. lock (this.readLock)
  999. {
  1000. try
  1001. {
  1002. if (success)
  1003. {
  1004. if (FinishSyncRead(traceExceptionsAsErrors) != 0)
  1005. {
  1006. Exception exception = ConvertPipeException(new PipeException(SR.GetString(SR.PipeSignalExpected)), TransferOperation.Read);
  1007. TraceEventType traceEventType = TraceEventType.Information;
  1008. if (traceExceptionsAsErrors)
  1009. {
  1010. traceEventType = TraceEventType.Error;
  1011. }
  1012. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(exception, traceEventType);
  1013. }
  1014. }
  1015. }
  1016. finally
  1017. {
  1018. ExitReadingState();
  1019. if (!this.isReadOutstanding)
  1020. {
  1021. ReadIOCompleted();
  1022. }
  1023. }
  1024. }
  1025. }
  1026. }
  1027. void WaitForWriteZero(TimeSpan timeout, bool traceExceptionsAsErrors)
  1028. {
  1029. bool success = false;
  1030. try
  1031. {
  1032. WaitForSyncWrite(timeout, traceExceptionsAsErrors);
  1033. success = true;
  1034. }
  1035. finally
  1036. {
  1037. lock (this.writeLock)
  1038. {
  1039. try
  1040. {
  1041. if (success)
  1042. {
  1043. FinishSyncWrite(traceExceptionsAsErrors);
  1044. }
  1045. }
  1046. finally
  1047. {
  1048. ExitWritingState();
  1049. if (!this.isWriteOutstanding)
  1050. {
  1051. WriteIOCompleted();
  1052. }
  1053. }
  1054. }
  1055. }
  1056. }
  1057. public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
  1058. {
  1059. WriteHelper(buffer, offset, size, immediate, timeout, ref this.writeOverlapped.Holder[0]);
  1060. }
  1061. // The holder is a perf optimization that lets us avoid repeatedly indexing into the array.
  1062. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1063. unsafe void WriteHelper(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, ref object holder)
  1064. {
  1065. try
  1066. {
  1067. FinishPendingWrite(timeout);
  1068. ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
  1069. int bytesToWrite = size;
  1070. if (size > this.writeBufferSize)
  1071. {
  1072. size = this.writeBufferSize;
  1073. }
  1074. while (bytesToWrite > 0)
  1075. {
  1076. lock (this.writeLock)
  1077. {
  1078. ValidateEnterWritingState(true);
  1079. StartSyncWrite(buffer, offset, size, ref holder);
  1080. EnterWritingState();
  1081. }
  1082. bool success = false;
  1083. try
  1084. {
  1085. WaitForSyncWrite(timeout, true, ref holder);
  1086. success = true;
  1087. }
  1088. finally
  1089. {
  1090. lock (this.writeLock)
  1091. {
  1092. try
  1093. {
  1094. if (success)
  1095. {
  1096. FinishSyncWrite(true);
  1097. }
  1098. }
  1099. finally
  1100. {
  1101. ExitWritingState();
  1102. if (!this.isWriteOutstanding)
  1103. {
  1104. WriteIOCompleted();
  1105. }
  1106. }
  1107. }
  1108. }
  1109. bytesToWrite -= size;
  1110. offset += size;
  1111. if (size > bytesToWrite)
  1112. {
  1113. size = bytesToWrite;
  1114. }
  1115. }
  1116. }
  1117. catch (PipeException e)
  1118. {
  1119. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Write), ExceptionEventType);
  1120. }
  1121. }
  1122. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1123. public unsafe void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager)
  1124. {
  1125. bool shouldReturnBuffer = true;
  1126. try
  1127. {
  1128. if (size > this.writeBufferSize)
  1129. {
  1130. WriteHelper(buffer, offset, size, immediate, timeout, ref this.writeOverlapped.Holder[0]);
  1131. return;
  1132. }
  1133. FinishPendingWrite(timeout);
  1134. ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
  1135. lock (this.writeLock)
  1136. {
  1137. ValidateEnterWritingState(true);
  1138. // This method avoids the call to GetOverlappedResult for synchronous completions. Perf?
  1139. bool success = false;
  1140. try
  1141. {
  1142. shouldReturnBuffer = false;
  1143. StartSyncWrite(buffer, offset, size);
  1144. success = true;
  1145. }
  1146. finally
  1147. {
  1148. if (!this.isWriteOutstanding)
  1149. {
  1150. shouldReturnBuffer = true;
  1151. }
  1152. else
  1153. {
  1154. if (success)
  1155. {
  1156. EnterWritingState();
  1157. Fx.Assert(this.pendingWriteBuffer == null, "Need to pend a write but one's already pending.");
  1158. this.pendingWriteBuffer = buffer;
  1159. this.pendingWriteBufferManager = bufferManager;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. }
  1165. catch (PipeException e)
  1166. {
  1167. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(ConvertPipeException(e, TransferOperation.Write), ExceptionEventType);
  1168. }
  1169. finally
  1170. {
  1171. if (shouldReturnBuffer)
  1172. {
  1173. bufferManager.ReturnBuffer(buffer);
  1174. }
  1175. }
  1176. }
  1177. void ValidateEnterReadingState(bool checkEOF)
  1178. {
  1179. if (checkEOF)
  1180. {
  1181. if (closeState == CloseState.Closing)
  1182. {
  1183. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeAlreadyClosing)), ExceptionEventType);
  1184. }
  1185. }
  1186. if (inReadingState)
  1187. {
  1188. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeReadPending)), ExceptionEventType);
  1189. }
  1190. if (closeState == CloseState.HandleClosed)
  1191. {
  1192. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeClosed)), ExceptionEventType);
  1193. }
  1194. }
  1195. void ValidateEnterWritingState(bool checkShutdown)
  1196. {
  1197. if (checkShutdown)
  1198. {
  1199. if (isShutdownWritten)
  1200. {
  1201. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeAlreadyShuttingDown)), ExceptionEventType);
  1202. }
  1203. if (closeState == CloseState.Closing)
  1204. {
  1205. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeAlreadyClosing)), ExceptionEventType);
  1206. }
  1207. }
  1208. if (inWritingState)
  1209. {
  1210. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeWritePending)), ExceptionEventType);
  1211. }
  1212. if (closeState == CloseState.HandleClosed)
  1213. {
  1214. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new PipeException(SR.GetString(SR.PipeClosed)), ExceptionEventType);
  1215. }
  1216. }
  1217. void StartSyncRead(byte[] buffer, int offset, int size)
  1218. {
  1219. StartSyncRead(buffer, offset, size, ref this.readOverlapped.Holder[0]);
  1220. }
  1221. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1222. unsafe void StartSyncRead(byte[] buffer, int offset, int size, ref object holder)
  1223. {
  1224. if (this.isReadOutstanding)
  1225. {
  1226. throw Fx.AssertAndThrow("StartSyncRead called when read I/O was already pending.");
  1227. }
  1228. try
  1229. {
  1230. this.isReadOutstanding = true;
  1231. this.readOverlapped.StartSyncOperation(buffer, ref holder);
  1232. if (UnsafeNativeMethods.ReadFile(this.pipe.DangerousGetHandle(), this.readOverlapped.BufferPtr + offset, size, IntPtr.Zero, this.readOverlapped.NativeOverlapped) == 0)
  1233. {
  1234. int error = Marshal.GetLastWin32Error();
  1235. if (error != UnsafeNativeMethods.ERROR_IO_PENDING)
  1236. {
  1237. this.isReadOutstanding = false;
  1238. if (error != UnsafeNativeMethods.ERROR_MORE_DATA)
  1239. {
  1240. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Exceptions.CreateReadException(error));
  1241. }
  1242. }
  1243. }
  1244. else
  1245. {
  1246. this.isReadOutstanding = false;
  1247. }
  1248. }
  1249. finally
  1250. {
  1251. if (!this.isReadOutstanding)
  1252. {
  1253. this.readOverlapped.CancelSyncOperation(ref holder);
  1254. }
  1255. }
  1256. }
  1257. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1258. unsafe void WaitForSyncRead(TimeSpan timeout, bool traceExceptionsAsErrors)
  1259. {
  1260. if (this.isReadOutstanding)
  1261. {
  1262. if (!this.readOverlapped.WaitForSyncOperation(timeout))
  1263. {
  1264. Abort(SR.GetString(SR.PipeConnectionAbortedReadTimedOut, this.readTimeout), TransferOperation.Read);
  1265. Exception timeoutException = new TimeoutException(SR.GetString(SR.PipeReadTimedOut, timeout));
  1266. TraceEventType traceEventType = TraceEventType.Information;
  1267. if (traceExceptionsAsErrors)
  1268. {
  1269. traceEventType = TraceEventType.Error;
  1270. }
  1271. // This intentionally doesn't reset isReadOutstanding, because technically it still is, and we need to not free the buffer.
  1272. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(timeoutException, traceEventType);
  1273. }
  1274. else
  1275. {
  1276. this.isReadOutstanding = false;
  1277. }
  1278. }
  1279. }
  1280. // Must be called in a lock.
  1281. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1282. unsafe int FinishSyncRead(bool traceExceptionsAsErrors)
  1283. {
  1284. int bytesRead = -1;
  1285. Exception readException;
  1286. if (this.closeState == CloseState.HandleClosed)
  1287. {
  1288. readException = CreatePipeClosedException(TransferOperation.Read);
  1289. }
  1290. else
  1291. {
  1292. readException = Exceptions.GetOverlappedReadException(this.pipe, this.readOverlapped.NativeOverlapped, out bytesRead);
  1293. }
  1294. if (readException != null)
  1295. {
  1296. TraceEventType traceEventType = TraceEventType.Information;
  1297. if (traceExceptionsAsErrors)
  1298. {
  1299. traceEventType = TraceEventType.Error;
  1300. }
  1301. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(readException, traceEventType);
  1302. }
  1303. return bytesRead;
  1304. }
  1305. void StartSyncWrite(byte[] buffer, int offset, int size)
  1306. {
  1307. StartSyncWrite(buffer, offset, size, ref this.writeOverlapped.Holder[0]);
  1308. }
  1309. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1310. unsafe void StartSyncWrite(byte[] buffer, int offset, int size, ref object holder)
  1311. {
  1312. if (this.isWriteOutstanding)
  1313. {
  1314. throw Fx.AssertAndThrow("StartSyncWrite called when write I/O was already pending.");
  1315. }
  1316. try
  1317. {
  1318. this.syncWriteSize = size;
  1319. this.isWriteOutstanding = true;
  1320. this.writeOverlapped.StartSyncOperation(buffer, ref holder);
  1321. if (UnsafeNativeMethods.WriteFile(this.pipe.DangerousGetHandle(), this.writeOverlapped.BufferPtr + offset, size, IntPtr.Zero, this.writeOverlapped.NativeOverlapped) == 0)
  1322. {
  1323. int error = Marshal.GetLastWin32Error();
  1324. if (error != UnsafeNativeMethods.ERROR_IO_PENDING)
  1325. {
  1326. this.isWriteOutstanding = false;
  1327. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Exceptions.CreateWriteException(error));
  1328. }
  1329. }
  1330. else
  1331. {
  1332. this.isWriteOutstanding = false;
  1333. }
  1334. }
  1335. finally
  1336. {
  1337. if (!this.isWriteOutstanding)
  1338. {
  1339. this.writeOverlapped.CancelSyncOperation(ref holder);
  1340. }
  1341. }
  1342. }
  1343. void WaitForSyncWrite(TimeSpan timeout, bool traceExceptionsAsErrors)
  1344. {
  1345. WaitForSyncWrite(timeout, traceExceptionsAsErrors, ref this.writeOverlapped.Holder[0]);
  1346. }
  1347. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1348. unsafe void WaitForSyncWrite(TimeSpan timeout, bool traceExceptionsAsErrors, ref object holder)
  1349. {
  1350. if (this.isWriteOutstanding)
  1351. {
  1352. if (!this.writeOverlapped.WaitForSyncOperation(timeout, ref holder))
  1353. {
  1354. Abort(SR.GetString(SR.PipeConnectionAbortedWriteTimedOut, this.writeTimeout), TransferOperation.Write);
  1355. Exception timeoutException = new TimeoutException(SR.GetString(SR.PipeWriteTimedOut, timeout));
  1356. TraceEventType traceEventType = TraceEventType.Information;
  1357. if (traceExceptionsAsErrors)
  1358. {
  1359. traceEventType = TraceEventType.Error;
  1360. }
  1361. // This intentionally doesn't reset isWriteOutstanding, because technically it still is, and we need to not free the buffer.
  1362. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(timeoutException, traceEventType);
  1363. }
  1364. else
  1365. {
  1366. this.isWriteOutstanding = false;
  1367. }
  1368. }
  1369. }
  1370. // Must be called in a lock.
  1371. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1372. unsafe void FinishSyncWrite(bool traceExceptionsAsErrors)
  1373. {
  1374. int bytesWritten;
  1375. Exception writeException;
  1376. if (this.closeState == CloseState.HandleClosed)
  1377. {
  1378. writeException = CreatePipeClosedException(TransferOperation.Write);
  1379. }
  1380. else
  1381. {
  1382. writeException = Exceptions.GetOverlappedWriteException(this.pipe, this.writeOverlapped.NativeOverlapped, out bytesWritten);
  1383. if (writeException == null && bytesWritten != this.syncWriteSize)
  1384. {
  1385. writeException = new PipeException(SR.GetString(SR.PipeWriteIncomplete));
  1386. }
  1387. }
  1388. if (writeException != null)
  1389. {
  1390. TraceEventType traceEventType = TraceEventType.Information;
  1391. if (traceExceptionsAsErrors)
  1392. {
  1393. traceEventType = TraceEventType.Error;
  1394. }
  1395. throw DiagnosticUtility.ExceptionUtility.ThrowHelper(writeException, traceEventType);
  1396. }
  1397. }
  1398. enum CloseState
  1399. {
  1400. Open,
  1401. Closing,
  1402. HandleClosed,
  1403. }
  1404. enum TransferOperation
  1405. {
  1406. Write,
  1407. Read,
  1408. Undefined,
  1409. }
  1410. static class Exceptions
  1411. {
  1412. static PipeException CreateException(string resourceString, int error)
  1413. {
  1414. return new PipeException(SR.GetString(resourceString, PipeError.GetErrorString(error)), error);
  1415. }
  1416. public static PipeException CreateReadException(int error)
  1417. {
  1418. return CreateException(SR.PipeReadError, error);
  1419. }
  1420. public static PipeException CreateWriteException(int error)
  1421. {
  1422. return CreateException(SR.PipeWriteError, error);
  1423. }
  1424. // Must be called in a lock, after checking for HandleClosed.
  1425. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1426. public static unsafe PipeException GetOverlappedWriteException(PipeHandle pipe,
  1427. NativeOverlapped* nativeOverlapped, out int bytesWritten)
  1428. {
  1429. if (UnsafeNativeMethods.GetOverlappedResult(pipe.DangerousGetHandle(), nativeOverlapped, out bytesWritten, 0) == 0)
  1430. {
  1431. int error = Marshal.GetLastWin32Error();
  1432. return Exceptions.CreateWriteException(error);
  1433. }
  1434. else
  1435. {
  1436. return null;
  1437. }
  1438. }
  1439. // Must be called in a lock, after checking for HandleClosed.
  1440. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1441. public static unsafe PipeException GetOverlappedReadException(PipeHandle pipe,
  1442. NativeOverlapped* nativeOverlapped, out int bytesRead)
  1443. {
  1444. if (UnsafeNativeMethods.GetOverlappedResult(pipe.DangerousGetHandle(), nativeOverlapped, out bytesRead, 0) == 0)
  1445. {
  1446. int error = Marshal.GetLastWin32Error();
  1447. if (error == UnsafeNativeMethods.ERROR_MORE_DATA)
  1448. {
  1449. return null;
  1450. }
  1451. else
  1452. {
  1453. return Exceptions.CreateReadException(error);
  1454. }
  1455. }
  1456. else
  1457. {
  1458. return null;
  1459. }
  1460. }
  1461. }
  1462. }
  1463. class PipeConnectionInitiator : IConnectionInitiator
  1464. {
  1465. int bufferSize;
  1466. IPipeTransportFactorySettings pipeSettings;
  1467. public PipeConnectionInitiator(int bufferSize, IPipeTransportFactorySettings pipeSettings)
  1468. {
  1469. this.bufferSize = bufferSize;
  1470. this.pipeSettings = pipeSettings;
  1471. }
  1472. Exception CreateConnectFailedException(Uri remoteUri, PipeException innerException)
  1473. {
  1474. return new CommunicationException(
  1475. SR.GetString(SR.PipeConnectFailed, remoteUri.AbsoluteUri), innerException);
  1476. }
  1477. public IConnection Connect(Uri remoteUri, TimeSpan timeout)
  1478. {
  1479. string resolvedAddress;
  1480. BackoffTimeoutHelper backoffHelper;
  1481. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  1482. this.PrepareConnect(remoteUri, timeoutHelper.RemainingTime(), out resolvedAddress, out backoffHelper);
  1483. IConnection connection = null;
  1484. while (connection == null)
  1485. {
  1486. connection = this.TryConnect(remoteUri, resolvedAddress, backoffHelper);
  1487. if (connection == null)
  1488. {
  1489. backoffHelper.WaitAndBackoff();
  1490. if (DiagnosticUtility.ShouldTraceInformation)
  1491. {
  1492. TraceUtility.TraceEvent(
  1493. TraceEventType.Information,
  1494. TraceCode.FailedPipeConnect,
  1495. SR.GetString(
  1496. SR.TraceCodeFailedPipeConnect,
  1497. timeoutHelper.RemainingTime(),
  1498. remoteUri));
  1499. }
  1500. }
  1501. }
  1502. return connection;
  1503. }
  1504. internal static string GetPipeName(Uri uri, IPipeTransportFactorySettings transportFactorySettings)
  1505. {
  1506. AppContainerInfo appInfo = GetAppContainerInfo(transportFactorySettings);
  1507. // for wildcard hostName support, we first try and connect to the StrongWildcard,
  1508. // then the Exact HostName, and lastly the WeakWildcard
  1509. string[] hostChoices = new string[] { "+", uri.Host, "*" };
  1510. bool[] globalChoices = new bool[] { true, false };
  1511. for (int i = 0; i < hostChoices.Length; i++)
  1512. {
  1513. for (int iGlobal = 0; iGlobal < globalChoices.Length; iGlobal++)
  1514. {
  1515. if (appInfo != null && globalChoices[iGlobal])
  1516. {
  1517. // Don't look at shared memory to acces pipes
  1518. // that are created in the local NamedObjectPath
  1519. continue;
  1520. }
  1521. // walk up the path hierarchy, looking for first match
  1522. string path = PipeUri.GetPath(uri);
  1523. while (path.Length > 0)
  1524. {
  1525. string sharedMemoryName = PipeUri.BuildSharedMemoryName(hostChoices[i], path, globalChoices[iGlobal], appInfo);
  1526. try
  1527. {
  1528. PipeSharedMemory sharedMemory = PipeSharedMemory.Open(sharedMemoryName, uri);
  1529. if (sharedMemory != null)
  1530. {
  1531. try
  1532. {
  1533. string pipeName = sharedMemory.GetPipeName(appInfo);
  1534. if (pipeName != null)
  1535. {
  1536. return pipeName;
  1537. }
  1538. }
  1539. finally
  1540. {
  1541. sharedMemory.Dispose();
  1542. }
  1543. }
  1544. }
  1545. catch (AddressAccessDeniedException exception)
  1546. {
  1547. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.GetString(
  1548. SR.EndpointNotFound, uri.AbsoluteUri), exception));
  1549. }
  1550. path = PipeUri.GetParentPath(path);
  1551. }
  1552. }
  1553. }
  1554. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1555. new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, uri.AbsoluteUri),
  1556. new PipeException(SR.GetString(SR.PipeEndpointNotFound, uri.AbsoluteUri))));
  1557. }
  1558. public IAsyncResult BeginConnect(Uri uri, TimeSpan timeout, AsyncCallback callback, object state)
  1559. {
  1560. return new ConnectAsyncResult(this, uri, timeout, callback, state);
  1561. }
  1562. public IConnection EndConnect(IAsyncResult result)
  1563. {
  1564. return ConnectAsyncResult.End(result);
  1565. }
  1566. void PrepareConnect(Uri remoteUri, TimeSpan timeout, out string resolvedAddress, out BackoffTimeoutHelper backoffHelper)
  1567. {
  1568. PipeUri.Validate(remoteUri);
  1569. if (DiagnosticUtility.ShouldTraceInformation)
  1570. {
  1571. TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Information, TraceCode.InitiatingNamedPipeConnection,
  1572. SR.GetString(SR.TraceCodeInitiatingNamedPipeConnection),
  1573. new StringTraceRecord("Uri", remoteUri.ToString()), this, null);
  1574. }
  1575. resolvedAddress = GetPipeName(remoteUri, this.pipeSettings);
  1576. const int backoffBufferMilliseconds = 150;
  1577. TimeSpan backoffTimeout;
  1578. if (timeout >= TimeSpan.FromMilliseconds(backoffBufferMilliseconds * 2))
  1579. {
  1580. backoffTimeout = TimeoutHelper.Add(timeout, TimeSpan.Zero - TimeSpan.FromMilliseconds(backoffBufferMilliseconds));
  1581. }
  1582. else
  1583. {
  1584. backoffTimeout = Ticks.ToTimeSpan((Ticks.FromMilliseconds(backoffBufferMilliseconds) / 2) + 1);
  1585. }
  1586. backoffHelper = new BackoffTimeoutHelper(backoffTimeout, TimeSpan.FromMinutes(5));
  1587. }
  1588. [ResourceConsumption(ResourceScope.Machine)]
  1589. IConnection TryConnect(Uri remoteUri, string resolvedAddress, BackoffTimeoutHelper backoffHelper)
  1590. {
  1591. const int access = UnsafeNativeMethods.GENERIC_READ | UnsafeNativeMethods.GENERIC_WRITE;
  1592. bool lastAttempt = backoffHelper.IsExpired();
  1593. int flags = UnsafeNativeMethods.FILE_FLAG_OVERLAPPED;
  1594. // By default Windows named pipe connection is created with impersonation, but we want
  1595. // to create it with anonymous and let WCF take care of impersonation/identification.
  1596. flags |= UnsafeNativeMethods.SECURITY_QOS_PRESENT | UnsafeNativeMethods.SECURITY_ANONYMOUS;
  1597. PipeHandle pipeHandle = UnsafeNativeMethods.CreateFile(resolvedAddress, access, 0, IntPtr.Zero,
  1598. UnsafeNativeMethods.OPEN_EXISTING, flags, IntPtr.Zero);
  1599. int error = Marshal.GetLastWin32Error();
  1600. if (pipeHandle.IsInvalid)
  1601. {
  1602. pipeHandle.SetHandleAsInvalid();
  1603. }
  1604. else
  1605. {
  1606. int mode = UnsafeNativeMethods.PIPE_READMODE_MESSAGE;
  1607. if (UnsafeNativeMethods.SetNamedPipeHandleState(pipeHandle, ref mode, IntPtr.Zero, IntPtr.Zero) == 0)
  1608. {
  1609. error = Marshal.GetLastWin32Error();
  1610. pipeHandle.Close();
  1611. PipeException innerException = new PipeException(SR.GetString(SR.PipeModeChangeFailed,
  1612. PipeError.GetErrorString(error)), error);
  1613. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1614. CreateConnectFailedException(remoteUri, innerException));
  1615. }
  1616. return new PipeConnection(pipeHandle, bufferSize, false, true);
  1617. }
  1618. if (error == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND || error == UnsafeNativeMethods.ERROR_PIPE_BUSY)
  1619. {
  1620. if (lastAttempt)
  1621. {
  1622. Exception innerException = new PipeException(SR.GetString(SR.PipeConnectAddressFailed,
  1623. resolvedAddress, PipeError.GetErrorString(error)), error);
  1624. TimeoutException timeoutException;
  1625. string endpoint = remoteUri.AbsoluteUri;
  1626. if (error == UnsafeNativeMethods.ERROR_PIPE_BUSY)
  1627. {
  1628. timeoutException = new TimeoutException(SR.GetString(SR.PipeConnectTimedOutServerTooBusy,
  1629. endpoint, backoffHelper.OriginalTimeout), innerException);
  1630. }
  1631. else
  1632. {
  1633. timeoutException = new TimeoutException(SR.GetString(SR.PipeConnectTimedOut,
  1634. endpoint, backoffHelper.OriginalTimeout), innerException);
  1635. }
  1636. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(timeoutException);
  1637. }
  1638. return null;
  1639. }
  1640. else
  1641. {
  1642. PipeException innerException = new PipeException(SR.GetString(SR.PipeConnectAddressFailed,
  1643. resolvedAddress, PipeError.GetErrorString(error)), error);
  1644. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1645. CreateConnectFailedException(remoteUri, innerException));
  1646. }
  1647. }
  1648. static AppContainerInfo GetAppContainerInfo(IPipeTransportFactorySettings transportFactorySettings)
  1649. {
  1650. if (AppContainerInfo.IsAppContainerSupported &&
  1651. transportFactorySettings != null &&
  1652. transportFactorySettings.PipeSettings != null)
  1653. {
  1654. ApplicationContainerSettings appSettings = transportFactorySettings.PipeSettings.ApplicationContainerSettings;
  1655. if (appSettings != null && appSettings.TargetingAppContainer)
  1656. {
  1657. return AppContainerInfo.CreateAppContainerInfo(appSettings.PackageFullName, appSettings.SessionId);
  1658. }
  1659. }
  1660. return null;
  1661. }
  1662. class ConnectAsyncResult : AsyncResult
  1663. {
  1664. PipeConnectionInitiator parent;
  1665. Uri remoteUri;
  1666. string resolvedAddress;
  1667. BackoffTimeoutHelper backoffHelper;
  1668. TimeoutHelper timeoutHelper;
  1669. IConnection connection;
  1670. static Action<object> waitCompleteCallback;
  1671. public ConnectAsyncResult(PipeConnectionInitiator parent, Uri remoteUri, TimeSpan timeout,
  1672. AsyncCallback callback, object state)
  1673. : base(callback, state)
  1674. {
  1675. this.parent = parent;
  1676. this.remoteUri = remoteUri;
  1677. this.timeoutHelper = new TimeoutHelper(timeout);
  1678. parent.PrepareConnect(remoteUri, this.timeoutHelper.RemainingTime(), out this.resolvedAddress, out this.backoffHelper);
  1679. if (this.ConnectAndWait())
  1680. {
  1681. this.Complete(true);
  1682. }
  1683. }
  1684. bool ConnectAndWait()
  1685. {
  1686. this.connection = this.parent.TryConnect(this.remoteUri, this.resolvedAddress, this.backoffHelper);
  1687. bool completed = (this.connection != null);
  1688. if (!completed)
  1689. {
  1690. if (waitCompleteCallback == null)
  1691. {
  1692. waitCompleteCallback = new Action<object>(OnWaitComplete);
  1693. }
  1694. this.backoffHelper.WaitAndBackoff(waitCompleteCallback, this);
  1695. }
  1696. return completed;
  1697. }
  1698. public static IConnection End(IAsyncResult result)
  1699. {
  1700. ConnectAsyncResult thisPtr = AsyncResult.End<ConnectAsyncResult>(result);
  1701. return thisPtr.connection;
  1702. }
  1703. static void OnWaitComplete(object state)
  1704. {
  1705. Exception exception = null;
  1706. ConnectAsyncResult thisPtr = (ConnectAsyncResult)state;
  1707. bool completeSelf = true;
  1708. try
  1709. {
  1710. if (DiagnosticUtility.ShouldTraceInformation)
  1711. {
  1712. TraceUtility.TraceEvent(
  1713. TraceEventType.Information,
  1714. TraceCode.FailedPipeConnect,
  1715. SR.GetString(
  1716. SR.TraceCodeFailedPipeConnect,
  1717. thisPtr.timeoutHelper.RemainingTime(),
  1718. thisPtr.remoteUri));
  1719. }
  1720. completeSelf = thisPtr.ConnectAndWait();
  1721. }
  1722. catch (Exception e)
  1723. {
  1724. if (Fx.IsFatal(e))
  1725. {
  1726. throw;
  1727. }
  1728. exception = e;
  1729. }
  1730. if (completeSelf)
  1731. {
  1732. thisPtr.Complete(false, exception);
  1733. }
  1734. }
  1735. }
  1736. }
  1737. class PipeConnectionListener : IConnectionListener
  1738. {
  1739. Uri pipeUri;
  1740. int bufferSize;
  1741. HostNameComparisonMode hostNameComparisonMode;
  1742. bool isDisposed;
  1743. bool isListening;
  1744. List<PendingAccept> pendingAccepts;
  1745. bool anyPipesCreated;
  1746. PipeSharedMemory sharedMemory;
  1747. List<SecurityIdentifier> allowedSids;
  1748. bool useCompletionPort;
  1749. int maxInstances;
  1750. public PipeConnectionListener(Uri pipeUri, HostNameComparisonMode hostNameComparisonMode, int bufferSize,
  1751. List<SecurityIdentifier> allowedSids, bool useCompletionPort, int maxConnections)
  1752. {
  1753. PipeUri.Validate(pipeUri);
  1754. this.pipeUri = pipeUri;
  1755. this.hostNameComparisonMode = hostNameComparisonMode;
  1756. this.allowedSids = allowedSids;
  1757. this.bufferSize = bufferSize;
  1758. pendingAccepts = new List<PendingAccept>();
  1759. this.useCompletionPort = useCompletionPort;
  1760. this.maxInstances = Math.Min(maxConnections, UnsafeNativeMethods.PIPE_UNLIMITED_INSTANCES);
  1761. }
  1762. object ThisLock
  1763. {
  1764. get { return this; }
  1765. }
  1766. public string PipeName { get { return sharedMemory.PipeName; } }
  1767. public IAsyncResult BeginAccept(AsyncCallback callback, object state)
  1768. {
  1769. lock (ThisLock)
  1770. {
  1771. if (isDisposed)
  1772. {
  1773. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException("", SR.GetString(SR.PipeListenerDisposed)));
  1774. }
  1775. if (!isListening)
  1776. {
  1777. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.PipeListenerNotListening)));
  1778. }
  1779. PipeHandle pipeHandle = CreatePipe();
  1780. PendingAccept pendingAccept = new PendingAccept(this, pipeHandle, useCompletionPort, callback, state);
  1781. if (!pendingAccept.CompletedSynchronously)
  1782. {
  1783. this.pendingAccepts.Add(pendingAccept);
  1784. }
  1785. return pendingAccept;
  1786. }
  1787. }
  1788. public IConnection EndAccept(IAsyncResult result)
  1789. {
  1790. PendingAccept pendingAccept = result as PendingAccept;
  1791. if (pendingAccept == null)
  1792. {
  1793. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("result", SR.GetString(SR.InvalidAsyncResult));
  1794. }
  1795. PipeHandle acceptedPipe = pendingAccept.End();
  1796. if (acceptedPipe == null)
  1797. {
  1798. return null;
  1799. }
  1800. else
  1801. {
  1802. return new PipeConnection(acceptedPipe, bufferSize,
  1803. pendingAccept.IsBoundToCompletionPort, pendingAccept.IsBoundToCompletionPort);
  1804. }
  1805. }
  1806. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1807. [ResourceConsumption(ResourceScope.Machine)]
  1808. unsafe PipeHandle CreatePipe()
  1809. {
  1810. int openMode = UnsafeNativeMethods.PIPE_ACCESS_DUPLEX | UnsafeNativeMethods.FILE_FLAG_OVERLAPPED;
  1811. if (!anyPipesCreated)
  1812. {
  1813. openMode |= UnsafeNativeMethods.FILE_FLAG_FIRST_PIPE_INSTANCE;
  1814. }
  1815. byte[] binarySecurityDescriptor;
  1816. try
  1817. {
  1818. binarySecurityDescriptor = SecurityDescriptorHelper.FromSecurityIdentifiers(allowedSids, UnsafeNativeMethods.GENERIC_READ | UnsafeNativeMethods.GENERIC_WRITE);
  1819. }
  1820. catch (Win32Exception e)
  1821. {
  1822. // While Win32exceptions are not expected, if they do occur we need to obey the pipe/communication exception model.
  1823. Exception innerException = new PipeException(e.Message, e);
  1824. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(innerException.Message, innerException));
  1825. }
  1826. PipeHandle pipeHandle;
  1827. int error;
  1828. string pipeName = null;
  1829. fixed (byte* pinnedSecurityDescriptor = binarySecurityDescriptor)
  1830. {
  1831. UnsafeNativeMethods.SECURITY_ATTRIBUTES securityAttributes = new UnsafeNativeMethods.SECURITY_ATTRIBUTES();
  1832. securityAttributes.lpSecurityDescriptor = (IntPtr)pinnedSecurityDescriptor;
  1833. pipeName = this.sharedMemory.PipeName;
  1834. pipeHandle = UnsafeNativeMethods.CreateNamedPipe(
  1835. pipeName,
  1836. openMode,
  1837. UnsafeNativeMethods.PIPE_TYPE_MESSAGE | UnsafeNativeMethods.PIPE_READMODE_MESSAGE,
  1838. maxInstances, bufferSize, bufferSize, 0, securityAttributes);
  1839. error = Marshal.GetLastWin32Error();
  1840. }
  1841. if (pipeHandle.IsInvalid)
  1842. {
  1843. pipeHandle.SetHandleAsInvalid();
  1844. Exception innerException = new PipeException(SR.GetString(SR.PipeListenFailed,
  1845. pipeUri.AbsoluteUri, PipeError.GetErrorString(error)), error);
  1846. if (error == UnsafeNativeMethods.ERROR_ACCESS_DENIED)
  1847. {
  1848. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAccessDeniedException(innerException.Message, innerException));
  1849. }
  1850. else if (error == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  1851. {
  1852. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(innerException.Message, innerException));
  1853. }
  1854. else
  1855. {
  1856. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(innerException.Message, innerException));
  1857. }
  1858. }
  1859. else
  1860. {
  1861. if (TD.NamedPipeCreatedIsEnabled())
  1862. {
  1863. TD.NamedPipeCreated(pipeName);
  1864. }
  1865. }
  1866. bool closePipe = true;
  1867. try
  1868. {
  1869. if (useCompletionPort)
  1870. {
  1871. ThreadPool.BindHandle(pipeHandle);
  1872. }
  1873. anyPipesCreated = true;
  1874. closePipe = false;
  1875. return pipeHandle;
  1876. }
  1877. finally
  1878. {
  1879. if (closePipe)
  1880. {
  1881. pipeHandle.Close();
  1882. }
  1883. }
  1884. }
  1885. public void Dispose()
  1886. {
  1887. lock (ThisLock)
  1888. {
  1889. if (!isDisposed)
  1890. {
  1891. if (sharedMemory != null)
  1892. {
  1893. sharedMemory.Dispose();
  1894. }
  1895. for (int i = 0; i < pendingAccepts.Count; i++)
  1896. {
  1897. pendingAccepts[i].Abort();
  1898. }
  1899. isDisposed = true;
  1900. }
  1901. }
  1902. }
  1903. public void Listen()
  1904. {
  1905. lock (ThisLock)
  1906. {
  1907. if (!isListening)
  1908. {
  1909. string sharedMemoryName = PipeUri.BuildSharedMemoryName(pipeUri, hostNameComparisonMode, true);
  1910. if (!PipeSharedMemory.TryCreate(allowedSids, pipeUri, sharedMemoryName, out this.sharedMemory))
  1911. {
  1912. PipeSharedMemory tempSharedMemory = null;
  1913. // first see if we're in RANU by creating a unique Uri in the global namespace
  1914. Uri tempUri = new Uri(pipeUri, Guid.NewGuid().ToString());
  1915. string tempSharedMemoryName = PipeUri.BuildSharedMemoryName(tempUri, hostNameComparisonMode, true);
  1916. if (PipeSharedMemory.TryCreate(allowedSids, tempUri, tempSharedMemoryName, out tempSharedMemory))
  1917. {
  1918. // we're not RANU, throw PipeNameInUse
  1919. tempSharedMemory.Dispose();
  1920. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1921. PipeSharedMemory.CreatePipeNameInUseException(UnsafeNativeMethods.ERROR_ACCESS_DENIED, pipeUri));
  1922. }
  1923. else
  1924. {
  1925. // try the session namespace since we're RANU
  1926. sharedMemoryName = PipeUri.BuildSharedMemoryName(pipeUri, hostNameComparisonMode, false);
  1927. this.sharedMemory = PipeSharedMemory.Create(allowedSids, pipeUri, sharedMemoryName);
  1928. }
  1929. }
  1930. isListening = true;
  1931. }
  1932. }
  1933. }
  1934. void RemovePendingAccept(PendingAccept pendingAccept)
  1935. {
  1936. lock (ThisLock)
  1937. {
  1938. Fx.Assert(this.pendingAccepts.Contains(pendingAccept), "An unknown PendingAccept is removing itself.");
  1939. this.pendingAccepts.Remove(pendingAccept);
  1940. }
  1941. }
  1942. class PendingAccept : AsyncResult
  1943. {
  1944. PipeHandle pipeHandle;
  1945. PipeHandle result;
  1946. OverlappedIOCompleteCallback onAcceptComplete;
  1947. static Action<object> onStartAccept;
  1948. OverlappedContext overlapped;
  1949. bool isBoundToCompletionPort;
  1950. PipeConnectionListener listener;
  1951. EventTraceActivity eventTraceActivity;
  1952. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1953. public unsafe PendingAccept(PipeConnectionListener listener, PipeHandle pipeHandle, bool isBoundToCompletionPort,
  1954. AsyncCallback callback, object state)
  1955. : base(callback, state)
  1956. {
  1957. this.pipeHandle = pipeHandle;
  1958. this.result = pipeHandle;
  1959. this.listener = listener;
  1960. onAcceptComplete = new OverlappedIOCompleteCallback(OnAcceptComplete);
  1961. overlapped = new OverlappedContext();
  1962. this.isBoundToCompletionPort = isBoundToCompletionPort;
  1963. if (TD.PipeConnectionAcceptStartIsEnabled())
  1964. {
  1965. this.eventTraceActivity = new EventTraceActivity();
  1966. TD.PipeConnectionAcceptStart(this.eventTraceActivity, this.listener.pipeUri != null ? this.listener.pipeUri.ToString() : string.Empty);
  1967. }
  1968. if (!Thread.CurrentThread.IsThreadPoolThread)
  1969. {
  1970. if (onStartAccept == null)
  1971. {
  1972. onStartAccept = new Action<object>(OnStartAccept);
  1973. }
  1974. ActionItem.Schedule(onStartAccept, this);
  1975. }
  1976. else
  1977. {
  1978. StartAccept(true);
  1979. }
  1980. }
  1981. public bool IsBoundToCompletionPort
  1982. {
  1983. get { return this.isBoundToCompletionPort; }
  1984. }
  1985. static void OnStartAccept(object state)
  1986. {
  1987. PendingAccept pendingAccept = (PendingAccept)state;
  1988. pendingAccept.StartAccept(false);
  1989. }
  1990. Exception CreatePipeAcceptFailedException(int errorCode)
  1991. {
  1992. Exception innerException = new PipeException(SR.GetString(SR.PipeAcceptFailed,
  1993. PipeError.GetErrorString(errorCode)), errorCode);
  1994. return new CommunicationException(innerException.Message, innerException);
  1995. }
  1996. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  1997. unsafe void StartAccept(bool synchronous)
  1998. {
  1999. Exception completionException = null;
  2000. bool completeSelf = false;
  2001. try
  2002. {
  2003. try
  2004. {
  2005. this.overlapped.StartAsyncOperation(null, onAcceptComplete, this.isBoundToCompletionPort);
  2006. while (true)
  2007. {
  2008. if (UnsafeNativeMethods.ConnectNamedPipe(pipeHandle, overlapped.NativeOverlapped) == 0)
  2009. {
  2010. int error = Marshal.GetLastWin32Error();
  2011. switch (error)
  2012. {
  2013. case UnsafeNativeMethods.ERROR_NO_DATA:
  2014. if (UnsafeNativeMethods.DisconnectNamedPipe(pipeHandle) != 0)
  2015. {
  2016. continue;
  2017. }
  2018. else
  2019. {
  2020. completeSelf = true;
  2021. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeAcceptFailedException(error));
  2022. }
  2023. case UnsafeNativeMethods.ERROR_PIPE_CONNECTED:
  2024. completeSelf = true;
  2025. break;
  2026. case UnsafeNativeMethods.ERROR_IO_PENDING:
  2027. break;
  2028. default:
  2029. completeSelf = true;
  2030. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeAcceptFailedException(error));
  2031. }
  2032. }
  2033. else
  2034. {
  2035. completeSelf = true;
  2036. }
  2037. break;
  2038. }
  2039. }
  2040. catch (ObjectDisposedException exception)
  2041. {
  2042. // A ---- with Abort can cause PipeHandle to throw this.
  2043. Fx.Assert(this.result == null, "Got an ObjectDisposedException but not an Abort!");
  2044. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
  2045. completeSelf = true;
  2046. }
  2047. finally
  2048. {
  2049. if (completeSelf)
  2050. {
  2051. this.overlapped.CancelAsyncOperation();
  2052. this.overlapped.Free();
  2053. }
  2054. }
  2055. }
  2056. #pragma warning suppress 56500 // [....], transferring exception to another thread
  2057. catch (Exception e)
  2058. {
  2059. if (Fx.IsFatal(e))
  2060. {
  2061. throw;
  2062. }
  2063. completeSelf = true;
  2064. completionException = e;
  2065. }
  2066. if (completeSelf)
  2067. {
  2068. if (!synchronous)
  2069. {
  2070. this.listener.RemovePendingAccept(this);
  2071. }
  2072. base.Complete(synchronous, completionException);
  2073. }
  2074. }
  2075. // Must be called in PipeConnectionListener's lock.
  2076. public void Abort()
  2077. {
  2078. this.result = null; // we need to return null after an abort
  2079. pipeHandle.Close();
  2080. }
  2081. public PipeHandle End()
  2082. {
  2083. AsyncResult.End<PendingAccept>(this);
  2084. return this.result;
  2085. }
  2086. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  2087. unsafe void OnAcceptComplete(bool haveResult, int error, int numBytes)
  2088. {
  2089. this.listener.RemovePendingAccept(this);
  2090. if (!haveResult)
  2091. {
  2092. // No ---- with Abort here since Abort can't be called once RemovePendingAccept happens.
  2093. if (this.result != null && UnsafeNativeMethods.GetOverlappedResult(this.pipeHandle,
  2094. this.overlapped.NativeOverlapped, out numBytes, 0) == 0)
  2095. {
  2096. error = Marshal.GetLastWin32Error();
  2097. }
  2098. else
  2099. {
  2100. error = 0;
  2101. }
  2102. }
  2103. this.overlapped.Free();
  2104. if (TD.PipeConnectionAcceptStopIsEnabled())
  2105. {
  2106. TD.PipeConnectionAcceptStop(this.eventTraceActivity);
  2107. }
  2108. if (error != 0)
  2109. {
  2110. this.pipeHandle.Close();
  2111. base.Complete(false, CreatePipeAcceptFailedException(error));
  2112. }
  2113. else
  2114. {
  2115. base.Complete(false);
  2116. }
  2117. }
  2118. }
  2119. }
  2120. static class SecurityDescriptorHelper
  2121. {
  2122. static byte[] worldCreatorOwnerWithReadAndWriteDescriptorDenyNetwork;
  2123. static byte[] worldCreatorOwnerWithReadDescriptorDenyNetwork;
  2124. static SecurityDescriptorHelper()
  2125. {
  2126. worldCreatorOwnerWithReadAndWriteDescriptorDenyNetwork = FromSecurityIdentifiersFull(null, UnsafeNativeMethods.GENERIC_READ | UnsafeNativeMethods.GENERIC_WRITE);
  2127. worldCreatorOwnerWithReadDescriptorDenyNetwork = FromSecurityIdentifiersFull(null, UnsafeNativeMethods.GENERIC_READ);
  2128. }
  2129. internal static byte[] FromSecurityIdentifiers(List<SecurityIdentifier> allowedSids, int accessRights)
  2130. {
  2131. if (allowedSids == null)
  2132. {
  2133. if (accessRights == (UnsafeNativeMethods.GENERIC_READ | UnsafeNativeMethods.GENERIC_WRITE))
  2134. {
  2135. return worldCreatorOwnerWithReadAndWriteDescriptorDenyNetwork;
  2136. }
  2137. if (accessRights == UnsafeNativeMethods.GENERIC_READ)
  2138. {
  2139. return worldCreatorOwnerWithReadDescriptorDenyNetwork;
  2140. }
  2141. }
  2142. return FromSecurityIdentifiersFull(allowedSids, accessRights);
  2143. }
  2144. static byte[] FromSecurityIdentifiersFull(List<SecurityIdentifier> allowedSids, int accessRights)
  2145. {
  2146. int capacity = allowedSids == null ? 3 : 2 + allowedSids.Count;
  2147. DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, capacity);
  2148. // add deny ACE first so that we don't get short circuited
  2149. dacl.AddAccess(AccessControlType.Deny, new SecurityIdentifier(WellKnownSidType.NetworkSid, null),
  2150. UnsafeNativeMethods.GENERIC_ALL, InheritanceFlags.None, PropagationFlags.None);
  2151. // clients get different rights, since they shouldn't be able to listen
  2152. int clientAccessRights = GenerateClientAccessRights(accessRights);
  2153. if (allowedSids == null)
  2154. {
  2155. dacl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(WellKnownSidType.WorldSid, null),
  2156. clientAccessRights, InheritanceFlags.None, PropagationFlags.None);
  2157. }
  2158. else
  2159. {
  2160. for (int i = 0; i < allowedSids.Count; i++)
  2161. {
  2162. SecurityIdentifier allowedSid = allowedSids[i];
  2163. dacl.AddAccess(AccessControlType.Allow, allowedSid,
  2164. clientAccessRights, InheritanceFlags.None, PropagationFlags.None);
  2165. }
  2166. }
  2167. dacl.AddAccess(AccessControlType.Allow, GetProcessLogonSid(), accessRights, InheritanceFlags.None, PropagationFlags.None);
  2168. if (AppContainerInfo.IsRunningInAppContainer)
  2169. {
  2170. // NamedPipeBinding requires dacl with current AppContainer SID
  2171. // to setup multiple NamedPipes in the BeginAccept loop.
  2172. dacl.AddAccess(
  2173. AccessControlType.Allow,
  2174. AppContainerInfo.GetCurrentAppContainerSid(),
  2175. accessRights,
  2176. InheritanceFlags.None,
  2177. PropagationFlags.None);
  2178. }
  2179. CommonSecurityDescriptor securityDescriptor =
  2180. new CommonSecurityDescriptor(false, false, ControlFlags.None, null, null, null, dacl);
  2181. byte[] binarySecurityDescriptor = new byte[securityDescriptor.BinaryLength];
  2182. securityDescriptor.GetBinaryForm(binarySecurityDescriptor, 0);
  2183. return binarySecurityDescriptor;
  2184. }
  2185. // Security: We cannot grant rights for FILE_CREATE_PIPE_INSTANCE to clients, otherwise other apps can intercept server side pipes.
  2186. // FILE_CREATE_PIPE_INSTANCE is granted in 2 ways, via GENERIC_WRITE or directly specified. Remove both.
  2187. static int GenerateClientAccessRights(int accessRights)
  2188. {
  2189. int everyoneAccessRights = accessRights;
  2190. if ((everyoneAccessRights & UnsafeNativeMethods.GENERIC_WRITE) != 0)
  2191. {
  2192. everyoneAccessRights &= ~UnsafeNativeMethods.GENERIC_WRITE;
  2193. // Since GENERIC_WRITE grants the permissions to write to a file, we need to add it back.
  2194. const int clientWriteAccess = UnsafeNativeMethods.FILE_WRITE_ATTRIBUTES | UnsafeNativeMethods.FILE_WRITE_DATA | UnsafeNativeMethods.FILE_WRITE_EA;
  2195. everyoneAccessRights |= clientWriteAccess;
  2196. }
  2197. // Future proofing: FILE_CREATE_PIPE_INSTANCE isn't used currently but we need to ensure it is not granted.
  2198. everyoneAccessRights &= ~UnsafeNativeMethods.FILE_CREATE_PIPE_INSTANCE;
  2199. return everyoneAccessRights;
  2200. }
  2201. // The logon sid is generated on process start up so it is unique to this process.
  2202. static SecurityIdentifier GetProcessLogonSid()
  2203. {
  2204. int pid = Process.GetCurrentProcess().Id;
  2205. return System.ServiceModel.Activation.Utility.GetLogonSidForPid(pid);
  2206. }
  2207. }
  2208. unsafe class PipeSharedMemory : IDisposable
  2209. {
  2210. internal const string PipePrefix = @"\\.\pipe\";
  2211. internal const string PipeLocalPrefix = @"\\.\pipe\Local\";
  2212. SafeFileMappingHandle fileMapping;
  2213. string pipeName;
  2214. string pipeNameGuidPart;
  2215. Uri pipeUri;
  2216. PipeSharedMemory(SafeFileMappingHandle fileMapping, Uri pipeUri)
  2217. : this(fileMapping, pipeUri, null)
  2218. {
  2219. }
  2220. PipeSharedMemory(SafeFileMappingHandle fileMapping, Uri pipeUri, string pipeName)
  2221. {
  2222. this.pipeName = pipeName;
  2223. this.fileMapping = fileMapping;
  2224. this.pipeUri = pipeUri;
  2225. }
  2226. public static PipeSharedMemory Create(List<SecurityIdentifier> allowedSids, Uri pipeUri, string sharedMemoryName)
  2227. {
  2228. PipeSharedMemory result;
  2229. if (TryCreate(allowedSids, pipeUri, sharedMemoryName, out result))
  2230. {
  2231. return result;
  2232. }
  2233. else
  2234. {
  2235. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeNameInUseException(UnsafeNativeMethods.ERROR_ACCESS_DENIED, pipeUri));
  2236. }
  2237. }
  2238. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  2239. public unsafe static bool TryCreate(List<SecurityIdentifier> allowedSids, Uri pipeUri, string sharedMemoryName, out PipeSharedMemory result)
  2240. {
  2241. Guid pipeGuid = Guid.NewGuid();
  2242. string pipeName = BuildPipeName(pipeGuid.ToString());
  2243. byte[] binarySecurityDescriptor;
  2244. try
  2245. {
  2246. binarySecurityDescriptor = SecurityDescriptorHelper.FromSecurityIdentifiers(allowedSids, UnsafeNativeMethods.GENERIC_READ);
  2247. }
  2248. catch (Win32Exception e)
  2249. {
  2250. // While Win32exceptions are not expected, if they do occur we need to obey the pipe/communication exception model.
  2251. Exception innerException = new PipeException(e.Message, e);
  2252. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(innerException.Message, innerException));
  2253. }
  2254. SafeFileMappingHandle fileMapping;
  2255. int error;
  2256. result = null;
  2257. fixed (byte* pinnedSecurityDescriptor = binarySecurityDescriptor)
  2258. {
  2259. UnsafeNativeMethods.SECURITY_ATTRIBUTES securityAttributes = new UnsafeNativeMethods.SECURITY_ATTRIBUTES();
  2260. securityAttributes.lpSecurityDescriptor = (IntPtr)pinnedSecurityDescriptor;
  2261. fileMapping = UnsafeNativeMethods.CreateFileMapping((IntPtr)(-1), securityAttributes,
  2262. UnsafeNativeMethods.PAGE_READWRITE, 0, sizeof(SharedMemoryContents), sharedMemoryName);
  2263. error = Marshal.GetLastWin32Error();
  2264. }
  2265. if (fileMapping.IsInvalid)
  2266. {
  2267. fileMapping.SetHandleAsInvalid();
  2268. if (error == UnsafeNativeMethods.ERROR_ACCESS_DENIED)
  2269. {
  2270. return false;
  2271. }
  2272. else
  2273. {
  2274. Exception innerException = new PipeException(SR.GetString(SR.PipeNameCantBeReserved,
  2275. pipeUri.AbsoluteUri, PipeError.GetErrorString(error)), error);
  2276. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAccessDeniedException(innerException.Message, innerException));
  2277. }
  2278. }
  2279. // now we have a valid file mapping handle
  2280. if (error == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  2281. {
  2282. fileMapping.Close();
  2283. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeNameInUseException(error, pipeUri));
  2284. }
  2285. PipeSharedMemory pipeSharedMemory = new PipeSharedMemory(fileMapping, pipeUri, pipeName);
  2286. bool disposeSharedMemory = true;
  2287. try
  2288. {
  2289. pipeSharedMemory.InitializeContents(pipeGuid);
  2290. disposeSharedMemory = false;
  2291. result = pipeSharedMemory;
  2292. if (TD.PipeSharedMemoryCreatedIsEnabled())
  2293. {
  2294. TD.PipeSharedMemoryCreated(sharedMemoryName);
  2295. }
  2296. return true;
  2297. }
  2298. finally
  2299. {
  2300. if (disposeSharedMemory)
  2301. {
  2302. pipeSharedMemory.Dispose();
  2303. }
  2304. }
  2305. }
  2306. [ResourceConsumption(ResourceScope.Machine)]
  2307. public static PipeSharedMemory Open(string sharedMemoryName, Uri pipeUri)
  2308. {
  2309. SafeFileMappingHandle fileMapping = UnsafeNativeMethods.OpenFileMapping(
  2310. UnsafeNativeMethods.FILE_MAP_READ, false, sharedMemoryName);
  2311. if (fileMapping.IsInvalid)
  2312. {
  2313. int error = Marshal.GetLastWin32Error();
  2314. fileMapping.SetHandleAsInvalid();
  2315. if (error == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND)
  2316. {
  2317. fileMapping = UnsafeNativeMethods.OpenFileMapping(
  2318. UnsafeNativeMethods.FILE_MAP_READ, false, "Global\\" + sharedMemoryName);
  2319. if (fileMapping.IsInvalid)
  2320. {
  2321. error = Marshal.GetLastWin32Error();
  2322. fileMapping.SetHandleAsInvalid();
  2323. if (error == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND)
  2324. {
  2325. return null;
  2326. }
  2327. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeNameCannotBeAccessedException(error, pipeUri));
  2328. }
  2329. return new PipeSharedMemory(fileMapping, pipeUri);
  2330. }
  2331. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeNameCannotBeAccessedException(error, pipeUri));
  2332. }
  2333. return new PipeSharedMemory(fileMapping, pipeUri);
  2334. }
  2335. public void Dispose()
  2336. {
  2337. if (fileMapping != null)
  2338. {
  2339. fileMapping.Close();
  2340. fileMapping = null;
  2341. }
  2342. }
  2343. public string PipeName
  2344. {
  2345. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  2346. get
  2347. {
  2348. if (pipeName == null)
  2349. {
  2350. SafeViewOfFileHandle view = GetView(false);
  2351. try
  2352. {
  2353. SharedMemoryContents* contents = (SharedMemoryContents*)view.DangerousGetHandle();
  2354. if (contents->isInitialized)
  2355. {
  2356. Thread.MemoryBarrier();
  2357. this.pipeNameGuidPart = contents->pipeGuid.ToString();
  2358. this.pipeName = BuildPipeName(this.pipeNameGuidPart);
  2359. }
  2360. }
  2361. finally
  2362. {
  2363. view.Close();
  2364. }
  2365. }
  2366. return pipeName;
  2367. }
  2368. }
  2369. internal string GetPipeName(AppContainerInfo appInfo)
  2370. {
  2371. if (appInfo == null)
  2372. {
  2373. return this.PipeName;
  2374. }
  2375. else if (this.PipeName != null)
  2376. {
  2377. // Build the PipeName for a pipe inside an AppContainer as follows
  2378. // \\.\pipe\Sessions\<SessionId>\<NamedObjectPath>\<PipeGuid>
  2379. return string.Format(
  2380. CultureInfo.InvariantCulture,
  2381. @"\\.\pipe\Sessions\{0}\{1}\{2}",
  2382. appInfo.SessionId,
  2383. appInfo.NamedObjectPath,
  2384. this.pipeNameGuidPart);
  2385. }
  2386. return null;
  2387. }
  2388. [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
  2389. void InitializeContents(Guid pipeGuid)
  2390. {
  2391. SafeViewOfFileHandle view = GetView(true);
  2392. try
  2393. {
  2394. SharedMemoryContents* contents = (SharedMemoryContents*)view.DangerousGetHandle();
  2395. contents->pipeGuid = pipeGuid;
  2396. Thread.MemoryBarrier();
  2397. contents->isInitialized = true;
  2398. }
  2399. finally
  2400. {
  2401. view.Close();
  2402. }
  2403. }
  2404. public static Exception CreatePipeNameInUseException(int error, Uri pipeUri)
  2405. {
  2406. Exception innerException = new PipeException(SR.GetString(SR.PipeNameInUse, pipeUri.AbsoluteUri), error);
  2407. return new AddressAlreadyInUseException(innerException.Message, innerException);
  2408. }
  2409. static Exception CreatePipeNameCannotBeAccessedException(int error, Uri pipeUri)
  2410. {
  2411. Exception innerException = new PipeException(SR.GetString(SR.PipeNameCanNotBeAccessed,
  2412. PipeError.GetErrorString(error)), error);
  2413. return new AddressAccessDeniedException(SR.GetString(SR.PipeNameCanNotBeAccessed2, pipeUri.AbsoluteUri), innerException);
  2414. }
  2415. SafeViewOfFileHandle GetView(bool writable)
  2416. {
  2417. SafeViewOfFileHandle handle = UnsafeNativeMethods.MapViewOfFile(fileMapping,
  2418. writable ? UnsafeNativeMethods.FILE_MAP_WRITE : UnsafeNativeMethods.FILE_MAP_READ,
  2419. 0, 0, (IntPtr)sizeof(SharedMemoryContents));
  2420. if (handle.IsInvalid)
  2421. {
  2422. int error = Marshal.GetLastWin32Error();
  2423. handle.SetHandleAsInvalid();
  2424. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreatePipeNameCannotBeAccessedException(error, pipeUri));
  2425. }
  2426. return handle;
  2427. }
  2428. static string BuildPipeName(string pipeGuid)
  2429. {
  2430. return (AppContainerInfo.IsRunningInAppContainer ? PipeLocalPrefix : PipePrefix) + pipeGuid;
  2431. }
  2432. [StructLayout(LayoutKind.Sequential)]
  2433. struct SharedMemoryContents
  2434. {
  2435. public bool isInitialized;
  2436. public Guid pipeGuid;
  2437. }
  2438. }
  2439. static class PipeUri
  2440. {
  2441. public static string BuildSharedMemoryName(Uri uri, HostNameComparisonMode hostNameComparisonMode, bool global)
  2442. {
  2443. string path = PipeUri.GetPath(uri);
  2444. string host = null;
  2445. switch (hostNameComparisonMode)
  2446. {
  2447. case HostNameComparisonMode.StrongWildcard:
  2448. host = "+";
  2449. break;
  2450. case HostNameComparisonMode.Exact:
  2451. host = uri.Host;
  2452. break;
  2453. case HostNameComparisonMode.WeakWildcard:
  2454. host = "*";
  2455. break;
  2456. }
  2457. return PipeUri.BuildSharedMemoryName(host, path, global);
  2458. }
  2459. internal static string BuildSharedMemoryName(string hostName, string path, bool global, AppContainerInfo appContainerInfo)
  2460. {
  2461. if (appContainerInfo == null)
  2462. {
  2463. return BuildSharedMemoryName(hostName, path, global);
  2464. }
  2465. else
  2466. {
  2467. Fx.Assert(appContainerInfo.SessionId != ApplicationContainerSettingsDefaults.CurrentSession, "Session has not yet been initialized.");
  2468. Fx.Assert(!String.IsNullOrEmpty(appContainerInfo.NamedObjectPath),
  2469. "NamedObjectPath cannot be empty when creating the SharedMemoryName when running in an AppContainer.");
  2470. //We need to use a session symlink for the lowbox appcontainer.
  2471. // Session\{0}\{1}\{2}\<SharedMemoryName>
  2472. return string.Format(
  2473. CultureInfo.InvariantCulture,
  2474. @"Session\{0}\{1}\{2}",
  2475. appContainerInfo.SessionId,
  2476. appContainerInfo.NamedObjectPath,
  2477. BuildSharedMemoryName(hostName, path, global));
  2478. }
  2479. }
  2480. static string BuildSharedMemoryName(string hostName, string path, bool global)
  2481. {
  2482. StringBuilder builder = new StringBuilder();
  2483. builder.Append(Uri.UriSchemeNetPipe);
  2484. builder.Append("://");
  2485. builder.Append(hostName.ToUpperInvariant());
  2486. builder.Append(path);
  2487. string canonicalName = builder.ToString();
  2488. byte[] canonicalBytes = Encoding.UTF8.GetBytes(canonicalName);
  2489. byte[] hashedBytes;
  2490. string separator;
  2491. if (canonicalBytes.Length >= 128)
  2492. {
  2493. using (HashAlgorithm hash = GetHashAlgorithm())
  2494. {
  2495. hashedBytes = hash.ComputeHash(canonicalBytes);
  2496. }
  2497. separator = ":H";
  2498. }
  2499. else
  2500. {
  2501. hashedBytes = canonicalBytes;
  2502. separator = ":E";
  2503. }
  2504. builder = new StringBuilder();
  2505. if (global)
  2506. {
  2507. // we may need to create the shared memory in the global namespace so we work with terminal services+admin
  2508. builder.Append("Global\\");
  2509. }
  2510. else
  2511. {
  2512. builder.Append("Local\\");
  2513. }
  2514. builder.Append(Uri.UriSchemeNetPipe);
  2515. builder.Append(separator);
  2516. builder.Append(Convert.ToBase64String(hashedBytes));
  2517. return builder.ToString();
  2518. }
  2519. static HashAlgorithm GetHashAlgorithm()
  2520. {
  2521. if (SecurityUtilsEx.RequiresFipsCompliance)
  2522. return new SHA1CryptoServiceProvider();
  2523. else
  2524. return new SHA1Managed();
  2525. }
  2526. public static string GetPath(Uri uri)
  2527. {
  2528. string path = uri.LocalPath.ToUpperInvariant();
  2529. if (!path.EndsWith("/", StringComparison.Ordinal))
  2530. path = path + "/";
  2531. return path;
  2532. }
  2533. public static string GetParentPath(string path)
  2534. {
  2535. if (path.EndsWith("/", StringComparison.Ordinal))
  2536. path = path.Substring(0, path.Length - 1);
  2537. if (path.Length == 0)
  2538. return path;
  2539. return path.Substring(0, path.LastIndexOf('/') + 1);
  2540. }
  2541. public static void Validate(Uri uri)
  2542. {
  2543. if (uri.Scheme != Uri.UriSchemeNetPipe)
  2544. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("uri", SR.GetString(SR.PipeUriSchemeWrong));
  2545. }
  2546. }
  2547. static class PipeError
  2548. {
  2549. public static string GetErrorString(int error)
  2550. {
  2551. StringBuilder stringBuilder = new StringBuilder(512);
  2552. if (UnsafeNativeMethods.FormatMessage(UnsafeNativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS |
  2553. UnsafeNativeMethods.FORMAT_MESSAGE_FROM_SYSTEM | UnsafeNativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY,
  2554. IntPtr.Zero, error, CultureInfo.CurrentCulture.LCID, stringBuilder, stringBuilder.Capacity, IntPtr.Zero) != 0)
  2555. {
  2556. stringBuilder = stringBuilder.Replace("\n", "");
  2557. stringBuilder = stringBuilder.Replace("\r", "");
  2558. return SR.GetString(
  2559. SR.PipeKnownWin32Error,
  2560. stringBuilder.ToString(),
  2561. error.ToString(CultureInfo.InvariantCulture),
  2562. Convert.ToString(error, 16));
  2563. }
  2564. else
  2565. {
  2566. return SR.GetString(
  2567. SR.PipeUnknownWin32Error,
  2568. error.ToString(CultureInfo.InvariantCulture),
  2569. Convert.ToString(error, 16));
  2570. }
  2571. }
  2572. }
  2573. }