Browse Source

Apewer-6.0.5:调整 FromTrusted 规则,减少了存在 CDN 时的误判。对 .NET FX 2.0 加入命名管道。

dev
Elivo 5 years ago
parent
commit
59ca45dcb8
  1. 11
      Apewer.Run/_Program.cs
  2. 13
      Apewer/Apewer.csproj
  3. 23
      Apewer/Externals/System.Core-3.5.0.0/Microsoft/Win32/SECURITY_ATTRIBUTES.cs
  4. 37
      Apewer/Externals/System.Core-3.5.0.0/Microsoft/Win32/SafeHandles/SafePipeHandle.cs
  5. 148
      Apewer/Externals/System.Core-3.5.0.0/Microsoft/Win32/UnsafeNativeMethods.cs
  6. 15
      Apewer/Externals/System.Core-3.5.0.0/System/IO/HandleInheritability.cs
  7. 84
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/AnonymousPipeClientStream.cs
  8. 204
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/AnonymousPipeServerStream.cs
  9. 291
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/NamedPipeClientStream.cs
  10. 459
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/NamedPipeServerStream.cs
  11. 34
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAccessRights.cs
  12. 67
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAccessRule.cs
  13. 110
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAsyncResult.cs
  14. 50
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAuditRule.cs
  15. 20
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeDirection.cs
  16. 21
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeOptions.cs
  17. 243
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeSecurity.cs
  18. 22
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeState.cs
  19. 1062
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeStream.cs
  20. 116
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeStreamAsyncResult.cs
  21. 10
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeStreamImpersonationWorker.cs
  22. 20
      Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeTransmissionMode.cs
  23. 184
      Apewer/Externals/System.Core-3.5.0.0/System/IO/__Error.cs
  24. 17
      Apewer/Externals/System.Core-3.5.0.0/System/SR.cs
  25. 2
      Apewer/Internals/Constant.cs
  26. 100
      Apewer/Internals/Interop/Constant.cs
  27. 11
      Apewer/Internals/Interop/Delegate.cs
  28. 7
      Apewer/Internals/Interop/Kernel32.cs
  29. 21
      Apewer/Internals/Interop/MSLLHOOKSTRUCT.cs
  30. 22
      Apewer/Internals/Interop/User32.cs
  31. 19
      Apewer/Internals/Interop/WS2_32.cs
  32. 28
      Apewer/Internals/Interop/WinMM.cs
  33. 23
      Apewer/Internals/Interop/hostent.cs
  34. 39
      Apewer/KernelUtility.cs
  35. 31
      Apewer/Models/MouseButtons.cs
  36. 26
      Apewer/Models/MouseEvent.cs
  37. 22
      Apewer/Models/StringPairs.cs
  38. 53
      Apewer/NetworkUtility.cs
  39. 54
      Apewer/Web/WebUtility.cs
  40. 122
      Apewer/WindowsUtility.cs
  41. 4
      Apewer/_ChangeLog.md

11
Apewer.Run/_Program.cs

@ -1,5 +1,6 @@
using Apewer;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Apewer.Run
@ -11,6 +12,16 @@ namespace Apewer.Run
public static string[] Arguments = null;
static void Main(string[] args)
{
// Console.WriteLine(NetworkUtility.Resolve2("www.baidu.com"));
// RunPublicClass(args);
Console.WriteLine("ended");
Console.ReadKey();
}
static void RunPublicClass(params string[] args)
{
Arguments = args;
foreach (var type in ClassUtility.GetTypes(Assembly.GetExecutingAssembly()))

13
Apewer/Apewer.csproj

@ -5,23 +5,28 @@
<!-- Info -->
<PropertyGroup>
<AssemblyName>Apewer</AssemblyName>
<PackageId>Apewer</PackageId>
<Title>Apewer</Title>
<Version>6.0.5</Version>
</PropertyGroup>
<!-- Info -->
<PropertyGroup>
<Authors>Elivo</Authors>
<Company>Apewer Lab</Company>
<Copyright>Copyright Apewer Lab. All rights reserved.</Copyright>
<Description></Description>
<PackageId>Apewer</PackageId>
<RootNamespace>Apewer</RootNamespace>
<TargetFrameworks>netstandard2.1;net20;net40;net461;netcoreapp3.1</TargetFrameworks>
<Title>Apewer</Title>
<Product>Apewer Libraries</Product>
<Version>6.0.4</Version>
</PropertyGroup>
<!-- Info -->
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<LangVersion>latest</LangVersion>
<NoWarn>CS0108,CS0414,CS0612,CS0618,CS0649,CS1589,CS1570,CS1572,CS1573,CS3019,CS3021</NoWarn>
<NoWarn>CS0108,CS0162,CS0414,CS0612,CS0618,CS0649,CS1589,CS1570,CS1572,CS1573,CS3019,CS3021</NoWarn>
<OutputType>Library</OutputType>
</PropertyGroup>

23
Apewer/Externals/System.Core-3.5.0.0/Microsoft/Win32/SECURITY_ATTRIBUTES.cs

@ -0,0 +1,23 @@
#if NET20
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.Win32
{
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
internal int nLength;
internal unsafe byte* pSecurityDescriptor;
internal int bInheritHandle;
}
}
#endif

37
Apewer/Externals/System.Core-3.5.0.0/Microsoft/Win32/SafeHandles/SafePipeHandle.cs

@ -0,0 +1,37 @@
#if NET20
using Apewer.Internals.Interop;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Security;
using System.Security.Permissions;
namespace Microsoft.Win32.SafeHandles
{
[SecurityCritical(SecurityCriticalScope.Everything)]
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
internal sealed class SafePipeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafePipeHandle()
: base(true)
{
}
public SafePipeHandle(IntPtr preexistingHandle, bool ownsHandle)
: base(ownsHandle)
{
base.SetHandle(preexistingHandle);
}
protected override bool ReleaseHandle()
{
return Kernel32.CloseHandle(base.handle);
}
}
}
#endif

148
Apewer/Externals/System.Core-3.5.0.0/Microsoft/Win32/UnsafeNativeMethods.cs

@ -0,0 +1,148 @@
#if NET20
using Apewer.Internals.Interop;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
namespace Microsoft.Win32
{
[SuppressUnmanagedCodeSecurity]
internal static class UnsafeNativeMethods
{
#region constants
internal static readonly IntPtr NULL = IntPtr.Zero;
#endregion
#region dll methods
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal unsafe static extern bool ConnectNamedPipe(SafePipeHandle handle, NativeOverlapped* overlapped);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ConnectNamedPipe(SafePipeHandle handle, IntPtr overlapped);
[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern SafePipeHandle CreateNamedPipe(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, SECURITY_ATTRIBUTES securityAttributes);
[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto, EntryPoint = "CreateFile", SetLastError = true)]
internal static extern SafePipeHandle CreateNamedPipeClient(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CreatePipe(out SafePipeHandle hReadPipe, out SafePipeHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DisconnectNamedPipe(SafePipeHandle hNamedPipe);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FlushFileBuffers(SafePipeHandle hNamedPipe);
[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto)]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
internal static extern int GetFileType(SafePipeHandle handle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize);
[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, StringBuilder lpUserName, int nMaxUserNameSize);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, out int lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, out int lpFlags, IntPtr lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, IntPtr lpOutBufferSize, out int lpInBufferSize, IntPtr lpMaxInstances);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, out int lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances);
[DllImport("advapi32.dll", SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ImpersonateNamedPipeClient(SafePipeHandle hNamedPipe);
[DllImport("kernel32.dll", SetLastError = true)]
internal unsafe static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
[DllImport("kernel32.dll", SetLastError = true)]
internal unsafe static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);
[DllImport("advapi32.dll", SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal unsafe static extern bool SetNamedPipeHandleState(SafePipeHandle hNamedPipe, int* lpMode, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout);
[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitNamedPipe(string name, int timeout);
[DllImport("kernel32.dll", SetLastError = true)]
internal unsafe static extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
[DllImport("kernel32.dll", SetLastError = true)]
internal unsafe static extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
#endregion
#region manaegd methods
[SecurityCritical]
internal static string GetMessage(int errorCode)
{
StringBuilder stringBuilder = new StringBuilder(512);
if (FormatMessage(12800, NULL, errorCode, 0, stringBuilder, stringBuilder.Capacity, NULL) != 0)
{
return stringBuilder.ToString();
}
return "UnknownError_Num " + errorCode;
}
internal static int MakeHRFromErrorCode(int errorCode)
{
return -2147024896 | errorCode;
}
#endregion
}
}
#endif

15
Apewer/Externals/System.Core-3.5.0.0/System/IO/HandleInheritability.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace System.IO
{
[Serializable]
internal enum HandleInheritability
{
None,
Inheritable
}
}

84
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/AnonymousPipeClientStream.cs

@ -0,0 +1,84 @@
#if NET20
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class AnonymousPipeClientStream : PipeStream
{
public override PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
get
{
return PipeTransmissionMode.Byte;
}
}
public override PipeTransmissionMode ReadMode
{
[SecurityCritical]
set
{
CheckPipePropertyOperations();
switch (value)
{
case PipeTransmissionMode.Byte:
break;
default:
throw new ArgumentOutOfRangeException("value", "ArgumentOutOfRange_TransmissionModeByteOrMsg");
case PipeTransmissionMode.Message:
throw new NotSupportedException("NotSupported_AnonymousPipeMessagesNotSupported");
}
}
}
public AnonymousPipeClientStream(string pipeHandleAsString)
: this(PipeDirection.In, pipeHandleAsString)
{
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeClientStream(PipeDirection direction, string pipeHandleAsString)
: this(direction, new SafePipeHandle((IntPtr)long.Parse(pipeHandleAsString), true))
{
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePipeHandle)
: base(direction, 0)
{
if (direction == PipeDirection.InOut)
{
throw new NotSupportedException("NotSupported_AnonymousPipeUnidirectional");
}
if (UnsafeNativeMethods.GetFileType(safePipeHandle) != 3)
{
throw new IOException("IO_IO_InvalidPipeHandle");
}
base.InitializeHandle(safePipeHandle, true, false);
base.State = PipeState.Connected;
}
~AnonymousPipeClientStream()
{
Dispose(false);
}
}
}
#endif

204
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/AnonymousPipeServerStream.cs

@ -0,0 +1,204 @@
#if NET20
using Apewer.Internals.Interop;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class AnonymousPipeServerStream : PipeStream
{
private SafePipeHandle m_clientHandle;
private bool m_clientHandleExposed;
public SafePipeHandle ClientSafePipeHandle
{
[SecurityCritical]
get
{
m_clientHandleExposed = true;
return m_clientHandle;
}
}
public override PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
get
{
return PipeTransmissionMode.Byte;
}
}
public override PipeTransmissionMode ReadMode
{
[SecurityCritical]
set
{
CheckPipePropertyOperations();
switch (value)
{
case PipeTransmissionMode.Byte:
break;
default:
throw new ArgumentOutOfRangeException("value", System.SR.GetString("ArgumentOutOfRange_TransmissionModeByteOrMsg"));
case PipeTransmissionMode.Message:
throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeMessagesNotSupported"));
}
}
}
public AnonymousPipeServerStream()
: this(PipeDirection.Out, HandleInheritability.None, 0, null)
{
}
public AnonymousPipeServerStream(PipeDirection direction)
: this(direction, HandleInheritability.None, 0)
{
}
public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability)
: this(direction, inheritability, 0)
{
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
: base(direction, bufferSize)
{
if (direction == PipeDirection.InOut)
{
throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional"));
}
if (inheritability >= HandleInheritability.None && inheritability <= HandleInheritability.Inheritable)
{
SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
Create(direction, secAttrs, bufferSize);
return;
}
throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
: base(direction, bufferSize)
{
if (direction == PipeDirection.InOut)
{
throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional"));
}
if (inheritability >= HandleInheritability.None && inheritability <= HandleInheritability.Inheritable)
{
object obj;
SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out obj);
try
{
Create(direction, secAttrs, bufferSize);
}
finally
{
if (obj != null)
{
((GCHandle)obj).Free();
}
}
return;
}
throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
}
~AnonymousPipeServerStream()
{
Dispose(false);
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeServerStream(PipeDirection direction, SafePipeHandle serverSafePipeHandle, SafePipeHandle clientSafePipeHandle)
: base(direction, 0)
{
if (direction == PipeDirection.InOut)
{
throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional"));
}
if (UnsafeNativeMethods.GetFileType(serverSafePipeHandle) != 3)
{
throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle"));
}
if (UnsafeNativeMethods.GetFileType(clientSafePipeHandle) != 3)
{
throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle"));
}
base.InitializeHandle(serverSafePipeHandle, true, false);
m_clientHandle = clientSafePipeHandle;
m_clientHandleExposed = true;
base.State = PipeState.Connected;
}
[SecurityCritical]
public string GetClientHandleAsString()
{
m_clientHandleExposed = true;
return m_clientHandle.DangerousGetHandle().ToString();
}
[SecurityCritical]
public void DisposeLocalCopyOfClientHandle()
{
if (m_clientHandle != null && !m_clientHandle.IsClosed)
{
m_clientHandle.Dispose();
}
}
[SecurityCritical]
protected override void Dispose(bool disposing)
{
try
{
if (!m_clientHandleExposed && m_clientHandle != null && !m_clientHandle.IsClosed)
{
m_clientHandle.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
[SecurityCritical]
private void Create(PipeDirection direction, SECURITY_ATTRIBUTES secAttrs, int bufferSize)
{
SafePipeHandle safePipeHandle;
if (!((direction != PipeDirection.In) ? UnsafeNativeMethods.CreatePipe(out m_clientHandle, out safePipeHandle, secAttrs, bufferSize) : UnsafeNativeMethods.CreatePipe(out safePipeHandle, out m_clientHandle, secAttrs, bufferSize)))
{
System.IO.__Error.WinIOError(Marshal.GetLastWin32Error(), string.Empty);
}
SafePipeHandle handle;
if (!UnsafeNativeMethods.DuplicateHandle(UnsafeNativeMethods.GetCurrentProcess(), safePipeHandle, UnsafeNativeMethods.GetCurrentProcess(), out handle, 0u, false, 2u))
{
System.IO.__Error.WinIOError(Marshal.GetLastWin32Error(), string.Empty);
}
safePipeHandle.Dispose();
base.InitializeHandle(handle, false, false);
base.State = PipeState.Connected;
}
}
}
#endif

291
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/NamedPipeClientStream.cs

@ -0,0 +1,291 @@
#if NET20
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class NamedPipeClientStream : PipeStream
{
private string m_normalizedPipePath;
private TokenImpersonationLevel m_impersonationLevel;
private PipeOptions m_pipeOptions;
private HandleInheritability m_inheritability;
private int m_access;
public int NumberOfServerInstances
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
int result;
if (!Microsoft.Win32.UnsafeNativeMethods.GetNamedPipeHandleState(base.InternalHandle, Microsoft.Win32.UnsafeNativeMethods.NULL, out result, Microsoft.Win32.UnsafeNativeMethods.NULL, Microsoft.Win32.UnsafeNativeMethods.NULL, Microsoft.Win32.UnsafeNativeMethods.NULL, 0))
{
base.WinIOError(Marshal.GetLastWin32Error());
}
return result;
}
}
public NamedPipeClientStream(string pipeName)
: this(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None)
{
}
public NamedPipeClientStream(string serverName, string pipeName)
: this(serverName, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None)
{
}
public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction)
: this(serverName, pipeName, direction, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None)
{
}
public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction, PipeOptions options)
: this(serverName, pipeName, direction, options, TokenImpersonationLevel.None, HandleInheritability.None)
{
}
public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction, PipeOptions options, TokenImpersonationLevel impersonationLevel)
: this(serverName, pipeName, direction, options, impersonationLevel, HandleInheritability.None)
{
}
public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
: base(direction, 0)
{
if (pipeName == null)
{
throw new ArgumentNullException("pipeName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName", System.SR.GetString("ArgumentNull_ServerName"));
}
if (pipeName.Length == 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NeedNonemptyPipeName"));
}
if (serverName.Length == 0)
{
throw new ArgumentException(System.SR.GetString("Argument_EmptyServerName"));
}
if ((options & (PipeOptions)1073741823) != 0)
{
throw new ArgumentOutOfRangeException("options", System.SR.GetString("ArgumentOutOfRange_OptionsInvalid"));
}
if (impersonationLevel >= TokenImpersonationLevel.None && impersonationLevel <= TokenImpersonationLevel.Delegation)
{
if (inheritability >= HandleInheritability.None && inheritability <= HandleInheritability.Inheritable)
{
m_normalizedPipePath = Path.GetFullPath("\\\\" + serverName + "\\pipe\\" + pipeName);
if (string.Compare(m_normalizedPipePath, "\\\\.\\pipe\\anonymous", StringComparison.OrdinalIgnoreCase) == 0)
{
throw new ArgumentOutOfRangeException("pipeName", System.SR.GetString("ArgumentOutOfRange_AnonymousReserved"));
}
m_inheritability = inheritability;
m_impersonationLevel = impersonationLevel;
m_pipeOptions = options;
if ((PipeDirection.In & direction) != 0)
{
m_access |= -2147483648;
}
if ((PipeDirection.Out & direction) != 0)
{
m_access |= 1073741824;
}
return;
}
throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
}
throw new ArgumentOutOfRangeException("impersonationLevel", System.SR.GetString("ArgumentOutOfRange_ImpersonationInvalid"));
}
public NamedPipeClientStream(string serverName, string pipeName, PipeAccessRights desiredAccessRights, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
: base(DirectionFromRights(desiredAccessRights), 0)
{
if (pipeName == null)
{
throw new ArgumentNullException("pipeName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName", System.SR.GetString("ArgumentNull_ServerName"));
}
if (pipeName.Length == 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NeedNonemptyPipeName"));
}
if (serverName.Length == 0)
{
throw new ArgumentException(System.SR.GetString("Argument_EmptyServerName"));
}
if ((options & (PipeOptions)1073741823) != 0)
{
throw new ArgumentOutOfRangeException("options", System.SR.GetString("ArgumentOutOfRange_OptionsInvalid"));
}
if (impersonationLevel >= TokenImpersonationLevel.None && impersonationLevel <= TokenImpersonationLevel.Delegation)
{
if (inheritability >= HandleInheritability.None && inheritability <= HandleInheritability.Inheritable)
{
if ((desiredAccessRights & ~(PipeAccessRights.ReadData | PipeAccessRights.WriteData | PipeAccessRights.ReadAttributes | PipeAccessRights.WriteAttributes | PipeAccessRights.ReadExtendedAttributes | PipeAccessRights.WriteExtendedAttributes | PipeAccessRights.CreateNewInstance | PipeAccessRights.Delete | PipeAccessRights.ReadPermissions | PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership | PipeAccessRights.Synchronize | PipeAccessRights.AccessSystemSecurity)) != 0)
{
throw new ArgumentOutOfRangeException("desiredAccessRights", System.SR.GetString("ArgumentOutOfRange_InvalidPipeAccessRights"));
}
m_normalizedPipePath = Path.GetFullPath("\\\\" + serverName + "\\pipe\\" + pipeName);
if (string.Compare(m_normalizedPipePath, "\\\\.\\pipe\\anonymous", StringComparison.OrdinalIgnoreCase) == 0)
{
throw new ArgumentOutOfRangeException("pipeName", System.SR.GetString("ArgumentOutOfRange_AnonymousReserved"));
}
m_inheritability = inheritability;
m_impersonationLevel = impersonationLevel;
m_pipeOptions = options;
m_access = (int)desiredAccessRights;
return;
}
throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
}
throw new ArgumentOutOfRangeException("impersonationLevel", System.SR.GetString("ArgumentOutOfRange_ImpersonationInvalid"));
}
private static PipeDirection DirectionFromRights(PipeAccessRights rights)
{
PipeDirection pipeDirection = (PipeDirection)0;
if ((rights & PipeAccessRights.ReadData) != 0)
{
pipeDirection |= PipeDirection.In;
}
if ((rights & PipeAccessRights.WriteData) != 0)
{
pipeDirection |= PipeDirection.Out;
}
return pipeDirection;
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle)
: base(direction, 0)
{
if (Microsoft.Win32.UnsafeNativeMethods.GetFileType(safePipeHandle) != 3)
{
throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle"));
}
base.InitializeHandle(safePipeHandle, true, isAsync);
if (isConnected)
{
base.State = PipeState.Connected;
}
}
~NamedPipeClientStream()
{
Dispose(false);
}
public void Connect()
{
Connect(-1);
}
[SecurityCritical]
public void Connect(int timeout)
{
CheckConnectOperationsClient();
if (timeout < 0 && timeout != -1)
{
throw new ArgumentOutOfRangeException("timeout", System.SR.GetString("ArgumentOutOfRange_InvalidTimeout"));
}
SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(m_inheritability);
int num = (int)m_pipeOptions;
if (m_impersonationLevel != 0)
{
num |= 0x100000;
num |= (int)(m_impersonationLevel - 1) << 16;
}
int tickCount = Environment.TickCount;
int num2 = 0;
do
{
if (!Microsoft.Win32.UnsafeNativeMethods.WaitNamedPipe(m_normalizedPipePath, timeout - num2))
{
int lastWin32Error = Marshal.GetLastWin32Error();
switch (lastWin32Error)
{
case 2:
continue;
case 0:
goto end_IL_005c;
}
System.IO.__Error.WinIOError(lastWin32Error, string.Empty);
}
SafePipeHandle safePipeHandle = Microsoft.Win32.UnsafeNativeMethods.CreateNamedPipeClient(m_normalizedPipePath, m_access, FileShare.None, secAttrs, FileMode.Open, num, Microsoft.Win32.UnsafeNativeMethods.NULL);
if (safePipeHandle.IsInvalid)
{
int lastWin32Error2 = Marshal.GetLastWin32Error();
if (lastWin32Error2 != 231)
{
System.IO.__Error.WinIOError(lastWin32Error2, string.Empty);
goto IL_00cc;
}
continue;
}
goto IL_00cc;
IL_00cc:
base.InitializeHandle(safePipeHandle, false, (m_pipeOptions & PipeOptions.Asynchronous) != PipeOptions.None);
base.State = PipeState.Connected;
return;
continue;
end_IL_005c:
break;
}
while (timeout == -1 || (num2 = Environment.TickCount - tickCount) < timeout);
throw new TimeoutException();
}
[SecurityCritical]
protected internal override void CheckPipePropertyOperations()
{
base.CheckPipePropertyOperations();
if (base.State == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeNotYetConnected"));
}
if (base.State != PipeState.Broken)
{
return;
}
throw new IOException(System.SR.GetString("IO_IO_PipeBroken"));
}
private void CheckConnectOperationsClient()
{
if (base.State == PipeState.Connected)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeAlreadyConnected"));
}
if (base.State == PipeState.Closed)
{
System.IO.__Error.PipeNotOpen();
}
}
}
}
#endif

459
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/NamedPipeServerStream.cs

@ -0,0 +1,459 @@
#if NET20
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.IO.Pipes;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class NamedPipeServerStream : PipeStream
{
internal class ExecuteHelper
{
internal PipeStreamImpersonationWorker m_userCode;
internal SafePipeHandle m_handle;
internal bool m_mustRevert;
internal int m_impersonateErrorCode;
internal int m_revertImpersonateErrorCode;
[SecurityCritical]
internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle)
{
m_userCode = userCode;
m_handle = handle;
}
}
public const int MaxAllowedServerInstances = -1;
private static int s_maxUsernameLength;
private static readonly IOCompletionCallback WaitForConnectionCallback;
private static RuntimeHelpers.TryCode tryCode;
private static RuntimeHelpers.CleanupCode cleanupCode;
[SecurityCritical]
static unsafe NamedPipeServerStream()
{
s_maxUsernameLength = 20;
WaitForConnectionCallback = AsyncWaitForConnectionCallback;
tryCode = ImpersonateAndTryCode;
cleanupCode = RevertImpersonationOnBackout;
}
public NamedPipeServerStream(string pipeName)
: this(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction)
: this(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances)
: this(pipeName, direction, maxNumberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, PipeOptions.None, 0, 0, null, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, 0, 0, null, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, null, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, HandleInheritability.None, (PipeAccessRights)0)
{
}
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, inheritability, (PipeAccessRights)0)
{
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
: base(direction, transmissionMode, outBufferSize)
{
if (pipeName == null)
{
throw new ArgumentNullException("pipeName");
}
if (pipeName.Length == 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NeedNonemptyPipeName"));
}
if ((options & (PipeOptions)1073741823) != 0)
{
throw new ArgumentOutOfRangeException("options", System.SR.GetString("ArgumentOutOfRange_OptionsInvalid"));
}
if (inBufferSize < 0)
{
throw new ArgumentOutOfRangeException("inBufferSize", System.SR.GetString("ArgumentOutOfRange_NeedNonNegNum"));
}
if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && maxNumberOfServerInstances != -1)
{
throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", System.SR.GetString("ArgumentOutOfRange_MaxNumServerInstances"));
}
if (inheritability >= HandleInheritability.None && inheritability <= HandleInheritability.Inheritable)
{
if ((additionalAccessRights & ~(PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership | PipeAccessRights.AccessSystemSecurity)) != 0)
{
throw new ArgumentOutOfRangeException("additionalAccessRights", System.SR.GetString("ArgumentOutOfRange_AdditionalAccessLimited"));
}
if (Environment.OSVersion.Platform == PlatformID.Win32Windows)
{
throw new PlatformNotSupportedException(System.SR.GetString("PlatformNotSupported_NamedPipeServers"));
}
string fullPath = Path.GetFullPath("\\\\.\\pipe\\" + pipeName);
if (string.Compare(fullPath, "\\\\.\\pipe\\anonymous", StringComparison.OrdinalIgnoreCase) == 0)
{
throw new ArgumentOutOfRangeException("pipeName", System.SR.GetString("ArgumentOutOfRange_AnonymousReserved"));
}
object obj = null;
SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out obj);
try
{
Create(fullPath, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, additionalAccessRights, secAttrs);
}
finally
{
if (obj != null)
{
((GCHandle)obj).Free();
}
}
return;
}
throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
}
[SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle)
: base(direction, PipeTransmissionMode.Byte, 0)
{
if (UnsafeNativeMethods.GetFileType(safePipeHandle) != 3)
{
throw new IOException(System.SR.GetString("Pipe_InvalidHandle"));
}
base.InitializeHandle(safePipeHandle, true, isAsync);
if (isConnected)
{
base.State = PipeState.Connected;
}
}
~NamedPipeServerStream()
{
Dispose(false);
}
[SecurityCritical]
private void Create(string fullPipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeAccessRights rights, SECURITY_ATTRIBUTES secAttrs)
{
int openMode = (int)direction | ((maxNumberOfServerInstances == 1) ? 524288 : 0) | (int)options | (int)rights;
int pipeMode = (int)transmissionMode << 2 | (int)transmissionMode << 1;
if (maxNumberOfServerInstances == -1)
{
maxNumberOfServerInstances = 255;
}
SafePipeHandle safePipeHandle = UnsafeNativeMethods.CreateNamedPipe(fullPipeName, openMode, pipeMode, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs);
if (safePipeHandle.IsInvalid)
{
System.IO.__Error.WinIOError(Marshal.GetLastWin32Error(), string.Empty);
}
base.InitializeHandle(safePipeHandle, false, (options & PipeOptions.Asynchronous) != PipeOptions.None);
}
[SecurityCritical]
public void WaitForConnection()
{
CheckConnectOperationsServer();
if (base.IsAsync)
{
IAsyncResult asyncResult = BeginWaitForConnection(null, null);
EndWaitForConnection(asyncResult);
}
else
{
if (!UnsafeNativeMethods.ConnectNamedPipe(base.InternalHandle, UnsafeNativeMethods.NULL))
{
int lastWin32Error = Marshal.GetLastWin32Error();
if (lastWin32Error != 535)
{
System.IO.__Error.WinIOError(lastWin32Error, string.Empty);
}
if (lastWin32Error == 535 && base.State == PipeState.Connected)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeAlreadyConnected"));
}
}
base.State = PipeState.Connected;
}
}
[SecurityCritical]
[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
public unsafe IAsyncResult BeginWaitForConnection(AsyncCallback callback, object state)
{
CheckConnectOperationsServer();
if (!base.IsAsync)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeNotAsync"));
}
PipeAsyncResult pipeAsyncResult = new PipeAsyncResult();
pipeAsyncResult._handle = base.InternalHandle;
pipeAsyncResult._userCallback = callback;
pipeAsyncResult._userStateObject = state;
ManualResetEvent manualResetEvent = pipeAsyncResult._waitHandle = new ManualResetEvent(false);
Overlapped overlapped = new Overlapped(0, 0, IntPtr.Zero, pipeAsyncResult);
NativeOverlapped* ptr = pipeAsyncResult._overlapped = overlapped.Pack(WaitForConnectionCallback, null);
if (!UnsafeNativeMethods.ConnectNamedPipe(base.InternalHandle, ptr))
{
int lastWin32Error = Marshal.GetLastWin32Error();
switch (lastWin32Error)
{
case 535:
ptr->InternalLow = IntPtr.Zero;
if (base.State == PipeState.Connected)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeAlreadyConnected"));
}
pipeAsyncResult.CallUserCallback();
break;
default:
System.IO.__Error.WinIOError(lastWin32Error, string.Empty);
break;
case 997:
break;
}
}
return pipeAsyncResult;
}
[SecurityCritical]
public unsafe void EndWaitForConnection(IAsyncResult asyncResult)
{
CheckConnectOperationsServer();
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!base.IsAsync)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeNotAsync"));
}
PipeAsyncResult pipeAsyncResult = asyncResult as PipeAsyncResult;
if (pipeAsyncResult == null)
{
System.IO.__Error.WrongAsyncResult();
}
if (1 == Interlocked.CompareExchange(ref pipeAsyncResult._EndXxxCalled, 1, 0))
{
System.IO.__Error.EndWaitForConnectionCalledTwice();
}
WaitHandle waitHandle = pipeAsyncResult._waitHandle;
if (waitHandle != null)
{
try
{
waitHandle.WaitOne();
}
finally
{
waitHandle.Close();
}
}
NativeOverlapped* overlapped = pipeAsyncResult._overlapped;
if (overlapped != null)
{
Overlapped.Free(overlapped);
}
if (pipeAsyncResult._errorCode != 0)
{
System.IO.__Error.WinIOError(pipeAsyncResult._errorCode, string.Empty);
}
base.State = PipeState.Connected;
}
[SecurityCritical]
public void Disconnect()
{
CheckDisconnectOperations();
if (!UnsafeNativeMethods.DisconnectNamedPipe(base.InternalHandle))
{
System.IO.__Error.WinIOError(Marshal.GetLastWin32Error(), string.Empty);
}
base.State = PipeState.Disconnected;
}
[SecurityCritical]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
base.CheckWriteOperations();
ExecuteHelper executeHelper = new ExecuteHelper(impersonationWorker, base.InternalHandle);
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, executeHelper);
if (executeHelper.m_impersonateErrorCode != 0)
{
base.WinIOError(executeHelper.m_impersonateErrorCode);
}
else if (executeHelper.m_revertImpersonateErrorCode != 0)
{
base.WinIOError(executeHelper.m_revertImpersonateErrorCode);
}
}
[SecurityCritical]
private static void ImpersonateAndTryCode(object helper)
{
ExecuteHelper executeHelper = (ExecuteHelper)helper;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
if (UnsafeNativeMethods.ImpersonateNamedPipeClient(executeHelper.m_handle))
{
executeHelper.m_mustRevert = true;
}
else
{
executeHelper.m_impersonateErrorCode = Marshal.GetLastWin32Error();
}
}
if (executeHelper.m_mustRevert)
{
executeHelper.m_userCode();
}
}
[SecurityCritical]
[PrePrepareMethod]
private static void RevertImpersonationOnBackout(object helper, bool exceptionThrown)
{
ExecuteHelper executeHelper = (ExecuteHelper)helper;
if (executeHelper.m_mustRevert && !UnsafeNativeMethods.RevertToSelf())
{
executeHelper.m_revertImpersonateErrorCode = Marshal.GetLastWin32Error();
}
}
[SecurityCritical]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
public string GetImpersonationUserName()
{
base.CheckWriteOperations();
StringBuilder stringBuilder = new StringBuilder(s_maxUsernameLength);
if (!UnsafeNativeMethods.GetNamedPipeHandleState(base.InternalHandle, UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, stringBuilder, s_maxUsernameLength))
{
base.WinIOError(Marshal.GetLastWin32Error());
}
return stringBuilder.ToString();
}
[SecurityCritical]
private unsafe static void AsyncWaitForConnectionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
Overlapped overlapped = Overlapped.Unpack(pOverlapped);
PipeAsyncResult pipeAsyncResult = (PipeAsyncResult)overlapped.AsyncResult;
if (errorCode == 535)
{
errorCode = 0u;
}
pipeAsyncResult._errorCode = (int)errorCode;
pipeAsyncResult._completedSynchronously = false;
pipeAsyncResult._isComplete = true;
ManualResetEvent waitHandle = pipeAsyncResult._waitHandle;
if (waitHandle != null && !waitHandle.Set())
{
System.IO.__Error.WinIOError();
}
AsyncCallback userCallback = pipeAsyncResult._userCallback;
if (userCallback != null)
{
userCallback(pipeAsyncResult);
}
}
[SecurityCritical]
private void CheckConnectOperationsServer()
{
if (base.InternalHandle == null)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeHandleNotSet"));
}
if (base.State == PipeState.Closed)
{
System.IO.__Error.PipeNotOpen();
}
if (base.InternalHandle.IsClosed)
{
System.IO.__Error.PipeNotOpen();
}
if (base.State != PipeState.Broken)
{
return;
}
throw new IOException(System.SR.GetString("IO_IO_PipeBroken"));
}
[SecurityCritical]
private void CheckDisconnectOperations()
{
if (base.State == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeNotYetConnected"));
}
if (base.State == PipeState.Disconnected)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeAlreadyDisconnected"));
}
if (base.InternalHandle == null)
{
throw new InvalidOperationException(System.SR.GetString("InvalidOperation_PipeHandleNotSet"));
}
if (base.State == PipeState.Closed)
{
System.IO.__Error.PipeNotOpen();
}
if (base.InternalHandle.IsClosed)
{
System.IO.__Error.PipeNotOpen();
}
}
}
}
#endif

34
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAccessRights.cs

@ -0,0 +1,34 @@
#if NET20
using System;
using System.Collections.Generic;
using System.Text;
namespace System.IO.Pipes
{
[Flags]
internal enum PipeAccessRights
{
ReadData = 0x1,
WriteData = 0x2,
ReadAttributes = 0x80,
WriteAttributes = 0x100,
ReadExtendedAttributes = 0x8,
WriteExtendedAttributes = 0x10,
CreateNewInstance = 0x4,
Delete = 0x10000,
ReadPermissions = 0x20000,
ChangePermissions = 0x40000,
TakeOwnership = 0x80000,
Synchronize = 0x100000,
FullControl = 0x1F019F,
Read = 0x20089,
Write = 0x112,
ReadWrite = 0x2019B,
AccessSystemSecurity = 0x1000000
}
}
#endif

67
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAccessRule.cs

@ -0,0 +1,67 @@
#if NET20
using System;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class PipeAccessRule : AccessRule
{
public PipeAccessRights PipeAccessRights
{
get
{
return RightsFromAccessMask(base.AccessMask);
}
}
public PipeAccessRule(string identity, PipeAccessRights rights, AccessControlType type)
: this(new NTAccount(identity), AccessMaskFromRights(rights, type), false, type)
{
}
public PipeAccessRule(IdentityReference identity, PipeAccessRights rights, AccessControlType type)
: this(identity, AccessMaskFromRights(rights, type), false, type)
{
}
internal PipeAccessRule(IdentityReference identity, int accessMask, bool isInherited, AccessControlType type)
: base(identity, accessMask, isInherited, InheritanceFlags.None, PropagationFlags.None, type)
{
}
internal static int AccessMaskFromRights(PipeAccessRights rights, AccessControlType controlType)
{
if (rights >= (PipeAccessRights)0 && rights <= (PipeAccessRights.ReadData | PipeAccessRights.WriteData | PipeAccessRights.ReadAttributes | PipeAccessRights.WriteAttributes | PipeAccessRights.ReadExtendedAttributes | PipeAccessRights.WriteExtendedAttributes | PipeAccessRights.CreateNewInstance | PipeAccessRights.Delete | PipeAccessRights.ReadPermissions | PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership | PipeAccessRights.Synchronize | PipeAccessRights.AccessSystemSecurity))
{
switch (controlType)
{
case AccessControlType.Allow:
rights |= PipeAccessRights.Synchronize;
break;
case AccessControlType.Deny:
if (rights != PipeAccessRights.FullControl)
{
rights &= ~PipeAccessRights.Synchronize;
}
break;
}
return (int)rights;
}
throw new ArgumentOutOfRangeException("rights", System.SR.GetString("ArgumentOutOfRange_NeedValidPipeAccessRights"));
}
internal static PipeAccessRights RightsFromAccessMask(int accessMask)
{
return (PipeAccessRights)accessMask;
}
}
}
#endif

110
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAsyncResult.cs

