添加文件头

This commit is contained in:
springhgui 2022-01-02 00:23:39 +08:00
parent 9568077a27
commit 916253ed34
62 changed files with 856 additions and 389 deletions

264
.editorconfig Normal file
View File

@ -0,0 +1,264 @@
; EditorConfig to support per-solution formatting.
; Use the EditorConfig VS add-in to make this work.
; http://editorconfig.org/
;
; Here are some resources for what's supported for .NET/C#
; https://kent-boogaart.com/blog/editorconfig-reference-for-c-developers
; https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
;
; Be **careful** editing this because some of the rules don't support adding a severity level
; For instance if you change to `dotnet_sort_system_directives_first = true:warning` (adding `:warning`)
; then the rule will be silently ignored.
; This is the default for the codeline.
root = true
[*]
indent_style = space
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.cs]
indent_size = 4
dotnet_sort_system_directives_first = true
# Don't use this. qualifier
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
# use int x = .. over Int32
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
# use int.MaxValue over Int32.MaxValue
dotnet_style_predefined_type_for_member_access = true:suggestion
# Require var all the time.
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
# Disallow throw expressions.
csharp_style_throw_expression = false:suggestion
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
# Namespace settings
csharp_style_namespace_declarations = file_scoped
[*.{xml,config,*proj,nuspec,props,resx,targets,yml,tasks}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
[*.json]
indent_size = 2
[*.{ps1,psm1}]
indent_size = 4
[*.sh]
indent_size = 4
end_of_line = lf
[*.{razor,cshtml}]
charset = utf-8-bom
[*.{cs,vb}]
# CA1018: Mark attributes with AttributeUsageAttribute
dotnet_diagnostic.CA1018.severity = warning
# CA1047: Do not declare protected member in sealed type
dotnet_diagnostic.CA1047.severity = warning
# CA1305: Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = warning
# CA1507: Use nameof to express symbol names
dotnet_diagnostic.CA1507.severity = warning
# CA1725: Parameter names should match base declaration
dotnet_diagnostic.CA1725.severity = suggestion
# CA1802: Use literals where appropriate
dotnet_diagnostic.CA1802.severity = warning
# CA1805: Do not initialize unnecessarily
dotnet_diagnostic.CA1805.severity = warning
# CA1810: Do not initialize unnecessarily
dotnet_diagnostic.CA1810.severity = suggestion
# CA1821: Remove empty Finalizers
dotnet_diagnostic.CA1821.severity = warning
# CA1822: Make member static
dotnet_diagnostic.CA1822.severity = suggestion
# CA1823: Avoid unused private fields
dotnet_diagnostic.CA1823.severity = warning
# CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = warning
# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
dotnet_diagnostic.CA1826.severity = warning
# CA1827: Do not use Count() or LongCount() when Any() can be used
dotnet_diagnostic.CA1827.severity = warning
# CA1828: Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used
dotnet_diagnostic.CA1828.severity = warning
# CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1829.severity = warning
# CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder
dotnet_diagnostic.CA1830.severity = warning
# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
# CA1832: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
# CA1833: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
dotnet_diagnostic.CA1831.severity = warning
dotnet_diagnostic.CA1832.severity = warning
dotnet_diagnostic.CA1833.severity = warning
# CA1834: Consider using 'StringBuilder.Append(char)' when applicable
dotnet_diagnostic.CA1834.severity = warning
# CA1835: Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync'
dotnet_diagnostic.CA1835.severity = warning
# CA1836: Prefer IsEmpty over Count
dotnet_diagnostic.CA1836.severity = warning
# CA1837: Use 'Environment.ProcessId'
dotnet_diagnostic.CA1837.severity = warning
# CA1838: Avoid 'StringBuilder' parameters for P/Invokes
dotnet_diagnostic.CA1838.severity = warning
# CA1839: Use 'Environment.ProcessPath'
dotnet_diagnostic.CA1839.severity = warning
# CA1840: Use 'Environment.CurrentManagedThreadId'
dotnet_diagnostic.CA1840.severity = warning
# CA1841: Prefer Dictionary.Contains methods
dotnet_diagnostic.CA1841.severity = warning
# CA1842: Do not use 'WhenAll' with a single task
dotnet_diagnostic.CA1842.severity = warning
# CA1843: Do not use 'WaitAll' with a single task
dotnet_diagnostic.CA1843.severity = warning
# CA1845: Use span-based 'string.Concat'
dotnet_diagnostic.CA1845.severity = warning
# CA1846: Prefer AsSpan over Substring
dotnet_diagnostic.CA1846.severity = warning
# CA2008: Do not create tasks without passing a TaskScheduler
dotnet_diagnostic.CA2008.severity = warning
# CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
dotnet_diagnostic.CA2009.severity = warning
# CA2011: Avoid infinite recursion
dotnet_diagnostic.CA2011.severity = warning
# CA2012: Use ValueTask correctly
dotnet_diagnostic.CA2012.severity = warning
# CA2013: Do not use ReferenceEquals with value types
dotnet_diagnostic.CA2013.severity = warning
# CA2014: Do not use stackalloc in loops.
dotnet_diagnostic.CA2014.severity = warning
# CA2016: Forward the 'CancellationToken' parameter to methods that take one
dotnet_diagnostic.CA2016.severity = warning
# CA2200: Rethrow to preserve stack details
dotnet_diagnostic.CA2200.severity = warning
# CA2208: Instantiate argument exceptions correctly
dotnet_diagnostic.CA2208.severity = warning
# IDE0035: Remove unreachable code
dotnet_diagnostic.IDE0035.severity = warning
# IDE0036: Order modifiers
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
dotnet_diagnostic.IDE0036.severity = warning
# IDE0043: Format string contains invalid placeholder
dotnet_diagnostic.IDE0043.severity = warning
# IDE0044: Make field readonly
dotnet_diagnostic.IDE0044.severity = warning
# IDE0073: File header
dotnet_diagnostic.IDE0073.severity = warning
file_header_template = Licensed under the Apache License, Version 2.0 (the "License").\nYou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE\nCopyright (c) 2019 Gui.H
# IDE0161: Convert to file-scoped namespace
dotnet_diagnostic.IDE0161.severity = warning
[**/{test,samples,perf}/**.{cs,vb}]
# CA1018: Mark attributes with AttributeUsageAttribute
dotnet_diagnostic.CA1018.severity = suggestion
# CA1507: Use nameof to express symbol names
dotnet_diagnostic.CA1507.severity = suggestion
# CA1802: Use literals where appropriate
dotnet_diagnostic.CA1802.severity = suggestion
# CA1805: Do not initialize unnecessarily
dotnet_diagnostic.CA1805.severity = suggestion
# CA1823: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = suggestion
# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
dotnet_diagnostic.CA1826.severity = suggestion
# CA1827: Do not use Count() or LongCount() when Any() can be used
dotnet_diagnostic.CA1827.severity = suggestion
# CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1829.severity = suggestion
# CA1834: Consider using 'StringBuilder.Append(char)' when applicable
dotnet_diagnostic.CA1834.severity = suggestion
# CA1835: Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync'
dotnet_diagnostic.CA1835.severity = suggestion
# CA1837: Use 'Environment.ProcessId'
dotnet_diagnostic.CA1837.severity = suggestion
# CA1838: Avoid 'StringBuilder' parameters for P/Invokes
dotnet_diagnostic.CA1838.severity = suggestion
# CA1841: Prefer Dictionary.Contains methods
dotnet_diagnostic.CA1841.severity = suggestion
# CA1844: Provide memory-based overrides of async methods when subclassing 'Stream'
dotnet_diagnostic.CA1844.severity = suggestion
# CA1845: Use span-based 'string.Concat'
dotnet_diagnostic.CA1845.severity = suggestion
# CA1846: Prefer AsSpan over Substring
dotnet_diagnostic.CA1846.severity = suggestion
# CA2008: Do not create tasks without passing a TaskScheduler
dotnet_diagnostic.CA2008.severity = suggestion
# CA2012: Use ValueTask correctly
dotnet_diagnostic.CA2012.severity = suggestion
# IDE0044: Make field readonly
dotnet_diagnostic.IDE0044.severity = suggestion
# CA2016: Forward the 'CancellationToken' parameter to methods that take one
dotnet_diagnostic.CA2016.severity = suggestion
# Defaults for content in the shared src/ and shared runtime dir
[{**/Shared/runtime/**.{cs,vb},src/Shared/test/Shared.Tests/runtime/**.{cs,vb},**/microsoft.extensions.hostfactoryresolver.sources/**.{cs,vb}}]
# IDE0161: Convert to file-scoped namespace
dotnet_diagnostic.IDE0161.severity = silent

View File

@ -1,9 +1,13 @@
using FastTunnel.Api.Models;
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Api.Models;
using FastTunnel.Core.Config;
using FastTunnel.Server.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
@ -12,13 +16,12 @@ using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace FastTunnel.Api.Controllers
{
public class AccountController : BaseController
{
IOptionsMonitor<DefaultServerConfig> serverOptionsMonitor;
readonly IOptionsMonitor<DefaultServerConfig> serverOptionsMonitor;
public AccountController(IOptionsMonitor<DefaultServerConfig> optionsMonitor)
{

View File

@ -1,11 +1,12 @@
using FastTunnel.Server.Models;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Server.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FastTunnel.Api.Controllers
{

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Server.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -11,7 +17,7 @@ namespace FastTunnel.Api.Controllers
{
public class SystemController : BaseController
{
FastTunnelServer fastTunnelServer;
readonly FastTunnelServer fastTunnelServer;
public SystemController(FastTunnelServer fastTunnelServer)
{

View File

@ -9,8 +9,8 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.12.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.12.2" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.15.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
</ItemGroup>
<ItemGroup>

View File

@ -1,12 +1,13 @@
using FastTunnel.Server.Models;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Server.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastTunnel.Api.Filters
{

View File

@ -1,7 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
namespace FastTunnel.Server.Models
{

View File

@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastTunnel.Api.Models
{

View File

@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="5.0.3" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="6.0.0" />
</ItemGroup>
<ItemGroup>

View File

@ -1,44 +1,49 @@
using Microsoft.Extensions.Hosting;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using Microsoft.AspNetCore.Builder;
using FastTunnel.Core;
using Microsoft.Extensions.Configuration;
namespace FastTunnel.Client
{
class Program
{
public static void Main(string[] args)
{
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
namespace FastTunnel.Client;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
class Program
{
public static void Main(string[] args)
{
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
// -------------------FastTunnel START------------------
services.AddFastTunnelClient(hostContext.Configuration.GetSection("ClientSettings"));
// -------------------FastTunnel EDN--------------------
})
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
{
var enableFileLog = (bool)(context.Configuration.GetSection("EnableFileLog")?.Get(typeof(bool)) ?? false);
if (enableFileLog)
{
var enableFileLog = (bool)(context.Configuration.GetSection("EnableFileLog")?.Get(typeof(bool)) ?? false);
if (enableFileLog)
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddLog4Net();
}
});
}
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddLog4Net();
}
});
}

View File

@ -11,9 +11,6 @@
"EnableFileLog": false,
"ClientSettings": {
"Server": {
// [] urls
// ws(http)wss(https)
"Protocol": "ws",
// [] ip/urls
"ServerAddr": "test.cc",
// [] urls

View File

@ -1,21 +1,20 @@
using FastTunnel.Core.Config;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Config;
using FastTunnel.Core.Models;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using FastTunnel.Core.Extensions;
using System.Timers;
using System.Threading;
using Microsoft.Extensions.Logging;
using FastTunnel.Core.Handlers.Client;
using Microsoft.Extensions.Configuration;
using FastTunnel.Core.Sockets;
using Microsoft.Extensions.Options;
using System.Net.WebSockets;
using System.Text.Json;
using FastTunnel.Core.Protocol;
using Microsoft.AspNetCore.DataProtection;
using FastTunnel.Core.Utilitys;
namespace FastTunnel.Core.Client

View File

@ -1,16 +1,18 @@
using FastTunnel.Core.Config;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Config;
using FastTunnel.Core.Models;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System;
using FastTunnel.Core.Listener;
using FastTunnel.Core.Dispatchers;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System.IO;
using Yarp.Sample;
using Yarp.ReverseProxy.Configuration;
using System.Collections.Generic;
@ -18,10 +20,10 @@ namespace FastTunnel.Core.Client
{
public class FastTunnelServer
{
public int ConnectedClientCount = 0;
public int ConnectedClientCount;
public readonly IOptionsMonitor<DefaultServerConfig> ServerOption;
public IProxyConfigProvider proxyConfig;
ILogger<FastTunnelServer> logger;
readonly ILogger<FastTunnelServer> logger;
public ConcurrentDictionary<string, TaskCompletionSource<Stream>> ResponseTasks { get; } = new();

View File

@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System.Threading;
using System.Threading.Tasks;
namespace FastTunnel.Core.Client
{

View File

@ -1,8 +1,11 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace FastTunnel.Core.Config
{

View File

@ -1,7 +1,11 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace FastTunnel.Core.Config
{
@ -11,7 +15,7 @@ namespace FastTunnel.Core.Config
public string[] WebAllowAccessIps { get; set; }
public bool EnableForward { get; set; } = false;
public bool EnableForward { get; set; }
[Obsolete("由Tokens替换")]
public string Token { get; set; }

View File

@ -1,9 +1,11 @@
using FastTunnel.Core.Models;
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Models;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastTunnel.Core.Config
{

View File

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
namespace FastTunnel.Core.Config
{

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Text;

View File

@ -1,6 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
namespace FastTunnel.Core.Exceptions
{

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System.Text;
using System.Threading.Tasks;
namespace FastTunnel.Core.Extensions
{

View File

@ -1,7 +1,11 @@
using Microsoft.Extensions.Logging;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
namespace FastTunnel.Core.Extensions
{

View File

@ -1,6 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System.Text.Json;
namespace FastTunnel.Core.Extensions

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Core.Config;
using FastTunnel.Core.Forwarder.MiddleWare;
using FastTunnel.Core.Forwarder;
@ -94,4 +100,4 @@ namespace FastTunnel.Core
});
}
}
}
}

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Models;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;
using System.Net.Sockets;

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -14,6 +20,9 @@ namespace FastTunnel.Core.Extensions
var ct = new CancellationTokenSource(timeoutMs);
ct.Token.Register(() =>
{
if (tcs.Task.IsCompleted)
return;
tcs.TrySetCanceled();
action?.Invoke();
}, useSynchronizationContext: false);

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Exceptions;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Exceptions;
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;

View File

@ -7,7 +7,7 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Copyright>FastTunnel</Copyright>
<Description>expose a local server behind a NAT or firewall to the internet like ngrok and frp</Description>
<Authors>SpringHgui</Authors>
<Authors>Gui.H</Authors>
<Company>FastTunnel</Company>
<Product>FastTunnel</Product>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
@ -15,6 +15,7 @@
<RepositoryUrl>https://github.com/SpringHgui/FastTunnel</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageTags>FastTunnel.Core</PackageTags>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>FastTunnel.Core</PackageReleaseNotes>
</PropertyGroup>
@ -35,9 +36,9 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="5.0.0" />
<PackageReference Include="Yarp.ReverseProxy" Version="1.0.0-preview.12.21328.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" />
<PackageReference Include="Yarp.ReverseProxy" Version="1.0.0" />
</ItemGroup>
<ItemGroup>

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@ -1,19 +1,8 @@
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Licensed under the Apache License, Version 2.0 (the "License")
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Hosting;
using FastTunnel.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using FastTunnel.Core.Client;
using Microsoft.Extensions.Logging;
using FastTunnel.Core.Extensions;
@ -28,6 +17,7 @@ namespace FastTunnel.Core.Filters
ILogger<FastTunnelExceptionFilter> logger,
IWebHostEnvironment hostingEnvironment)
{
this.logger = logger;
_hostingEnvironment = hostingEnvironment;
}

View File

@ -1,4 +1,8 @@
using FastTunnel.Core.Client;
// Copyright (c) 2019-2022 Gui.H. https://github.com/FastTunnel/FastTunnel
// The FastTunnel licenses this file to you under the Apache License Version 2.0.
// For more details,You may obtain License file at: https://github.com/FastTunnel/FastTunnel/blob/v2/LICENSE
using FastTunnel.Core.Client;
using FastTunnel.Core.Extensions;
using FastTunnel.Core.Models;
using FastTunnel.Core.Sockets;
@ -20,12 +24,12 @@ namespace FastTunnel.Core.Forwarder
{
public class FastTunnelForwarderHttpClientFactory : ForwarderHttpClientFactory
{
ILogger<FastTunnelForwarderHttpClientFactory> logger;
FastTunnelServer _fastTunnelServer;
readonly ILogger<FastTunnelForwarderHttpClientFactory> logger;
readonly FastTunnelServer fastTunnelServer;
public FastTunnelForwarderHttpClientFactory(ILogger<FastTunnelForwarderHttpClientFactory> logger, FastTunnelServer fastTunnelServer)
{
this._fastTunnelServer = fastTunnelServer;
this.fastTunnelServer = fastTunnelServer;
this.logger = logger;
}
@ -44,7 +48,7 @@ namespace FastTunnel.Core.Forwarder
var res = await proxyAsync(host, context, cancellationToken);
return res;
}
catch (Exception ex)
catch (Exception)
{
throw;
}
@ -53,7 +57,7 @@ namespace FastTunnel.Core.Forwarder
public async ValueTask<Stream> proxyAsync(string host, SocketsHttpConnectionContext context, CancellationToken cancellation)
{
WebInfo web;
if (!_fastTunnelServer.WebList.TryGetValue(host, out web))
if (!fastTunnelServer.WebList.TryGetValue(host, out web))
{
// 客户端已离线
return await OfflinePage(host, context);
@ -63,10 +67,9 @@ namespace FastTunnel.Core.Forwarder
TaskCompletionSource<Stream> tcs = new(cancellation);
logger.LogDebug($"[Http]Swap开始 {msgId}|{host}=>{web.WebConfig.LocalIp}:{web.WebConfig.LocalPort}");
tcs.SetTimeOut(10000, () => { logger.LogDebug($"[Proxy TimeOut]:{msgId}"); });
//tcs.SetTimeOut(20000, () => { logger.LogDebug($"[Proxy TimeOut]:{msgId}"); });
_fastTunnelServer.ResponseTasks.TryAdd(msgId, tcs);
fastTunnelServer.ResponseTasks.TryAdd(msgId, tcs);
try
{
@ -79,17 +82,17 @@ namespace FastTunnel.Core.Forwarder
}
catch (WebSocketException)
{
tcs.TrySetCanceled();
_fastTunnelServer.ResponseTasks.TryRemove(msgId, out _);
// 通讯异常,返回客户端离线
return await OfflinePage(host, context);
}
catch (Exception)
{
_fastTunnelServer.ResponseTasks.TryRemove(msgId, out _);
throw;
}
finally
{
fastTunnelServer.ResponseTasks.TryRemove(msgId, out _);
}
}

View File

@ -1,32 +1,26 @@
using FastTunnel.Core.Client;
// Copyright (c) 2019-2022 Gui.H. https://github.com/FastTunnel/FastTunnel
// The FastTunnel licenses this file to you under the Apache License Version 2.0.
// For more details,You may obtain License file at: https://github.com/FastTunnel/FastTunnel/blob/v2/LICENSE
using FastTunnel.Core.Client;
using FastTunnel.Core.Extensions;
using FastTunnel.Core.Forwarder;
using FastTunnel.Core.Forwarder.MiddleWare;
using FastTunnel.Core.Handlers.Server;
using FastTunnel.Core.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Yarp.ReverseProxy.Configuration;
namespace FastTunnel.Core.MiddleWares
{
public class FastTunnelClientHandler
{
ILogger<FastTunnelClientHandler> logger;
FastTunnelServer fastTunnelServer;
Version serverVersion;
ILoginHandler loginHandler;
readonly ILogger<FastTunnelClientHandler> logger;
readonly FastTunnelServer fastTunnelServer;
readonly Version serverVersion;
readonly ILoginHandler loginHandler;
public FastTunnelClientHandler(
ILogger<FastTunnelClientHandler> logger, FastTunnelServer fastTunnelServer, ILoginHandler loginHandler)
@ -98,8 +92,7 @@ namespace FastTunnel.Core.MiddleWares
private bool checkToken(HttpContext context)
{
bool checkToken = false;
if ((fastTunnelServer.ServerOption.CurrentValue.Tokens != null && fastTunnelServer.ServerOption.CurrentValue.Tokens.Count() != 0)
|| !string.IsNullOrEmpty(fastTunnelServer.ServerOption.CurrentValue.Token))
if (fastTunnelServer.ServerOption.CurrentValue.Tokens != null && fastTunnelServer.ServerOption.CurrentValue.Tokens.Count != 0)
{
checkToken = true;
}
@ -111,8 +104,7 @@ namespace FastTunnel.Core.MiddleWares
if (!context.Request.Headers.TryGetValue(FastTunnelConst.FASTTUNNEL_TOKEN, out var token))
return false;
if (token.Equals(fastTunnelServer.ServerOption.CurrentValue.Token)
|| (fastTunnelServer.ServerOption.CurrentValue.Tokens?.Contains(token) ?? false))
if (fastTunnelServer.ServerOption.CurrentValue.Tokens?.Contains(token) ?? false)
return true;
return false;

View File

@ -54,7 +54,6 @@ namespace FastTunnel.Core.Forwarder.MiddleWare
responseAwaiter.TrySetResult(reverseConnection);
var closedAwaiter = new TaskCompletionSource<object>();
//closedAwaiter.SetTimeOut(20000, () => { logger.LogDebug($"[Swap TimeOut]:{requestId}"); });
lifetime.ConnectionClosed.Register((task) =>
{
@ -62,7 +61,7 @@ namespace FastTunnel.Core.Forwarder.MiddleWare
}, closedAwaiter);
await closedAwaiter.Task;
logger.LogError($"[PROXY]:Closed {requestId}");
logger.LogDebug($"[PROXY]:Closed {requestId}");
}
catch (Exception ex)
{

View File

@ -1,7 +1,11 @@
using System;
using System.Collections.Generic;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -19,7 +23,7 @@ namespace FastTunnel.Core.Forwarder
public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
MemoryStream m_Stream;
readonly MemoryStream m_Stream;
public ResponseStream(byte[] bytes)
{
@ -31,7 +35,7 @@ namespace FastTunnel.Core.Forwarder
throw new NotImplementedException();
}
bool complete = false;
bool complete;
public override int Read(byte[] buffer, int offset, int count)
{

View File

@ -1,4 +1,8 @@
using Microsoft.AspNetCore.Http;
// Copyright (c) 2019-2022 Gui.H. https://github.com/FastTunnel/FastTunnel
// The FastTunnel licenses this file to you under the Apache License Version 2.0.
// For more details,You may obtain License file at: https://github.com/FastTunnel/FastTunnel/blob/v2/LICENSE
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Config;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Config;
using FastTunnel.Core.Client;
using FastTunnel.Core.Models;
using System;

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Config;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Config;
using FastTunnel.Core.Models;
using Microsoft.Extensions.Logging;
using System;

View File

@ -1,4 +1,8 @@
using FastTunnel.Core.Client;
// Copyright (c) 2019-2022 Gui.H. https://github.com/FastTunnel/FastTunnel
// The FastTunnel licenses this file to you under the Apache License Version 2.0.
// For more details,You may obtain License file at: https://github.com/FastTunnel/FastTunnel/blob/v2/LICENSE
using FastTunnel.Core.Client;
using System;
using System.IO;
using System.Net.Sockets;
@ -13,7 +17,7 @@ namespace FastTunnel.Core.Handlers.Client
{
public class SwapHandler : IClientHandler
{
ILogger<SwapHandler> _logger;
readonly ILogger<SwapHandler> _logger;
public SwapHandler(ILogger<SwapHandler> logger)
{
@ -28,13 +32,14 @@ namespace FastTunnel.Core.Handlers.Client
try
{
using Stream serverStream = await createRemote(requestId, cleint, cancellationToken);
using Stream localStream = await createLocal(requestId, address, cancellationToken);
using (Stream serverStream = await createRemote(requestId, cleint, cancellationToken))
using (Stream localStream = await createLocal(requestId, address, cancellationToken))
{
var taskX = serverStream.CopyToAsync(localStream, cancellationToken);
var taskY = localStream.CopyToAsync(serverStream, cancellationToken);
var taskX = serverStream.CopyToAsync(localStream, cancellationToken);
var taskY = localStream.CopyToAsync(serverStream, cancellationToken);
await Task.WhenAny(taskX, taskY);
await Task.WhenAny(taskX, taskY);
}
}
catch (Exception ex)
{

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Core.Dispatchers;
using FastTunnel.Core.Exceptions;
using FastTunnel.Core.Extensions;
@ -30,6 +36,12 @@ namespace FastTunnel.Core.Dispatchers
_config = config;
}
/// <summary>
///
/// </summary>
/// <param name="_socket">用户请求</param>
/// <param name="client">FastTunnel客户端</param>
/// <returns></returns>
public async Task DispatchAsync(Socket _socket, WebSocket client)
{
var msgId = Guid.NewGuid().ToString().Replace("-", "");
@ -40,7 +52,7 @@ namespace FastTunnel.Core.Dispatchers
logger.LogDebug($"[Forward]Swap开始 {msgId}|{_config.RemotePort}=>{_config.LocalIp}:{_config.LocalPort}");
var tcs = new TaskCompletionSource<Stream>();
//tcs.SetTimeOut(10000, () => { logger.LogDebug($"[Dispatch TimeOut]:{msgId}"); });
tcs.SetTimeOut(10000, () => { logger.LogDebug($"[Dispatch TimeOut]:{msgId}"); });
_server.ResponseTasks.TryAdd(msgId, tcs);
@ -53,7 +65,7 @@ namespace FastTunnel.Core.Dispatchers
// TODO:客户端已掉线,但是没有移除对端口的监听
logger.LogError($"[Forward]Swap 客户端已离线 {sex.Message}");
tcs.TrySetCanceled();
_socket.Close();
Close(_socket);
return;
}
catch (Exception ex)
@ -61,14 +73,15 @@ namespace FastTunnel.Core.Dispatchers
// 网络不稳定
logger.LogError(ex, $"[Forward]Swap Exception");
tcs.TrySetCanceled();
_socket.Close();
Close(_socket);
return;
}
using var stream1 = await tcs.Task;
using var stream2 = new NetworkStream(_socket, true) { ReadTimeout = 1000 * 60 * 10 };
await Task.WhenAll(stream1.CopyToAsync(stream2), stream2.CopyToAsync(stream1));
using (var stream1 = await tcs.Task)
using (var stream2 = new NetworkStream(_socket, true) { ReadTimeout = 1000 * 60 * 10 })
{
await Task.WhenAll(stream1.CopyToAsync(stream2), stream2.CopyToAsync(stream1));
}
logger.LogDebug($"[Forward]Swap OK {msgId}");
}
@ -81,5 +94,20 @@ namespace FastTunnel.Core.Dispatchers
_server.ResponseTasks.TryRemove(msgId, out _);
}
}
private void Close(Socket socket)
{
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
socket.Close();
}
}
}
}

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;
@ -15,4 +21,4 @@ namespace FastTunnel.Core.Handlers
Task<bool> HandlerMsg(FastTunnelServer server, WebSocket client, string msg);
}
}
}

View File

@ -1,10 +1,11 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
namespace FastTunnel.Core.Handlers.Server

View File

@ -1,15 +1,17 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Core.Dispatchers;
using FastTunnel.Core.Extensions;
using FastTunnel.Core.Listener;
using FastTunnel.Core.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
@ -20,8 +22,8 @@ namespace FastTunnel.Core.Handlers.Server
{
public class LoginHandler : ILoginHandler
{
ILogger logger;
IProxyConfigProvider proxyConfig;
readonly ILogger logger;
readonly IProxyConfigProvider proxyConfig;
public const bool NeedRecive = true;
public LoginHandler(ILogger<LoginHandler> logger, IProxyConfigProvider proxyConfig)
@ -37,7 +39,7 @@ namespace FastTunnel.Core.Handlers.Server
await client.webSocket.SendCmdAsync(MessageType.Log, $"穿透协议 | 映射关系(公网=>内网)", CancellationToken.None);
Thread.Sleep(300);
if (requet.Webs != null && requet.Webs.Count() > 0)
if (requet.Webs != null && requet.Webs.Any())
{
hasTunnel = true;
foreach (var item in requet.Webs)
@ -68,7 +70,7 @@ namespace FastTunnel.Core.Handlers.Server
}
}
if (requet.Forwards != null && requet.Forwards.Count() > 0)
if (requet.Forwards != null && requet.Forwards.Any())
{
if (server.ServerOption.CurrentValue.EnableForward)
{

View File

@ -1,21 +1,22 @@
using FastTunnel.Core.Dispatchers;
using FastTunnel.Core.Models;
using Microsoft.AspNetCore.Hosting.Server;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Dispatchers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace FastTunnel.Core.Listener
{
public class PortProxyListener
{
ILogger _logerr;
readonly ILogger _logerr;
public string ListenIp { get; set; }
@ -23,10 +24,10 @@ namespace FastTunnel.Core.Listener
int m_numConnectedSockets;
bool shutdown = false;
bool shutdown;
ForwardDispatcher _requestDispatcher;
Socket listenSocket;
WebSocket client;
readonly Socket listenSocket;
readonly WebSocket client;
public PortProxyListener(string ip, int port, ILogger logerr, WebSocket client)
{

View File

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
namespace FastTunnel.Core.Models
{

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Listener;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Listener;
using System;
using System.Collections.Generic;
using System.Net.Sockets;

View File

@ -1,7 +1,10 @@
using FastTunnel.Core.Config;
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System.Collections.Generic;
using System.Text;
namespace FastTunnel.Core.Models
{

View File

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
namespace FastTunnel.Core.Models
{

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Text;

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Client;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Client;
using FastTunnel.Core.Handlers.Server;
using FastTunnel.Core.Protocol;
using System;
@ -25,8 +31,9 @@ namespace FastTunnel.Core.Models
readonly ILoginHandler loginHandler;
public IPAddress RemoteIpAddress { get; private set; }
IList<WebInfo> webInfos = new List<WebInfo>();
IList<ForwardInfo<ForwardHandlerArg>> forwardInfos = new List<ForwardInfo<ForwardHandlerArg>>();
readonly IList<WebInfo> webInfos = new List<WebInfo>();
readonly IList<ForwardInfo<ForwardHandlerArg>> forwardInfos = new List<ForwardInfo<ForwardHandlerArg>>();
public TunnelClient(WebSocket webSocket, FastTunnelServer fastTunnelServer, ILoginHandler loginHandler, IPAddress remoteIpAddress)
{
@ -74,7 +81,7 @@ namespace FastTunnel.Core.Models
}
catch (Exception ex)
{
Console.WriteLine($"处理客户端消息失败cmd={lineCmd}");
Console.WriteLine($"处理客户端消息失败cmd={lineCmd} {ex}");
return false;
}
}
@ -94,7 +101,7 @@ namespace FastTunnel.Core.Models
}
}
// TODO:
webSocket.CloseAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);
}
}
}

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Text;

View File

@ -1,4 +1,10 @@
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net.WebSockets;

View File

@ -1,9 +1,13 @@
using FastTunnel.Core.Extensions;
using System;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastTunnel.Core.Protocol
{

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Config;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Config;
using FastTunnel.Core.Client;
using FastTunnel.Core.Models;
using Microsoft.Extensions.Configuration;

View File

@ -1,4 +1,10 @@
using FastTunnel.Core.Extensions;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core.Extensions;
using FastTunnel.Core.Models;
using System;
using System.Collections.Generic;

View File

@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
namespace FastTunnel.Core.Utilitys
{

View File

@ -6,10 +6,8 @@
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
<UserSecretsId>421d8d0d-f934-45e6-9858-780312446b3b</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
@ -20,17 +18,17 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.9" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0-preview.4.21253.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="6.0.0-preview.4.21253.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="5.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="6.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
</ItemGroup>
<ItemGroup Condition="'$(Configuration)'=='Debug'">
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.1.5" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.1.5" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FastTunnel.Api\FastTunnel.Api.csproj" />

View File

@ -1,47 +1,47 @@
using FastTunnel.Core.Extensions;
using FastTunnel.Core.Services;
using log4net.Repository.Hierarchy;
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
namespace FastTunnel.Server
namespace FastTunnel.Server;
public class Program
{
public class Program
public static void Main(string[] args)
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"config/appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
{
var enableFileLog = (bool)context.Configuration.GetSection("EnableFileLog").Get(typeof(bool));
if (enableFileLog)
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddLog4Net();
}
});
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"config/appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
{
var enableFileLog = (bool)context.Configuration.GetSection("EnableFileLog").Get(typeof(bool));
if (enableFileLog)
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddLog4Net();
}
});
}

View File

@ -1,3 +1,9 @@
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using FastTunnel.Core;
using FastTunnel.Core.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@ -16,102 +22,101 @@ using System.Text;
using Microsoft.OpenApi.Models;
#endif
namespace FastTunnel.Server
namespace FastTunnel.Server;
public class Startup
{
public class Startup
public Startup(IConfiguration configuration)
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var serverOptions = Configuration.GetSection("FastTunnel").Get<DefaultServerConfig>();
options.TokenValidationParameters = new TokenValidationParameters
{
var serverOptions = Configuration.GetSection("FastTunnel").Get<DefaultServerConfig>();
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(serverOptions.Api.JWT.ClockSkew),
ValidateIssuerSigningKey = true,
ValidAudience = serverOptions.Api.JWT.ValidAudience,
ValidIssuer = serverOptions.Api.JWT.ValidIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serverOptions.Api.JWT.IssuerSigningKey))
};
options.TokenValidationParameters = new TokenValidationParameters
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(serverOptions.Api.JWT.ClockSkew),
ValidateIssuerSigningKey = true,
ValidAudience = serverOptions.Api.JWT.ValidAudience,
ValidIssuer = serverOptions.Api.JWT.ValidIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serverOptions.Api.JWT.IssuerSigningKey))
};
context.HandleResponse();
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
context.Response.ContentType = "application/json;charset=utf-8";
context.Response.StatusCode = StatusCodes.Status200OK;
await context.Response.WriteAsync(new
{
context.HandleResponse();
errorCode = 1,
errorMessage = context.Error ?? "Token is Required"
}.ToJson());
},
};
});
context.Response.ContentType = "application/json;charset=utf-8";
context.Response.StatusCode = StatusCodes.Status200OK;
services.AddAuthorization();
await context.Response.WriteAsync(new
{
errorCode = 1,
errorMessage = context.Error ?? "Token is Required"
}.ToJson());
},
};
});
services.AddAuthorization();
services.AddControllers();
services.AddControllers();
#if DEBUG
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v2", new OpenApiInfo { Title = "FastTunel.Api", Version = "v2" });
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v2", new OpenApiInfo { Title = "FastTunel.Api", Version = "v2" });
});
#endif
// -------------------FastTunnel STEP1 OF 3------------------
services.AddFastTunnelServer(Configuration.GetSection("FastTunnel"));
// -------------------FastTunnel STEP1 END-------------------
// -------------------FastTunnel STEP1 OF 3------------------
services.AddFastTunnelServer(Configuration.GetSection("FastTunnel"));
// -------------------FastTunnel STEP1 END-------------------
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
#if DEBUG
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v2/swagger.json", "FastTunel.WebApi v2"));
#endif
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
// -------------------FastTunnel STEP2 OF 3------------------
app.UseFastTunnelServer();
// -------------------FastTunnel STEP2 END-------------------
app.UseRouting();
// --------------------- Custom UI ----------------
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
// --------------------- Custom UI ----------------
app.UseEndpoints(endpoints =>
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
#if DEBUG
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v2/swagger.json", "FastTunel.WebApi v2"));
#endif
}
// -------------------FastTunnel STEP2 OF 3------------------
app.UseFastTunnelServer();
// -------------------FastTunnel STEP2 END-------------------
app.UseRouting();
// --------------------- Custom UI ----------------
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
// --------------------- Custom UI ----------------
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllers();
// -------------------FastTunnel STEP3 OF 3------------------
endpoints.MapFastTunnelServer();
// -------------------FastTunnel STEP3 END-------------------
});
}
}
}

View File

@ -8,27 +8,26 @@
}
},
"AllowedHosts": "*",
// Http&
// Http&
"urls": "http://*:1270",
//
//
"EnableFileLog": false,
"FastTunnel": {
//
// SubDomain ${SubDomain}.${WebDomain}访访
//
// SubDomain ${SubDomain}.${WebDomain}访访
"WebDomain": "test.cc",
// 访访ip
// 访访ip
"WebAllowAccessIps": [ "192.168.0.101" ],
// Forward.false
// Forward.false
"EnableForward": true,
// TokenTokenstoken TokenTokens
//"Token": "TOKEN_FOR_CLIENT_AUTHENTICATION",
// Tokenstoken
"Tokens": [ "TOKEN_FOR_CLIENT_AUTHENTICATION" ],
/**
* 访apiJWT
* 访apiJWT
*/
"Api": {
"JWT": {
@ -46,4 +45,4 @@
]
}
}
}
}

View File

@ -11,7 +11,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FastTunnel.Server", "FastTu
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{0E2A9DA2-26AE-4657-B4C5-3A913E2F5A3C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FastTunnel.Api", "FastTunnel.Api\FastTunnel.Api.csproj", "{7D560A9A-E480-40F4-AAF7-398447438255}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FastTunnel.Api", "FastTunnel.Api\FastTunnel.Api.csproj", "{7D560A9A-E480-40F4-AAF7-398447438255}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{54494A47-33E6-488B-B7D4-DBE8FD34916A}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution