예제 #1
0
        /// <summary>
        ///     启动
        /// </summary>
        /// <param name="server">服务器</param>
        /// <param name="mode">模式</param>
        /// <returns>是否启动成功</returns>
        public static async Task <bool> Start(Server server, Mode mode)
        {
            Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}");

            if (server.IsSocks5() && mode.Type == 4)
            {
                return(false);
            }

            NativeMethods.FlushDNSResolverCache();

            try
            {
                WebUtil.BestLocalEndPoint(new IPEndPoint(0x72727272, 53));
            }
            catch (Exception)
            {
                MessageBoxX.Show("No internet connection");
                return(false);
            }

            if (DNS.Lookup(server.Hostname) == null)
            {
                MessageBoxX.Show("Lookup Server hostname failed");
                return(false);
            }

            _ = Task.Run(Firewall.AddNetchFwRules);

            try
            {
                if (!await StartServer(server, mode))
                {
                    throw new StartFailedException();
                }

                if (!await StartMode(server, mode))
                {
                    throw new StartFailedException();
                }

                if (ModeController?.TestNatRequired ?? false)
                {
                    NatTest();
                }

                return(true);
            }
            catch (Exception e)
            {
                switch (e)
                {
                case DllNotFoundException _:
                case FileNotFoundException _:
                    MessageBoxX.Show(e.Message + "\n\n" + i18N.Translate("Missing File or runtime components"), owner: Global.MainForm);
                    break;

                case StartFailedException _:
                case PortInUseException _:
                    break;

                default:
                    Logging.Error($"主控制器未处理异常: {e}");
                    break;
                }

                try
                {
                    await Stop();
                }
                catch
                {
                    // ignored
                }

                return(false);
            }
        }