@ -0,0 +1,110 @@
#if NET20
using Microsoft.Win32.SafeHandles;
using System;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace System.IO.Pipes
{
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
internal sealed class PipeAsyncResult : IAsyncResult
{
internal AsyncCallback _userCallback;
internal object _userStateObject;
internal ManualResetEvent _waitHandle;
internal SafePipeHandle _handle;
internal unsafe NativeOverlapped* _overlapped;
internal int _EndXxxCalled;
internal int _errorCode;
internal bool _isComplete;
internal bool _completedSynchronously;
public object AsyncState
{
get
{
return _userStateObject;
}
}
public bool IsCompleted
{
get
{
return _isComplete;
}
}
public unsafe WaitHandle AsyncWaitHandle
{
[SecurityCritical]
get
{
if (_waitHandle == null)
{
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
if (_overlapped != null && _overlapped->EventHandle != IntPtr.Zero)
{
manualResetEvent.SafeWaitHandle = new SafeWaitHandle(_overlapped->EventHandle, true);
}
if (_isComplete)
{
manualResetEvent.Set();
}
_waitHandle = manualResetEvent;
}
return _waitHandle;
}
}
public bool CompletedSynchronously
{
get
{
return _completedSynchronously;
}
}
private void CallUserCallbackWorker(object callbackState)
{
_isComplete = true;
if (_waitHandle != null)
{
_waitHandle.Set();
}
_userCallback(this);
}
internal void CallUserCallback()
{
if (_userCallback != null)
{
_completedSynchronously = false;
ThreadPool.QueueUserWorkItem(CallUserCallbackWorker);
}
else
{
_isComplete = true;
if (_waitHandle != null)
{
_waitHandle.Set();
}
}
}
}
}
#endif

50
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeAuditRule.cs

@ -0,0 +1,50 @@
#if NET20
using System;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class PipeAuditRule : AuditRule
{
public PipeAccessRights PipeAccessRights
{
get
{
return PipeAccessRule.RightsFromAccessMask(base.AccessMask);
}
}
public PipeAuditRule(IdentityReference identity, PipeAccessRights rights, AuditFlags flags)
: this(identity, AccessMaskFromRights(rights), false, flags)
{
}
public PipeAuditRule(string identity, PipeAccessRights rights, AuditFlags flags)
: this(new NTAccount(identity), AccessMaskFromRights(rights), false, flags)
{
}
internal PipeAuditRule(IdentityReference identity, int accessMask, bool isInherited, AuditFlags flags)
: base(identity, accessMask, isInherited, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
private static int AccessMaskFromRights(PipeAccessRights rights)
{
if (rights >= (PipeAccessRights)0 && rights <= (PipeAccessRights.ReadData | PipeAccessRights.WriteData | PipeAccessRights.ReadAttributes | PipeAccessRights.WriteAttributes | PipeAccessRights.ReadExtendedAttributes | PipeAccessRights.WriteExtendedAttributes | PipeAccessRights.CreateNewInstance | PipeAccessRights.Delete | PipeAccessRights.ReadPermissions | PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership | PipeAccessRights.Synchronize | PipeAccessRights.AccessSystemSecurity))
{
return (int)rights;
}
throw new ArgumentOutOfRangeException("rights", System.SR.GetString("ArgumentOutOfRange_NeedValidPipeAccessRights"));
}
}
}
#endif

20
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeDirection.cs

@ -0,0 +1,20 @@
#if NET20
using System;
using System.Collections.Generic;
using System.Text;
namespace System.IO.Pipes
{
[Serializable]
internal enum PipeDirection
{
In = 1,
Out,
InOut
}
}
#endif

21
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeOptions.cs

@ -0,0 +1,21 @@
#if NET20
using System;
using System.Collections.Generic;
using System.Text;
namespace System.IO.Pipes
{
[Serializable]
[Flags]
internal enum PipeOptions
{
None = 0x0,
WriteThrough = int.MinValue,
Asynchronous = 0x40000000
}
}
#endif

243
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeSecurity.cs

