Esempio n. 1
0
    public void DropDiversion()
    {
        FileLoader fl = new FileLoader("JSONData" + Path.DirectorySeparatorChar + "Bestiary", "thediversion");
        string     actualenemyjson = fl.Read();
        Dictionary <string, System.Object> actualenemydict = Json.Deserialize(actualenemyjson) as Dictionary <string, System.Object>;
        string filename = "thediversion";
        int    track    = SpawnIndexToZoneID(spawnIdx);
        int    trackpos = 0;

        GameObject enemyobj = GameObject.Instantiate(Resources.Load("Prefabs/MainCanvas/Enemy")) as GameObject;

        GameObject.Destroy(enemyobj.GetComponent <Enemy>());
        Diversion d = enemyobj.AddComponent <Diversion>() as Diversion;

        enemyobj.transform.SetParent(Dial.spawnLayer, false);
        float chaindelay = (float)(double)actualenemydict["delay"];

        d.SetDelay(chaindelay);

        d.SetSrcFileName(filename);
        d.SetTrackID(track);
        d.SetTrackLane(trackpos);
        //calculate and set position
        float degrees = (track - 1) * 60;        //clockwise of y-axis

        degrees += 15 * trackpos;                //negative trackpos is left side, positive is right side, 0 is middle
        degrees  = ((360 - degrees) + 90) % 360; //convert to counterclockwise of x axis
        degrees *= Mathf.Deg2Rad;
        ((RectTransform)enemyobj.transform).anchoredPosition = new Vector2(Dial.ENEMY_SPAWN_LENGTH * Mathf.Cos(degrees),
                                                                           Dial.ENEMY_SPAWN_LENGTH * Mathf.Sin(degrees));
        d.spawnedByBoss = true;
        d.StartMoving();
    }
Esempio n. 2
0
        public void CreatePermutationIterativeTest()
        {
            var div    = new Diversion(10);
            var result = div.CreatePermutationsBinary(7);

            Assert.Fail();
        }
Esempio n. 3
0
        static DemoViewModel()
        {
            // Add the option to use the UI Dispatcher, and set it to be the default option for implicit diversions.
            Diversion.AddDiverter(MarshalOption.Dispatcher, Application.Current.Dispatcher, "Invoke", new List <KeyValuePair <Type, object> >().AddKey(typeof(Delegate)).AddKey(typeof(object[])), new DispatcherSynchronizationContext(), true);

            // Add a custom scheduler option that uses the Scheduler.Schedule(IScheduler, Action) extension method.
            Diversion.AddDiverter(_SchedulerKey, typeof(Scheduler), "Schedule", new List <KeyValuePair <Type, object> >().AddValue(_Scheduler).AddKey(typeof(Action)), null, false);
        }
Esempio n. 4
0
        private void Divert(DivertLayer layer)
        {
            const string filter = "tcp.DstPort == 80 or tcp.SrcPort == 80 or tcp.DstPort == 8082 or tcp.SrcPort == 8082";
            Diversion    diversion;

            try
            {
                diversion = Diversion.Open(filter, layer, -1000, 0);
                diversion.SetParam(DivertParam.QueueLength, 8192);
                diversion.SetParam(DivertParam.QueueTime, 2048);
            }
            catch (Exception e)
            {
                _fileLogger.Error(Tag, e.ToString());
                return;
            }

            if (!diversion.Handle.Valid)
            {
                _fileLogger.Error(Tag, $"Failed to open divert handle with error {Marshal.GetLastWin32Error()}");
                return;
            }



            while (_running)
            {
                var  buffer        = new byte[2048];
                var  address       = new Address();
                uint receiveLength = 0;
                if (!diversion.Receive(buffer, address, ref receiveLength))
                {
                    _fileLogger.Error(Tag, $"Failed to receive packet with error {Marshal.GetLastWin32Error()}");
                    continue;
                }

                var packet = new Packet(buffer, receiveLength);

                var hash = packet.GetHashCode();
                if (!KvStore.Connections.ContainsKey(hash))
                {
                    KvStore.Connections.TryAdd(hash, new Connection(diversion, address)
                    {
                        HashCode = hash
                    });
                }

                //if (!KvStore.ConnectionControllers.ContainsKey(hash))
                //    KvStore.ConnectionControllers.TryAdd(hash, new ConnectionController(packet,diversion));

                //Controlling Logic maybe
                KvStore.Connections[hash].Add(packet, address);
                //KvStore.ConnectionControllers[hash].Push(packet);
                //Monitoring Logic maybe
            }
        }
Esempio n. 5
0
        public override Skill Clone(int value)
        {
            var tmp = new Diversion
            {
                Description = Description,
                MaxValue    = MaxValue,
                Name        = Name,
                Value       = value
            };

            return(tmp);
        }
Esempio n. 6
0
        public ConnectionController(Packet initiatePacket, Diversion diversion)
        {
            client = new OnewayConnection(initiatePacket.SrcIp, initiatePacket.DestIp,
                                          initiatePacket.SrcPort, initiatePacket.DestPort);

            origin = new OnewayConnection(initiatePacket.DestIp, initiatePacket.SrcIp,
                                          initiatePacket.DestPort, initiatePacket.SrcPort);

            hashCode       = initiatePacket.GetHashCode();
            this.diversion = diversion;
            clientPB       = new QuickPacketBuilder(client);
            originPB       = new QuickPacketBuilder(origin);
        }
Esempio n. 7
0
 public Connection(Diversion diversion, Address address)
 {
     this.diversion        = diversion;
     CurrentState          = State.Closed;
     timeoutTimer          = new Timer();
     timeoutTimer.Elapsed += OnTimeout;
     timeoutTimer.Interval = 30 * 1000;
     timeoutTimer.Enabled  = true;
     fileLogger            = FileLogger.GetInstance();
     fileLogger.Debug(Tag, "new connection");
     this.address = address;
     IOSemaphore  = new SemaphoreSlim(1, 1);
 }
Esempio n. 8
0
        public void buildAllPossiblePermutationsTest()
        {
            var div = new Diversion(2);

            div.createPermutations();

            Assert.AreEqual(4, div.permutations.Count);
            Assert.AreEqual(true, div.permutations.Find(x => x == "00") != null);
            Assert.AreEqual(true, div.permutations.Find(x => x == "01") != null);
            Assert.AreEqual(true, div.permutations.Find(x => x == "11") != null);

            div = new Diversion(4);
            div.createPermutations();
            Assert.AreEqual(true, div.permutations.Find(x => x == "0001") != null);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += delegate { _running = false; };

            // open handle
            using (var handle = Diversion.WinDivertOpen("true", WinDivertLayer.Network, 100, 0))
            {
                if (handle.IsInvalid)
                {
                    Console.WriteLine("Unable to open handle. Error: " + Marshal.GetLastWin32Error());
                    return;
                }

                // prepare headers
                var ipHeader     = new IPHeader();
                var ipv6Header   = new IPv6Header();
                var icmpHeader   = new ICMPHeader();
                var icmpv6Header = new ICMPv6Header();
                var tcpHeader    = new TCPHeader();
                var udpHeader    = new UDPHeader();

                var    address = new Address();
                byte[] buffer  = new byte[65535];

                uint receiveLength = 0;
                uint sendLength    = 0;

                string processName;
                uint   pid = 0;

                // loop
                while (_running)
                {
                    pid = 0;
                }
                receiveLength = 0;
                sendLength    = 0;

                fixed(byte *data = buffer)
                {
                    Diversion.WinDivertHelperParsePacket(data, receiveLength, ipHeader, ipv6Header, icmpHeader,
                                                         icmpv6Header, tcpHeader, udpHeader, null, null);
                }
            }
        }
Esempio n. 10
0
        private static bool RunTest(Test test, Diversion injectionDiversion)
        {
            byte[] buffer = new byte[MaxPacket];

            string validationError = string.Empty;

            if(!Diversion.ValidateFilter(test.Filter, DivertLayer.Network, ref validationError))
            {
                System.Console.WriteLine("Error in filter string {0}", validationError);
                return false;
            }

            Address address = new Address();
            address.Direction = DivertDirection.Outbound;

            if(Diversion.EvaluateFilter(test.Filter, DivertLayer.Network, test.TestPacketData, (uint)test.TestPacketData.Length, address) != test.Match)
            {
                System.Console.WriteLine("Error - Filter {0} does not match the packet.", test.Filter);
                return false;
            }

            Diversion testDiversion1 = null;

            Diversion testDiversion2 = null;

            try
            {
                // (1) Open a WinDivert handle to the given filter
                testDiversion1 = Diversion.Open(test.Filter, DivertLayer.Network, 0, 0);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(string.Format("Failed to open testDiversion1 with error {0}\n", e.Message));
                return false;
            }

            if (!testDiversion1.Handle.Valid)
            {
                System.Console.WriteLine(string.Format("Failed to open testDiversion1 with error {0}.\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                return false;
            }

            if(!test.Match)
            {
                testDiversion2 = testDiversion1;

                try
                {
                    // Catch non-matching packets
                    testDiversion1 = Diversion.Open("true", DivertLayer.Network, 33, 0);
                }
                catch (System.Exception e)
                {
                    System.Console.WriteLine(string.Format("Failed to open testDiversion2 with error {0}\n", e.Message));
                    testDiversion1.Close();
                    return false;
                }

                if (!testDiversion2.Handle.Valid)
                {
                    System.Console.WriteLine(string.Format("Failed to open testDiversion2 with error {0}.\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                    testDiversion1.Close();
                    return false;
                }
            }

            // (2) Inject the packet
            uint injectLength = 0;
            if(!injectionDiversion.Send(test.TestPacketData, (uint)test.TestPacketData.Length, address, ref injectLength))
            {
                System.Console.WriteLine(string.Format("Error injecting test packet with error {0}.\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));

                if (testDiversion2 != null)
                {
                    testDiversion2.Close();
                }
                testDiversion1.Close();

                return false;
            }

            // (3) Wait for the packet to arrive
            DivertAsyncResult result = new DivertAsyncResult();
            uint recvLength = 0;
            if(!testDiversion1.ReceiveAsync(buffer, address, ref recvLength, result))
            {
                if(!result.NoError)
                {
                    System.Console.WriteLine(string.Format("Async packet reception failed with error {0}.\n", result.ErrorCode));

                    if (testDiversion2 != null)
                    {
                        testDiversion2.Close();
                    }
                    testDiversion1.Close();

                    return false;
                }

                if(!result.Get(250))
                {
                    System.Console.WriteLine(string.Format("Async packet read failed with error {0}.\n", result.ErrorCode));

                    if (testDiversion2 != null)
                    {
                        testDiversion2.Close();
                    }
                    testDiversion1.Close();

                    return false;
                }

                recvLength = result.Length;
            }

            if(address.Direction == DivertDirection.Outbound)
            {
                testDiversion1.CalculateChecksums(buffer, recvLength, 0);
            }

            // (4) Verify that the packet is the same
            if(recvLength != test.TestPacketData.Length)
            {
                System.Console.WriteLine("Received packet does not match test packet.\n");

                if (testDiversion2 != null)
                {
                    testDiversion2.Close();
                }
                testDiversion1.Close();

                return false;
            }

            for(int i = 0; i < test.TestPacketData.Length; ++i)
            {
                if(buffer[i] != test.TestPacketData[i])
                {
                    System.Console.WriteLine("Received packet does not match test packet.\n");

                    if (testDiversion2 != null)
                    {
                        testDiversion2.Close();
                    }
                    testDiversion1.Close();

                    return false;
                }
            }

            // (5) Clean-up
            if (testDiversion1 != null)
            {
                testDiversion1.Close();
            }
                        
            if (testDiversion2 != null)
            {
                testDiversion2.Close();
            }

            return true;
        }
Esempio n. 11
0
 static DemoViewModel()
 {
     // Add the option to use the UI Dispatcher.  The default diverter will still be current thread.
     // Instantiation of a DispatcherSynchronizationContext needs to happen on the main application thread in order for the correct Dispatcher value to be used.
     Diversion.AddDiverter(MarshalOption.Dispatcher, Application.Current.Dispatcher, "Invoke", new List <KeyValuePair <Type, object> >().AddKey(typeof(Delegate)).AddKey(typeof(object[])));
 }
Esempio n. 12
0
        private static void Main(string[] args)
        {
            string testsFilePath = System.AppDomain.CurrentDomain.BaseDirectory + @"TestData\Tests.json";

            if (!File.Exists(testsFilePath))
            {
                System.Console.WriteLine(string.Format("Tests JSON file does not exist where expected at {0}\n", testsFilePath));
                return;
            }

            string testData = File.ReadAllText(testsFilePath);

            System.Collections.Generic.List <Test> tests = new System.Collections.Generic.List <Test>();

            Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(testData);

            foreach (var tok in token.SelectToken("Tests"))
            {
                string name   = (string)tok.SelectToken("TestName");
                string filter = (string)tok.SelectToken("TestFilter");
                string data   = (string)tok.SelectToken("TestData");
                string match  = (string)tok.SelectToken("Match");

                tests.Add(new Test(name, filter, data, match));
            }

            // Open handles to:
            // (1) stop normal traffic from interacting with the tests; and
            // (2) stop test packets escaping to the Internet or TCP/IP stack.
            Diversion upper;
            Diversion lower;

            try
            {
                upper = Diversion.Open("true", DivertLayer.Network, -510, FilterFlags.Drop);
            }catch (System.Exception e)
            {
                System.Console.WriteLine(string.Format("Failed to open upper Diversion with error {0}\n", e.Message));
                return;
            }

            try
            {
                lower = Diversion.Open("true", DivertLayer.Network, 510, FilterFlags.Drop);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(string.Format("Failed to open lower Diversion with error {0}\n", e.Message));
                return;
            }

            if (!upper.Handle.Valid)
            {
                System.Console.WriteLine(string.Format("Failed to open upper Diversion with error {0}\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                return;
            }

            if (!lower.Handle.Valid)
            {
                System.Console.WriteLine(string.Format("Failed to open lower Diversion with error {0}\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                return;
            }

            // Wait for existing packets to flush:
            System.Threading.Thread.Sleep(100);

            int testsPassed = 0;
            int testsFailed = 0;

            // Run tests:
            for (int i = 0; i < tests.Count; ++i)
            {
                var test = tests[i];

                // Ensure the correct checksum
                upper.CalculateChecksums(test.TestPacketData, (uint)test.TestPacketData.Length, 0);

                bool testResult = RunTest(test, upper);

                if (testResult)
                {
                    System.Console.BackgroundColor = System.ConsoleColor.Green;
                    System.Console.ForegroundColor = System.ConsoleColor.White;
                    System.Console.WriteLine(test.TestName + " Passed.");
                    System.Console.ResetColor();
                    testsPassed++;
                }
                else
                {
                    System.Console.BackgroundColor = System.ConsoleColor.Red;
                    System.Console.ForegroundColor = System.ConsoleColor.White;
                    System.Console.WriteLine(test.TestName + " Failed!");
                    System.Console.ResetColor();
                    testsFailed++;
                }
            }

            if (!upper.Close())
            {
                System.Console.WriteLine("Failed to close upper handle");
            }

            if (!lower.Close())
            {
                System.Console.WriteLine("Failed to close lower handle");
            }

            System.Console.WriteLine("{0} tests passed and {1} tests failed.", testsPassed, testsFailed);
        }
Esempio n. 13
0
        private static bool RunTest(Test test, Diversion injectionDiversion)
        {
            byte[] buffer = new byte[MaxPacket];

            string validationError = string.Empty;

            if (!Diversion.ValidateFilter(test.Filter, DivertLayer.Network, ref validationError))
            {
                System.Console.WriteLine("Error in filter string {0}", validationError);
                return(false);
            }

            Address address = new Address();

            address.Direction = DivertDirection.Outbound;

            if (Diversion.EvaluateFilter(test.Filter, DivertLayer.Network, test.TestPacketData, (uint)test.TestPacketData.Length, address) != test.Match)
            {
                System.Console.WriteLine("Error - Filter {0} does not match the packet.", test.Filter);
                return(false);
            }

            Diversion testDiversion1 = null;

            Diversion testDiversion2 = null;

            try
            {
                // (1) Open a WinDivert handle to the given filter
                testDiversion1 = Diversion.Open(test.Filter, DivertLayer.Network, 0, 0);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(string.Format("Failed to open testDiversion1 with error {0}\n", e.Message));
                return(false);
            }

            if (!testDiversion1.Handle.Valid)
            {
                System.Console.WriteLine(string.Format("Failed to open testDiversion1 with error {0}.\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                return(false);
            }

            if (!test.Match)
            {
                testDiversion2 = testDiversion1;

                try
                {
                    // Catch non-matching packets
                    testDiversion1 = Diversion.Open("true", DivertLayer.Network, 33, 0);
                }
                catch (System.Exception e)
                {
                    System.Console.WriteLine(string.Format("Failed to open testDiversion2 with error {0}\n", e.Message));
                    testDiversion1.Close();
                    return(false);
                }

                if (!testDiversion2.Handle.Valid)
                {
                    System.Console.WriteLine(string.Format("Failed to open testDiversion2 with error {0}.\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
                    testDiversion1.Close();
                    return(false);
                }
            }

            // (2) Inject the packet
            uint injectLength = 0;

            if (!injectionDiversion.Send(test.TestPacketData, (uint)test.TestPacketData.Length, address, ref injectLength))
            {
                System.Console.WriteLine(string.Format("Error injecting test packet with error {0}.\n", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));

                if (testDiversion2 != null)
                {
                    testDiversion2.Close();
                }
                testDiversion1.Close();

                return(false);
            }

            // (3) Wait for the packet to arrive
            DivertAsyncResult result = new DivertAsyncResult();
            uint recvLength          = 0;

            if (!testDiversion1.ReceiveAsync(buffer, address, ref recvLength, result))
            {
                if (!result.NoError)
                {
                    System.Console.WriteLine(string.Format("Async packet reception failed with error {0}.\n", result.ErrorCode));

                    if (testDiversion2 != null)
                    {
                        testDiversion2.Close();
                    }
                    testDiversion1.Close();

                    return(false);
                }

                if (!result.Get(250))
                {
                    System.Console.WriteLine(string.Format("Async packet read failed with error {0}.\n", result.ErrorCode));

                    if (testDiversion2 != null)
                    {
                        testDiversion2.Close();
                    }
                    testDiversion1.Close();

                    return(false);
                }

                recvLength = result.Length;
            }

            if (address.Direction == DivertDirection.Outbound)
            {
                testDiversion1.CalculateChecksums(buffer, recvLength, 0);
            }

            // (4) Verify that the packet is the same
            if (recvLength != test.TestPacketData.Length)
            {
                System.Console.WriteLine("Received packet does not match test packet.\n");

                if (testDiversion2 != null)
                {
                    testDiversion2.Close();
                }
                testDiversion1.Close();

                return(false);
            }

            for (int i = 0; i < test.TestPacketData.Length; ++i)
            {
                if (buffer[i] != test.TestPacketData[i])
                {
                    System.Console.WriteLine("Received packet does not match test packet.\n");

                    if (testDiversion2 != null)
                    {
                        testDiversion2.Close();
                    }
                    testDiversion1.Close();

                    return(false);
                }
            }

            // (5) Clean-up
            if (testDiversion1 != null)
            {
                testDiversion1.Close();
            }

            if (testDiversion2 != null)
            {
                testDiversion2.Close();
            }

            return(true);
        }
Esempio n. 14
0
		/////////////////////////////////////////////////////////////////////////////

		public MasterOutput( GrandCentral gc )
		{
			// ******
			blocks = gc.GetTextBlocks();
			chars = gc.GetEscapedChars();

			// ******
			diversions = new Diversions();
			diversionsStack = new DiversionStack();

			// ******
			current = diversions.GetDiversion( Diversion.DEFAULT_DIV_NAME );
			sbOutput = current.Value;
		}
Esempio n. 15
0
		/////////////////////////////////////////////////////////////////////////////

		public void Divert( string divName )
		{
			// ******
			current = diversions.GetDiversion( divName );
			sbOutput = current.Value;
		}
Esempio n. 16
0
		/////////////////////////////////////////////////////////////////////////////

		public void PopDivert()
		{
			// ******
			if( diversionsStack.NotEmpty ) {
				current = diversionsStack.Pop();
				sbOutput = current.Value;
			}
		}
Esempio n. 17
0
		/////////////////////////////////////////////////////////////////////////////

		public void PushDivert( string divName )
		{
			// ******
			diversionsStack.Push( current );
			current = diversions.GetDiversion( divName );
			sbOutput = current.Value;
		}
Esempio n. 18
0
 public DiversionJewel1()
 {
     Name  = "Diversion Jewel 1";
     Skill = new Diversion(1);
     Type  = SlotType.Small;
 }
Esempio n. 19
0
    public Wave(Dictionary <string, System.Object> json)
    {
        canvas = GameObject.Find("Canvas").transform;
        System.Random rand = new System.Random();

        enemies = new List <GameObject> ();
        //note: ints in MiniJSON come out as longs, so must be cast twice
        levelID  = (int)(long)json ["levelID"];
        waveID   = (int)(long)json ["waveID"];
        maxTime  = (int)(long)json ["maxMilliseconds"];
        interval = (int)(long)json ["minimumInterval"];
        List <System.Object> enemyjson = (List <System.Object>)json ["enemies"];

        //step one: create a randomized list of spawn times
        int slots = maxTime / interval;
        //Debug.Log ("wave "+ waveID + " slots: " + slots);
        int occupants = enemyjson.Count;

        //create bool array to randomize
        List <bool> timeslots = new List <bool>();

        for (int i = 0; i < slots; i++)
        {
            if (i < occupants)
            {
                timeslots.Add(true);
            }
            else
            {
                timeslots.Add(false);
            }
        }
        //randomize this array (fisher-yates shuffle)
        for (int i = slots - 1; i > 0; i--)
        {
            int  j    = rand.Next(i + 1);
            bool temp = timeslots[i];
            timeslots[i] = timeslots[j];
            timeslots[j] = temp;
        }
        //make sure one enemy spawns immediately
        if (!timeslots[0])
        {
            for (int i = 1; i < slots; i++)
            {
                if (timeslots[i])
                {
                    timeslots[0] = true;
                    timeslots[i] = false;
                    break;
                }
            }
        }
        //create corresponding array of random-ish long bonuses to positions
        List <long> timeChaos = new List <long>();

        for (int i = 0; i < timeslots.Count; i++)
        {
            timeChaos.Add(0);
        }
        for (int i = 0; i < timeChaos.Count; i++)
        {
            if (timeslots[i])             //if an enemy should spawn in this timeframe,
            //get the previous bonus to make sure you're the min distance away
            {
                long previous = 0;
                if (i > 0)
                {
                    previous = timeChaos[i - 1];
                }
                //create random spawn time within the time slot allotted
                long chaos = rand.Next((int)previous, (int)interval);
                timeChaos[i] = chaos;
            }
        }
        //check to make sure nothing went wrong and timeslots and timechaos are both of length slots
        if (timeslots.Count != slots)
        {
            Debug.Log("timeslots is wrong length! slots is " + slots + " but timeslots length is " + timeslots.Count);
        }
        if (timeChaos.Count != slots)
        {
            Debug.Log("timechaos is wrong length! slots is " + slots + " but timechaos length is " + timeChaos.Count);
        }

        //finally, create final list of spawn times
        List <long> spawntimesInMillis = new List <long>();

        for (int i = 0; i < timeslots.Count; i++)
        {
            if (timeslots[i])
            {
                long spawntime = i * interval;
                spawntime += timeChaos[i];
                spawntimesInMillis.Add(spawntime);
            }
        }
        //for(int i = 0; i < spawntimesInMillis.Count; i++){
        //	Debug.Log ("wave "+ waveID + " spawntime "+i +": " + spawntimesInMillis[i]);
        //}
        //check to make sure nothing went wrong and spawntimes is of length occupants
        if (spawntimesInMillis.Count != enemyjson.Count)
        {
            Debug.Log("spawntimes and enemies don't match! (" + spawntimesInMillis.Count + "/" + enemyjson.Count + ")");
        }

        //shuffle the enemy order (fisher-yates)
        for (int i = enemyjson.Count - 1; i > 0; i--)
        {
            int           j    = rand.Next(i + 1);
            System.Object temp = enemyjson[i];
            enemyjson[i] = enemyjson[j];
            enemyjson[j] = temp;
        }

        for (int i = 0; i < enemyjson.Count; i++)
        {
            System.Object enemy = enemyjson[i];
            Dictionary <string, System.Object> enemydict = (Dictionary <string, System.Object>)enemy;
            //would load from bestiary using (string)enemydict["enemyID"], but no bestiary yet
            //long spawntimeInMillis = (long)enemydict["spawntime"];
            string filename = (string)enemydict["enemyID"];
            int    track    = (int)(long)enemydict["trackID"];
            int    trackpos = 0;
            if (enemydict.ContainsKey("trackpos"))
            {
                trackpos = (int)(long)enemydict["trackpos"];
            }
            //make enemy
            GameObject enemyspawn = GameObject.Instantiate(Resources.Load("Prefabs/MainCanvas/Enemy")) as GameObject;
            //Debug.Log("we're setting it to the spawn layer");
            //Debug.Log (Dial.spawnLayer == null);
            enemyspawn.transform.SetParent(Dial.spawnLayer, false);
            enemyspawn.SetActive(false);
            Enemy ec = enemyspawn.GetComponent <Enemy>();

            FileLoader fl = new FileLoader("JSONData" + Path.DirectorySeparatorChar + "Bestiary", filename);
            string     actualenemyjson = fl.Read();
            Dictionary <string, System.Object> actualenemydict = Json.Deserialize(actualenemyjson) as Dictionary <string, System.Object>;
            string enemytype = (string)actualenemydict["enemyType"];
            if (enemytype.Equals("Chainers"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Chainer c          = enemyobj.AddComponent <Chainer>() as Chainer;
                float   chaindelay = (float)(double)actualenemydict["delay"];
                c.delay = chaindelay;
                ec      = c;
            }
            else if (enemytype.Equals("TipOfTheSpear"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                TipOfTheSpear tots       = enemyobj.AddComponent <TipOfTheSpear>() as TipOfTheSpear;
                float         chaindelay = (float)(double)actualenemydict["delay"];
                tots.SetDelay(chaindelay);
                tots.leader = true;
                ec          = tots;
            }
            else if (enemytype.Equals("WallOfDoom"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                WallOfDoom wod = enemyobj.AddComponent <WallOfDoom>() as WallOfDoom;
                ec = wod;
            }
            else if (enemytype.Equals("TheDiversion"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Diversion d          = enemyobj.AddComponent <Diversion>() as Diversion;
                float     chaindelay = (float)(double)actualenemydict["delay"];
                d.SetDelay(chaindelay);
                ec = d;
            }
            else if (enemytype.Equals("MeatShield"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                MeatShield ms         = enemyobj.AddComponent <MeatShield>() as MeatShield;
                float      chaindelay = (float)(double)actualenemydict["delay"];
                ms.SetDelay(chaindelay);
                ms.leader = true;
                ec        = ms;
            }
            else if (enemytype.Equals("Splitter"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Splitter s = enemyobj.AddComponent <Splitter>() as Splitter;
                ec = s;
            }
            else if (enemytype.Equals("Blob"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Blob b = enemyobj.AddComponent <Blob>() as Blob;
                ec = b;
            }
            else if (enemytype.Equals("Megasplit"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Megasplit ms = enemyobj.AddComponent <Megasplit>() as Megasplit;
                ec = ms;
            }
            else if (enemytype.Equals("Melder"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Melder m = enemyobj.AddComponent <Melder>() as Melder;
                ec = m;
            }
            else if (enemytype.Equals("BigSplit"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                BigSplit bs = enemyobj.AddComponent <BigSplit>() as BigSplit;
                ec = bs;
            }
            else if (enemytype.Equals("Junior"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Junior j = enemyobj.AddComponent <Junior>() as Junior;
                ec = j;
            }
            else if (enemytype.Equals("Cheater"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Cheater ch = enemyobj.AddComponent <Cheater>() as Cheater;
                ec = ch;
            }
            else if (enemytype.Equals("Spite"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Spite s = enemyobj.AddComponent <Spite>() as Spite;
                ec = s;
            }
            else if (enemytype.Equals("Executor"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Executor s = enemyobj.AddComponent <Executor>() as Executor;
                ec = s;
            }
            else if (enemytype.Equals("Saboteur"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Saboteur s = enemyobj.AddComponent <Saboteur>() as Saboteur;
                ec = s;
            }
            else if (enemytype.Equals("Pusher"))
            {
                GameObject enemyobj = ec.gameObject;
                GameObject.Destroy(enemyobj.GetComponent <Enemy>());
                Pusher s = enemyobj.AddComponent <Pusher>() as Pusher;
                ec = s;
            }

            //give enemy a filename to load from

            ec.SetSrcFileName(filename);
            ec.SetTrackID(track);
            ec.SetTrackLane(trackpos);

            //calculate and set position
            float degrees = (track - 1) * 60 + 30;   //clockwise of y-axis
            degrees += 15 * trackpos;                //negative trackpos is left side, positive is right side, 0 is middle
            degrees  = ((360 - degrees) + 90) % 360; //convert to counterclockwise of x axis
            degrees *= Mathf.Deg2Rad;


            ((RectTransform)enemyspawn.transform).anchoredPosition = new Vector2(Dial.ENEMY_SPAWN_LENGTH * Mathf.Cos(degrees), Dial.ENEMY_SPAWN_LENGTH * Mathf.Sin(degrees));
            //set spawn time
            ec.SetSpawnTime(spawntimesInMillis[i]);

            enemies.Add(enemyspawn);
        }

        /*foreach (System.Object enemy in enemyjson) {
         *      //ec.ConfigureEnemy ();
         * }*/
    }
Esempio n. 20
0
        static void Main(string[] args)
        {
            // This is not really like the netdump example in the native WinDivert examples. Since we are
            // pulling the names of processes behind packet flows, we need to fully intercept/divert packets,
            // make the process query, then reinject. If we just sniff, the process will either be closed or
            // no longer bound to the local port the packet is associated with, and the process query will
            // be hit or miss (probably fail). So, by fully diverting rather than sniffing, we force
            // the process to hang open waiting for the packet while we check the process identity, then
            // hand the packet over untouched.
            //
            // Ideally you do not want to be querying the process on every single packet. Rather, you would
            // create a stucture that keeps track of a network flow, identify the process (protocol, whatever
            // else) one time, then only re-check when the flow has ended and a new flow has begun. This is
            // just for basic demonstration though, so we don't create and track any flows.
            //
            // Note also that the process identification is still not 100%. Many system processes run under
            // PID 4. I'm not satisfied with just getting SYSTEM for these processes, and I'd like to
            // ideally be able to identify exactly which processes they are. Still working on that.

            Console.WindowWidth = Console.LargestWindowWidth;

            bool running = true;

            Console.CancelKeyPress += delegate {
                running = false;
            };

            Diversion diversion;

            string filter = "true";

            try
            {
                diversion = Diversion.Open(filter, DivertLayer.Network, 100, 0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            if (!diversion.Handle.Valid)
            {
                Console.WriteLine("Failed to open divert handle with error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                return;
            }

            IPHeader     ipHeader     = new IPHeader();
            IPv6Header   ipv6Header   = new IPv6Header();
            ICMPHeader   icmpHeader   = new ICMPHeader();
            ICMPv6Header icmpv6Header = new ICMPv6Header();
            TCPHeader    tcpHeader    = new TCPHeader();
            UDPHeader    udpHeader    = new UDPHeader();

            Address address = new Address();

            byte[] buffer = new byte[65535];

            uint receiveLength = 0;
            uint sendLength    = 0;

            string processName;

            uint pid = 0;

            while (running)
            {
                pid = 0;

                receiveLength = 0;
                sendLength    = 0;

                if (!diversion.Receive(buffer, address, ref receiveLength))
                {
                    Console.WriteLine("Failed to receive packet with error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                    continue;
                }

                diversion.ParsePacket(buffer, receiveLength, ipHeader, ipv6Header, icmpHeader, icmpv6Header, tcpHeader, udpHeader);

                if (ipHeader.Valid && tcpHeader.Valid)
                {
                    Diversion.GetPacketProcess(address, tcpHeader, ipHeader, ref pid, out processName);

                    if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid);
                    }

                    Console.WriteLine(
                        "{0} IPv4 TCP packet captured destined for {1}:{2} from {3}:{4} {5}.",
                        address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound",
                        ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(),
                        ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(),
                        address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName)
                        );

                    Console.WriteLine(string.Format("ack: {0}, syn: {1}, len: {2}, seq: {3}", tcpHeader.Ack, tcpHeader.Syn, ipHeader.Length, tcpHeader.SequenceNumber));
                }
                else if (ipHeader.Valid && udpHeader.Valid)
                {
                    Diversion.GetPacketProcess(address, udpHeader, ipHeader, ref pid, out processName);

                    if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid);
                    }

                    Console.WriteLine(
                        "{0} IPv4 UDP packet captured destined for {1}:{2} from {3}:{4} {5}.",
                        address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound",
                        ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(),
                        ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(),
                        address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName)
                        );
                }
                else if (ipv6Header.Valid && tcpHeader.Valid)
                {
                    Diversion.GetPacketProcess(address, tcpHeader, ipv6Header, ref pid, out processName);

                    if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid);
                    }

                    Console.WriteLine(
                        "{0} IPv6 TCP packet captured destined for {1}:{2} from {3}:{4} {5}.",
                        address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound",
                        ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(),
                        ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(),
                        address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName)
                        );

                    Console.WriteLine(string.Format("ack: {0}, syn: {1}, len: {2}, seq: {3}", tcpHeader.Ack, tcpHeader.Syn, ipv6Header.Length, tcpHeader.SequenceNumber));
                }
                else if (ipv6Header.Valid && udpHeader.Valid)
                {
                    Diversion.GetPacketProcess(address, udpHeader, ipv6Header, ref pid, out processName);

                    if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid);
                    }

                    Console.WriteLine(
                        "{0} IPv6 UDP packet captured destined for {1}:{2} from {3}:{4} {5}.",
                        address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound",
                        ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(),
                        ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(),
                        address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName)
                        );
                }

                if (address.Direction == DivertDirection.Outbound)
                {
                    diversion.CalculateChecksums(buffer, receiveLength, 0);
                }

                diversion.SendAsync(buffer, receiveLength, address, ref sendLength);
            }

            diversion.Close();
        }