Esempio n. 1
0
        protected override void OnPlacementUpdatePosition(ref SlimDX.Vector3 pos)
        {
            if (!this.HostMap.IsNullMap)
            {
                var mapCell = this.HostMap.GetMapCell(pos.X, pos.Z);
                if (mapCell != null)
                {
                    if (this.HostMapCell != mapCell)
                    {
                        mapCell.AddRole(this);

                        //// 向玩家发送周围格NPC
                        //this.HostMap.UpdateNPCsToClient(this);
                        //// 向玩家发送周围格玩家
                        //this.HostMap.UpdatePlayersToClient(this);
                    }
                }
            }


            if (!this.HostMap.IsNullMap && HostMap.IsSavePos(this))
            {
                SetRoleDetailPos(pos.X, pos.Z);
                PlayerData.RoleDetail.Direction = this.Placement.GetDirection();
            }
        }
Esempio n. 2
0
 public virtual void OnDie()
 {
     RPC.PackageWriter pkg = new RPC.PackageWriter();
     //Wuxia.H_RpcRoot.smInstance.HIndex(pkg, Id).RPC_ChangeState(pkg, (byte)eFsmState.Die, mDeadBodyTime);
     Wuxia.H_RpcRoot.smInstance.HIndex(pkg, Id).RPC_Killed(pkg, CurrImpact.Skill.ID, CurrImpact.Skill.Level, CurrImpact.Owner.Id);
     HostMap.SendPkg2Clients(null, this.GetPosition(), pkg);
 }
Esempio n. 3
0
 public override void OnLeaveMap()
 {
     if (!HostMap.IsNullMap)
     {
         HostMap.RemoveNPC(this);
     }
     base.OnLeaveMap();
 }
Esempio n. 4
0
            internal Store GetStoreByHostName(string host)
            {
                if (!string.IsNullOrEmpty(host) && HostMap.TryGetValue(host, out var id))
                {
                    return(Stores.Get(id));
                }

                return(null);
            }
Esempio n. 5
0
        public override void OnLeaveMap()
        {
            if (!HostMap.IsNullMap)
            {
                HostMap.RemoveWayPoint(Id);
            }

            base.OnLeaveMap();
        }
Esempio n. 6
0
        public void RPC_GetPlayerInfo(ulong id, RPC.RPCForwardInfo fwd)
        {
            RPC.PackageWriter retPkg = new RPC.PackageWriter();
            PlayerInstance    player = HostMap.FindPlayer(id);

            if (player == null)
            {
                retPkg.Write((sbyte)(-1));
                retPkg.DoReturnPlanes2Client(fwd);
                return;
            }
            retPkg.Write((sbyte)1);
            ////一级属性
            //retPkg.Write(player.FinalPoint.Power);
            //retPkg.Write(player.FinalPoint.Body);
            //retPkg.Write(player.FinalPoint.Dex);
            ////二级属性
            //retPkg.Write(player.mFinalRoleValue.Atk);
            //retPkg.Write(player.mFinalRoleValue.MaxHP);
            //retPkg.Write(player.mFinalRoleValue.MaxMP);
            //retPkg.Write(player.mFinalRoleValue.Hit);
            //retPkg.Write(player.mFinalRoleValue.Dodge);
            //retPkg.Write(player.mFinalRoleValue.Crit);
            //retPkg.Write(player.mFinalRoleValue.CritDef);
            //retPkg.Write(player.mFinalRoleValue.DeadlyHitRate);
            //retPkg.Write(player.mFinalRoleValue.Def[0]);
            //retPkg.Write(player.mFinalRoleValue.Def[1]);
            //retPkg.Write(player.mFinalRoleValue.Def[2]);
            //retPkg.Write(player.mFinalRoleValue.Def[3]);
            //retPkg.Write(player.mFinalRoleValue.Def[4]);
            //retPkg.Write(player.mFinalRoleValue.UpHurtRate);
            //retPkg.Write(player.mFinalRoleValue.DownHurtRate);
            //retPkg.Write(player.mFinalRoleValue.UnusualDefRate);

            retPkg.Write(player.FinalRoleValue.Power);
            retPkg.Write(player.FinalRoleValue.Body);
            retPkg.Write(player.FinalRoleValue.Dex);
            //二级属性
            retPkg.Write(player.FinalRoleValue.Atk);
            retPkg.Write(player.FinalRoleValue.MaxHP);
            retPkg.Write(player.FinalRoleValue.MaxMP);
            retPkg.Write(player.FinalRoleValue.Hit);
            retPkg.Write(player.FinalRoleValue.Dodge);
            retPkg.Write(player.FinalRoleValue.Crit);
            retPkg.Write(player.FinalRoleValue.CritDef);
            retPkg.Write(player.FinalRoleValue.DeadlyHitRate);
            retPkg.Write(player.FinalRoleValue.GetDef(eElemType.Gold));
            retPkg.Write(player.FinalRoleValue.GetDef(eElemType.Wood));
            retPkg.Write(player.FinalRoleValue.GetDef(eElemType.Water));
            retPkg.Write(player.FinalRoleValue.GetDef(eElemType.Fire));
            retPkg.Write(player.FinalRoleValue.GetDef(eElemType.Earth));
            retPkg.Write(player.FinalRoleValue.UpHurtRate);
            retPkg.Write(player.FinalRoleValue.DownHurtRate);
            retPkg.Write(player.FinalRoleValue.UnusualDefRate);
            retPkg.DoReturnPlanes2Client(fwd);
        }
Esempio n. 7
0
        public void GIVEN_IPv6_WHEN_ToString_THEN_RepresentationIsCorrect()
        {
            // Arrange
            var map = new HostMap("::1", "localhost");

            // Act
            var result = map.ToString();

            // Assert
            Assert.AreEqual("::1\tlocalhost", result);
        }
Esempio n. 8
0
        //复活
        public void Relive(eReliveMode mode)
        {
            this.CurHP = this.FinalRoleValue.MaxHP;
            this.CurMP = this.FinalRoleValue.MaxMP;

            var pkg = new RPC.PackageWriter();

            //Wuxia.H_RpcRoot.smInstance.RPC_OnChiefRoleRelive(pkg, GetPosition().X, this.GetPosition().Z);
            //pkg.DoCommandPlanes2Client(Planes2GateConnect, ClientLinkId);
            Wuxia.H_RpcRoot.smInstance.HIndex(pkg, Id).RPC_Relive(pkg, GetPosition().X, this.GetPosition().Z);
            HostMap.SendPkg2Clients(null, this.GetPosition(), pkg);
        }
        private void ReloadProxyRule()
        {
            if (_hostDaemon == null)
            {
                _hostDaemon = new HostDaemon();
                _hostDaemon.ChnIpChanged    += (o, args) => ReloadIPRange();
                _hostDaemon.UserRuleChanged += (o, args) => HostMap.Reload();
            }

            ReloadIPRange();
            HostMap.Reload();
        }
Esempio n. 10
0
        public void GIVEN_EqualByValue_WHEN_Equals_THEN_True()
        {
            // Arrange
            var one = new HostMap("127.0.0.1", "localhost");
            var two = new HostMap("127.0.0.1", "localhost");

            // Act
            var result = one.Equals(two);

            // Assert
            Assert.IsTrue(result);
        }
Esempio n. 11
0
        public void GIVEN_NotEqualByValue_WHEN_Equals_THEN_False()
        {
            // Arrange
            var one = new HostMap("127.0.0.1", "localhost");
            var two = new HostMap("192.168.0.1", "gateway");

            // Act
            var result = one.Equals(two);

            // Assert
            Assert.IsFalse(result);
        }
        public void ExploreCustomUserRuleFile()
        {
            string customUserRuleFilename = HostMap.Instance().GetCustomUserRuleFile();

            if (CustomUserRuleFileReadyToOpen != null)
            {
                CustomUserRuleFileReadyToOpen(this, new PathEventArgs()
                {
                    Path = customUserRuleFilename
                });
            }
        }
Esempio n. 13
0
 private int RunCommand()
 {
     if (HostMap.IsMap(map.Value()))
     {
         HostsFile.Add(map.Value());
     }
     else
     {
         Program.WriteLine($"Error: The input '{map.Value()}' was not a valid map.");
         return(1);
     }
     return(Ok);
 }