@ -0,0 +1,243 @@
#if NET20
using Microsoft.Win32.SafeHandles;
using System;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
namespace System.IO.Pipes
{
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class PipeSecurity : NativeObjectSecurity
{
public override Type AccessRightType
{
get
{
return typeof(PipeAccessRights);
}
}
public override Type AccessRuleType
{
get
{
return typeof(PipeAccessRule);
}
}
public override Type AuditRuleType
{
get
{
return typeof(PipeAuditRule);
}
}
public PipeSecurity()
: base(false, ResourceType.KernelObject)
{
}
internal PipeSecurity(SafePipeHandle safeHandle, AccessControlSections includeSections)
: base(false, ResourceType.KernelObject, safeHandle, includeSections)
{
}
public void AddAccessRule(PipeAccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
base.AddAccessRule(rule);
}
public void SetAccessRule(PipeAccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
base.SetAccessRule(rule);
}
public void ResetAccessRule(PipeAccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(PipeAccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
AuthorizationRuleCollection accessRules = base.GetAccessRules(true, true, rule.IdentityReference.GetType());
for (int i = 0; i < accessRules.Count; i++)
{
PipeAccessRule pipeAccessRule = accessRules[i] as PipeAccessRule;
if (pipeAccessRule != null && pipeAccessRule.PipeAccessRights == rule.PipeAccessRights && pipeAccessRule.IdentityReference == rule.IdentityReference && pipeAccessRule.AccessControlType == rule.AccessControlType)
{
return base.RemoveAccessRule(rule);
}
}
if (rule.PipeAccessRights != PipeAccessRights.FullControl)
{
return base.RemoveAccessRule(new PipeAccessRule(rule.IdentityReference, PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny), false, rule.AccessControlType));
}
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleSpecific(PipeAccessRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule");
}
AuthorizationRuleCollection accessRules = base.GetAccessRules(true, true, rule.IdentityReference.GetType());
for (int i = 0; i < accessRules.Count; i++)
{
PipeAccessRule pipeAccessRule = accessRules[i] as PipeAccessRule;
if (pipeAccessRule != null && pipeAccessRule.PipeAccessRights == rule.PipeAccessRights && pipeAccessRule.IdentityReference == rule.IdentityReference && pipeAccessRule.AccessControlType == rule.AccessControlType)
{
base.RemoveAccessRuleSpecific(rule);
return;
}
}
if (rule.PipeAccessRights != PipeAccessRights.FullControl)
{
base.RemoveAccessRuleSpecific(new PipeAccessRule(rule.IdentityReference, PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny), false, rule.AccessControlType));
}
else
{
base.RemoveAccessRuleSpecific(rule);
}
}
public void AddAuditRule(PipeAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(PipeAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(PipeAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(PipeAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(PipeAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
if (inheritanceFlags != 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NonContainerInvalidAnyFlag"), "inheritanceFlags");
}
if (propagationFlags != 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NonContainerInvalidAnyFlag"), "propagationFlags");
}
return new PipeAccessRule(identityReference, accessMask, isInherited, type);
}
public sealed override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
if (inheritanceFlags != 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NonContainerInvalidAnyFlag"), "inheritanceFlags");
}
if (propagationFlags != 0)
{
throw new ArgumentException(System.SR.GetString("Argument_NonContainerInvalidAnyFlag"), "propagationFlags");
}
return new PipeAuditRule(identityReference, accessMask, isInherited, flags);
}
private AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections accessControlSections = AccessControlSections.None;
if (base.AccessRulesModified)
{
accessControlSections = AccessControlSections.Access;
}
if (base.AuditRulesModified)
{
accessControlSections |= AccessControlSections.Audit;
}
if (base.OwnerModified)
{
accessControlSections |= AccessControlSections.Owner;
}
if (base.GroupModified)
{
accessControlSections |= AccessControlSections.Group;
}
return accessControlSections;
}
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
protected internal void Persist(SafeHandle handle)
{
base.WriteLock();
try
{
AccessControlSections accessControlSectionsFromChanges = GetAccessControlSectionsFromChanges();
base.Persist(handle, accessControlSectionsFromChanges);
bool flag2 = base.AccessRulesModified = false;
bool flag4 = base.AuditRulesModified = flag2;
bool ownerModified = base.GroupModified = flag4;
base.OwnerModified = ownerModified;
}
finally
{
base.WriteUnlock();
}
}
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
protected internal void Persist(string name)
{
base.WriteLock();
try
{
AccessControlSections accessControlSectionsFromChanges = GetAccessControlSectionsFromChanges();
base.Persist(name, accessControlSectionsFromChanges);
bool flag2 = base.AccessRulesModified = false;
bool flag4 = base.AuditRulesModified = flag2;
bool ownerModified = base.GroupModified = flag4;
base.OwnerModified = ownerModified;
}
finally
{
base.WriteUnlock();
}
}
}
}
#endif

22
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeState.cs

@ -0,0 +1,22 @@
#if NET20
using System;
using System.Collections.Generic;
using System.Text;
namespace System.IO.Pipes
{
[Serializable]
internal enum PipeState
{
WaitingToConnect,
Connected,
Broken,
Disconnected,
Closed
}
}
#endif

1062
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeStream.cs

File diff suppressed because it is too large

116
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeStreamAsyncResult.cs

@ -0,0 +1,116 @@
#if NET20
using Microsoft.Win32.SafeHandles;
using System;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace System.IO.Pipes
{
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
internal sealed class PipeStreamAsyncResult : IAsyncResult
{
internal AsyncCallback _userCallback;
internal object _userStateObject;
internal ManualResetEvent _waitHandle;
internal SafePipeHandle _handle;
internal unsafe NativeOverlapped* _overlapped;
internal int _EndXxxCalled;
internal int _numBytes;
internal int _errorCode;
internal bool _isMessageComplete;
internal bool _isWrite;
internal bool _isComplete;
internal bool _completedSynchronously;
public object AsyncState
{
get
{
return _userStateObject;
}
}
public bool IsCompleted
{
get
{
return _isComplete;
}
}
public unsafe WaitHandle AsyncWaitHandle
{
[SecurityCritical]
get
{
if (_waitHandle == null)
{
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
if (_overlapped != null && _overlapped->EventHandle != IntPtr.Zero)
{
manualResetEvent.SafeWaitHandle = new SafeWaitHandle(_overlapped->EventHandle, true);
}
if (_isComplete)
{
manualResetEvent.Set();
}
_waitHandle = manualResetEvent;
}
return _waitHandle;
}
}
public bool CompletedSynchronously
{
get
{
return _completedSynchronously;
}
}
private void CallUserCallbackWorker(object callbackState)
{
_isComplete = true;
if (_waitHandle != null)
{
_waitHandle.Set();
}
_userCallback(this);
}
internal void CallUserCallback()
{
if (_userCallback != null)
{
_completedSynchronously = false;
ThreadPool.QueueUserWorkItem(CallUserCallbackWorker);
}
else
{
_isComplete = true;
if (_waitHandle != null)
{
_waitHandle.Set();
}
}
}
}
}
#endif

10
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeStreamImpersonationWorker.cs

@ -0,0 +1,10 @@
#if NET20
namespace System.IO.Pipes
{
internal delegate void PipeStreamImpersonationWorker();
}
#endif

20
Apewer/Externals/System.Core-3.5.0.0/System/IO/Pipes/PipeTransmissionMode.cs

@ -0,0 +1,20 @@
#if NET20
using System;
using System.Collections.Generic;
using System.Text;
namespace System.IO.Pipes
{
[Serializable]
internal enum PipeTransmissionMode
{
Byte,
Message
}
}
#endif

184
Apewer/Externals/System.Core-3.5.0.0/System/IO/__Error.cs

@ -0,0 +1,184 @@
#if NET20
using Microsoft.Win32;
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
namespace System.IO
{
internal static class __Error
{
internal static void EndOfFile()
{
throw new EndOfStreamException(System.SR.GetString("IO_EOF_ReadBeyondEOF"));
}
internal static void FileNotOpen()
{
throw new ObjectDisposedException(null, System.SR.GetString("ObjectDisposed_FileClosed"));
}
internal static void PipeNotOpen()
{
throw new ObjectDisposedException(null, System.SR.GetString("ObjectDisposed_PipeClosed"));
}
internal static void ReadNotSupported()
{
throw new NotSupportedException(System.SR.GetString("NotSupported_UnreadableStream"));
}
internal static void SeekNotSupported()
{
throw new NotSupportedException(System.SR.GetString("NotSupported_UnseekableStream"));
}
internal static void WrongAsyncResult()
{
throw new ArgumentException(System.SR.GetString("Argument_WrongAsyncResult"));
}
internal static void EndReadCalledTwice()
{
throw new ArgumentException(System.SR.GetString("InvalidOperation_EndReadCalledMultiple"));
}
internal static void EndWriteCalledTwice()
{
throw new ArgumentException(System.SR.GetString("InvalidOperation_EndWriteCalledMultiple"));
}
internal static void EndWaitForConnectionCalledTwice()
{
throw new ArgumentException(System.SR.GetString("InvalidOperation_EndWaitForConnectionCalledMultiple"));
}
internal static string GetDisplayablePath(string path, bool isInvalidPath)
{
if (string.IsNullOrEmpty(path))
{
return path;
}
bool flag = false;
if (path.Length < 2)
{
return path;
}
if (path[0] == Path.DirectorySeparatorChar && path[1] == Path.DirectorySeparatorChar)
{
flag = true;
}
else if (path[1] == Path.VolumeSeparatorChar)
{
flag = true;
}
if (!flag && !isInvalidPath)
{
return path;
}
bool flag2 = false;
try
{
if (!isInvalidPath)
{
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[1]
{
path
}).Demand();
flag2 = true;
}
}
catch (SecurityException)
{
}
catch (ArgumentException)
{
}
catch (NotSupportedException)
{
}
if (!flag2)
{
path = ((path[path.Length - 1] != Path.DirectorySeparatorChar) ? Path.GetFileName(path) : System.SR.GetString("IO_IO_NoPermissionToDirectoryName"));
}
return path;
}
[SecurityCritical]
internal static void WinIOError()
{
int lastWin32Error = Marshal.GetLastWin32Error();
WinIOError(lastWin32Error, string.Empty);
}
[SecurityCritical]
internal static void WinIOError(int errorCode, string maybeFullPath)
{
bool isInvalidPath = errorCode == 123 || errorCode == 161;
string displayablePath = GetDisplayablePath(maybeFullPath, isInvalidPath);
switch (errorCode)
{
case 2:
if (displayablePath.Length == 0)
{
throw new FileNotFoundException(System.SR.GetString("IO_FileNotFound"));
}
throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, System.SR.GetString("IO_FileNotFound_FileName"), displayablePath), displayablePath);
case 3:
if (displayablePath.Length == 0)
{
throw new DirectoryNotFoundException(System.SR.GetString("IO_PathNotFound_NoPathName"));
}
throw new DirectoryNotFoundException(string.Format(CultureInfo.CurrentCulture, System.SR.GetString("IO_PathNotFound_Path"), displayablePath));
case 5:
if (displayablePath.Length == 0)
{
throw new UnauthorizedAccessException(System.SR.GetString("UnauthorizedAccess_IODenied_NoPathName"));
}
throw new UnauthorizedAccessException(string.Format(CultureInfo.CurrentCulture, System.SR.GetString("UnauthorizedAccess_IODenied_Path"), displayablePath));
case 183:
if (displayablePath.Length == 0)
{
break;
}
throw new IOException(System.SR.GetString("IO_IO_AlreadyExists_Name", displayablePath), Microsoft.Win32.UnsafeNativeMethods.MakeHRFromErrorCode(errorCode));
case 206:
throw new PathTooLongException(System.SR.GetString("IO_PathTooLong"));
case 15:
throw new DriveNotFoundException(string.Format(CultureInfo.CurrentCulture, System.SR.GetString("IO_DriveNotFound_Drive"), displayablePath));
case 87:
throw new IOException(Microsoft.Win32.UnsafeNativeMethods.GetMessage(errorCode), Microsoft.Win32.UnsafeNativeMethods.MakeHRFromErrorCode(errorCode));
case 32:
if (displayablePath.Length == 0)
{
throw new IOException(System.SR.GetString("IO_IO_SharingViolation_NoFileName"), Microsoft.Win32.UnsafeNativeMethods.MakeHRFromErrorCode(errorCode));
}
throw new IOException(System.SR.GetString("IO_IO_SharingViolation_File", displayablePath), Microsoft.Win32.UnsafeNativeMethods.MakeHRFromErrorCode(errorCode));
case 80:
if (displayablePath.Length == 0)
{
break;
}
throw new IOException(string.Format(CultureInfo.CurrentCulture, System.SR.GetString("IO_IO_FileExists_Name"), displayablePath), Microsoft.Win32.UnsafeNativeMethods.MakeHRFromErrorCode(errorCode));
case 995:
throw new OperationCanceledException();
}
throw new IOException(Microsoft.Win32.UnsafeNativeMethods.GetMessage(errorCode), Microsoft.Win32.UnsafeNativeMethods.MakeHRFromErrorCode(errorCode));
}
internal static void WriteNotSupported()
{
throw new NotSupportedException(System.SR.GetString("NotSupported_UnwritableStream"));
}
}
}
#endif

17
Apewer/Externals/System.Core-3.5.0.0/System/SR.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace System
{
class SR
{
public static string GetString(string name) => name ?? "";
public static string GetString(string name, params object[] args) => name ?? "";
}
}

2
Apewer/Internals/Constant.cs

@ -36,7 +36,7 @@ namespace Apewer.Internals
public const string LucidCollection = "3456789acefhknpstwxyz";
/// <summary>所有 GUID 中的字符,包含字母、数字和连字符。</summary>
public const string GuidCollection = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-";
public const string GuidCollection = "0123456789ABCDEFabcdef-";
/// <summary>所有十六进制字符。</summary>
public const string HexCollection = "0123456789abcdef";

100
Apewer/Internals/Interop/Constant.cs

