예제 #1
0
        private void RunSpeedTest()
        {
            string testIndexId = string.Empty;
            int    pid         = -1;

            if (_config.vmess.Count <= 0)
            {
                return;
            }

            pid = _v2rayHandler.LoadV2rayConfigString(_config, _selecteds);
            if (pid < 0)
            {
                _updateFunc(_selecteds[0].selected, UIRes.I18N("OperationFailed"));
                return;
            }

            string         url             = _config.constItem.speedTestUrl;
            DownloadHandle downloadHandle2 = new DownloadHandle();

            downloadHandle2.UpdateCompleted += (sender2, args) =>
            {
                var index = _config.FindIndexId(testIndexId);
                if (index < 0)
                {
                    return;
                }
                _updateFunc(index, args.Msg);
            };
            downloadHandle2.Error += (sender2, args) =>
            {
                var index = _config.FindIndexId(testIndexId);
                if (index < 0)
                {
                    return;
                }
                _updateFunc(index, args.GetException().Message);
            };

            var timeout = 10;

            foreach (var it in _selecteds)
            {
                if (it.configType == (int)EConfigType.Custom)
                {
                    continue;
                }
                if (it.port <= 0)
                {
                    continue;
                }
                testIndexId = it.indexId;
                if (_config.FindIndexId(it.indexId) < 0)
                {
                    continue;
                }

                WebProxy webProxy = new WebProxy(Global.Loopback, it.port);
                var      ws       = downloadHandle2.DownloadDataAsync(url, webProxy, timeout - 2);

                Thread.Sleep(1000 * timeout);

                ws.CancelAsync();
                ws.Dispose();

                Thread.Sleep(1000 * 2);
            }
            if (pid > 0)
            {
                _v2rayHandler.V2rayStopPid(pid);
            }
        }
예제 #2
0
        private void UpdateHandler(ulong totalUp, ulong totalDown, ulong up, ulong down, List <Mode.ServerStatistics> statistics)
        {
            double up_amount = 0.0, down_amount;
            string up_unit = "", down_unit;

            up   /= (ulong)(config.statisticsFreshRate / 1000f);
            down /= (ulong)(config.statisticsFreshRate / 1000f);

            Utils.ToHumanReadable(up, out up_amount, out up_unit);
            Utils.ToHumanReadable(down, out down_amount, out down_unit);
            up_unit   += "/s";
            down_unit += "/s";

            toolSslBlank4.Text = string.Format(
                "{4}: {0:f2} {1} | {5}: {2:f2} {3}",
                up_amount,
                up_unit,
                down_amount,
                down_unit,
                UIRes.I18N("uploadSpeed"),
                UIRes.I18N("downloadSpeed")
                );

            List <string[]> datas = new List <string[]>();

            for (int i = 0; i < config.vmess.Count; i++)
            {
                string totalUp_   = string.Empty,
                       totalDown_ = string.Empty,
                       todayUp_   = string.Empty,
                       todayDown_ = string.Empty;
                var index         = statistics.FindIndex(item_ => Utils.IsIdenticalServer(item_, new ServerStatistics(config.vmess[i].remarks, config.vmess[i].address, config.vmess[i].port, config.vmess[i].path, config.vmess[i].requestHost, 0, 0, 0, 0)));
                if (index != -1)
                {
                    Func <ulong, string> human_fy = (amount) =>
                    {
                        double result;
                        string unit;
                        Utils.ToHumanReadable(amount, out result, out unit);
                        return($"{string.Format("{0:f2}", result)}{unit}");
                    };
                    totalUp_   = human_fy(statistics[index].totalUp);
                    totalDown_ = human_fy(statistics[index].totalDown);
                    todayUp_   = human_fy(statistics[index].todayUp);
                    todayDown_ = human_fy(statistics[index].todayDown);
                }

                datas.Add(new string[] { totalUp_, totalDown_, todayUp_, todayDown_ });
            }

            lvServers.Invoke((MethodInvoker) delegate
            {
                lvServers.SuspendLayout();
                for (int i = 0; i < datas.Count; i++)
                {
                    lvServers.Items[i].SubItems[7].Text  = datas[i][0];
                    lvServers.Items[i].SubItems[8].Text  = datas[i][1];
                    lvServers.Items[i].SubItems[9].Text  = datas[i][2];
                    lvServers.Items[i].SubItems[10].Text = datas[i][3];
                }
                lvServers.ResumeLayout();
            });
        }
예제 #3
0
        /// <summary>
        /// 保存基础设置
        /// </summary>
        /// <returns></returns>
        private int SaveBase()
        {
            //日志
            bool   logEnabled = chklogEnabled.Checked;
            string loglevel   = cmbloglevel.Text.Trim();

            //Mux
            bool   muxEnabled = chkmuxEnabled.Checked;
            string muxNumber  = muxNumBox.Text;

            if (Utils.IsNullOrEmpty(muxNumber))
            {
                muxNumber = "8";
            }

            config.muxNumber = Utils.ToInt(muxNumber);
            //本地监听
            string localPort       = txtlocalPort.Text.Trim();
            string protocol        = cmbprotocol.Text.Trim();
            bool   udpEnabled      = chkudpEnabled.Checked;
            bool   sniffingEnabled = chksniffingEnabled.Checked;

            if (Utils.IsNullOrEmpty(localPort) || !Utils.IsNumberic(localPort))
            {
                UI.Show(UIRes.I18N("FillLocalListeningPort"));
                return(-1);
            }
            if (Utils.IsNullOrEmpty(protocol))
            {
                UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                return(-1);
            }
            config.inbound[0].localPort       = Utils.ToInt(localPort);
            config.inbound[0].protocol        = protocol;
            config.inbound[0].udpEnabled      = udpEnabled;
            config.inbound[0].sniffingEnabled = sniffingEnabled;

            //本地监听2
            string localPort2 = txtlocalPort2.Text.Trim();
            string protocol2  = cmbprotocol2.Text.Trim();
            //bool udpEnabled2 = chkudpEnabled2.Checked;
            bool sniffingEnabled2 = chksniffingEnabled2.Checked;

            //if (chkAllowIn2.Checked)
            //{
            if (Utils.IsNullOrEmpty(localPort2) || !Utils.IsNumberic(localPort2))
            {
                UI.Show(UIRes.I18N("FillLocalListeningPort"));
                return(-1);
            }
            //    if (Utils.IsNullOrEmpty(protocol2))
            //    {
            //        UI.Show(UIRes.I18N("PleaseSelectProtocol"));
            //        return -1;
            //    }
            //    if (config.inbound.Count < 2)
            //    {
            //        config.inbound.Add(new Mode.InItem());
            //    }
            //    config.inbound[1].localPort = Utils.ToInt(localPort2);
            //    config.inbound[1].protocol = protocol2;
            //    config.inbound[1].udpEnabled = udpEnabled2;
            //    config.inbound[1].sniffingEnabled = sniffingEnabled2;
            //}
            //else
            //{
            //    if (config.inbound.Count > 1)
            //    {
            //        config.inbound.RemoveAt(1);
            //    }
            //}

            //日志
            config.logEnabled = logEnabled;
            config.loglevel   = loglevel;

            //Mux
            config.muxEnabled = muxEnabled;

            //directDNS
            config.directDNS = txtremoteDNS.Text.Trim();

            return(0);
        }