Esempio n. 14
0
        public void GIVEN_EqualByValue_WHEN_GetHashCode_THEN_True()
        {
            // Arrange
            var one = new HostMap("127.0.0.1", "localhost");
            var two = new HostMap("127.0.0.1", "localhost");

            // Act
            var oneHash = one.GetHashCode();
            var twoHash = two.GetHashCode();

            // Assert
            Assert.AreEqual(oneHash, twoHash);
        }
Esempio n. 15
0
        public void GIVEN_NotEqualByValue_WHEN_GetHashCode_THEN_False()
        {
            // Arrange
            var one = new HostMap("127.0.0.1", "localhost");
            var two = new HostMap("192.168.0.1", "gateway");

            // Act
            var oneHash = one.GetHashCode();
            var twoHash = two.GetHashCode();

            // Assert
            Assert.AreNotEqual(oneHash, twoHash);
        }
Esempio n. 16
0
        public override bool CanAttack(RoleActor target)
        {
            if (!base.CanAttack(target))
            {
                return(false);
            }

            if (HostMap.CanAttack(this, target) == eMapAttackRule.AtkOK)
            {
                return(true);
            }

            if (NPCData.Template.type == (byte)eNpcType.Npc)
            {
                return(false);
            }

            if (target is NPCInstance)
            {
                var npc = target as NPCInstance;
                if (npc.NPCData.Template.type == (byte)eNpcType.Npc)
                {
                    return(false);
                }

                if (target.Camp == eCamp.None)
                {
                    return(false);
                }
            }
            else if (target is PlayerInstance)
            {
                if (target.Camp != this.Camp)
                {
                    return(true);
                }

                if (this.Camp == eCamp.None)
                {
                    return(true);
                }
            }

            if (target.Camp == this.Camp)
            {
                return(false);
            }


            return(true);
        }
Esempio n. 17
0
        //监测阵营关系导致的是否可以攻击
        public virtual bool CanAttack(RoleActor target)
        {
            if (!CanAttack())
            {
                return(false);
            }

            if (HostMap.CanAttack(this, target) == eMapAttackRule.AtkNO)
            {
                return(false);
            }

            return(target.CanBeAttacked());
        }
Esempio n. 18
0
        public virtual void UpdateAttr()
        {
            if (mUpdateAttrList.Count == 0)
            {
                return;
            }

            if (CurHP > FinalRoleValue.MaxHP)
            {
                CurHP = FinalRoleValue.MaxHP;
                OnAttrChanged(eSkillAttrIndex.HP);
            }
            if (CurMP > FinalRoleValue.MaxMP)
            {
                CurMP = FinalRoleValue.MaxMP;
                OnAttrChanged(eSkillAttrIndex.MP);
            }
            List <AttrStruct> attrs = new List <AttrStruct>();

            foreach (var idx in mUpdateAttrList)
            {
                if (!IsBroadCastAttr(idx))
                {
                    continue;
                }

                AttrStruct attr = new AttrStruct();
                if (!GetAttrStruct(ref attr, idx))
                {
                    continue;
                }

                attrs.Add(attr);
            }
            mUpdateAttrList.Clear();
            if (attrs.Count == 0)
            {
                return;
            }

            RPC.PackageWriter pkg = new RPC.PackageWriter();
            RPC.DataWriter    dw  = new RPC.DataWriter();
            RPC.IAutoSaveAndLoad.DaraWriteList <AttrStruct>(attrs, dw, true);
            Wuxia.H_RpcRoot.smInstance.HIndex(pkg, this.Id).RPC_UpdateRoleAttr(pkg, dw);
            HostMap.SendPkg2Clients(null, GetPosition(), pkg);
        }
Esempio n. 19
0
 public virtual bool OnValueChanged(string name, RPC.DataWriter value)
 {
     switch (name)
     {
     case "RoleHp":
     case "RoleMaxHp":
     case "RoleLevel":                        //这些都是玩家要看到的
         if (!HostMap.IsNullMap)
         {
             RoleActor ignore = name == "RoleHp" && null != CurrImpact && CurrImpact is AttackImpact ? CurrImpact.Owner : null;
             var       pkg    = new RPC.PackageWriter();
             Wuxia.H_RpcRoot.smInstance.HIndex(pkg, this.Id).RPC_UpdateRoleValue(pkg, name, value);
             HostMap.SendPkg2Clients(ignore, GetPosition(), pkg);
         }
         return(true);
     }
     return(false);
 }
Esempio n. 20
0
        public RoleActor FindHatredTarget()
        {
            List <RoleActor> roleList   = new List <RoleActor>();
            UInt32           actorTypes = (1 << (Int32)eActorGameType.Player) | (1 << (Int32)eActorGameType.Npc) | (1 << (Int32)eActorGameType.PlayerImage);
            var pos = GetPosition();

            if (!HostMap.TourRoles(ref pos, 10.0f, actorTypes, roleList))
            {
                return(null);
            }

            foreach (var tar in roleList)
            {
                if (CanAttack(tar))
                {
                    return(tar);
                }
            }

            return(null);
        }
        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(true);
        }
Esempio n. 22
0
 public void GIVEN_NullHostName_WHEN_Create_THEN_Exception()
 {
     // Act - Bang!
     var map = new HostMap("127.0.0.1", null);
 }
