Browse Source

allow ws than wss by connection reset

HOME 2 years ago
parent
commit
e0b4adb730

+ 36 - 49
AspNetTools/WebSocketForwardModule.cs

@@ -1,10 +1,7 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
 using System.Net;
 using System.Net.Sockets;
 using System.Net.WebSockets;
-using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Web;
@@ -13,72 +10,62 @@ namespace AspNetTools
 {
     public static class WebSocketForwardModule
     {
-        public static void ForwardCurrentContext(string op, string pass, IPEndPoint endPoint,int bufferSize=1024)
+        public static void ForwardCurrentContext(string opKey, string opValue, IPEndPoint endPoint, int bufferSize = 1024)
         {
             var ctx = HttpContext.Current;
             var req = HttpContext.Current.Request;
-            if (req.QueryString["op"] == op)
+            if (req.QueryString[opKey] == opValue)
             {
                 ctx.Handler = null;
                 var rsp = HttpContext.Current.Response;
-                if (ctx.IsDebuggingEnabled == false && req.IsSecureConnection == false)
-                {
-                    rsp.ContentType = "text/html";
-                    rsp.Write("Prod env is Secure Connection required");
-                    ctx.ApplicationInstance.CompleteRequest();
-                    return;
-                }
+                //if (ctx.IsDebuggingEnabled == false && req.IsSecureConnection == false)
+                //{
+                //    rsp.ContentType = "text/html";
+                //    rsp.Write("Prod env is Secure Connection required");
+                //    ctx.ApplicationInstance.CompleteRequest();
+                //    return;
+                //}
 
-                if (req["pass"] == pass)
+                if (ctx.IsWebSocketRequest)
                 {
-                    if (ctx.IsWebSocketRequest)
+                    ctx.AcceptWebSocketRequest(async (ws) =>
                     {
-                        ctx.AcceptWebSocketRequest(async (ws) =>
-                        {
-                            var fcl = new TcpClient();
-                            fcl.Connect(endPoint);
-                            var ns = fcl.GetStream();
+                        var fcl = new TcpClient();
+                        fcl.Connect(endPoint);
+                        var ns = fcl.GetStream();
 
-                            var tIn = Task.Run(async () =>
+                        var tIn = Task.Run(async () =>
+                        {
+                            var buf = new byte[bufferSize];
+                            var arrSeg = new ArraySegment<byte>(buf);
+                            while (ws.WebSocket.CloseStatus.HasValue == false)
                             {
-                                var buf = new byte[bufferSize];
-                                var arrSeg = new ArraySegment<byte>(buf);
-                                while (ws.WebSocket.CloseStatus.HasValue == false)
-                                {
-                                    var x = await ws.WebSocket.ReceiveAsync(arrSeg, CancellationToken.None);
-                                    await ns.WriteAsync(buf, 0, x.Count);
-                                }
-                            });
+                                var x = await ws.WebSocket.ReceiveAsync(arrSeg, CancellationToken.None);
+                                await ns.WriteAsync(buf, 0, x.Count);
+                            }
+                        });
 
-                            var tOut = Task.Run(async () =>
+                        var tOut = Task.Run(async () =>
+                        {
+                            var buf = new byte[bufferSize];
+                            while (ws.WebSocket.CloseStatus.HasValue == false)
                             {
-                                var buf = new byte[bufferSize];
-                                while (ws.WebSocket.CloseStatus.HasValue == false)
-                                {
-                                    var count = await ns.ReadAsync(buf, 0, buf.Length);
-                                    var arrSeg = new ArraySegment<byte>(buf, 0, count);
-                                    await ws.WebSocket.SendAsync(arrSeg, WebSocketMessageType.Binary, true, CancellationToken.None);
-                                }
-                            });
-
-                            Task.WaitAll(tIn, tOut);
-                            fcl.Close();
+                                var count = await ns.ReadAsync(buf, 0, buf.Length);
+                                var arrSeg = new ArraySegment<byte>(buf, 0, count);
+                                await ws.WebSocket.SendAsync(arrSeg, WebSocketMessageType.Binary, true, CancellationToken.None);
+                            }
                         });
-                    }
-                    else
-                    {
-                        rsp.ContentType = "text/html";
-                        rsp.Write("Welcome back. Master!");
-                    }
+
+                        Task.WaitAll(tIn, tOut);
+                        fcl.Close();
+                    });
                 }
                 else
                 {
                     rsp.ContentType = "text/html";
-                    rsp.StatusCode = 403;
-                    rsp.Write("Access denied");
+                    rsp.Write("Welcome back. Master!");
                 }
             }
         }
-
     }
 }

+ 7 - 1
WebServerTools.sln

@@ -34,7 +34,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebGet", "WebGet\WebGet.csp
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HostingUploadingTest", "HostingUploadingTest\HostingUploadingTest.csproj", "{7D628249-8B22-4086-8BB5-691B1B57810B}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HostingUploadingTarget", "HostingUploadingTarget\HostingUploadingTarget.csproj", "{39A8C829-19FF-4157-8EBA-5E42364DDB12}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HostingUploadingTarget", "HostingUploadingTarget\HostingUploadingTarget.csproj", "{39A8C829-19FF-4157-8EBA-5E42364DDB12}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebSocketEcho", "WebSocketEcho\WebSocketEcho.csproj", "{33AEF25B-1E70-4BD0-9B0F-3715E27D8C12}"
 EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -86,6 +88,10 @@ Global
 		{39A8C829-19FF-4157-8EBA-5E42364DDB12}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{39A8C829-19FF-4157-8EBA-5E42364DDB12}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{39A8C829-19FF-4157-8EBA-5E42364DDB12}.Release|Any CPU.Build.0 = Release|Any CPU
+		{33AEF25B-1E70-4BD0-9B0F-3715E27D8C12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{33AEF25B-1E70-4BD0-9B0F-3715E27D8C12}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{33AEF25B-1E70-4BD0-9B0F-3715E27D8C12}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{33AEF25B-1E70-4BD0-9B0F-3715E27D8C12}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 1 - 0
WebSocketEcho/Echo.ashx

@@ -0,0 +1 @@
+<%@ WebHandler Language="C#" CodeBehind="Echo.ashx.cs" Class="WebSocketEcho.Echo" %>

+ 91 - 0
WebSocketEcho/Echo.ashx.cs

@@ -0,0 +1,91 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.WebSockets;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Web;
+using System.Web.WebSockets;
+
+namespace WebSocketEcho
+{
+    /// <summary>
+    /// Echo 的摘要说明
+    /// </summary>
+    public class Echo : IHttpHandler
+    {
+
+        // list of client WebSockets that are open
+        private static readonly IList<WebSocket> Clients = new List<WebSocket>();
+
+        // ensure thread-safety of the WebSocket clients
+        private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
+
+        public void ProcessRequest(HttpContext context)
+        {
+            if (context.IsWebSocketRequest)
+                context.AcceptWebSocketRequest(ProcessSocketRequest); 
+        }
+
+        private async Task ProcessSocketRequest(AspNetWebSocketContext context)
+        {
+            var socket = context.WebSocket;
+
+            // add socket to socket list
+            Locker.EnterWriteLock();
+            try
+            {
+                Clients.Add(socket);
+            }
+            finally
+            {
+                Locker.ExitWriteLock();
+            }
+             
+            // maintain socket
+            while (true)
+            {
+                var array = new byte[1024];
+                var buffer = new ArraySegment<byte>(array);
+
+                // async wait for a change in the socket
+                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
+
+                if (socket.State == WebSocketState.Open)
+                {
+                    // echo to all clients
+                    foreach (var client in Clients)
+                    {
+                        var seg = new ArraySegment<byte>(array, 0, result.Count);
+                        await client.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None);
+                    }
+                }
+                else
+                {
+                    // client is no longer available - delete from list
+                    Locker.EnterWriteLock();
+                    try
+                    {
+                        Clients.Remove(socket);
+                    }
+                    finally
+                    {
+                        Locker.ExitWriteLock();
+                    }
+
+                    break;
+
+                }
+            }
+        }
+
+
+        public bool IsReusable
+        {
+            get
+            {
+                return false;
+            }
+        }
+    }
+}

+ 35 - 0
WebSocketEcho/Properties/AssemblyInfo.cs

@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 有关程序集的常规信息通过下列特性集
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("WebSocketEcho")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("WebSocketEcho")]
+[assembly: AssemblyCopyright("Copyright ©  2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 会使此程序集中的类型
+// 对 COM 组件不可见。如果需要
+// 从 COM 访问此程序集中的某个类型,请针对该类型将 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于 typelib 的 ID
+[assembly: Guid("33aef25b-1e70-4bd0-9b0f-3715e27d8c12")]
+
+// 程序集的版本信息由下列四个值组成:
+//
+//      主版本
+//      次版本
+//      内部版本号
+//      修订版本
+//
+// 可以指定所有值,也可以使用“修订号”和“内部版本号”的默认值,
+// 方法是按如下所示使用 "*":
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 31 - 0
WebSocketEcho/Web.Debug.config

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- 有关使用 web.config 转换的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkId=125889 -->
+
+<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
+  <!--
+    在下例中,“SetAttributes”转换将更改 
+    “connectionString”的值,以仅在“Match”定位器 
+    找到值为“MyDB”的特性“name”时使用“ReleaseSQLServer”。
+    
+    <connectionStrings>
+      <add name="MyDB" 
+        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
+        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
+    </connectionStrings>
+  -->
+  <system.web>
+    <!--
+      
+      在下例中,“Replace”转换将替换 
+      web.config 文件的整个 <customErrors> 节。
+      请注意,由于 
+      在 <system.web> 节点下仅有一个 customErrors 节,因此不需要使用“xdt:Locator”特性。
+      
+      <customErrors defaultRedirect="GenericError.htm"
+        mode="RemoteOnly" xdt:Transform="Replace">
+        <error statusCode="500" redirect="InternalError.htm"/>
+      </customErrors>
+    -->
+  </system.web>
+</configuration>

+ 32 - 0
WebSocketEcho/Web.Release.config

@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- 有关使用 web.config 转换的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkId=125889 -->
+
+<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
+  <!--
+    在下例中,“SetAttributes”转换将更改 
+    “connectionString”的值,以仅在“Match”定位器 
+    找到值为“MyDB”的特性“name”时使用“ReleaseSQLServer”。
+    
+    <connectionStrings>
+      <add name="MyDB" 
+        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
+        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
+    </connectionStrings>
+  -->
+  <system.web>
+    <compilation xdt:Transform="RemoveAttributes(debug)" />
+    <!--
+      
+      在下例中,“Replace”转换将替换 
+      web.config 文件的整个 <customErrors> 节。
+      请注意,由于 
+      在 <system.web> 节点下仅有一个 customErrors 节,因此不需要使用“xdt:Locator”特性。
+      
+      <customErrors defaultRedirect="GenericError.htm"
+        mode="RemoteOnly" xdt:Transform="Replace">
+        <error statusCode="500" redirect="InternalError.htm"/>
+      </customErrors>
+    -->
+  </system.web>
+</configuration>

+ 11 - 0
WebSocketEcho/Web.config

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  有关如何配置 ASP.NET 应用程序的详细信息,请访问
+  https://go.microsoft.com/fwlink/?LinkId=169433
+-->
+<configuration>
+  <system.web>
+    <compilation debug="true" targetFramework="4.6.1" />
+    <httpRuntime targetFramework="4.6.1" />
+  </system.web>
+</configuration>

+ 113 - 0
WebSocketEcho/WebSocketEcho.csproj

@@ -0,0 +1,113 @@
+<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProductVersion>
+    </ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{33AEF25B-1E70-4BD0-9B0F-3715E27D8C12}</ProjectGuid>
+    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>WebSocketEcho</RootNamespace>
+    <AssemblyName>WebSocketEcho</AssemblyName>
+    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
+    <UseIISExpress>true</UseIISExpress>
+    <Use64BitIISExpress />
+    <IISExpressSSLPort />
+    <IISExpressAnonymousAuthentication />
+    <IISExpressWindowsAuthentication />
+    <IISExpressUseClassicPipelineMode />
+    <UseGlobalApplicationHostFile />
+    <NuGetPackageImportStamp>
+    </NuGetPackageImportStamp>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Web.DynamicData" />
+    <Reference Include="System.Web.Entity" />
+    <Reference Include="System.Web.ApplicationServices" />
+    <Reference Include="System.ComponentModel.DataAnnotations" />
+    <Reference Include="System" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="System.Web.Extensions" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Web" />
+    <Reference Include="System.Xml" />
+    <Reference Include="System.Configuration" />
+    <Reference Include="System.Web.Services" />
+    <Reference Include="System.EnterpriseServices" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="Web.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Echo.ashx.cs">
+      <DependentUpon>Echo.ashx</DependentUpon>
+    </Compile>
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="Echo.ashx" />
+    <None Include="Web.Debug.config">
+      <DependentUpon>Web.config</DependentUpon>
+    </None>
+    <None Include="Web.Release.config">
+      <DependentUpon>Web.config</DependentUpon>
+    </None>
+  </ItemGroup>
+  <PropertyGroup>
+    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
+    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
+  </PropertyGroup>
+  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
+  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
+  <ProjectExtensions>
+    <VisualStudio>
+      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
+        <WebProjectProperties>
+          <UseIIS>True</UseIIS>
+          <AutoAssignPort>True</AutoAssignPort>
+          <DevelopmentServerPort>45003</DevelopmentServerPort>
+          <DevelopmentServerVPath>/</DevelopmentServerVPath>
+          <IISUrl>http://localhost:45003/</IISUrl>
+          <NTLMAuthentication>False</NTLMAuthentication>
+          <UseCustomServer>False</UseCustomServer>
+          <CustomServerUrl>
+          </CustomServerUrl>
+          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
+        </WebProjectProperties>
+      </FlavorProperties>
+    </VisualStudio>
+  </ProjectExtensions>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>

+ 2 - 1
WebV2rayHosting/Web.config

@@ -17,7 +17,8 @@
     <httpRuntime targetFramework="4.6.1"/>
   </system.web>
   <appSettings>
-	  <add key="pass" value="fg"/>
+	  <add key="key" value="op"/>
+	  <add key="value" value="v2"/>
 	  <add key="bsk" value="1024"/>
 	  <add key="exe" value="mysqld"/>
 	  <add key="cfg" value="config.pb"/>

+ 7 - 2
WebV2rayHosting/Wv2hModule.cs

@@ -25,7 +25,7 @@ namespace Wv2h
 
         public void Init(HttpApplication context)
         {
-            Log("SshWsModule Init, OS:" + Environment.OSVersion.ToString());
+            Log("WsModule Init, OS:" + Environment.OSVersion);
 
             AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
             {
@@ -70,12 +70,17 @@ namespace Wv2h
             //forward ws to v2
             context.PostMapRequestHandler += delegate
             {
-                WebSocketForwardModule.ForwardCurrentContext("v2", ConfigurationManager.AppSettings["pass"], _listening, 1024 * int.Parse(ConfigurationManager.AppSettings["bsk"]));
+                WebSocketForwardModule.ForwardCurrentContext(
+                    ConfigurationManager.AppSettings["key"], 
+                    ConfigurationManager.AppSettings["value"],
+                    _listening, 1024 * int.Parse(ConfigurationManager.AppSettings["bsk"]));
             };
         }
 
         public void Dispose()
         {
+            Log("WsModule Dispose");
+
             lock (_lock)
             {
                 if (_process?.HasExited != true)