예제 #4
0
        private void tsbSubUpdate_Click(object sender, EventArgs e)
        {
            AppendText(false, UIRes.I18N("MsgUpdateSubscriptionStart"));

            if (config.subItem == null || config.subItem.Count <= 0)
            {
                AppendText(false, UIRes.I18N("MsgNoValidSubscription"));
                return;
            }

            for (int k = 1; k <= config.subItem.Count; k++)
            {
                string id       = config.subItem[k - 1].id.Trim();
                string url      = config.subItem[k - 1].url.Trim();
                string hashCode = $"{k}->";
                if (config.subItem[k - 1].enabled == false)
                {
                    continue;
                }
                if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url))
                {
                    AppendText(false, $"{hashCode}{UIRes.I18N("MsgNoValidSubscription")}");
                    continue;
                }

                V2rayUpdateHandle v2rayUpdateHandle3 = new V2rayUpdateHandle();
                v2rayUpdateHandle3.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, $"{hashCode}{UIRes.I18N("MsgGetSubscriptionSuccessfully")}");
                        var result = Utils.Base64Decode(args.Msg);
                        if (Utils.IsNullOrEmpty(result))
                        {
                            AppendText(false, $"{hashCode}{UIRes.I18N("MsgSubscriptionDecodingFailed")}");
                            return;
                        }

                        ConfigHandler.RemoveServerViaSubid(ref config, id);
                        AppendText(false, $"{hashCode}{UIRes.I18N("MsgClearSubscription")}");
                        RefreshServers();
                        if (AddBatchServers(result, id) == 0)
                        {
                        }
                        else
                        {
                            AppendText(false, $"{hashCode}{UIRes.I18N("MsgFailedImportSubscription")}");
                        }
                        AppendText(false, $"{hashCode}{UIRes.I18N("MsgUpdateSubscriptionEnd")}");
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                v2rayUpdateHandle3.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };

                v2rayUpdateHandle3.WebDownloadString(url);
                AppendText(false, $"{hashCode}{UIRes.I18N("MsgStartGettingSubscriptions")}");
            }
        }
예제 #5
0
        private void tsbCheckUpdateCore_Click(object sender, EventArgs e)
        {
            DownloadHandle downloadHandle = null;

            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();
                downloadHandle.AbsoluteCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgParsingV2rayCoreSuccessfully"));

                        string url = args.Msg;
                        this.Invoke((MethodInvoker)(delegate
                        {
                            if (UI.ShowYesNo(string.Format(UIRes.I18N("DownloadYesNo"), url)) == DialogResult.No)
                            {
                                return;
                            }
                            else
                            {
                                downloadHandle.DownloadFileAsync(config, url, null, -1);
                            }
                        }));
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));
                        AppendText(false, UIRes.I18N("MsgUnpacking"));

                        try
                        {
                            CloseV2ray();

                            string fileName = downloadHandle.DownloadFileName;
                            fileName = Utils.GetPath(fileName);
                            FileManager.ZipExtractToFile(fileName);

                            AppendText(false, UIRes.I18N("MsgUpdateV2rayCoreSuccessfullyMore"));

                            Global.reloadV2ray = true;
                            LoadV2ray();

                            AppendText(false, UIRes.I18N("MsgUpdateV2rayCoreSuccessfully"));
                        }
                        catch (Exception ex)
                        {
                            AppendText(false, ex.Message);
                        }
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };
            }

            AppendText(false, UIRes.I18N("MsgStartUpdatingV2rayCore"));
            downloadHandle.AbsoluteV2rayCore(config);
        }
예제 #6
0
        /// <summary>
        /// 从剪贴板导入URL
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static VmessItem ImportFromClipboardConfig(string clipboardData, out string msg)
        {
            msg = string.Empty;
            VmessItem vmessItem = new VmessItem();

            try
            {
                //载入配置文件
                string result = clipboardData.TrimEx();// Utils.GetClipboardData();
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedReadConfiguration");
                    return(null);
                }

                if (result.StartsWith(Global.vmessProtocol))
                {
                    int indexSplit = result.IndexOf("?");
                    if (indexSplit > 0)
                    {
                        vmessItem = ResolveStdVmess(result) ?? ResolveVmess4Kitsunebi(result);
                    }
                    else
                    {
                        vmessItem = ResolveVmess(result, out msg);
                    }

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else if (result.StartsWith(Global.ssProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem = ResolveSSLegacy(result);
                    if (vmessItem == null)
                    {
                        vmessItem = ResolveSip002(result);
                    }
                    if (vmessItem == null)
                    {
                        return(null);
                    }
                    if (vmessItem.address.Length == 0 || vmessItem.port == 0 || vmessItem.security.Length == 0 || vmessItem.id.Length == 0)
                    {
                        return(null);
                    }

                    vmessItem.configType = (int)EConfigType.Shadowsocks;
                }
                else if (result.StartsWith(Global.socksProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem = ResolveSocks(result);
                }
                else if (result.StartsWith(Global.trojanProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem = ResolveTrojan(result);
                }
                else if (result.StartsWith(Global.vlessProtocol))
                {
                    vmessItem = ResolveStdVLESS(result);

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else
                {
                    msg = UIRes.I18N("NonvmessOrssProtocol");
                    return(null);
                }
            }
            catch
            {
                msg = UIRes.I18N("Incorrectconfiguration");
                return(null);
            }

            return(vmessItem);
        }
예제 #7
0
        private void CheckUpdateCore(string type)
        {
            DownloadHandle downloadHandle = null;

            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();
                downloadHandle.AbsoluteCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, string.Format(UIRes.I18N("MsgParsingSuccessfully"), "v2rayCore"));

                        string url = args.Msg;
                        this.Invoke((MethodInvoker)(delegate
                        {
                            askToDownload(downloadHandle, url);
                        }));
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));
                        AppendText(false, UIRes.I18N("MsgUnpacking"));

                        try
                        {
                            CloseV2ray();

                            string fileName = downloadHandle.DownloadFileName;
                            fileName = Utils.GetPath(fileName);
                            FileManager.ZipExtractToFile(fileName);

                            AppendText(false, UIRes.I18N("MsgUpdateV2rayCoreSuccessfullyMore"));

                            Global.reloadV2ray = true;
                            LoadV2ray();

                            AppendText(false, UIRes.I18N("MsgUpdateV2rayCoreSuccessfully"));
                        }
                        catch (Exception ex)
                        {
                            AppendText(false, ex.Message);
                        }
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };
            }

            AppendText(false, string.Format(UIRes.I18N("MsgStartUpdating"), "v2rayCore"));
            downloadHandle.CheckUpdateAsync(type);
        }
예제 #8
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            ConfigHandler.LoadConfig(ref config);
            v2rayHandler = new V2rayHandler();
            v2rayHandler.ProcessEvent += v2rayHandler_ProcessEvent;
            statistics = new StatisticsHandler(config,
                                               (ulong totalUp, ulong totalDown, ulong up, ulong down, List <Mode.ServerStatistics> statistics) =>
            {
                double up_amount = 0.0, down_amount;
                string up_unit   = "", down_unit;

                up   /= (ulong)(config.statisticsFreshRate / 1000f);
                down /= (ulong)(config.statisticsFreshRate / 1000f);

                Utils.ToHumanReadable(up, out up_amount, out up_unit);
                Utils.ToHumanReadable(down, out down_amount, out down_unit);
                up_unit   += "/s";
                down_unit += "/s";

                toolSslBlank4.Text = string.Format(
                    "{4}: {0:f2} {1} | {5}: {2:f2} {3}",
                    up_amount,
                    up_unit,
                    down_amount,
                    down_unit,
                    UIRes.I18N("uploadSpeed"),
                    UIRes.I18N("downloadSpeed")
                    );


                List <string[]> datas = new List <string[]>();
                for (int i = 0; i < config.vmess.Count; i++)
                {
                    string totalUp_ = string.Empty,
                    totalDown_      = string.Empty,
                    todayUp_        = string.Empty,
                    todayDown_      = string.Empty;
                    var index       = statistics.FindIndex(item_ => (config.vmess[i].address == item_.address && config.vmess[i].port == item_.port));
                    if (index != -1)
                    {
                        Func <ulong, string> human_fy = (amount) =>
                        {
                            double result;
                            string unit;
                            Utils.ToHumanReadable(amount, out result, out unit);
                            return($"{string.Format("{0:f2}", result)}{unit}");
                        };
                        totalUp_   = human_fy(statistics[index].totalUp);
                        totalDown_ = human_fy(statistics[index].totalDown);
                        todayUp_   = human_fy(statistics[index].todayUp);
                        todayDown_ = human_fy(statistics[index].todayDown);
                    }

                    datas.Add(new string[] { totalUp_, totalDown_, todayUp_, todayDown_ });
                }

                lvServers.Invoke((MethodInvoker) delegate
                {
                    lvServers.SuspendLayout();
                    for (int i = 0; i < datas.Count; i++)
                    {
                        lvServers.Items[i].SubItems[7].Text  = datas[i][0];
                        lvServers.Items[i].SubItems[8].Text  = datas[i][1];
                        lvServers.Items[i].SubItems[9].Text  = datas[i][2];
                        lvServers.Items[i].SubItems[10].Text = datas[i][3];
                    }
                    lvServers.ResumeLayout();
                });
            });
        }
예제 #9
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            string address  = txtAddress.Text;
            string port     = txtPort.Text;
            string id       = txtId.Text;
            string alterId  = txtAlterId.Text;
            string security = cmbSecurity.Text;
            string network  = cmbNetwork.Text;
            string remarks  = txtRemarks.Text;

            string headerType     = cmbHeaderType.Text;
            string requestHost    = txtRequestHost.Text;
            string path           = txtPath.Text;
            string streamSecurity = cmbStreamSecurity.Text;
            string allowInsecure  = cmbAllowInsecure.Text;
            string sni            = txtSNI.Text;

            if (Utils.IsNullOrEmpty(address))
            {
                UI.Show(UIRes.I18N("FillServerAddress"));
                return;
            }
            if (Utils.IsNullOrEmpty(port) || !Utils.IsNumberic(port))
            {
                UI.Show(UIRes.I18N("FillCorrectServerPort"));
                return;
            }
            if (Utils.IsNullOrEmpty(id))
            {
                UI.Show(UIRes.I18N("FillUUID"));
                return;
            }
            if (Utils.IsNullOrEmpty(alterId) || !Utils.IsNumberic(alterId))
            {
                UI.Show(UIRes.I18N("FillCorrectAlterId"));
                return;
            }

            vmessItem.address  = address;
            vmessItem.port     = Utils.ToInt(port);
            vmessItem.id       = id;
            vmessItem.alterId  = Utils.ToInt(alterId);
            vmessItem.security = security;
            vmessItem.network  = network;
            vmessItem.remarks  = remarks;

            vmessItem.headerType     = headerType;
            vmessItem.requestHost    = requestHost.Replace(" ", "");
            vmessItem.path           = path.Replace(" ", "");
            vmessItem.streamSecurity = streamSecurity;
            vmessItem.allowInsecure  = allowInsecure;
            vmessItem.sni            = sni;

            if (ConfigHandler.AddServer(ref config, vmessItem, EditIndex) == 0)
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                UI.ShowWarning(UIRes.I18N("OperationFailed"));
            }
        }
예제 #10
0
        private void tsbCheckUpdateN_Click(object sender, EventArgs e)
        {
            //System.Diagnostics.Process.Start(Global.UpdateUrl);
            DownloadHandle downloadHandle = null;

            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();
                downloadHandle.AbsoluteCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, string.Format(UIRes.I18N("MsgParsingSuccessfully"), "v2rayN"));

                        string url = args.Msg;
                        this.Invoke((MethodInvoker)(delegate
                        {
                            askToDownload(downloadHandle, url);
                        }));
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));

                        try
                        {
                            string  fileName = Utils.GetPath(downloadHandle.DownloadFileName);
                            Process process  = new Process
                            {
                                StartInfo = new ProcessStartInfo
                                {
                                    FileName         = "v2rayUpgrade.exe",
                                    Arguments        = "\"" + fileName + "\"",
                                    WorkingDirectory = Utils.StartupPath()
                                }
                            };
                            process.Start();
                            if (process.Id > 0)
                            {
                                menuExit_Click(null, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendText(false, ex.Message);
                        }
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };
            }

            AppendText(false, string.Format(UIRes.I18N("MsgStartUpdating"), "v2rayN"));
            downloadHandle.CheckUpdateAsync("v2rayN");
        }
예제 #11
0
        public void UpdateSubscriptionProcess(Config config, Action <bool, string> update)
        {
            updateUI = update;

            updateUI(false, UIRes.I18N("MsgUpdateSubscriptionStart"));

            if (config.subItem == null || config.subItem.Count <= 0)
            {
                updateUI(false, UIRes.I18N("MsgNoValidSubscription"));
                return;
            }

            for (int k = 1; k <= config.subItem.Count; k++)
            {
                string id       = config.subItem[k - 1].id.TrimEx();
                string url      = config.subItem[k - 1].url.TrimEx();
                string hashCode = $"{k}->";
                if (config.subItem[k - 1].enabled == false)
                {
                    continue;
                }
                if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url))
                {
                    updateUI(false, $"{hashCode}{UIRes.I18N("MsgNoValidSubscription")}");
                    continue;
                }

                DownloadHandle downloadHandle3 = new DownloadHandle();
                downloadHandle3.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        updateUI(false, $"{hashCode}{UIRes.I18N("MsgGetSubscriptionSuccessfully")}");
                        string result = Utils.Base64Decode(args.Msg);
                        if (Utils.IsNullOrEmpty(result))
                        {
                            updateUI(false, $"{hashCode}{UIRes.I18N("MsgSubscriptionDecodingFailed")}");
                            return;
                        }

                        ConfigHandler.RemoveServerViaSubid(ref config, id);
                        updateUI(false, $"{hashCode}{UIRes.I18N("MsgClearSubscription")}");
                        //  RefreshServers();
                        int ret = MainFormHandler.Instance.AddBatchServers(config, result, id);
                        if (ret > 0)
                        {
                            // RefreshServers();
                        }
                        else
                        {
                            updateUI(false, $"{hashCode}{UIRes.I18N("MsgFailedImportSubscription")}");
                        }
                        updateUI(true, $"{hashCode}{UIRes.I18N("MsgUpdateSubscriptionEnd")}");
                    }
                    else
                    {
                        updateUI(false, args.Msg);
                    }
                };
                downloadHandle3.Error += (sender2, args) =>
                {
                    updateUI(false, args.GetException().Message);
                };

                downloadHandle3.WebDownloadString(url);
                updateUI(false, $"{hashCode}{UIRes.I18N("MsgStartGettingSubscriptions")}");
            }
        }
예제 #12
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            string url = txtUrl.Text;

            if (Utils.IsNullOrEmpty(url))
            {
                UI.Show(UIRes.I18N("PleaseFillUrl"));
                return;
            }

            string configFileName = txtConfigFileName.Text;

            if (Utils.IsNullOrEmpty(configFileName))
            {
                UI.Show(UIRes.I18N("PleaseFillConfigFileName"));
                return;
            }

            string remark = txtRemarks.Text;

            if (Utils.IsNullOrEmpty(remark))
            {
                UI.Show(UIRes.I18N("PleaseFillRemarks"));
                return;
            }

            if (!Utils.UrlIsExists(url))
            {
                UI.ShowWarning("无效的地址!!!");
                return;
            }

            var configContent = Utils.GetRemoteCustomConfig(url);

            if (string.IsNullOrEmpty(configContent))
            {
                UI.ShowWarning("远程配置文件为空!!!");
                return;
            }

            vmessItem.url            = url;
            vmessItem.configFileName = configFileName + ".json";
            vmessItem.address        = "customConf/" + vmessItem.configFileName;
            vmessItem.remarks        = remark;
            vmessItem.configType     = (int)EConfigType.Custom;

            //创建配置文件
            if (!Directory.Exists("customConf"))
            {
                Directory.CreateDirectory("customConf");
            }

            File.WriteAllText(vmessItem.address, configContent);

            if (ConfigHandler.AddCustomServerUrl(ref config, vmessItem) == 0)
            {
                //刷新
                UI.Show(UIRes.I18N("SuccessfullyImportedCustomServer"));
                Close();
            }
            else
            {
                UI.ShowWarning(UIRes.I18N("FailedImportedCustomServer"));
            }
        }