Esempio n. 23
0
 public void GIVEN_NonsenseIP_WHEN_CreateHostMap_THEN_Exception()
 {
     // Act - Bang
     var map = new HostMap("BANANAS", "localhost");
 }
        public 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.SaveToFile = _config.logEnable;
            Logging.OpenLogFile();

            if (_hostDaemon == null)
            {
                _hostDaemon = new HostDaemon();
                _hostDaemon.ChnIpChanged    += (o, args) => ReloadIPRange();
                _hostDaemon.UserRuleChanged += (o, args) => HostMap.Reload();
            }
            ReloadIPRange();
            HostMap.Reload();

            GlobalConfiguration.OSSupportsLocalIPv6 = Socket.OSSupportsIPv6;

            if (privoxyRunner == null)
            {
                privoxyRunner = new HttpProxyRunner();
            }
            if (_pacDaemon == null)
            {
                _pacDaemon = new PACDaemon();
                _pacDaemon.PACFileChanged      += (o, args) => UpdateSystemProxy();
                _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;
            }
            if (_pacServer == null)
            {
                _pacServer = new PACServer(_pacDaemon);
            }
            _pacServer.UpdatePacUrl(_config);
            if (gfwListUpdater == null)
            {
                gfwListUpdater = new GfwListUpdater();
                gfwListUpdater.UpdateCompleted += (o, args) => UpdatePACFromGFWListCompleted?.Invoke(o, args);
                gfwListUpdater.Error           += (o, args) => UpdatePACFromGFWListError?.Invoke(o, args);
            }

            _listener?.Stop();

            privoxyRunner.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.Start(_config);

                var local    = new Local(_config, _transfer, _chnRangeSet);
                var services = new List <Listener.IService>
                {
                    local,
                    _pacServer,
                    new HttpPortForwarder(privoxyRunner.RunningPort, _config)
                };
                _listener = new Listener(services);
                _listener.Start(_config, 0);
            }
            catch (Exception e)
            {
                ThrowSocketException(ref e);
                Logging.LogUsefulException(e);
                ReportError(e);
            }

            _port_map_listener = new List <Listener>();
            foreach (var pair in _config.GetPortMapCache())
            {
                try
                {
                    var local    = new Local(_config, _transfer, _chnRangeSet);
                    var services = new List <Listener.IService> {
                        local
                    };
                    var listener = new Listener(services);
                    listener.Start(_config, pair.Key);
                    _port_map_listener.Add(listener);
                }
                catch (Exception e)
                {
                    ThrowSocketException(ref e);
                    Logging.LogUsefulException(e);
                    ReportError(e);
                }
            }

            Application.Current.Dispatcher?.Invoke(() => { ConfigChanged?.Invoke(this, new EventArgs()); });

            UpdateSystemProxy();
            Utils.ReleaseMemory();
        }
 public int IsHandle(byte[] firstPacket, int length, Socket socket)
 {
     if (length >= 7 && _config.proxyRuleMode != (int)ProxyRuleMode.Disable)
     {
         IPAddress ipAddress = null;
         if (firstPacket[0] == 1)
         {
             byte[] addr = new byte[4];
             Array.Copy(firstPacket, 1, addr, 0, addr.Length);
             ipAddress = new IPAddress(addr);
         }
         else if (firstPacket[0] == 3)
         {
             int    len  = firstPacket[1];
             byte[] addr = new byte[len];
             if (length >= len + 2)
             {
                 Array.Copy(firstPacket, 2, addr, 0, addr.Length);
                 string host = Encoding.UTF8.GetString(firstPacket, 2, len);
                 if (IPAddress.TryParse(host, out ipAddress))
                 {
                     //pass
                 }
                 else
                 {
                     if (host.ToLower() == "localhost") //TODO: load system host file
                     {
                         return(1);
                     }
                     if ((_config.proxyRuleMode == (int)ProxyRuleMode.BypassLanAndChina || _config.proxyRuleMode == (int)ProxyRuleMode.BypassLanAndNotChina) && _IPRange != null)
                     {
                         if (!IPAddress.TryParse(host, out ipAddress))
                         {
                             Shadowsocks.Model.HostMap hostMap = HostMap.Instance();
                             string host_addr;
                             if (hostMap.GetHost(host, out host_addr))
                             {
                                 if (!String.IsNullOrEmpty(host_addr))
                                 {
                                     string lower_host_addr = host_addr.ToLower();
                                     if (lower_host_addr.StartsWith("reject") ||
                                         lower_host_addr.StartsWith("direct")
                                         )
                                     {
                                         return(1);
                                     }
                                     else if (lower_host_addr.StartsWith("localproxy"))
                                     {
                                         return(2);
                                     }
                                     else if (lower_host_addr.StartsWith("remoteproxy"))
                                     {
                                         return(0);
                                     }
                                     else if (lower_host_addr.IndexOf('.') >= 0 || lower_host_addr.IndexOf(':') >= 0)
                                     {
                                         if (!IPAddress.TryParse(lower_host_addr, out ipAddress))
                                         {
                                             //
                                         }
                                     }
                                 }
                             }
                             if (ipAddress == null)
                             {
                                 ipAddress = Utils.DnsBuffer.Get(host);
                             }
                         }
                         if (ipAddress == null)
                         {
                             if (host.IndexOf('.') >= 0)
                             {
                                 ipAddress = Util.Utils.QueryDns(host, _config.dns_server);
                             }
                             else
                             {
                                 ipAddress = Utils.QueryDns(host, null);
                             }
                             if (ipAddress != null)
                             {
                                 Utils.DnsBuffer.Set(host, new IPAddress(ipAddress.GetAddressBytes()));
                                 if (host.IndexOf('.') >= 0)
                                 {
                                     if (Util.Utils.isLAN(ipAddress)) // assume that it is polution if return LAN address
                                     {
                                         return(0);
                                     }
                                 }
                             }
                             else
                             {
                                 Logging.Log(LogLevel.Debug, "DNS query fail: " + host);
                             }
                         }
                     }
                 }
             }
         }
         else if (firstPacket[0] == 4)
         {
             byte[] addr = new byte[16];
             Array.Copy(firstPacket, 1, addr, 0, addr.Length);
             ipAddress = new IPAddress(addr);
         }
         if (ipAddress != null)
         {
             if (Util.Utils.isLAN(ipAddress))
             {
                 return(1);
             }
             if ((_config.proxyRuleMode == (int)ProxyRuleMode.BypassLanAndChina || _config.proxyRuleMode == (int)ProxyRuleMode.BypassLanAndNotChina) && _IPRange != null &&
                 ipAddress.AddressFamily == AddressFamily.InterNetwork
                 )
             {
                 if (_IPRange.IsInIPRange(ipAddress))
                 {
                     return(2);
                 }
                 Utils.DnsBuffer.Sweep();
             }
         }
     }
     return(0);
 }
            private void Connect()
            {
                try
                {
                    IPAddress ipAddress   = null;
                    int       _targetPort = 0;
                    {
                        if (_firstPacket[0] == 1)
                        {
                            byte[] addr = new byte[4];
                            Array.Copy(_firstPacket, 1, addr, 0, addr.Length);
                            ipAddress    = new IPAddress(addr);
                            _targetPort  = (_firstPacket[5] << 8) | _firstPacket[6];
                            _remote_host = ipAddress.ToString();
                            Logging.Info((_remote_go_proxy ? "Local proxy" : "Direct") + " connect " + _remote_host + ":" + _targetPort.ToString());
                        }
                        else if (_firstPacket[0] == 4)
                        {
                            byte[] addr = new byte[16];
                            Array.Copy(_firstPacket, 1, addr, 0, addr.Length);
                            ipAddress    = new IPAddress(addr);
                            _targetPort  = (_firstPacket[17] << 8) | _firstPacket[18];
                            _remote_host = ipAddress.ToString();
                            Logging.Info((_remote_go_proxy ? "Local proxy" : "Direct") + " connect " + _remote_host + ":" + _targetPort.ToString());
                        }
                        else if (_firstPacket[0] == 3)
                        {
                            int    len  = _firstPacket[1];
                            byte[] addr = new byte[len];
                            Array.Copy(_firstPacket, 2, addr, 0, addr.Length);
                            _remote_host = Encoding.UTF8.GetString(_firstPacket, 2, len);
                            _targetPort  = (_firstPacket[len + 2] << 8) | _firstPacket[len + 3];
                            Logging.Info((_remote_go_proxy ? "Local proxy" : "Direct") + " connect " + _remote_host + ":" + _targetPort.ToString());

                            if (!_remote_go_proxy)
                            {
                                if (!IPAddress.TryParse(_remote_host, out ipAddress))
                                {
                                    Shadowsocks.Model.HostMap hostMap = HostMap.Instance();
                                    string host_addr;
                                    if (hostMap.GetHost(_remote_host, out host_addr))
                                    {
                                        if (!String.IsNullOrEmpty(host_addr))
                                        {
                                            string lower_host_addr = host_addr.ToLower();
                                            if (lower_host_addr.StartsWith("reject"))
                                            {
                                                Close();
                                                return;
                                            }
                                            else if (lower_host_addr.IndexOf('.') >= 0 || lower_host_addr.IndexOf(':') >= 0)
                                            {
                                                if (!IPAddress.TryParse(lower_host_addr, out ipAddress))
                                                {
                                                    //
                                                }
                                            }
                                        }
                                    }
                                    if (ipAddress == null)
                                    {
                                        ipAddress = Utils.DnsBuffer.Get(_remote_host);
                                    }
                                }
                                if (ipAddress == null)
                                {
                                    if (_remote_host.IndexOf('.') >= 0)
                                    {
                                        ipAddress = Util.Utils.QueryDns(_remote_host, _config.dns_server);
                                    }
                                    else
                                    {
                                        ipAddress = Utils.QueryDns(_remote_host, null);
                                    }
                                }
                                if (ipAddress != null)
                                {
                                    Utils.DnsBuffer.Set(_remote_host, new IPAddress(ipAddress.GetAddressBytes()));
                                    Utils.DnsBuffer.Sweep();
                                }
                                else
                                {
                                    throw new SocketException((int)SocketError.HostNotFound);
                                }
                            }
                        }
                        _remote_port = _targetPort;
                    }
                    if (_remote_go_proxy)
                    {
                        IPAddress.TryParse(_config.proxyHost, out ipAddress);
                        _targetPort = _config.proxyPort;
                    }
                    // ProxyAuth recv only socks5 head, so don't need to save anything else
                    IPEndPoint remoteEP = new IPEndPoint(ipAddress, _targetPort);

                    _remote = new ProxySocketTun(ipAddress.AddressFamily,
                                                 SocketType.Stream, ProtocolType.Tcp);
                    _remote.GetSocket().NoDelay = true;

                    // Connect to the remote endpoint.
                    _remote.BeginConnect(remoteEP,
                                         new AsyncCallback(ConnectCallback), null);
                }
                catch (Exception e)
                {
                    Logging.LogUsefulException(e);
                    Close();
                }
            }
