Skip to content

Commit

Permalink
up grpc state
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Aug 30, 2019
1 parent 3154df1 commit d0ca8b2
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 85 deletions.
6 changes: 3 additions & 3 deletions v2rayN/v2rayN/Forms/MainForm.cs
Expand Up @@ -129,15 +129,15 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;

statistics?.saveToFile();
statistics?.SaveToFile();

HideForm();
return;
}
if (e.CloseReason == CloseReason.ApplicationExitCall)
{
ConfigHandler.SaveConfig(ref config);
statistics?.saveToFile();
statistics?.SaveToFile();
statistics?.Close();
}
}
Expand Down Expand Up @@ -168,7 +168,7 @@ protected override void WndProc(ref Message m)
Utils.SaveLog("Windows shutdown UnsetProxy");
//CloseV2ray();
ConfigHandler.ToJsonFile(config);
statistics?.saveToFile();
statistics?.SaveToFile();
ProxySetting.UnsetProxy();
m.Result = (IntPtr)1;
break;
Expand Down
7 changes: 6 additions & 1 deletion v2rayN/v2rayN/Global.cs
Expand Up @@ -146,7 +146,7 @@ class Global
public const string InboundProxyTagName = "proxy";
public const string Loopback = "127.0.0.1";
public const string InboundAPIProtocal = "dokodemo-door";
public const uint InboundAPIPort = 10805;

public enum StatisticsFreshRate
{
quick = 1000,
Expand Down Expand Up @@ -185,6 +185,11 @@ public enum StatisticsFreshRate
/// </summary>
public static int pacPort { get; set; }

/// <summary>
///
/// </summary>
public static int statePort { get; set; }

#endregion


Expand Down
65 changes: 43 additions & 22 deletions v2rayN/v2rayN/Handler/StatisticsHandler.cs
@@ -1,16 +1,13 @@
using System;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.Threading;

using v2rayN.Mode;
using v2rayN.Protos.Statistics;

using Grpc.Core;

namespace v2rayN.Handler
{
class StatisticsHandler
Expand Down Expand Up @@ -63,19 +60,24 @@ public StatisticsHandler(Mode.Config config, Action<ulong, ulong, ulong, ulong,
Statistic.Add(statistic);
}

loadFromFile();
LoadFromFile();

grpcInit();
GrpcInit();

workThread_ = new Thread(new ThreadStart(run));
workThread_ = new Thread(new ThreadStart(Run));
workThread_.Start();
}

private void grpcInit()
private void GrpcInit()
{
channel_ = new Channel($"127.0.0.1:{Global.InboundAPIPort}", ChannelCredentials.Insecure);
channel_.ConnectAsync();
client_ = new StatsService.StatsServiceClient(channel_);
if (channel_ == null)
{
Global.statePort = GetFreePort();

channel_ = new Channel($"127.0.0.1:{Global.statePort}", ChannelCredentials.Insecure);
channel_.ConnectAsync();
client_ = new StatsService.StatsServiceClient(channel_);
}
}

public void Close()
Expand All @@ -92,7 +94,7 @@ public void Close()
}
}

public void run()
public void Run()
{
while (!exitFlag_)
{
Expand Down Expand Up @@ -120,7 +122,7 @@ public void run()
down = 0;

//TODO: parse output
parseOutput(res.Stat, out up, out down);
ParseOutput(res.Stat, out up, out down);

Up = up;
Down = down;
Expand All @@ -139,10 +141,9 @@ public void run()
if (UpdateUI)
updateFunc_(TotalUp, TotalDown, Up, Down, Statistic);
}

Thread.Sleep(config_.statisticsFreshRate);
channel_.ConnectAsync();
}
Thread.Sleep(config_.statisticsFreshRate);
channel_.ConnectAsync();
}
catch (Exception ex)
{
Expand All @@ -151,7 +152,7 @@ public void run()
}
}

public void parseOutput(Google.Protobuf.Collections.RepeatedField<Stat> source, out ulong up, out ulong down)
public void ParseOutput(Google.Protobuf.Collections.RepeatedField<Stat> source, out ulong up, out ulong down)
{

up = 0; down = 0;
Expand Down Expand Up @@ -189,7 +190,7 @@ public void parseOutput(Google.Protobuf.Collections.RepeatedField<Stat> source,
}
}

public void saveToFile()
public void SaveToFile()
{
if (!Directory.Exists(logPath_))
{
Expand Down Expand Up @@ -249,7 +250,7 @@ public void saveToFile()
}
}

public void loadFromFile()
public void LoadFromFile()
{
if (!Directory.Exists(logPath_)) return;

Expand Down Expand Up @@ -397,5 +398,25 @@ private void DeleteExpiredLog()
Utils.SaveLog(ex.Message, ex);
}
}