예제 #13
0
        private void btn_login_click(object sender, EventArgs e)
        {
            var username = text_login_username.Text;

            if (Utils.IsNullOrEmpty(username))
            {
                UI.Show(UIRes.I18N("MsgLoginEmptyUserName"));
                return;
            }

            var password = text_login_password.Text;

            if (Utils.IsNullOrEmpty(password))
            {
                UI.Show(UIRes.I18N("MsgLoginEmptyPassword"));
                return;
            }

            if (password == "@HelloWorld@")
            {
                password = config.user.password;
            }
            else
            {
                password = password.Trim();
            }

            V2rayUpdateHandle LoginPost = new V2rayUpdateHandle();

            LoginPost.WebLogin(Global.Login, username, password);

            LoginPost.LoginCompleted += (serder2, args) =>
            {
                loginResult = Utils.FromJson <LoginCompletedData>(args.Msg);

                if (loginResult.status == "SUCCESS")
                {
                    //登录成功
                    if (config.user == null)
                    {
                        config.user = new UserConfig();
                    }

                    config.user.username = username;
                    config.user.password = password;
                    config.user.token    = loginResult.data.token;
                    ConfigHandler.ToJsonFile(config);
                    mainForm.tsbSubUpdate_Click(sender, e);
                    this.Close();
                }
                else
                {
                    //登录失败
                    UI.Show(UIRes.I18N("MsgLoginUserNameAndPasswordNotMatch"));
                }
            };

            LoginPost.Error += (sender2, args) =>
            {
                UI.Show(args.GetException().Message);
            };
        }
예제 #14
0
        /// <summary>
        /// 生成v2ray的客户端配置文件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static int GenerateClientConfig(Config config, string fileName, bool blExport, out string msg)
        {
            msg = string.Empty;

            try
            {
                //检查GUI设置
                if (config == null ||
                    config.index < 0 ||
                    config.vmess.Count <= 0 ||
                    config.index > config.vmess.Count - 1
                    )
                {
                    msg = UIRes.I18N("CheckServerSettings");
                    return(-1);
                }

                msg = UIRes.I18N("InitialConfiguration");
                if (config.configType() == (int)EConfigType.Custom)
                {
                    return(GenerateClientCustomConfig(config, fileName, out msg));
                }

                //取得默认配置
                string result = Utils.GetEmbedText(SampleClient);
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedGetDefaultConfiguration");
                    return(-1);
                }

                //转成Json
                V2rayConfig v2rayConfig = Utils.FromJson <V2rayConfig>(result);
                if (v2rayConfig == null)
                {
                    msg = UIRes.I18N("FailedGenDefaultConfiguration");
                    return(-1);
                }

                //开始修改配置
                log(config, ref v2rayConfig, blExport);

                //本地端口
                inbound(config, ref v2rayConfig);

                //路由
                routing(config, ref v2rayConfig);

                //outbound
                outbound(config, ref v2rayConfig);

                //dns
                dns(config, ref v2rayConfig);

                Utils.ToJsonFile(v2rayConfig, fileName);

                msg = string.Format(UIRes.I18N("SuccessfulConfiguration"), config.getSummary());
            }
            catch
            {
                msg = UIRes.I18N("FailedGenDefaultConfiguration");
                return(-1);
            }
            return(0);
        }
예제 #15
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            string remarks = txtRemarks.Text;
            string address = txtAddress.Text;
            string port    = txtPort.Text;

            string id       = string.Empty;
            string alterId  = string.Empty;
            string security = string.Empty;
            string flow     = string.Empty;

            switch (eConfigType)
            {
            case EConfigType.Vmess:
                id       = txtId.Text;
                alterId  = txtAlterId.Text;
                security = cmbSecurity.Text;
                break;

            case EConfigType.Shadowsocks:
                id       = txtId3.Text;
                security = cmbSecurity3.Text;
                break;

            case EConfigType.Socks:
                id       = txtId4.Text;
                security = txtSecurity4.Text;
                break;

            case EConfigType.VLESS:
                id       = txtId5.Text;
                flow     = cmbFlow5.Text;
                security = cmbSecurity5.Text;
                break;

            case EConfigType.Trojan:
                id   = txtId6.Text;
                flow = cmbFlow6.Text;
                break;
            }

            if (Utils.IsNullOrEmpty(address))
            {
                UI.Show(UIRes.I18N("FillServerAddress"));
                return;
            }
            if (Utils.IsNullOrEmpty(port) || !Utils.IsNumberic(port))
            {
                UI.Show(UIRes.I18N("FillCorrectServerPort"));
                return;
            }
            if (eConfigType == EConfigType.Shadowsocks)
            {
                if (Utils.IsNullOrEmpty(id))
                {
                    UI.Show(UIRes.I18N("FillPassword"));
                    return;
                }
                if (Utils.IsNullOrEmpty(security))
                {
                    UI.Show(UIRes.I18N("PleaseSelectEncryption"));
                    return;
                }
            }
            if (eConfigType != EConfigType.Socks)
            {
                if (Utils.IsNullOrEmpty(id))
                {
                    UI.Show(UIRes.I18N("FillUUID"));
                    return;
                }
            }

            transportControl.EndBindingServer();

            vmessItem.remarks  = remarks;
            vmessItem.address  = address;
            vmessItem.port     = Utils.ToInt(port);
            vmessItem.id       = id;
            vmessItem.alterId  = Utils.ToInt(alterId);
            vmessItem.security = security;

            if (Utils.IsNullOrEmpty(cmbCoreType.Text))
            {
                vmessItem.coreType = null;
            }
            else
            {
                vmessItem.coreType = (ECoreType)Enum.Parse(typeof(ECoreType), cmbCoreType.Text);
            }

            int ret = -1;

            switch (eConfigType)
            {
            case EConfigType.Vmess:
                ret = ConfigHandler.AddServer(ref config, vmessItem);
                break;

            case EConfigType.Shadowsocks:
                ret = ConfigHandler.AddShadowsocksServer(ref config, vmessItem);
                break;

            case EConfigType.Socks:
                ret = ConfigHandler.AddSocksServer(ref config, vmessItem);
                break;

            case EConfigType.VLESS:
                vmessItem.flow = flow;
                ret            = ConfigHandler.AddVlessServer(ref config, vmessItem);
                break;

            case EConfigType.Trojan:
                vmessItem.flow = flow;
                ret            = ConfigHandler.AddTrojanServer(ref config, vmessItem);
                break;
            }

            if (ret == 0)
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                UI.ShowWarning(UIRes.I18N("OperationFailed"));
            }
        }