@ -165,9 +165,6 @@ namespace Apewer.Internals.Interop
/// <summary></summary>
public const int ULW_ALPHA = 2;
/// <summary></summary>
public const int WH_KEYBOARD_LL = 13;
/// <summary></summary>
public const int WM_CLOSE = 0x0010;
@ -231,6 +228,103 @@ namespace Apewer.Internals.Interop
public const int EWX_POWEROFF = 0x00000008;
public const int EWX_FORCEIFHUNG = 0x00000010;
#region Windows Hook
/// <summary>
/// Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar.
/// For more information, see the MessageProc hook procedure.
/// </summary>
public const int WH_MSGFILTER = -1;
/// <summary>
/// Installs a hook procedure that records input messages posted to the system message queue.
/// This hook is useful for recording macros.
/// For more information, see the JournalRecordProc hook procedure.
/// </summary>
public const int WH_JOURNALRECORD = 0;
/// <summary>
/// Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure.
/// For more information, see the JournalPlaybackProc hook procedure.
/// </summary>
public const int WH_JOURNALPLAYBACK = 1;
/// <summary>
/// Installs a hook procedure that monitors keystroke messages.
/// For more information, see the KeyboardProc hook procedure.
/// </summary>
public const int WH_KEYBOARD = 2;
/// <summary>
/// Installs a hook procedure that monitors messages posted to a message queue.
/// For more information, see the GetMsgProc hook procedure.
/// </summary>
public const int WH_GETMESSAGE = 3;
/// <summary>
/// Installs a hook procedure that monitors messages before the system sends them to the destination window procedure.
/// For more information, see the CallWndProc hook procedure.
/// </summary>
public const int WH_CALLWNDPROC = 4;
/// <summary>
/// Installs a hook procedure that receives notifications useful to a CBT application.
/// For more information, see the CBTProc hook procedure.
/// </summary>
public const int WH_CBT = 5;
/// <summary>
/// Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar.
/// The hook procedure monitors these messages for all applications in the same desktop as the calling thread.
/// For more information, see the SysMsgProc hook procedure.
/// </summary>
public const int WH_SYSMSGFILTER = 6;
/// <summary>
/// Installs a hook procedure that monitors mouse messages.
/// For more information, see the MouseProc hook procedure.
/// </summary>
public const int WH_MOUSE = 7;
/// <summary>
/// Installs a hook procedure useful for debugging other hook procedures.
/// For more information, see the DebugProc hook procedure.
/// </summary>
public const int WH_DEBUG = 9;
/// <summary>
/// Installs a hook procedure that receives notifications useful to shell applications.
/// For more information, see the ShellProc hook procedure.
/// </summary>
public const int WH_SHELL = 10;
/// <summary>
/// Installs a hook procedure that will be called when the application's foreground thread is about to become idle.
/// This hook is useful for performing low priority tasks during idle time.
/// For more information, see the ForegroundIdleProc hook procedure.
/// </summary>
public const int WH_FOREGROUNDIDLE = 11;
/// <summary>
/// Installs a hook procedure that monitors messages after they have been processed by the destination window procedure.
/// For more information, see the CallWndRetProc hook procedure.
/// </summary>
public const int WH_CALLWNDPROCRET = 12;
/// <summary>
/// Installs a hook procedure that monitors low-level keyboard input events.
/// For more information, see the LowLevelKeyboardProc hook procedure.
/// </summary>
public const int WH_KEYBOARD_LL = 13;
/// <summary
/// >Installs a hook procedure that monitors low-level mouse input events.
/// For more information, see the LowLevelMouseProc hook procedure.
/// </summary>
public const int WH_MOUSE_LL = 14;
#endregion
}
}

11
Apewer/Internals/Interop/Delegate.cs

@ -3,17 +3,8 @@
namespace Apewer.Internals.Interop
{
/// <summary></summary>
/// <param name="hWnd"></param>
/// <param name="lParam"></param>
/// <returns></returns>
delegate bool EnumWindowsCallBack(int hWnd, int lParam);
/// <summary></summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
delegate int SetWindowsHookExHookProc(int nCode, Int32 wParam, IntPtr lParam);
delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
}

7
Apewer/Internals/Interop/Kernel32.cs

@ -16,10 +16,9 @@ namespace Apewer.Internals.Interop
public static extern int CloseHandle(int hObject);
/// <summary>关闭内核对象句柄。</summary>
/// <param name="hObject"></param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr handle);
/// <summary>打开要映射的文件。</summary>
/// <param name="lpFileName"></param>

21
Apewer/Internals/Interop/MSLLHOOKSTRUCT.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Apewer.Internals.Interop
{
/// <summary>Mouse Hook Struct</summary>
[StructLayout(LayoutKind.Sequential)]
internal class MSLLHOOKSTRUCT
{
public Point pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
}

22
Apewer/Internals/Interop/User32.cs

@ -17,14 +17,14 @@ namespace Apewer.Internals.Interop
[DllImport("user32")]
public static extern bool AnimateWindow(IntPtr hwnd, int dwtime, int dwflag);
/// <summary></summary>
/// <param name="idHook"></param>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
/// <summary>Passes the hook information to the next hook procedure in the current hook chain. A hook procedure can call this function either before or after processing the hook information.</summary>
/// <param name="idHook">This parameter is ignored.</param>
/// <param name="nCode">The hook code passed to the current hook procedure. The next hook procedure uses this code to determine how to process the hook information.</param>
/// <param name="wParam">The wParam value passed to the current hook procedure. The meaning of this parameter depends on the type of hook associated with the current hook chain.</param>
/// <param name="lParam">The lParam value passed to the current hook procedure. The meaning of this parameter depends on the type of hook associated with the current hook chain.</param>
/// <returns>This value is returned by the next hook procedure in the chain. The current hook procedure must also return this value. The meaning of the return value depends on the hook type. For more information, see the descriptions of the individual hook procedures.</returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
/// <summary></summary>
/// <param name="devMode"></param>
@ -249,13 +249,9 @@ namespace Apewer.Internals.Interop
public static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary></summary>
/// <param name="idHook"></param>
/// <param name="lpfn"></param>
/// <param name="hInstance"></param>
/// <param name="threadId"></param>
/// <returns></returns>
/// <remarks>https://docs.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-setwindowshookexa</remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, SetWindowsHookExHookProc lpfn, IntPtr hInstance, int threadId);
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
/// <summary></summary>
/// <param name="hwnd"></param>

19
Apewer/Internals/Interop/WS2_32.cs

@ -0,0 +1,19 @@
using System;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace Apewer.Internals.Interop
{
internal class WS2_32
{
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern IntPtr gethostbyaddr([In] ref int addr, [In] int len, [In] ProtocolFamily type);
[DllImport("ws2_32.dll", BestFitMapping = false, CharSet = CharSet.Ansi, SetLastError = true, ThrowOnUnmappableChar = true)]
internal static extern IntPtr gethostbyname([In] string host);
}
}

28
Apewer/Internals/Interop/WinMM.cs

@ -11,6 +11,34 @@ namespace Apewer.Internals.Interop
#region WinMM
internal const int MMIO_FINDRIFF = 32;
internal const int WAVE_FORMAT_PCM = 1;
internal const int WAVE_FORMAT_ADPCM = 2;
internal const int WAVE_FORMAT_IEEE_FLOAT = 3;
internal const int MMIO_READ = 0;
internal const int MMIO_ALLOCBUF = 65536;
internal const int SND_SYNC = 0;
internal const int SND_ASYNC = 1;
internal const int SND_NODEFAULT = 2;
internal const int SND_MEMORY = 4;
internal const int SND_LOOP = 8;
internal const int SND_PURGE = 64;
internal const int SND_FILENAME = 131072;
internal const int SND_NOSTOP = 16;
[DllImport("winmm.dll")]
public static extern long mciGetCreatorTask(long wDeviceID);

23
Apewer/Internals/Interop/hostent.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Apewer.Internals.Interop
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct hostent
{
public IntPtr h_name;
public IntPtr h_aliases;
public short h_addrtype;
public short h_length;
public IntPtr h_addr_list;
}
}

39
Apewer/KernelUtility.cs

@ -221,28 +221,43 @@ namespace Apewer
/// <para>System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase</para>
/// <para>D:\Website\</para>
/// </summary>
public static string ApplicationBasePath
{
get { return AppDomain.CurrentDomain.SetupInformation.ApplicationBase; }
}
public static string ApplicationBasePath {get=> AppDomain.CurrentDomain.SetupInformation.ApplicationBase; }
/// <summary>处理当前在消息队列中的所有 Windows 消息。</summary>
public static void DoEvents() => Application.DoEvents();
/// <summary>
/// <para>System.Windows.Forms.Application.StartupPath</para>
/// <para>c:\windows\system32\inetsrv</para>
/// </summary>
private static string StartupPath
{
get { return Application.StartupPath; }
}
public static string StartupPath { get => Application.StartupPath; }
/// <summary>
/// <para>System.Windows.Forms.Application.ExecutablePath</para>
/// <para>c:\windows\system32\inetsrv\w3wp.exe</para>
/// </summary>
public static string ExecutablePath
{
get { return Application.ExecutablePath; }
}
public static string ExecutablePath { get => Application.ExecutablePath; }
#region System.Windows.Forms.Application
/// <summary>在没有窗体的情况下,在当前线程上开始运行标准应用程序消息循环。</summary>
/// <exception cref="InvalidOperationException"></exception>
public static void ApplicationRun() => Application.Run();
/// <summary>在当前线程上开始运行标准应用程序消息循环,并使指定窗体可见。</summary>
/// <exception cref="InvalidOperationException"></exception>
public static void ApplicationRun(Form form) => Application.Run(form);
/// <summary>关闭应用程序并立即启动一个新实例。</summary>
public static void ApplicationRestart() => Application.Restart();
/// <summary>通知所有消息泵必须终止,并且在处理了消息以后关闭所有应用程序窗口。</summary>
public static void ApplicationExit() => Application.Exit();
/// <summary>退出当前线程上的消息循环,并关闭该线程上的所有窗口。</summary>
public static void ApplicationExitThread() => Application.ExitThread();
#endregion
#endif

31
Apewer/Models/MouseButtons.cs

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Apewer.Models
{
/// <summary></summary>
public enum MouseButtons
{
/// <summary></summary>
None = 0x0,
/// <summary></summary>
Left = 0x100000,
/// <summary></summary>
Right = 0x200000,
/// <summary></summary>
Middle = 0x400000,
/// <summary></summary>
XButton1 = 0x800000,
/// <summary></summary>
XButton2 = 0x1000000
}
}

26
Apewer/Models/MouseEvent.cs

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Apewer.Models
{
/// <summary></summary>
public struct MouseEvent
{
/// <summary></summary>
public int Hook;
/// <summary></summary>
public int X;
/// <summary></summary>
public int Y;
/// <summary></summary>
public long Button;
}
}

22
Apewer/Models/StringPairs.cs

@ -65,17 +65,29 @@ namespace Apewer.Models
var lowerArg = TextUtility.ToLower(key);
var matched = false;
// 先精准匹配。
foreach (var item in this)
{
if (item.Key == key) return item.Value;
if (string.IsNullOrEmpty(item.Key)) continue;
if (item.Key == key)
{
if (string.IsNullOrEmpty(item.Value)) continue;
return item.Value;
}
}
// 再模糊匹配。
if (ignoreCase)
{
var lowerItem = TextUtility.ToLower(item.Key);
if (lowerItem == lowerArg)
foreach (var item in this)
{
if (string.IsNullOrEmpty(item.Key)) continue;
var lowerKey = TextUtility.ToLower(item.Key);
if (lowerKey == lowerArg)
{
matched = true;
if (!string.IsNullOrEmpty(item.Value)) return item.Value;
if (string.IsNullOrEmpty(item.Value)) continue;
return item.Value;
}
}
}

53
Apewer/NetworkUtility.cs

@ -2,10 +2,12 @@
using Apewer.Internals.Interop;
using Apewer.Network;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
namespace Apewer
@ -236,6 +238,57 @@ namespace Apewer
return "";
}
/// <summary>对目标地址进行解析。</summary>
private static IPHostEntry InternalResolve(string hostName)
{
if (hostName.Length <= 255 && (hostName.Length != 255 || hostName[254] == '.'))
{
var intPtr = WS2_32.gethostbyname(hostName);
if (intPtr != IntPtr.Zero) return NativeToHostEntry(intPtr);
}
return null;
}
private static IntPtr IntPtrAdd(IntPtr a, int b)
{
return (IntPtr)((long)a + b);
}
private static IPHostEntry NativeToHostEntry(IntPtr nativePointer)
{
hostent hostent = (hostent)Marshal.PtrToStructure(nativePointer, typeof(hostent));
IPHostEntry iPHostEntry = new IPHostEntry();
if (hostent.h_name != IntPtr.Zero)
{
iPHostEntry.HostName = Marshal.PtrToStringAnsi(hostent.h_name);
}
ArrayList arrayList = new ArrayList();
IntPtr intPtr = hostent.h_addr_list;
nativePointer = Marshal.ReadIntPtr(intPtr);
while (nativePointer != IntPtr.Zero)
{
int newAddress = Marshal.ReadInt32(nativePointer);
arrayList.Add(new IPAddress(newAddress));
intPtr = IntPtrAdd(intPtr, IntPtr.Size);
nativePointer = Marshal.ReadIntPtr(intPtr);
}
iPHostEntry.AddressList = new IPAddress[arrayList.Count];
arrayList.CopyTo(iPHostEntry.AddressList, 0);
arrayList.Clear();
intPtr = hostent.h_aliases;
nativePointer = Marshal.ReadIntPtr(intPtr);
while (nativePointer != IntPtr.Zero)
{
string value = Marshal.PtrToStringAnsi(nativePointer);
arrayList.Add(value);
intPtr = IntPtrAdd(intPtr, IntPtr.Size);
nativePointer = Marshal.ReadIntPtr(intPtr);
}
iPHostEntry.Aliases = new string[arrayList.Count];
arrayList.CopyTo(iPHostEntry.Aliases, 0);
return iPHostEntry;
}
/// <summary>将由字符串表示的 IPv4 地址转换为 32 位整数。</summary>
public static int GetNumber(IPAddress ipv4)
{

54
Apewer/Web/WebUtility.cs

@ -170,35 +170,49 @@ namespace Apewer.Web
{
if (request == null) return false;
// 检测直连 IP,
var direct = GetDirectIP(request);
if (!string.IsNullOrEmpty(direct))
{
if (NetworkUtility.FromLAN(direct)) return true;
}
// 遍历传入的地址。
if (addresses != null && addresses.Length > 0)
// 解析可信地址。
var ips = new List<string>();
if (addresses != null)
{
// 读取 HTTP 头。
var forwarded = GetForwardedIP(request);
if (!NetworkUtility.IsIP(forwarded)) return false;
foreach (var address in addresses)
{
if (NetworkUtility.IsIP(address))
var ip = address;
if (!NetworkUtility.IsIP(ip)) ip = NetworkUtility.Resolve(ip);
if (!NetworkUtility.IsIP(ip)) continue;
if (ips.Contains(ip)) continue;
ips.Add(ip);
}
}
// 检测代理 IP。
var headers = GetHeaders(request);
var proxyIP = headers.GetValue("Ali-Cdn-Real-Ip", true).SafeTrim();
if (proxyIP.NotEmpty())
{
if (forwarded == address) return true;
if (proxyIP.IndexOf(" ") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf(" "));
if (proxyIP.IndexOf("|") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf("|"));
if (proxyIP.IndexOf(",") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf(","));
if (proxyIP.IndexOf(":") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf(":"));
}
else
if (proxyIP.IsEmpty())
{
var ip = NetworkUtility.Resolve(address);
if (NetworkUtility.IsIP(ip))
proxyIP = headers.GetValue("X-Forwarded-For", true).SafeTrim();
if (proxyIP.NotEmpty())
{
if (forwarded == ip) return true;
}
if (proxyIP.IndexOf(" ") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf(" "));
if (proxyIP.IndexOf("|") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf("|"));
if (proxyIP.IndexOf(",") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf(","));
if (proxyIP.IndexOf(":") > 0) proxyIP = proxyIP.Substring(0, proxyIP.IndexOf(":"));
}
}
if (proxyIP.NotEmpty()) return ips.Contains(proxyIP);
// 检测直连 IP,
var directIP = GetDirectIP(request);
if (NetworkUtility.IsIP(directIP))
{
if (NetworkUtility.FromLAN(directIP)) return true;
if (ips.Contains(directIP)) return true;
}
return false;

122
Apewer/WindowsUtility.cs

@ -1,19 +1,22 @@
using Apewer.Internals.Interop;
#if NETFX
using System.Management;
#endif
#if NETFX || NETCORE
using System.Windows.Forms;
#endif
using Apewer.Internals.Interop;
using Apewer.Models;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
#if NETFX
using System.Management;
#endif
#if NETFX || NETCORE
using System.Windows.Forms;
#endif
using System.Threading;
namespace Apewer
{
@ -240,6 +243,62 @@ namespace Apewer
return output;
}
/// <summary>启动控制台进程,获取输出。</summary>
public static Exception RunConsole(string cmd, string arg, Func<string, string> output, Func<string, string> error, Action exited = null)
{
var exception = null as Exception;
// var list = new List<string>();
var process = new Process();
try
{
process.EnableRaisingEvents = true;
process.StartInfo = new ProcessStartInfo()
{
FileName = cmd ?? "",
Arguments = arg ?? "",
CreateNoWindow = true,
UseShellExecute = false, // 必须禁用操作系统外壳程序。
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
};
process.OutputDataReceived += (s, e) =>
{
var input = output?.Invoke(e.Data);
if (input != null) process.StandardInput.Write(input);
};
process.ErrorDataReceived += (s, e) =>
{
var input = error?.Invoke(e.Data);
if (input != null) process.StandardInput.Write(input);
};
process.Exited += (s, e) =>
{
exited?.Invoke();
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
process.Close();
}
catch (Exception ex)
{
exception = ex;
}
KernelUtility.Dispose(process);
return exception;
}
/// <summary>启动控制台进程,获取输出。</summary>
public static Exception RunConsole(string cmd, string arg, Action<string> received, Action exited = null)
{
return RunConsole(cmd, arg, (s) => { received?.Invoke(s); return null; }, (s) => { received?.Invoke(s); return null; }, exited);
}
#endregion
#region 硬件。
@ -436,7 +495,7 @@ namespace Apewer
#endregion
#region 鼠标指针
#region 鼠标。
/// <summary>移动鼠标指针。</summary>
public static void MousePointerMove(int x, int y)
@ -480,6 +539,49 @@ namespace Apewer
User32.mouse_Callback(MouseCallbackFlag.RightUp, x, y, 0, UIntPtr.Zero);
}
/// <summary>钩住鼠标。当前线程必须具有消息循环。</summary>
private static int HookMouse(Func<MouseEvent, bool> func)
{
if (func == null) return 0;
var proc = new HookProc(LowLevelMouseProc);
var hInstance = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
var hook = 0;
hook = User32.SetWindowsHookEx(Constant.WH_MOUSE_LL, (int nCode, IntPtr wParam, IntPtr lParam) =>
{
if (func == null || nCode < 0)
{
return User32.CallNextHookEx(hook, nCode, wParam, lParam);
}
else
{
var info = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
var data = new MouseEvent()
{
Hook = hook,
X = info.pt.x,
Y = info.pt.y,
Button = wParam.ToInt64()
};
var @continue = func.Invoke(data);
return @continue ? User32.CallNextHookEx(hook, nCode, wParam, lParam) : 0;
}
}, hInstance, 0);
return hook;
}
/// <summary>An application-defined or library-defined callback function used with the SetWindowsHookEx function. The system calls this function every time a new mouse input event is about to be posted into a thread input queue.</summary>
/// <param name="nCode">A code the hook procedure uses to determine how to process the message. If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx. This parameter can be one of the following values.</param>
/// <param name="wParam">The identifier of the mouse message. This parameter can be one of the following messages: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_MOUSEHWHEEL, WM_RBUTTONDOWN, or WM_RBUTTONUP.</param>
/// <param name="lParam">A pointer to an MSLLHOOKSTRUCT structure.</param>
/// <returns></returns>
private static int LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam)
{
return 0;
}
/// <summary>释放钩子。</summary>
private static bool Unhook(int hook) => User32.UnhookWindowsHookEx(hook);
#endregion
#region 窗体控制。

4
Apewer/_ChangeLog.md

@ -5,6 +5,10 @@
### 最新提交
### 6.0.5
- 对 WindowsUtility.RunConsole 增加重载,可按行获取输出,且可获取错误流;
- 调整 FromTrusted 的规则,减少了存在反向代理时的误判。
### 6.0.4
- 修正 GetClientIP 参数不生效的问题。

Loading…
Cancel
Save