private int GetFreePort()
{
int defaultPort = 28123;
try
{
// TCP stack please do me a favor
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
catch (Exception ex)
{
// in case access denied
Utils.SaveLog(ex.Message, ex);
return defaultPort;
}
}
}
}
16 changes: 9 additions & 7 deletions v2rayN/v2rayN/Handler/V2rayConfigHandler.cs
Expand Up @@ -631,26 +631,28 @@ public static int statistic(Config config, ref V2rayConfig v2rayConfig)
v2rayConfig.stats = new Stats();

apiObj.tag = tag;
apiObj.services = services.ToList();
apiObj.services = services.ToList();
v2rayConfig.api = apiObj;

policySystemSetting.statsInboundDownlink = true;
policySystemSetting.statsInboundUplink = true;
policyObj.system = policySystemSetting;
v2rayConfig.policy = policyObj;
if(!v2rayConfig.inbounds.Exists(item => { return item.tag == tag; }))

if (!v2rayConfig.inbounds.Exists(item => { return item.tag == tag; }))
{
var apiInbound = new Mode.Inbounds();
var apiInboundSettings = new Mode.Inboundsettings();
apiInbound.tag = tag;
apiInbound.listen = Global.Loopback;
apiInbound.port = config.port();
apiInbound.port = Global.statePort;
apiInbound.protocol = Global.InboundAPIProtocal;
apiInboundSettings.address = Global.Loopback;
apiInbound.settings = apiInboundSettings;
v2rayConfig.inbounds.Add(apiInbound);
}
if(!v2rayConfig.routing.rules.Exists(item => { return item.outboundTag == tag; }))

if (!v2rayConfig.routing.rules.Exists(item => { return item.outboundTag == tag; }))
{
var apiRoutingRule = new Mode.RulesItem();
apiRoutingRule.inboundTag = tag;
Expand Down Expand Up @@ -1153,14 +1155,14 @@ public static VmessItem ImportFromClipboardConfig(string clipboardData, out stri
vmessItem.network = Global.DefaultNetwork;
vmessItem.headerType = Global.None;


vmessItem.configVersion = Utils.ToInt(vmessQRCode.v);
vmessItem.remarks = Utils.ToString(vmessQRCode.ps);
vmessItem.address = Utils.ToString(vmessQRCode.add);
vmessItem.port = Utils.ToInt(vmessQRCode.port);
vmessItem.id = Utils.ToString(vmessQRCode.id);
vmessItem.alterId = Utils.ToInt(vmessQRCode.aid);

if (!Utils.IsNullOrEmpty(vmessQRCode.net))
{
vmessItem.network = vmessQRCode.net;
Expand All @@ -1169,7 +1171,7 @@ public static VmessItem ImportFromClipboardConfig(string clipboardData, out stri
{
vmessItem.headerType = vmessQRCode.type;
}

vmessItem.requestHost = Utils.ToString(vmessQRCode.host);
vmessItem.path = Utils.ToString(vmessQRCode.path);
vmessItem.streamSecurity = Utils.ToString(vmessQRCode.tls);
Expand Down
28 changes: 1 addition & 27 deletions v2rayN/v2rayN/Mode/V2rayConfig.cs
Expand Up @@ -21,40 +21,14 @@ public class V2rayConfig
/// </summary>
public List<Outbounds> outbounds { get; set; }

/// 网速统计
/// 使用v2ray api功能
///
/// routing->rules 需要加上这一条
/// {
/// "inboundTag": [
/// "api"
/// ],
/// "outboundTag": "api",
/// "type": "field"
/// }

/// <summary>
/// 统计需要, 空对象
/// </summary>
public Stats stats { get; set; }

/// <summary>
/// 需要tag和services
/// "api": {
/// "tag": "api",
/// "services": [
/// "StatsService"
/// ]
/// }

/// </summary>
public API api { get; set; }

/// <summary>
/// policy 都设置为true;
/// "system": {
/// "statsInboundUplink": true,
/// "statsInboundDownlink": true
/// }
/// </summary>
public Policy policy;

Expand Down
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Properties/AssemblyInfo.cs
Expand Up @@ -33,4 +33,4 @@
// 方法是按如下所示使用“*”:
//[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("2.37")]
[assembly: AssemblyFileVersion("2.38")]
26 changes: 2 additions & 24 deletions v2rayN/v2rayN/Sample/SampleClientConfig.txt
@@ -1,17 +1,4 @@
{
"stats": {},
"api": {
"tag": "api",
"services": [
"StatsService"
]
},
"policy": {
"system": {
"statsInboundUplink": true,
"statsInboundDownlink": true
}
},
{
"log": {
"access": "",
"error": "",
Expand Down Expand Up @@ -39,16 +26,7 @@
"tls"
]
}
},
{
"listen": "127.0.0.1",
"port": 10805,
"protocol": "dokodemo-door",
"settings": {
"address": "127.0.0.1"
},
"tag": "api"
}
}
],
"outbounds": [{
"tag": "proxy",
Expand Down

0 comments on commit d0ca8b2

Please sign in to comment.