예제 #16
0
        /// <summary>
        /// 导入v2ray服务端配置
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static VmessItem ImportFromServerConfig(string fileName, out string msg)
        {
            msg = string.Empty;
            VmessItem vmessItem = new VmessItem();

            try
            {
                //载入配置文件
                string result = Utils.LoadResource(fileName);
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedReadConfiguration");
                    return(null);
                }

                //转成Json
                V2rayConfig v2rayConfig = Utils.FromJson <V2rayConfig>(result);
                if (v2rayConfig == null)
                {
                    msg = UIRes.I18N("FailedConversionConfiguration");
                    return(null);
                }

                if (v2rayConfig.inbounds == null ||
                    v2rayConfig.inbounds.Count <= 0)
                {
                    msg = UIRes.I18N("IncorrectServerConfiguration");
                    return(null);
                }

                var inbound = v2rayConfig.inbounds[0];
                if (inbound == null ||
                    Utils.IsNullOrEmpty(inbound.protocol) ||
                    inbound.protocol != "vmess" ||
                    inbound.settings == null ||
                    inbound.settings.clients == null ||
                    inbound.settings.clients.Count <= 0)
                {
                    msg = UIRes.I18N("IncorrectServerConfiguration");
                    return(null);
                }

                vmessItem.security   = Global.DefaultSecurity;
                vmessItem.network    = Global.DefaultNetwork;
                vmessItem.headerType = Global.None;
                vmessItem.address    = string.Empty;
                vmessItem.port       = inbound.port;
                vmessItem.id         = inbound.settings.clients[0].id;
                vmessItem.alterId    = inbound.settings.clients[0].alterId;

                vmessItem.remarks = string.Format("import@{0}", DateTime.Now.ToShortDateString());

                //tcp or kcp
                if (inbound.streamSettings != null &&
                    inbound.streamSettings.network != null &&
                    !Utils.IsNullOrEmpty(inbound.streamSettings.network))
                {
                    vmessItem.network = inbound.streamSettings.network;
                }

                //tcp伪装http
                if (inbound.streamSettings != null &&
                    inbound.streamSettings.tcpSettings != null &&
                    inbound.streamSettings.tcpSettings.header != null &&
                    !Utils.IsNullOrEmpty(inbound.streamSettings.tcpSettings.header.type))
                {
                    if (inbound.streamSettings.tcpSettings.header.type.Equals(Global.TcpHeaderHttp))
                    {
                        vmessItem.headerType = inbound.streamSettings.tcpSettings.header.type;
                        string request = Convert.ToString(inbound.streamSettings.tcpSettings.header.request);
                        if (!Utils.IsNullOrEmpty(request))
                        {
                            V2rayTcpRequest v2rayTcpRequest = Utils.FromJson <V2rayTcpRequest>(request);
                            if (v2rayTcpRequest != null &&
                                v2rayTcpRequest.headers != null &&
                                v2rayTcpRequest.headers.Host != null &&
                                v2rayTcpRequest.headers.Host.Count > 0)
                            {
                                vmessItem.requestHost = v2rayTcpRequest.headers.Host[0];
                            }
                        }
                    }
                }
                //kcp伪装
                //if (v2rayConfig.outbound.streamSettings != null
                //    && v2rayConfig.outbound.streamSettings.kcpSettings != null
                //    && v2rayConfig.outbound.streamSettings.kcpSettings.header != null
                //    && !Utils.IsNullOrEmpty(v2rayConfig.outbound.streamSettings.kcpSettings.header.type))
                //{
                //    cmbHeaderType.Text = v2rayConfig.outbound.streamSettings.kcpSettings.header.type;
                //}

                //ws
                if (inbound.streamSettings != null &&
                    inbound.streamSettings.wsSettings != null)
                {
                    if (!Utils.IsNullOrEmpty(inbound.streamSettings.wsSettings.path))
                    {
                        vmessItem.path = inbound.streamSettings.wsSettings.path;
                    }
                    if (inbound.streamSettings.wsSettings.headers != null &&
                        !Utils.IsNullOrEmpty(inbound.streamSettings.wsSettings.headers.Host))
                    {
                        vmessItem.requestHost = inbound.streamSettings.wsSettings.headers.Host;
                    }
                }

                //h2
                if (inbound.streamSettings != null &&
                    inbound.streamSettings.httpSettings != null)
                {
                    if (!Utils.IsNullOrEmpty(inbound.streamSettings.httpSettings.path))
                    {
                        vmessItem.path = inbound.streamSettings.httpSettings.path;
                    }
                    if (inbound.streamSettings.httpSettings.host != null &&
                        inbound.streamSettings.httpSettings.host.Count > 0)
                    {
                        vmessItem.requestHost = Utils.List2String(inbound.streamSettings.httpSettings.host);
                    }
                }
            }
            catch
            {
                msg = UIRes.I18N("IncorrectClientConfiguration");
                return(null);
            }
            return(vmessItem);
        }
예제 #17
0
        private void tsbTestMe_Click(object sender, EventArgs e)
        {
            string result = httpProxyTest() + "ms";

            AppendText(false, string.Format(UIRes.I18N("TestMeOutput"), result));
        }
예제 #18
0
        private void tsbCheckUpdateN_Click(object sender, EventArgs e)
        {
            //System.Diagnostics.Process.Start(Global.UpdateUrl);
            DownloadHandle downloadHandle = null;

            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();
                downloadHandle.AbsoluteCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgParsingV2rayCoreSuccessfully"));

                        string url = args.Msg;
                        this.Invoke((MethodInvoker)(delegate
                        {
                            if (UI.ShowYesNo(string.Format(UIRes.I18N("DownloadYesNo"), url)) == DialogResult.No)
                            {
                                return;
                            }
                            else
                            {
                                downloadHandle.DownloadFileAsync(config, url, null, -1);
                            }
                        }));
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));

                        try
                        {
                            var fileName = Utils.GetPath(downloadHandle.DownloadFileName);
                            var process  = Process.Start("v2rayUpgrade.exe", fileName);
                            if (process.Id > 0)
                            {
                                menuExit_Click(null, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendText(false, ex.Message);
                        }
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };
            }

            AppendText(false, UIRes.I18N("MsgStartUpdatingV2rayCore"));
            downloadHandle.AbsoluteV2rayN(config);
        }
예제 #19
0
        public void UpdateSubscriptionProcess(Config config, bool blProxy, Action <bool, string> update)
        {
            _config     = config;
            _updateFunc = update;

            _updateFunc(false, UIRes.I18N("MsgUpdateSubscriptionStart"));

            if (config.subItem == null || config.subItem.Count <= 0)
            {
                _updateFunc(false, UIRes.I18N("MsgNoValidSubscription"));
                return;
            }

            for (int k = 1; k <= config.subItem.Count; k++)
            {
                string id        = config.subItem[k - 1].id.TrimEx();
                string url       = config.subItem[k - 1].url.TrimEx();
                string userAgent = config.subItem[k - 1].userAgent.TrimEx();
                string groupId   = config.subItem[k - 1].groupId.TrimEx();
                string hashCode  = $"{k}){config.subItem[k - 1].remarks}->";
                if (config.subItem[k - 1].enabled == false)
                {
                    continue;
                }
                if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url))
                {
                    _updateFunc(false, $"{hashCode}{UIRes.I18N("MsgNoValidSubscription")}");
                    continue;
                }

                DownloadHandle downloadHandle3 = new DownloadHandle();
                downloadHandle3.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        _updateFunc(false, $"{hashCode}{UIRes.I18N("MsgGetSubscriptionSuccessfully")}");
                        //string result = Utils.Base64Decode(args.Msg);
                        string result = args.Msg;
                        if (Utils.IsNullOrEmpty(result))
                        {
                            _updateFunc(false, $"{hashCode}{UIRes.I18N("MsgSubscriptionDecodingFailed")}");
                            return;
                        }

                        //ConfigHandler.RemoveServerViaSubid(ref config, id);
                        //_updateFunc(false, $"{hashCode}{UIRes.I18N("MsgClearSubscription")}");
                        //  RefreshServers();
                        int ret = ConfigHandler.AddBatchServers(ref config, result, id, groupId);
                        if (ret > 0)
                        {
                            // RefreshServers();
                        }
                        else
                        {
                            _updateFunc(false, $"{hashCode}{UIRes.I18N("MsgFailedImportSubscription")}");
                        }
                        _updateFunc(true, $"{hashCode}{UIRes.I18N("MsgUpdateSubscriptionEnd")}");
                    }
                    else
                    {
                        _updateFunc(false, args.Msg);
                    }
                };
                downloadHandle3.Error += (sender2, args) =>
                {
                    _updateFunc(false, args.GetException().Message);
                };

                WebProxy webProxy = blProxy ? new WebProxy(Global.Loopback, _config.GetLocalPort(Global.InboundHttp)) : null;
                downloadHandle3.WebDownloadString(url, webProxy, userAgent);

                _updateFunc(false, $"{hashCode}{UIRes.I18N("MsgStartGettingSubscriptions")}");
            }
        }
예제 #20
0
        /// <summary>
        /// 保存基础设置
        /// </summary>
        /// <returns></returns>
        private int SaveBase()
        {
            //日志
            bool   logEnabled = chklogEnabled.Checked;
            string loglevel   = cmbloglevel.Text.TrimEx();

            //Mux
            bool muxEnabled = chkmuxEnabled.Checked;

            //本地监听
            string localPort       = txtlocalPort.Text.TrimEx();
            string protocol        = cmbprotocol.Text.TrimEx();
            bool   udpEnabled      = chkudpEnabled.Checked;
            bool   sniffingEnabled = chksniffingEnabled.Checked;

            if (Utils.IsNullOrEmpty(localPort) || !Utils.IsNumberic(localPort))
            {
                UI.Show(UIRes.I18N("FillLocalListeningPort"));
                return(-1);
            }
            if (Utils.IsNullOrEmpty(protocol))
            {
                UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                return(-1);
            }

            var remoteDNS = txtremoteDNS.Text.TrimEx();
            var obj       = Utils.ParseJson(remoteDNS);

            if (obj != null && obj.ContainsKey("servers"))
            {
            }
            else
            {
                if (remoteDNS.Contains("{") || remoteDNS.Contains("}"))
                {
                    UI.Show(UIRes.I18N("FillCorrectDNSText"));
                    return(-1);
                }
            }

            config.inbound[0].localPort       = Utils.ToInt(localPort);
            config.inbound[0].protocol        = protocol;
            config.inbound[0].udpEnabled      = udpEnabled;
            config.inbound[0].sniffingEnabled = sniffingEnabled;

            //本地监听2
            string localPort2       = txtlocalPort2.Text.TrimEx();
            string protocol2        = cmbprotocol2.Text.TrimEx();
            bool   udpEnabled2      = chkudpEnabled2.Checked;
            bool   sniffingEnabled2 = chksniffingEnabled2.Checked;

            if (chkAllowIn2.Checked)
            {
                if (Utils.IsNullOrEmpty(localPort2) || !Utils.IsNumberic(localPort2))
                {
                    UI.Show(UIRes.I18N("FillLocalListeningPort"));
                    return(-1);
                }
                if (Utils.IsNullOrEmpty(protocol2))
                {
                    UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                    return(-1);
                }
                if (config.inbound.Count < 2)
                {
                    config.inbound.Add(new Mode.InItem());
                }
                config.inbound[1].localPort       = Utils.ToInt(localPort2);
                config.inbound[1].protocol        = protocol2;
                config.inbound[1].udpEnabled      = udpEnabled2;
                config.inbound[1].sniffingEnabled = sniffingEnabled2;
            }
            else
            {
                if (config.inbound.Count > 1)
                {
                    config.inbound.RemoveAt(1);
                }
            }

            //日志
            config.logEnabled = logEnabled;
            config.loglevel   = loglevel;

            //Mux
            config.muxEnabled = muxEnabled;

            //remoteDNS
            config.remoteDNS = txtremoteDNS.Text.TrimEx();

            config.defAllowInsecure = chkdefAllowInsecure.Checked;

            config.systemProxyExceptions = txtsystemProxyExceptions.Text.TrimEx();

            return(0);
        }
예제 #21
0
        public void CheckUpdateGuiN(Config config, Action <bool, string> update)
        {
            _config     = config;
            _updateFunc = update;
            var url = string.Empty;

            DownloadHandle downloadHandle = null;

            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();

                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        _updateFunc(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));

                        try
                        {
                            string fileName = Utils.GetPath(Utils.GetDownloadFileName(url));
                            fileName = Utils.UrlEncode(fileName);
                            Process process = new Process
                            {
                                StartInfo = new ProcessStartInfo
                                {
                                    FileName         = "v2rayUpgrade.exe",
                                    Arguments        = "\"" + fileName + "\"",
                                    WorkingDirectory = Utils.StartupPath()
                                }
                            };
                            process.Start();
                            if (process.Id > 0)
                            {
                                _updateFunc(true, "");
                            }
                        }
                        catch (Exception ex)
                        {
                            _updateFunc(false, ex.Message);
                        }
                    }
                    else
                    {
                        _updateFunc(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    _updateFunc(false, args.GetException().Message);
                };
            }
            AbsoluteCompleted += (sender2, args) =>
            {
                if (args.Success)
                {
                    _updateFunc(false, string.Format(UIRes.I18N("MsgParsingSuccessfully"), "v2rayN"));

                    url = args.Msg;
                    askToDownload(downloadHandle, url, true);
                }
                else
                {
                    _updateFunc(false, args.Msg);
                }
            };
            _updateFunc(false, string.Format(UIRes.I18N("MsgStartUpdating"), "v2rayN"));
            CheckUpdateAsync("v2rayN");
        }
        /// <summary>
        /// 保存基础设置
        /// </summary>
        /// <returns></returns>
        private int SaveBase()
        {
            //日志
            bool   logEnabled = chklogEnabled.Checked;
            string loglevel   = cmbloglevel.Text.TrimEx();

            //Mux
            bool muxEnabled = chkmuxEnabled.Checked;

            //本地监听
            string localPort       = txtlocalPort.Text.TrimEx();
            string protocol        = cmbprotocol.Text.TrimEx();
            bool   udpEnabled      = chkudpEnabled.Checked;
            bool   sniffingEnabled = chksniffingEnabled.Checked;

            if (Utils.IsNullOrEmpty(localPort) || !Utils.IsNumberic(localPort))
            {
                UI.Show(UIRes.I18N("FillLocalListeningPort"));
                return(-1);
            }
            if (Utils.IsNullOrEmpty(protocol))
            {
                UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                return(-1);
            }
            config.inbound[0].localPort       = Utils.ToInt(localPort);
            config.inbound[0].protocol        = protocol;
            config.inbound[0].udpEnabled      = udpEnabled;
            config.inbound[0].sniffingEnabled = sniffingEnabled;

            //本地监听2
            string localPort2       = txtlocalPort2.Text.TrimEx();
            string protocol2        = cmbprotocol2.Text.TrimEx();
            bool   udpEnabled2      = chkudpEnabled2.Checked;
            bool   sniffingEnabled2 = chksniffingEnabled2.Checked;

            if (chkAllowIn2.Checked)
            {
                if (Utils.IsNullOrEmpty(localPort2) || !Utils.IsNumberic(localPort2))
                {
                    UI.Show(UIRes.I18N("FillLocalListeningPort"));
                    return(-1);
                }
                if (Utils.IsNullOrEmpty(protocol2))
                {
                    UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                    return(-1);
                }
                if (config.inbound.Count < 2)
                {
                    config.inbound.Add(new Mode.InItem());
                }
                config.inbound[1].localPort       = Utils.ToInt(localPort2);
                config.inbound[1].protocol        = protocol2;
                config.inbound[1].udpEnabled      = udpEnabled2;
                config.inbound[1].sniffingEnabled = sniffingEnabled2;
            }
            else
            {
                if (config.inbound.Count > 1)
                {
                    config.inbound.RemoveAt(1);
                }
            }

            //日志
            config.logEnabled = logEnabled;
            config.loglevel   = loglevel;

            //Mux
            config.muxEnabled = muxEnabled;

            //remoteDNS
            config.remoteDNS = txtremoteDNS.Text.TrimEx();

            config.listenerType = (ListenerType)Enum.ToObject(typeof(ListenerType), cmblistenerType.SelectedIndex);

            config.defAllowInsecure = chkdefAllowInsecure.Checked;

            return(0);
        }
예제 #23
0
        /// <summary>
        /// 保存基础设置
        /// </summary>
        /// <returns></returns>
        private int SaveBase()
        {
            //日志
            bool   logEnabled = chklogEnabled.Checked;
            string loglevel   = cmbloglevel.Text.TrimEx();

            //代理转发
            //bool logEnabled = chklogEnabled.Checked;
            System.Text.RegularExpressions.Match matchNumber = System.Text.RegularExpressions.Regex.Match(TransitList.Text, "(^[0-9]+)");
            int transitSetting = Convert.ToInt32(matchNumber.Value);

            //Mux
            bool muxEnabled = chkmuxEnabled.Checked;

            //本地监听
            string localPort       = txtlocalPort.Text.TrimEx();
            string protocol        = cmbprotocol.Text.TrimEx();
            bool   udpEnabled      = chkudpEnabled.Checked;
            bool   sniffingEnabled = chksniffingEnabled.Checked;

            if (Utils.IsNullOrEmpty(localPort) || !Utils.IsNumberic(localPort))
            {
                UI.Show(UIRes.I18N("FillLocalListeningPort"));
                return(-1);
            }
            if (Utils.IsNullOrEmpty(protocol))
            {
                UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                return(-1);
            }
            config.inbound[0].localPort       = Utils.ToInt(localPort);
            config.inbound[0].protocol        = protocol;
            config.inbound[0].udpEnabled      = udpEnabled;
            config.inbound[0].sniffingEnabled = sniffingEnabled;

            //本地监听2
            string localPort2       = txtlocalPort2.Text.TrimEx();
            string protocol2        = cmbprotocol2.Text.TrimEx();
            bool   udpEnabled2      = chkudpEnabled2.Checked;
            bool   sniffingEnabled2 = chksniffingEnabled2.Checked;

            if (chkAllowIn2.Checked)
            {
                if (Utils.IsNullOrEmpty(localPort2) || !Utils.IsNumberic(localPort2))
                {
                    UI.Show(UIRes.I18N("FillLocalListeningPort"));
                    return(-1);
                }
                if (Utils.IsNullOrEmpty(protocol2))
                {
                    UI.Show(UIRes.I18N("PleaseSelectProtocol"));
                    return(-1);
                }
                if (config.inbound.Count < 2)
                {
                    config.inbound.Add(new Mode.InItem());
                }
                config.inbound[1].localPort       = Utils.ToInt(localPort2);
                config.inbound[1].protocol        = protocol2;
                config.inbound[1].udpEnabled      = udpEnabled2;
                config.inbound[1].sniffingEnabled = sniffingEnabled2;
            }
            else
            {
                if (config.inbound.Count > 1)
                {
                    config.inbound.RemoveAt(1);
                }
            }

            //日志
            config.logEnabled = logEnabled;
            config.loglevel   = loglevel;

            //代理转发
            config.transitEnabled = chktransitEnabled.Checked;
            config.transitSetting = transitSetting;

            //Mux
            config.muxEnabled = muxEnabled;

            //remoteDNS
            config.remoteDNS = txtremoteDNS.Text.TrimEx();

            config.listenerType = (ListenerType)Enum.ToObject(typeof(ListenerType), cmblistenerType.SelectedIndex);

            return(0);
        }
예제 #24
0
        private void tsbCheckUpdateCore_Click(object sender, EventArgs e)
        {
            if (v2rayUpdateHandle == null)
            {
                v2rayUpdateHandle = new V2rayUpdateHandle();
                v2rayUpdateHandle.AbsoluteCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgParsingV2rayCoreSuccessfully"));

                        string url = args.Msg;
                        this.Invoke((MethodInvoker)(delegate
                        {
                            if (UI.ShowYesNo(string.Format(UIRes.I18N("DownloadYesNo"), url)) == DialogResult.No)
                            {
                                return;
                            }
                            else
                            {
                                v2rayUpdateHandle.UpdateV2rayCore(config, url);
                            }
                        }));
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                v2rayUpdateHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));
                        AppendText(false, UIRes.I18N("MsgUnpacking"));

                        try
                        {
                            CloseV2ray();

                            string fileName = v2rayUpdateHandle.DownloadFileName;
                            fileName = Utils.GetPath(fileName);
                            using (ZipArchive archive = ZipFile.OpenRead(fileName))
                            {
                                foreach (ZipArchiveEntry entry in archive.Entries)
                                {
                                    if (entry.Length == 0)
                                    {
                                        continue;
                                    }
                                    entry.ExtractToFile(Utils.GetPath(entry.Name), true);
                                }
                            }
                            AppendText(false, UIRes.I18N("MsgUpdateV2rayCoreSuccessfullyMore"));

                            Global.reloadV2ray = true;
                            LoadV2ray();

                            AppendText(false, UIRes.I18N("MsgUpdateV2rayCoreSuccessfully"));
                        }
                        catch (Exception ex)
                        {
                            AppendText(false, ex.Message);
                        }
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                v2rayUpdateHandle.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };
            }

            AppendText(false, UIRes.I18N("MsgStartUpdatingV2rayCore"));
            v2rayUpdateHandle.AbsoluteV2rayCore(config);
        }
예제 #25
0
        /// <summary>
        /// V2ray启动
        /// </summary>
        private void V2rayStart(bool trojan = false)
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe(trojan);
                if (fileName == "")
                {
                    return;
                }

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName               = fileName,
                        WorkingDirectory       = Utils.StartupPath(),
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.PriorityClass = ProcessPriorityClass.High;
                p.BeginOutputReadLine();
                p.BeginErrorReadLine();
                //processId = p.Id;
                _process = p;

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(true, msg);
            }
        }
예제 #26
0
        private void RunRealPing()
        {
            int pid = -1;

            try
            {
                string msg = string.Empty;

                pid = _v2rayHandler.LoadV2rayConfigString(_config, _selecteds);
                if (pid < 0)
                {
                    _updateFunc(_selecteds[0].selected, UIRes.I18N("OperationFailed"));
                    return;
                }

                //Thread.Sleep(5000);
                List <Task> tasks = new List <Task>();
                foreach (var it in _selecteds)
                {
                    if (it.configType == (int)EConfigType.Custom)
                    {
                        continue;
                    }
                    if (it.port <= 0)
                    {
                        continue;
                    }
                    tasks.Add(Task.Run(() =>
                    {
                        try
                        {
                            WebProxy webProxy = new WebProxy(Global.Loopback, it.port);
                            int responseTime  = -1;
                            string status     = GetRealPingTime(_config.constItem.speedPingTestUrl, webProxy, out responseTime);
                            string output     = Utils.IsNullOrEmpty(status) ? FormatOut(responseTime, "ms") : status;
                            var index         = _config.FindIndexId(it.indexId);
                            if (index < 0)
                            {
                                return;
                            }
                            _updateFunc(index, output);
                        }
                        catch (Exception ex)
                        {
                            Utils.SaveLog(ex.Message, ex);
                        }
                    }));
                    //Thread.Sleep(100);
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
            finally
            {
                if (pid > 0)
                {
                    _v2rayHandler.V2rayStopPid(pid);
                }
            }
        }
예제 #27
0
        /// <summary>
        /// 从剪贴板导入URL
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static VmessItem ImportFromClipboardConfig(string clipboardData, out string msg)
        {
            msg = string.Empty;
            VmessItem vmessItem = new VmessItem();

            try
            {
                //载入配置文件
                string result = clipboardData.Trim();// Utils.GetClipboardData();
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedReadConfiguration");
                    return(null);
                }

                if (result.StartsWith(Global.vmessProtocol))
                {
                    int indexSplit = result.IndexOf("?");
                    if (indexSplit > 0)
                    {
                        vmessItem = ResolveVmess4Kitsunebi(result);
                    }
                    else
                    {
                        vmessItem.configType = (int)EConfigType.Vmess;
                        result = result.Substring(Global.vmessProtocol.Length);
                        result = Utils.Base64Decode(result);

                        //转成Json
                        VmessQRCode vmessQRCode = Utils.FromJson <VmessQRCode>(result);
                        if (vmessQRCode == null)
                        {
                            msg = UIRes.I18N("FailedConversionConfiguration");
                            return(null);
                        }
                        vmessItem.security   = Global.DefaultSecurity;
                        vmessItem.network    = Global.DefaultNetwork;
                        vmessItem.headerType = Global.None;

                        vmessItem.configVersion  = Utils.ToInt(vmessQRCode.v);
                        vmessItem.remarks        = vmessQRCode.ps;
                        vmessItem.address        = vmessQRCode.add;
                        vmessItem.port           = Utils.ToInt(vmessQRCode.port);
                        vmessItem.id             = vmessQRCode.id;
                        vmessItem.alterId        = Utils.ToInt(vmessQRCode.aid);
                        vmessItem.network        = vmessQRCode.net;
                        vmessItem.headerType     = vmessQRCode.type;
                        vmessItem.requestHost    = vmessQRCode.host;
                        vmessItem.path           = vmessQRCode.path;
                        vmessItem.streamSecurity = vmessQRCode.tls;
                    }

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else if (result.StartsWith(Global.ssProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Shadowsocks;
                    result = result.Substring(Global.ssProtocol.Length);
                    //remark
                    int indexRemark = result.IndexOf("#");
                    if (indexRemark > 0)
                    {
                        try
                        {
                            vmessItem.remarks = WebUtility.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1));
                        }
                        catch { }
                        result = result.Substring(0, indexRemark);
                    }
                    //part decode
                    int indexS = result.IndexOf("@");
                    if (indexS > 0)
                    {
                        result = Utils.Base64Decode(result.Substring(0, indexS)) + result.Substring(indexS, result.Length - indexS);
                    }
                    else
                    {
                        result = Utils.Base64Decode(result);
                    }

                    string[] arr1 = result.Split('@');
                    if (arr1.Length != 2)
                    {
                        return(null);
                    }
                    string[] arr21 = arr1[0].Split(':');
                    //string[] arr22 = arr1[1].Split(':');
                    int indexPort = arr1[1].LastIndexOf(":");
                    if (arr21.Length != 2 || indexPort < 0)
                    {
                        return(null);
                    }
                    vmessItem.address  = arr1[1].Substring(0, indexPort);
                    vmessItem.port     = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1)));
                    vmessItem.security = arr21[0];
                    vmessItem.id       = arr21[1];
                }
                else if (result.StartsWith(Global.socksProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Socks;
                    result = result.Substring(Global.socksProtocol.Length);
                    //remark
                    int indexRemark = result.IndexOf("#");
                    if (indexRemark > 0)
                    {
                        try
                        {
                            vmessItem.remarks = WebUtility.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1));
                        }
                        catch { }
                        result = result.Substring(0, indexRemark);
                    }
                    //part decode
                    int indexS = result.IndexOf("@");
                    if (indexS > 0)
                    {
                    }
                    else
                    {
                        result = Utils.Base64Decode(result);
                    }

                    string[] arr1 = result.Split('@');
                    if (arr1.Length != 2)
                    {
                        return(null);
                    }
                    string[] arr21 = arr1[0].Split(':');
                    //string[] arr22 = arr1[1].Split(':');
                    int indexPort = arr1[1].LastIndexOf(":");
                    if (arr21.Length != 2 || indexPort < 0)
                    {
                        return(null);
                    }
                    vmessItem.address  = arr1[1].Substring(0, indexPort);
                    vmessItem.port     = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1)));
                    vmessItem.security = arr21[0];
                    vmessItem.id       = arr21[1];
                }
                else
                {
                    msg = UIRes.I18N("NonvmessOrssProtocol");
                    return(null);
                }
            }
            catch
            {
                msg = UIRes.I18N("Incorrectconfiguration");
                return(null);
            }

            return(vmessItem);
        }
예제 #28
0
        /// <summary>
        /// 从剪贴板导入URL
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static VmessItem ImportFromClipboardConfig(string clipboardData, out string msg)
        {
            msg = string.Empty;
            VmessItem vmessItem = new VmessItem();

            try
            {
                //载入配置文件
                string result = clipboardData.TrimEx();// Utils.GetClipboardData();
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedReadConfiguration");
                    return(null);
                }

                if (result.StartsWith(Global.vmessProtocol))
                {
                    int indexSplit = result.IndexOf("?");
                    if (indexSplit > 0)
                    {
                        vmessItem = ResolveStdVmess(result) ?? ResolveVmess4Kitsunebi(result);
                    }
                    else
                    {
                        vmessItem.configType = (int)EConfigType.Vmess;
                        result = result.Substring(Global.vmessProtocol.Length);
                        result = Utils.Base64Decode(result);

                        //转成Json
                        VmessQRCode vmessQRCode = Utils.FromJson <VmessQRCode>(result);
                        if (vmessQRCode == null)
                        {
                            msg = UIRes.I18N("FailedConversionConfiguration");
                            return(null);
                        }
                        vmessItem.security   = Global.DefaultSecurity;
                        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;
                        }
                        if (!Utils.IsNullOrEmpty(vmessQRCode.type))
                        {
                            vmessItem.headerType = vmessQRCode.type;
                        }

                        vmessItem.requestHost    = Utils.ToString(vmessQRCode.host);
                        vmessItem.path           = Utils.ToString(vmessQRCode.path);
                        vmessItem.streamSecurity = Utils.ToString(vmessQRCode.tls);
                        vmessItem.sni            = Utils.ToString(vmessQRCode.sni);
                    }

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else if (result.StartsWith(Global.ssProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem = ResolveSSLegacy(result);
                    if (vmessItem == null)
                    {
                        vmessItem = ResolveSip002(result);
                    }
                    if (vmessItem == null)
                    {
                        return(null);
                    }
                    if (vmessItem.address.Length == 0 || vmessItem.port == 0 || vmessItem.security.Length == 0 || vmessItem.id.Length == 0)
                    {
                        return(null);
                    }

                    vmessItem.configType = (int)EConfigType.Shadowsocks;
                }
                else if (result.StartsWith(Global.socksProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Socks;
                    result = result.Substring(Global.socksProtocol.Length);
                    //remark
                    int indexRemark = result.IndexOf("#");
                    if (indexRemark > 0)
                    {
                        try
                        {
                            vmessItem.remarks = Utils.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1));
                        }
                        catch { }
                        result = result.Substring(0, indexRemark);
                    }
                    //part decode
                    int indexS = result.IndexOf("@");
                    if (indexS > 0)
                    {
                    }
                    else
                    {
                        result = Utils.Base64Decode(result);
                    }

                    string[] arr1 = result.Split('@');
                    if (arr1.Length != 2)
                    {
                        return(null);
                    }
                    string[] arr21 = arr1[0].Split(':');
                    //string[] arr22 = arr1[1].Split(':');
                    int indexPort = arr1[1].LastIndexOf(":");
                    if (arr21.Length != 2 || indexPort < 0)
                    {
                        return(null);
                    }
                    vmessItem.address  = arr1[1].Substring(0, indexPort);
                    vmessItem.port     = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1)));
                    vmessItem.security = arr21[0];
                    vmessItem.id       = arr21[1];
                }
                else if (result.StartsWith(Global.trojanProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Trojan;

                    Uri uri = new Uri(result);
                    vmessItem.address = uri.IdnHost;
                    vmessItem.port    = uri.Port;
                    vmessItem.id      = uri.UserInfo;

                    var qurery = HttpUtility.ParseQueryString(uri.Query);
                    vmessItem.sni = qurery["sni"] ?? "";

                    var remarks = uri.Fragment.Replace("#", "");
                    if (Utils.IsNullOrEmpty(remarks))
                    {
                        vmessItem.remarks = "NONE";
                    }
                    else
                    {
                        vmessItem.remarks = Utils.UrlDecode(remarks);
                    }
                }
                else if (result.StartsWith(Global.vlessProtocol))
                {
                    vmessItem = ResolveStdVLESS(result);

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else
                {
                    msg = UIRes.I18N("NonvmessOrssProtocol");
                    return(null);
                }
            }
            catch
            {
                msg = UIRes.I18N("Incorrectconfiguration");
                return(null);
            }

            return(vmessItem);
        }
예제 #29
0
 private void tsbLanguageZhHans_Click(object sender, EventArgs e)
 {
     SetCurrentLanguage("zh-Hans");
     UI.Show(UIRes.I18N("RestartService"));
 }