1
0
mirror of https://github.com/SoftEtherVPN/SoftEtherVPN.git synced 2024-11-22 17:39:53 +03:00

Initial vpnserver-jsonrpc-clients

This commit is contained in:
Daiyuu Nobori 2019-05-28 11:42:26 +09:00
parent d63f637253
commit 03841e4181
13 changed files with 56990 additions and 0 deletions

View File

@ -0,0 +1,350 @@
# Created by https://www.gitignore.io/api/visualstudio
# Edit at https://www.gitignore.io/?templates=visualstudio
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- Backup*.rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# End of https://www.gitignore.io/api/visualstudio

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,282 @@
// SoftEther VPN Server JSON-RPC Stub code for C#
//
// JsonRpc.cs - JSON-RPC Client Utility Functions
//
// Automatically generated at 2019-05-28 11:40:24 by vpnserver-jsonrpc-codegen
//
// Licensed under the Apache License 2.0
// Copyright (c) 2014-2019 SoftEther VPN Project
using System;
using System.IO;
using System.Net.Security;
using System.Net.Http;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace SoftEther.JsonRpc
{
/// <summary>
/// Internal utility class
/// </summary>
static class ClientUtil
{
public const int DefaultMaxDepth = 8;
public static string NonNull(this string s) { if (s == null) return ""; else return s; }
public static bool IsEmpty(this string str)
{
if (str == null || str.Trim().Length == 0)
return true;
else
return false;
}
public static bool IsFilled(this string str) => !IsEmpty(str);
public static string ObjectToJson(this object obj, bool include_null = false, bool escape_html = false, int? max_depth = ClientUtil.DefaultMaxDepth, bool compact = false, bool reference_handling = false) => ClientUtil.Serialize(obj, include_null, escape_html, max_depth, compact, reference_handling);
public static T JsonToObject<T>(this string str, bool include_null = false, int? max_depth = ClientUtil.DefaultMaxDepth) => ClientUtil.Deserialize<T>(str, include_null, max_depth);
public static object JsonToObject(this string str, Type type, bool include_null = false, int? max_depth = ClientUtil.DefaultMaxDepth) => ClientUtil.Deserialize(str, type, include_null, max_depth);
public static string Serialize(object obj, bool include_null = false, bool escape_html = false, int? max_depth = ClientUtil.DefaultMaxDepth, bool compact = false, bool reference_handling = false)
{
JsonSerializerSettings setting = new JsonSerializerSettings()
{
MaxDepth = max_depth,
NullValueHandling = include_null ? NullValueHandling.Include : NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Error,
PreserveReferencesHandling = reference_handling ? PreserveReferencesHandling.All : PreserveReferencesHandling.None,
StringEscapeHandling = escape_html ? StringEscapeHandling.EscapeHtml : StringEscapeHandling.Default,
};
return JsonConvert.SerializeObject(obj, compact ? Formatting.None : Formatting.Indented, setting);
}
public static T Deserialize<T>(string str, bool include_null = false, int? max_depth = ClientUtil.DefaultMaxDepth)
=> (T)Deserialize(str, typeof(T), include_null, max_depth);
public static object Deserialize(string str, Type type, bool include_null = false, int? max_depth = ClientUtil.DefaultMaxDepth)
{
JsonSerializerSettings setting = new JsonSerializerSettings()
{
MaxDepth = max_depth,
NullValueHandling = include_null ? NullValueHandling.Include : NullValueHandling.Ignore,
ObjectCreationHandling = ObjectCreationHandling.Replace,
ReferenceLoopHandling = ReferenceLoopHandling.Error,
};
return JsonConvert.DeserializeObject(str, type, setting);
}
public static void Print(this object o)
{
string str = o.ObjectToJson();
if (o is string) str = (string)o;
Console.WriteLine(str);
}
}
/// <summary>
/// JSON-RPC exception class
/// </summary>
class JsonRpcException : Exception
{
public JsonRpcError RpcError { get; }
public JsonRpcException(JsonRpcError err)
: base($"Code={err.Code}, Message={err.Message.NonNull()}" +
(err == null || err.Data == null ? "" : $", Data={err.Data.ObjectToJson(compact: true)}"))
{
this.RpcError = err;
}
}
/// <summary>
/// JSON-RPC request class. See https://www.jsonrpc.org/specification
/// </summary>
class JsonRpcRequest
{
[JsonProperty("jsonrpc", Order = 1)]
public string Version { get; set; } = "2.0";
[JsonProperty("id", Order = 2)]
public string Id { get; set; } = null;
[JsonProperty("method", Order = 3)]
public string Method { get; set; } = "";
[JsonProperty("params", Order = 4)]
public object Params { get; set; } = null;
public JsonRpcRequest() { }
public JsonRpcRequest(string method, object param, string id)
{
this.Method = method;
this.Params = param;
this.Id = id;
}
}
/// <summary>
/// JSON-RPC response class with generics
/// </summary>
/// <typeparam name="TResult"></typeparam>
class JsonRpcResponse<TResult>
{
[JsonProperty("jsonrpc", Order = 1)]
public virtual string Version { get; set; } = "2.0";
[JsonProperty("id", NullValueHandling = NullValueHandling.Include, Order = 2)]
public virtual string Id { get; set; } = null;
[JsonProperty("result", Order = 3)]
public virtual TResult Result { get; set; } = default(TResult);
[JsonProperty("error", Order = 4)]
public virtual JsonRpcError Error { get; set; } = null;
[JsonIgnore]
public virtual bool IsError => this.Error != null;
[JsonIgnore]
public virtual bool IsOk => !IsError;
public virtual void ThrowIfError()
{
if (this.IsError) throw new JsonRpcException(this.Error);
}
public override string ToString()
{
return this.ObjectToJson(compact: true);
}
}
/// <summary>
/// JSON-RPC error class. See https://www.jsonrpc.org/specification
/// </summary>
class JsonRpcError
{
public JsonRpcError() { }
public JsonRpcError(int code, string message, object data = null)
{
this.Code = code;
this.Message = message.NonNull();
if (this.Message.IsEmpty()) this.Message = $"JSON-RPC Error {code}";
this.Data = data;
}
[JsonProperty("code")]
public int Code { get; set; } = 0;
[JsonProperty("message")]
public string Message { get; set; } = null;
[JsonProperty("data")]
public object Data { get; set; } = null;
}
/// <summary>
/// JSON-RPC client. See https://www.jsonrpc.org/specification
/// </summary>
class JsonRpcClient
{
HttpClientHandler client_handler;
HttpClient client;
public const int DefaultTimeoutMsecs = 60 * 1000;
public int TimeoutMsecs { get => (int)client.Timeout.TotalMilliseconds; set => client.Timeout = new TimeSpan(0, 0, 0, 0, value); }
public Dictionary<string, string> HttpHeaders { get; } = new Dictionary<string, string>();
string base_url;
/// <summary>
/// JSON-RPC client class constructor
/// </summary>
/// <param name="url">The URL</param>
/// <param name="cert_check_proc">The SSL certificate validation callback</param>
public JsonRpcClient(string url, Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> cert_check_proc = null)
{
if (cert_check_proc == null) cert_check_proc = (message, cert, chain, errors) => true;
client_handler = new HttpClientHandler();
this.client_handler.AllowAutoRedirect = true;
this.client_handler.MaxAutomaticRedirections = 10;
client_handler.ServerCertificateCustomValidationCallback = cert_check_proc;
client = new HttpClient(client_handler, true);
//Console.WriteLine("new HttpClient(client_handler, true);");
this.base_url = url;
this.TimeoutMsecs = DefaultTimeoutMsecs;
}
/// <summary>
/// Call a single RPC call (without error check). You can wait for the response with Task<string> or await statement.
/// </summary>
/// <param name="method_name">The name of RPC method</param>
/// <param name="param">The parameters</param>
public async Task<string> CallInternalAsync(string method_name, object param)
{
string id = DateTime.Now.Ticks.ToString();
JsonRpcRequest req = new JsonRpcRequest(method_name, param, id);
string req_string = req.ObjectToJson();
//Console.WriteLine($"req: {req_string}");
HttpContent content = new StringContent(req_string, Encoding.UTF8, "application/json");
foreach (string key in this.HttpHeaders.Keys)
{
string value = this.HttpHeaders[key];
content.Headers.Add(key, value);
}
HttpResponseMessage response = await this.client.PostAsync(base_url, content);
Stream responseStream = await response.Content.ReadAsStreamAsync();
if (!response.IsSuccessStatusCode)
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
throw new Exception($"Error: {response.StatusCode}: {await streamReader.ReadToEndAsync()}");
}
}
string ret_string;
using (StreamReader streamReader = new StreamReader(responseStream))
{
ret_string = await streamReader.ReadToEndAsync();
}
//Console.WriteLine($"ret: {ret_string}");
return ret_string;
}
/// <summary>
/// Call a single RPC call (with error check). You can wait for the response with Promise<TResult> or await statement. In the case of error, it will be thrown.
/// </summary>
/// <param name="method_name">The name of RPC method</param>
/// <param name="param">The parameters</param>
public async Task<TResult> CallAsync<TResult>(string method_name, object param)
{
string ret_string = await CallInternalAsync(method_name, param);
JsonRpcResponse <TResult> ret = ret_string.JsonToObject<JsonRpcResponse<TResult>>();
ret.ThrowIfError();
return ret.Result;
}
}
}

View File

@ -0,0 +1,17 @@
// SoftEther VPN Server JSON-RPC Stub code for C#
//
// Program.cs - The Main() entry point
//
// Automatically generated at 2019-05-28 11:40:24 by vpnserver-jsonrpc-codegen
//
// Licensed under the Apache License 2.0
// Copyright (c) 2014-2019 SoftEther VPN Project
class Program
{
static void Main(string[] args)
{
VPNRPCTest test = new VPNRPCTest();
test.Test_All();
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RootNamespace>SoftEther.VPNServerRpc</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.10.0" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2041
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vpnserver-jsonrpc-client-csharp", "vpnserver-jsonrpc-client-csharp.csproj", "{81CA3EC4-026E-4D37-9889-828186BBB8C0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{81CA3EC4-026E-4D37-9889-828186BBB8C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{81CA3EC4-026E-4D37-9889-828186BBB8C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81CA3EC4-026E-4D37-9889-828186BBB8C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81CA3EC4-026E-4D37-9889-828186BBB8C0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D87E5CF1-9A10-431C-AC42-F1041470AEE8}
EndGlobalSection
EndGlobal

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff