protected void Reload() { Encryption.RNG.Reload(); // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); if (privoxyRunner == null) { privoxyRunner = new PrivoxyRunner(); } if (_pacServer == null) { _pacServer = new PACServer(); _pacServer.PACFileChanged += pacServer_PACFileChanged; _pacServer.UserRuleFileChanged += pacServer_UserRuleFileChanged; } _pacServer.UpdatePACURL(_config); if (gfwListUpdater == null) { gfwListUpdater = new GFWListUpdater(); gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; gfwListUpdater.Error += pacServer_PACUpdateError; } //availabilityStatistics.UpdateConfiguration(this); if (_availabilityStatics == null) { _availabilityStatics = new AvailabilityStatistics(); _availabilityStatics.UpdateConfiguration(_config); } _listener?.Stop(); StopPlugins(); // don't put PrivoxyRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open privoxyRunner.Stop(); try { var strategy = GetCurrentStrategy(); strategy?.ReloadServers(); StartPlugin(); privoxyRunner.Start(_config); TCPRelay tcpRelay = new TCPRelay(this, _config); UDPRelay udpRelay = new UDPRelay(this); List <Listener.IService> services = new List <Listener.IService> { tcpRelay, udpRelay, _pacServer, new PortForwarder(privoxyRunner.RunningPort) }; _listener = new Listener(services); _listener.Start(_config); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException) { SocketException se = (SocketException)e; if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port already in use"), e); } } Logging.LogUsefulException(e); ReportError(e); } if (ConfigChanged != null) { ConfigChanged(this, new EventArgs()); } UpdateSystemProxy(); Utils.ReleaseMemory(true); }
protected void Reload() { Encryption.RNG.Reload(); // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); Configuration.Process(ref _config); NLogConfig.LoadConfiguration(); logger.Info($"WPF Localization Extension|Current culture: {LocalizeDictionary.CurrentCulture}"); // set User-Agent for httpClient try { if (!string.IsNullOrWhiteSpace(_config.userAgentString)) { httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString); } } catch { // reset userAgent to default and reapply Configuration.ResetUserAgent(_config); httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString); } StatisticsConfiguration = StatisticsStrategyConfiguration.Load(); privoxyRunner = privoxyRunner ?? new PrivoxyRunner(); _pacDaemon = _pacDaemon ?? new PACDaemon(_config); _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged; _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged; _pacServer = _pacServer ?? new PACServer(_pacDaemon); _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled. GeositeUpdater.ResetEvent(); GeositeUpdater.UpdateCompleted += PacServer_PACUpdateCompleted; GeositeUpdater.Error += PacServer_PACUpdateError; availabilityStatistics.UpdateConfiguration(this); _listener?.Stop(); StopPlugins(); // don't put PrivoxyRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open privoxyRunner.Stop(); try { var strategy = GetCurrentStrategy(); strategy?.ReloadServers(); StartPlugin(); privoxyRunner.Start(_config); TCPRelay tcpRelay = new TCPRelay(this, _config); tcpRelay.OnConnected += UpdateLatency; tcpRelay.OnInbound += UpdateInboundCounter; tcpRelay.OnOutbound += UpdateOutboundCounter; tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server); UDPRelay udpRelay = new UDPRelay(this); List <Listener.IService> services = new List <Listener.IService> { tcpRelay, udpRelay, _pacServer, new PortForwarder(privoxyRunner.RunningPort) }; _listener = new Listener(services); _listener.Start(_config); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException se) { if (se.SocketErrorCode == SocketError.AddressAlreadyInUse) { e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e); } else if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e); } } logger.LogUsefulException(e); ReportError(e); } ConfigChanged?.Invoke(this, new EventArgs()); UpdateSystemProxy(); }
public bool AskAddServerBySSURL(string ssURL) { var dr = MessageBox.Show(I18N.GetString("Import from URL: {0} ?", ssURL), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { if (AddServerBySSURL(ssURL)) { MessageBox.Show(I18N.GetString("Successfully imported from {0}", ssURL)); return(true); } else { MessageBox.Show(I18N.GetString("Failed to import. Please check if the link is valid.")); } } return(false); }
protected void Reload() { if (_port_map_listener != null) { foreach (var l in _port_map_listener) { l.Stop(); } _port_map_listener = null; } // some logic in configuration updated the config when saving, we need to read it again _config = MergeGetConfiguration(_config); _config.FlushPortMapCache(); Logging.save_to_file = _config.logEnable; Logging.OpenLogFile(); ReloadIPRange(); var hostMap = new HostMap(); hostMap.LoadHostFile(); HostMap.Instance().Clear(hostMap); if (privoxyRunner == null) { privoxyRunner = new HttpProxyRunner(); } if (_pacServer == null) { _pacServer = new PACServer(); _pacServer.PACFileChanged += pacServer_PACFileChanged; _pacServer.UserRuleFileChanged += pacServer_UserRuleFileChanged; } _pacServer.UpdateConfiguration(_config); if (gfwListUpdater == null) { gfwListUpdater = new GFWListUpdater(); gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; gfwListUpdater.Error += pacServer_PACUpdateError; } if (chnDomainsAndIPUpdater == null) { chnDomainsAndIPUpdater = new ChnDomainsAndIPUpdater(); chnDomainsAndIPUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; chnDomainsAndIPUpdater.Error += pacServer_PACUpdateError; } _listener?.Stop(); // don't put PrivoxyRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open try { privoxyRunner.Stop(); privoxyRunner.Start(_config); var local = new Local(_config, _transfer, _rangeSet); var services = new List <Listener.Service> { local, _pacServer, new APIServer(this, _config), new HttpPortForwarder(privoxyRunner.RunningPort, _config) }; _listener = new Listener(services); _listener.Start(_config, 0); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException se) { if (se.SocketErrorCode == SocketError.AddressAlreadyInUse) { e = new Exception(string.Format(I18N.GetString("Port {0} already in use"), _config.localPort), se); } else if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(string.Format(I18N.GetString("Port {0} is reserved by system"), _config.localPort), se); } } Logging.LogUsefulException(e); ReportError(e); } _port_map_listener = new List <Listener>(); foreach (var pair in _config.GetPortMapCache()) { try { var local = new Local(_config, _transfer, _rangeSet); var services = new List <Listener.Service> { local }; var listener = new Listener(services); listener.Start(_config, pair.Key); _port_map_listener.Add(listener); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException se) { if (se.SocketErrorCode == SocketError.AddressAlreadyInUse) { e = new Exception(string.Format(I18N.GetString("Port {0} already in use"), pair.Key), e); } else if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(string.Format(I18N.GetString("Port {0} is reserved by system"), pair.Key), se); } } Logging.LogUsefulException(e); ReportError(e); } } ConfigChanged?.Invoke(this, new EventArgs()); UpdateSystemProxy(); Utils.ReleaseMemory(); }
public static void Update(Configuration config, bool forceDisable) { bool global = config.global; bool enabled = config.enabled; if (forceDisable) { enabled = false; } RegistryKey registry = null; try { registry = Utils.OpenUserRegKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); if (registry == null) { Logging.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings"); return; } if (enabled) { if (global) { registry.SetValue("ProxyEnable", 1); registry.SetValue("ProxyServer", "127.0.0.1:" + config.localPort.ToString()); registry.SetValue("AutoConfigURL", ""); } else { string pacUrl; if (config.useOnlinePac && !config.pacUrl.IsNullOrEmpty()) { pacUrl = config.pacUrl; } else { pacUrl = $"http://127.0.0.1:{config.localPort}/pac?t={GetTimestamp( DateTime.Now )}"; } registry.SetValue("ProxyEnable", 0); var readProxyServer = registry.GetValue("ProxyServer"); registry.SetValue("ProxyServer", ""); registry.SetValue("AutoConfigURL", pacUrl); } } else { registry.SetValue("ProxyEnable", 0); registry.SetValue("ProxyServer", ""); registry.SetValue("AutoConfigURL", ""); } //Set AutoDetectProxy IEAutoDetectProxy(!enabled); NotifyIE(); //Must Notify IE first, or the connections do not chanage CopyProxySettingFromLan(); } catch (Exception e) { Logging.LogUsefulException(e); // TODO this should be moved into views MessageBox.Show(I18N.GetString("Failed to update registry")); } finally { if (registry != null) { try { registry.Close(); registry.Dispose(); } catch (Exception e) { Logging.LogUsefulException(e); } } } }
protected void Reload() { if (_port_map_listener != null) { foreach (Listener l in _port_map_listener) { l.Stop(); } _port_map_listener = null; } // some logic in configuration updated the config when saving, we need to read it again _config = MergeGetConfiguration(_config); _config.FlushPortMapCache(); ReloadIPRange(); HostMap hostMap = new HostMap(); hostMap.LoadHostFile(); HostMap.Instance().Clear(hostMap); #if !_CONSOLE if (polipoRunner == null) { polipoRunner = new HttpProxyRunner(); } #endif if (_pacServer == null) { _pacServer = new PACServer(); _pacServer.PACFileChanged += pacServer_PACFileChanged; } _pacServer.UpdateConfiguration(_config); if (gfwListUpdater == null) { gfwListUpdater = new GFWListUpdater(); gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; gfwListUpdater.Error += pacServer_PACUpdateError; } // don't put polipoRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open bool _firstRun = firstRun; for (int i = 1; i <= 5; ++i) { _firstRun = false; try { if (_listener != null && !_listener.isConfigChange(_config)) { Local local = new Local(_config, _transfer, _rangeSet); _listener.GetServices()[0] = local; #if !_CONSOLE if (polipoRunner.HasExited()) { polipoRunner.Stop(); polipoRunner.Start(_config); _listener.GetServices()[3] = new HttpPortForwarder(polipoRunner.RunningPort, _config); } #endif } else { if (_listener != null) { _listener.Stop(); _listener = null; } #if !_CONSOLE polipoRunner.Stop(); polipoRunner.Start(_config); #endif Local local = new Local(_config, _transfer, _rangeSet); List <Listener.Service> services = new List <Listener.Service>(); services.Add(local); services.Add(_pacServer); services.Add(new APIServer(this, _config)); #if !_CONSOLE services.Add(new HttpPortForwarder(polipoRunner.RunningPort, _config)); #endif _listener = new Listener(services); _listener.Start(_config, 0); } break; } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException) { SocketException se = (SocketException)e; if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port already in use") + string.Format(" {0}", _config.localPort), e); } } Logging.LogUsefulException(e); if (!_firstRun) { ReportError(e); break; } else { Thread.Sleep(1000 * i * i); } if (_listener != null) { _listener.Stop(); _listener = null; } } } _port_map_listener = new List <Listener>(); foreach (KeyValuePair <int, PortMapConfigCache> pair in _config.GetPortMapCache()) { try { Local local = new Local(_config, _transfer, _rangeSet); List <Listener.Service> services = new List <Listener.Service>(); services.Add(local); Listener listener = new Listener(services); listener.Start(_config, pair.Key); _port_map_listener.Add(listener); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException) { SocketException se = (SocketException)e; if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port already in use") + string.Format(" {0}", pair.Key), e); } } Logging.LogUsefulException(e); ReportError(e); } } ConfigChanged?.Invoke(this, new EventArgs()); UpdateSystemProxy(); Util.Utils.ReleaseMemory(); }
public void Start(Configuration config, int port) { this._config = config; this._shareOverLAN = config.shareOverLan; this._authUser = config.authUser; this._authPass = config.authPass; _stop = false; int localPort = port == 0 ? _config.localPort : port; if (CheckIfPortInUse(localPort)) { throw new Exception(I18N.GetString("Port already in use")); } try { // Create a TCP/IP socket. bool ipv6 = true; //bool ipv6 = false; _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); if (ipv6) { try { _socket_v6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); //_socket_v6.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false); _socket_v6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch { _socket_v6 = null; } } IPEndPoint localEndPoint = null; IPEndPoint localEndPointV6 = null; localEndPoint = new IPEndPoint(IPAddress.Any, localPort); localEndPointV6 = new IPEndPoint(IPAddress.IPv6Any, localPort); // Bind the socket to the local endpoint and listen for incoming connections. if (_socket_v6 != null) { _socket_v6.Bind(localEndPointV6); _socket_v6.Listen(1024); } //try { //throw new SocketException(); _socket.Bind(localEndPoint); _socket.Listen(1024); } //catch (SocketException e) //{ // if (_socket_v6 == null) // { // throw e; // } // else // { // _socket.Close(); // _socket = _socket_v6; // _socket_v6 = null; // } //} // Start an asynchronous socket to listen for connections. Console.WriteLine("ShadowsocksR started on port " + localPort.ToString()); _socket.BeginAccept( new AsyncCallback(AcceptCallback), _socket); if (_socket_v6 != null) { _socket_v6.BeginAccept( new AsyncCallback(AcceptCallback), _socket_v6); } } catch (SocketException e) { Logging.LogUsefulException(e); if (_socket != null) { _socket.Close(); _socket = null; } if (_socket_v6 != null) { _socket_v6.Close(); _socket_v6 = null; } throw; } }
protected void Reload() { // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); if (polipoRunner == null) { polipoRunner = new PolipoRunner(); } if (_pacServer == null) { _pacServer = new PACServer(); _pacServer.PACFileChanged += pacServer_PACFileChanged; } _pacServer.UpdateConfiguration(_config); if (gfwListUpdater == null) { gfwListUpdater = new GFWListUpdater(); gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; gfwListUpdater.Error += pacServer_PACUpdateError; } if (_listener != null) { _listener.Stop(); } // don't put polipoRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open polipoRunner.Stop(); try { polipoRunner.Start(_config); Local local = new Local(_config); List <Listener.Service> services = new List <Listener.Service>(); services.Add(local); services.Add(_pacServer); services.Add(new PortForwarder(polipoRunner.RunningPort)); _listener = new Listener(services); _listener.Start(_config); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException) { SocketException se = (SocketException)e; if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port already in use"), e); } } Logging.LogUsefulException(e); ReportError(e); } if (ConfigChanged != null) { ConfigChanged(this, new EventArgs()); } UpdateSystemProxy(); Util.Utils.ReleaseMemory(); }
protected void Reload() { Encryption.RNG.Reload(); // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); StatisticsConfiguration = StatisticsStrategyConfiguration.Load(); if (_pacServer == null) { _pacServer = new PACServer(); _pacServer.PACFileChanged += pacServer_PACFileChanged; _pacServer.UserRuleFileChanged += pacServer_UserRuleFileChanged; } _pacServer.UpdateConfiguration(_config); if (gfwListUpdater == null) { gfwListUpdater = new GFWListUpdater(); gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; gfwListUpdater.Error += pacServer_PACUpdateError; } availabilityStatistics.UpdateConfiguration(this); if (_listener != null) { _listener.Stop(); } try { var strategy = GetCurrentStrategy(); if (strategy != null) { strategy.ReloadServers(); } TCPRelay tcpRelay = new TCPRelay(this, _config); UDPRelay udpRelay = new UDPRelay(this); List <Listener.IService> services = new List <Listener.IService>(); services.Add(_pacServer); services.Add(tcpRelay); services.Add(udpRelay); _listener = new Listener(services); _listener.Start(_config); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException) { SocketException se = (SocketException)e; if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port already in use"), e); } } Logging.LogUsefulException(e); ReportError(e); } if (ConfigChanged != null) { ConfigChanged(this, new EventArgs()); } UpdateSystemProxy(); Utils.ReleaseMemory(true); }
/***********************************************<Start> add by Ian.May 2016/09/26*********************************************************/ protected void FogReload() // FogReload process shouldn't change _configBackUp content { Console.WriteLine("FogMode Reloading......"); ConfigurationShadowFog _fogServerReply = new ConfigurationShadowFog(); string fogNodeList = ConfigurationShadowFog.GetFogNodeList(_clientUser, isShadowFogStarted); // Bad http response such as 404 will directly jump to shadowsocks reload(); if (null != fogNodeList) { // _fogServerReply is used to recieve all msgs including errors when http response is 200 OK // handle bad scheduler reply try { // a better way is to use JObject or JArray, refer to UpdateChecker.cs _fogServerReply = JsonConvert.DeserializeObject <ConfigurationShadowFog>(fogNodeList); /******************************************************/ Console.WriteLine("FogNode = " + _fogServerReply.configs[0].server); /******************************************************/ } catch (Exception e) { // not use msg box because of following error code will pop up again Console.WriteLine("FogNodeInfo Format: " + e.Message); } if (Convert.ToBoolean(_fogServerReply.errorcode)) { MessageBox.Show(I18N.GetString("Error code : ") + _fogServerReply.errorcode + "\n\r" + I18N.GetString("Error msg : ") + _fogServerReply.errormsg); throw new Exception("Error"); } Console.WriteLine("access_token=" + _fogServerReply.access_token); Console.WriteLine("expires_in=" + _fogServerReply.expires_in); // In case the scheduler reply with null, this is an bad entrance to make shadowsocks strategymode crashed; if (null != _fogServerReply.configs) { _config.configs = _fogServerReply.configs; //value pass proved; Configuration.Save(_config); //_config now is written into gui-config.json with FogNode IP and Ports for "Reload()" next... Console.WriteLine(I18N.GetString("Fog Node obtained. Please check connection!")); } } Reload(); // Reload() first load the _config from local gui-config.json // here should add oneline to save servers from _configBackup and the other settings from _config // while NOT CHANGING _config itself string _configString = JsonConvert.SerializeObject(_config, Formatting.Indented); Configuration _configCache = JsonConvert.DeserializeObject <Configuration>(_configString); _configCache.configs = _configBackup.configs; Configuration.Save(_configCache); }