Example #1
0
 public static void IsSsServerInfoValid(SsServerInfo server)
 {
     Utils.IsPortValid(server.server_port);
     Utils.IsPasswordNotEmpty(server.password);
     Utils.IsServerIPNotEmpty(server.server);
     Utils.IsServerIPNotEmpty(server.method);
 }
        public ConfigForm(ShadowsocksController controller)
        {
            InitializeComponent();

            this.Font = System.Drawing.SystemFonts.MessageBoxFont;
            this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon());
            this._lastSelectedSsServerInfo = null;
            this._ssController = controller;
            controller.ConfigChanged += ssController_ConfigChanged;

            UpdateTexts();
            LoadCurrentConfiguration();
        }
        public bool AddServerBySSURL(string ssURL)
        {
            try
            {
                var server = new SsServerInfo(ssURL);
                _config.ServerInfos.Add(server);
                _config.selectedSsServerInfoIndex = _config.ServerInfos.Count - 1;

                SaveConfig(_config);
                return true;
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                return false;
            }
        }
        /**
         * once failed, try after 5 min
         * and (last write - last read) < 5s
         * and (now - last read) <  5s  // means not stuck
         * and latency < 200ms, try after 30s
         */
        public void ChooseNewServer()
        {
            SsServerInfo oldServer = _currentServer;
            List<ServerStatus> servers = new List<ServerStatus>(_serverStatus.Values);
            DateTime now = DateTime.Now;
            foreach (var status in servers)
            {
                // all of failure, latency, (lastread - lastwrite) normalized to 1000, then
                // 100 * failure - 2 * latency - 0.5 * (lastread - lastwrite)
                status.score =
                    100 * 1000 * Math.Min(5 * 60, (now - status.lastFailure).TotalSeconds)
                    - 2 * 5 * (Math.Min(2000, status.latency.TotalMilliseconds) / (1 + (now - status.lastTimeDetectLatency).TotalSeconds / 30 / 10) +
                    -0.5 * 200 * Math.Min(5, (status.lastRead - status.lastWrite).TotalSeconds));
                Logging.Debug(String.Format("server: {0} latency:{1} score: {2}", status.server.DisplayName(), status.latency, status.score));
            }
            ServerStatus max = null;
            foreach (var status in servers)
            {
                if (max == null)
                {
                    max = status;
                }
                else
                {
                    if (status.score >= max.score)
                    {
                        max = status;
                    }
                }
            }
            if (max != null)
            {
                _currentServer = max.server;
                if (_currentServer != oldServer)
                {
                    Console.WriteLine("HA switching to server: {0}", _currentServer.DisplayName());
                }

                Logging.Debug(String.Format("choosing server: {0}", _currentServer.DisplayName()));
            }
        }
        public void ParseRawHtml(Action<object> completedCallBack)
        {
            var rSsServerNames = "<div class=\"col-lg-4 text-center\">\\s*(.*?服务器地址.*?端口.*?加密方式.*?状态.*?)\\s*</div>";
            var results = Utils.MultiMatchSingleGroupWithRegex(rSsServerNames, _rRawHtml);
            {
                TheServerInfos = new List<SsServerInfo>();
                foreach (var item in results)
                {
                    var tempItem = new SsServerInfo();
                    //var rEmptyLabelSection = "<div class=\"dl\">\\s*<span class=\"dt\">\\s*</span>\\s*<div class=\"dd\">\\s*(.*?)\\s*</div>\\s*</div>";
                    var rServerIP = "<h4>(.*?)服务器地址:(.*?)</h4>";
                    var temp = Utils.SingleMatchTwoGroupsWithRegex(rServerIP, item);
                    var tServerNamePrefix = temp.Key;
                    tempItem.server = temp.Value;

                    var rServerPort = "<h4>端口:(.*?)</h4>";
                    tempItem.server_port = Convert.ToInt32(Utils.SingleMatchGroupWithRegex(rServerPort, item));

                    var rPassword = "******";
                    tempItem.password = Utils.SingleMatchGroupWithRegex(rPassword, item);

                    var rMethod = "<h4>加密方式:(.*?)</h4>";
                    tempItem.method = Utils.SingleMatchGroupWithRegex(rMethod, item);

                    var rStatus = "<h4>状态:<font color=\"green\">(.*?)</font></h4>";
                    var tempStatus = Utils.SingleMatchGroupWithRegex(rStatus, item);
                    tempItem.remarks = string.Format("iS-{0}-{1}", tServerNamePrefix, tempStatus);

                    TheServerInfos.Add(tempItem);
                }
            }

            // Process callback, should be data-saving-method
            if (completedCallBack != null)
            {
                //callBack.BeginInvoke(temps, null, null);
                completedCallBack(null);
            }
        }
        private void RemoveExpiredSsServerInfoFromConfig(SsServerInfo serverInfo)
        {
            try
            {
                var currentConfiguration = _controller.GetCurrentConfiguration();
                currentConfiguration.ServerInfos.Remove(serverInfo);
                _controller.SaveServers(currentConfiguration.ServerInfos, currentConfiguration.localPort);

                var aaa = string.Format("Expired ss-server ({0}) has been removed, {1} left", serverInfo.DisplayName(), currentConfiguration.ServerInfos.Count);
                Shadowsocks.View.MenuViewController.ShowBalloonTip("Info", aaa, System.Windows.Forms.ToolTipIcon.Warning, 1000);
            }
            catch (Exception ex)
            {
                Logging.LogUsefulException(ex);
            }
        }
        private void ConnectCallback(IAsyncResult ar)
        {
            SsServerInfo server = null;
            if (closed)
            {
                return;
            }
            try
            {
                var timer = (ServerTimer)ar.AsyncState;
                server = timer.Server;
                timer.Elapsed -= connectTimer_Elapsed;
                timer.Enabled = false;
                timer.Dispose();

                // Complete the connection.
                remote.EndConnect(ar);

                connected = true;

                //Console.WriteLine("Socket connected to {0}",
                //    remote.RemoteEndPoint.ToString());

                var latency = DateTime.Now - _startConnectTime;

                var strategy = controller.GetCurrentStrategy();
                if (strategy != null)
                {
                    strategy.UpdateLatency(server, latency);
                }

                StartPipe();
            }
            catch (ArgumentException e)
            {
            }
            catch (Exception e)
            {
                if (server != null)
                {
                    var strategy = controller.GetCurrentStrategy();
                    if (strategy != null)
                    {
                        strategy.SetFailure(server);
                    }
                }

                Logging.LogUsefulException(e);
                RetryConnect();
            }
        }
 public void CreateRemote()
 {
     SsServerInfo server = controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)connection.RemoteEndPoint);
     this.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
     this.server = server;
 }
        private void lbxServersList_SelectedIndexChanged(object sender, EventArgs e)
        {
            var itemDisplayName = Convert.ToString(lbxServersList.SelectedItem);
            var lastItemDisplayName = _lastSelectedSsServerInfo == null ? string.Empty : _lastSelectedSsServerInfo.DisplayName();

            var newSelectedIndex = lbxServersList.SelectedIndex;
            var lastSelectedIndex = _currentConfiguration.ServerInfos.FindIndex(o => o.DisplayName() == lastItemDisplayName);
            if (newSelectedIndex != lastSelectedIndex)
            {
                _lastSelectedSsServerInfo = _currentConfiguration.ServerInfos.Find(o => o.DisplayName() == itemDisplayName);
                RenderSelectedSsServerInfo();
            }

            // Record the last selected item index
            _oldSelectedItemIndex = lbxServersList.SelectedIndex;
        }
        public void ParseRawHtml(Action<object> completedCallBack)
        {
            TheServerInfos = new List<SsServerInfo>();
            var rSsServerNames = "<tr>\\s*<td>(.*?)</td>\\s*<td>(.*?)</td>\\s*<td>(.*?)</td>\\s*<td>(.*?)</td>\\s*<td>(.*?)</td>\\s*<td>(.*?)</td>\\s*</tr>";
            var matches = new System.Text.RegularExpressions.Regex(rSsServerNames, System.Text.RegularExpressions.RegexOptions.Singleline).Matches(_rRawHtml);
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var tempItem = new SsServerInfo();
                tempItem.remarks = match.Groups[1].ToString();
                tempItem.server = match.Groups[2].ToString();
                tempItem.server_port = Convert.ToInt32(match.Groups[3].ToString());
                tempItem.password = match.Groups[4].ToString();
                tempItem.method = match.Groups[5].ToString();
                var temp = match.Groups[6].ToString();
                TheServerInfos.Add(tempItem);
            }

            // Process callback, should be data-saving-method
            if (completedCallBack != null)
            {
                //callBack.BeginInvoke(temps, null, null);
                completedCallBack(null);
            }
        }