Esempio n. 27
0
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Utils.GetExecutablePath()));
#if !_CONSOLE
            foreach (var arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }
            using (var mutex = new Mutex(false, "Global\\ShadowsocksR_" + Directory.GetCurrentDirectory().GetDeterministicHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + Environment.NewLine +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif

#if !_CONSOLE
                var tryTimes = 0;
                while (Configuration.Load() == null)
                {
                    if (tryTimes >= 5)
                        return;
                    using (var dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    tryTimes += 1;
                }
#endif

                _controller = new ShadowsocksController();
                HostMap.Instance().LoadHostFile();

                // Logging
                Logging.DefaultOut = Console.Out;
                Logging.DefaultError = Console.Error;

#if _DOTNET_4_0
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

#endif
#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
                SystemEvents.SessionEnding += _viewController.Quit_Click;
#endif

                _controller.Start();

#if !_CONSOLE

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
Esempio n. 28
0
        private static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Utils.GetExecutablePath()) ?? throw new InvalidOperationException());
            if (args.Contains(Constants.ParameterSetautorun))
            {
                if (!AutoStartup.Switch())
                {
                    Environment.ExitCode = 1;
                }
                return;
            }

            var identifier = $@"Global\{UpdateChecker.Name}_{Directory.GetCurrentDirectory().GetDeterministicHashCode()}";

            using var singleInstance = new SingleInstance(identifier);
            if (!singleInstance.IsFirstInstance)
            {
                singleInstance.PassArgumentsToFirstInstance(args.Length == 0
                        ? args.Append(Constants.ParameterMultiplyInstance)
                        : args);
                return;
            }
            singleInstance.ArgumentsReceived += SingleInstance_ArgumentsReceived;

            var app = new Application
            {
                ShutdownMode = ShutdownMode.OnExplicitShutdown
            };

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            I18NUtil.SetLanguage(app.Resources, @"App");
            ViewUtils.SetResource(app.Resources, @"../View/NotifyIconResources.xaml", 1);

            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
            app.Exit += App_Exit;

            var tryTimes = 0;

            while (Configuration.Load() == null)
            {
                if (tryTimes >= 5)
                {
                    return;
                }
                var dlg = new InputPasswordWindow();
                if (dlg.ShowDialog() == true)
                {
                    Configuration.SetPassword(dlg.Password);
                }
                else
                {
                    return;
                }
                tryTimes += 1;
            }

            _controller = new ShadowsocksController();
            HostMap.Instance().LoadHostFile();

            // Logging
            Logging.DefaultOut   = Console.Out;
            Logging.DefaultError = Console.Error;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            _viewController             = new MenuViewController(_controller);
            SystemEvents.SessionEnding += _viewController.Quit_Click;

            _controller.Start();
            Reg.SetUrlProtocol(@"ssr");
            Reg.SetUrlProtocol(@"sub");
            singleInstance.ListenForArgumentsFromSuccessiveInstances();
            app.Run();
        }
        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();
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
#if !_CONSOLE
            foreach (string arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!Controller.AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }
            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + Environment.NewLine +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif
                Directory.SetCurrentDirectory(Application.StartupPath);

#if !_CONSOLE
                int try_times = 0;
                while (Configuration.Load() == null)
                {
                    if (try_times >= 5)
                        return;
                    using (InputPassword dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    try_times += 1;
                }
#endif

                _controller = new ShadowsocksController();
                HostMap.Instance().LoadHostFile();

                // Logging
                Configuration cfg = _controller.GetConfiguration();
                Logging.save_to_file = cfg.logEnable;

                //#if !DEBUG
                if (try_times > 0)
                    Logging.save_to_file = false;
                Logging.OpenLogFile();
                //#endif

#if _DOTNET_4_0
                // Enable Modern TLS when .NET 4.5+ installed.
                if (Util.EnvCheck.CheckDotNet45())
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif
#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
#endif

                _controller.Start();

#if !_CONSOLE
                //Util.Utils.ReleaseMemory();

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }