Example #1
0
 public DataTransferEventArgs(TransferType type, PacketFamily family, PacketAction action, byte[] rawData)
 {
     Type         = type;
     PacketFamily = family;
     PacketAction = action;
     RawByteData  = rawData;
 }
Example #2
0
 public DataTransferEventArgs(TransferType type, PacketFamily family, PacketAction action, byte[] rawData)
 {
     Type = type;
     PacketFamily = family;
     PacketAction = action;
     RawByteData = rawData;
 }
Example #3
0
        private string Command(ReadOnlyCollection <string> input)
        {
            DisplayText.Length = 0;
            string errorMessage = "";

            TheStopwatch.Reset();
            TheStopwatch.Start();
            bool   error  = false;
            string output = "";

            try {
                PacketAction pAction = ExamineUserInput(input);
                switch (pAction)
                {
                case PacketAction.Method:
                    AddMethod(input);
                    output = "Method " + Maker.MostRecentNameAdded;
                    break;

                case PacketAction.Field:
                    AddMethod(input);
                    output = "Field " + Maker.MostRecentNameAdded;
                    break;

                case PacketAction.Statement:
                    DoFieldsInitialisationIfOne();
                    Maker.DoStatement <REPL>(this, input, false);
                    output = "Statement";
                    break;

                case PacketAction.Expression:
                    DoFieldsInitialisationIfOne();
                    output = "Expression\n" + Maker.DoExpression <REPL, object>(this, input, false).ToString();
                    break;

                default: return("");
                }
            } catch (Exception ex) {
                output = ex.Message;
                error  = true;
            }
            if (StopwatchOn)
            {
                TheStopwatch.Stop();
                output = "time " + ((long)((1000000.0 * TheStopwatch.ElapsedTicks / Stopwatch.Frequency))).ToString() + "us\n" + output;
            }
            if (error)
            {
                output = "-" + output;
            }
            else
            {
                output = "+" + output;
            }
            if (DisplayText.Length != 0)
            {
                output += "\n" + DisplayText;
            }
            return(output);
        }
Example #4
0
        public IPacketBuilder WithAction(PacketAction action)
        {
            var newData = new List <byte>(_data);

            newData[0] = (byte)action;
            return(new PacketBuilder(newData));
        }
Example #5
0
 public PacketBuilder(PacketFamily family, PacketAction action)
 {
     _data = new List <byte> {
         (byte)action, (byte)family
     };
     _encoderService = new NumberEncoderService();
 }
Example #6
0
 public OldPacket(PacketFamily family, PacketAction action)
 {
     data = new List <byte>(2)
     {
         (byte)action, (byte)family
     };
 }
Example #7
0
        /// <summary>
        /// Setup the PacketSendService mock to return a packet with the specified family/action/data from SendEncodedPacketAndWaitAsync
        /// </summary>
        /// <param name="packetSendServiceMock">The mocked packet send service</param>
        /// <param name="family">Packet family for the "received" packet</param>
        /// <param name="action">Packet action for the "received" packet</param>
        /// <param name="data">Packet data payload (any additional data that should be in the packet)</param>
        internal static void SetupReceivedPacketHasHeader(this Mock <IPacketSendService> packetSendServiceMock,
                                                          PacketFamily family,
                                                          PacketAction action,
                                                          params byte[] data)
        {
            var receivedPacket = new PacketBuilder(family, action)
                                 .AddBytes(data)
                                 .Build();

            packetSendServiceMock.Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny <IPacket>()))
            .Returns(Task.FromResult(receivedPacket));
        }
Example #8
0
 /// <summary>
 /// Raises the filtering packet event.
 /// </summary>
 /// <param name="pak">The pak.</param>
 private void RaiseFilteringPacketEvent(Packet pak)
 {
     try
     {
         PacketAction e = FilteringPacketEvent;
         if (e != null)
         {
             e(pak);
         }
     }
     catch (Exception e)
     {
         Log.Error(e.Message, e);
     }
 }
Example #9
0
        public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action)
        {
            var fap = new FamilyActionPair(family, action);

            if (_inBandPackets.Contains(fap))
            {
                return(PacketHandlingType.InBand);
            }

            if (_outOfBandPackets.Contains(fap))
            {
                return(PacketHandlingType.OutOfBand);
            }

            return(PacketHandlingType.NotHandled);
        }
Example #10
0
        private static void AddPacket(string name, byte header, PacketAction action)
        {
            if (Locked)
            {
                return;
            }

            if (_headersToActions.ContainsKey(header))
            {
                Console.WriteLine("Cannot add core packet " + name + "!");
                return;
            }

            _headersToActions.Add(header, action);
            _headersToNames.Add(header, name);
            _namesToHeaders.Add(name, header);
        }
Example #11
0
        //Add packet. Will be added to list on Finalize();
        public static void AddPacket(string name, PacketAction action)
        {
            if (Locked)
            {
                return;
            }

            foreach (Packet packet in _registerQueue)
            {
                if (packet.name == name)
                {
                    Console.WriteLine("Cannot create duplicate packet type: " + name + "!");
                    return;
                }
            }

            _registerQueue.Add(new Packet(name, action));
        }
Example #12
0
        public static void Handle(NetIncomingMessage message, NetServer server, NetConnection client)
        {
            PacketFamily family  = (PacketFamily)message.ReadByte();
            PacketAction action  = (PacketAction)message.ReadByte();
            Handler      handler = handlers[(byte)family, (byte)action];

            if (handler == null)
            {
                System.Diagnostics.Debug.WriteLine("No handler set for " + family + "_" + action);
            }
            else
            {
                lock (client)
                {
                    handler(message, server, client);
                }
            }
        }
Example #13
0
        /// <summary> Reads all packets from the message and invokes the event handlers. </summary>
        protected override void HandlePacket(PipeMessage msg, bool outgoing)
        {
            Debug.Assert(msg.HasData);
            var data = msg.Data;

            int packetStart = 0;

            while (packetStart < data.Length)
            {
                //read cleartext packet header
                Debug.Assert(BitConverter.ToInt16(data, packetStart + 0) == 0x0002, "Unknown xor offset");
                short packetLen = BitConverter.ToInt16(data, packetStart + 2);

                //extract packet and parse it
                byte[] slice = new byte[packetLen]; //TODO: C# 7 slicing
                Array.Copy(data, packetStart, slice, 0, packetLen);
                SWPacket p = SWPacket.Parse(slice);
                PacketAction?.Invoke(this, new SnifferEventArgs(p, outgoing, msg.Header.SocketId));

                //update packet start
                packetStart += packetLen;
            }
        }
Example #14
0
        private static Handler[,] InitializeHandlers()
        {
            handlers = new Handler[256, 256];

            foreach (var type in Assembly.GetCallingAssembly().GetTypes())
            {
                if (type.Namespace == typeof(Handler).Namespace + ".Handlers" && type.Name.EndsWith("Handler"))
                {
                    PacketFamily family = (PacketFamily)Enum.Parse(typeof(PacketFamily), type.Name.Substring(0, type.Name.Length - 7));

                    foreach (MethodInfo method in type.GetMethods())
                    {
                        if (method.IsStatic && method.Name.StartsWith("Handle"))
                        {
                            PacketAction action = (PacketAction)Enum.Parse(typeof(PacketAction), method.Name.Substring(6));

                            handlers[(byte)family, (byte)action] = (Handler)Delegate.CreateDelegate(typeof(Handler), method);
                        }
                    }
                }
            }

            return(handlers);
        }
 public bool HandlerExists(PacketFamily family, PacketAction action)
 {
     return(_handlers.ContainsKey(new FamilyActionPair(family, action)));
 }
Example #16
0
 public static ushort PID(PacketFamily family, PacketAction action)
 {
     return((ushort)((ushort)family | (ushort)action << 8));
 }
Example #17
0
        // packet handler
        public static void ProcessPacket(Client client, string allPacketString)
        {
            string[] allPackets = allPacketString.Split('\0');
            for (int i = 0; i < allPackets.Length; i++)
            {
                string[] packet = allPackets[i].Split(' ');

                if (string.IsNullOrEmpty(packet[0]))
                {
                    break;
                }

                // handle packet based on type
                PacketAction action = (PacketAction)int.Parse(packet[0]);
                switch (action)
                {
                // place ship
                case PacketAction.PLACESHIP:
                {
                    Tuple <int, int> location = MnemonicToIndex(packet[1]);
                    client.ChangeGrid(location.Item1, location.Item2, 'S');
                    break;
                }

                // both clients connected, start game
                case PacketAction.GAMEREADY:
                {
                    client.GameReady = true;
                    if (_client1 != null && _client1.IsConnected() && _client1.GameReady &&
                        _client2 != null && _client2.IsConnected() && _client2.GameReady)
                    {
                        Random r      = new Random();
                        int    select = r.Next() % 2;      // coin flip to decide who goes first
                        if (select == 0)
                        {
                            // client 1 goes first
                            _client1.SendPacket(((int)PacketAction.PLAYERTURN).ToString());
                            _client2.SendPacket(((int)PacketAction.OPPONENTTURN).ToString());
                        }
                        else
                        {
                            // client 2 goes first
                            _client2.SendPacket(((int)PacketAction.PLAYERTURN).ToString());
                            _client1.SendPacket(((int)PacketAction.OPPONENTTURN).ToString());
                        }
                    }
                    break;
                }

                // player attack success
                case PacketAction.PLAYERATTACK:
                {
                    // if client 1 is attacking,
                    if (client == _client1)
                    {
                        // get attack coordinates
                        Tuple <int, int> location = MnemonicToIndex(packet[1]);

                        // if there is an enemy ship at the coordinates,
                        if (_client2.GetAttack(location.Item1, location.Item2))
                        {
                            // check if client 2 has any ships left,
                            if (!_client2.CheckIfLose())
                            {
                                // send attack to client 2
                                string message = ((int)PacketAction.OPPONENTATTACK).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client2.SendPacket(message);

                                // send feedback to client 1
                                message = ((int)PacketAction.PLAYERHIT).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client1.SendPacket(message);
                            }
                            // if client 2 has no ships left
                            else
                            {
                                // client 1 wins
                                string message = ((int)PacketAction.PLAYERWIN).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client1.SendPacket(message);

                                // client 2 loses
                                // send packet to display all the opponent's ships
                                for (int x = 0; x < Client.GRID_SIZE; x++)
                                {
                                    for (int y = 0; y < Client.GRID_SIZE; y++)
                                    {
                                        if (_client1.CheckGridStatus(x, y) == 'S')
                                        {
                                            message = ((int)PacketAction.DISPLAYSHIP).ToString() + " " + IndexToMnemonic(x, y);
                                            _client2.SendPacket(message);
                                        }
                                    }
                                }

                                message = ((int)PacketAction.PLAYERLOSS).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client2.SendPacket(message);
                            }
                        }
                        // if there is no enemy ship at the coordinates,
                        else
                        {
                            // send attack to client 2
                            string message = ((int)PacketAction.OPPONENTATTACK).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                            _client2.SendPacket(message);

                            //send feedback to client 1
                            message = ((int)PacketAction.PLAYERMISS).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                            _client1.SendPacket(message);
                        }
                    }

                    // or, if client 2 is attacking,
                    else
                    {
                        // get attack coordinates
                        Tuple <int, int> location = MnemonicToIndex(packet[1]);

                        // if there is an enemy ship at the coordinates,
                        if (_client1.GetAttack(location.Item1, location.Item2))
                        {
                            // check if client 1 has any ships left,
                            if (!_client1.CheckIfLose())
                            {
                                // send attack to client 1
                                string message = ((int)PacketAction.OPPONENTATTACK).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client1.SendPacket(message);

                                // send feedback to client 2
                                message = ((int)PacketAction.PLAYERHIT).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client2.SendPacket(message);
                            }
                            // if client 1 has no ships left
                            else
                            {
                                // client 2 wins
                                string message = ((int)PacketAction.PLAYERWIN).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client2.SendPacket(message);

                                // client 1 loses
                                // send packet to display all the opponent's ships
                                for (int x = 0; x < Client.GRID_SIZE; x++)
                                {
                                    for (int y = 0; y < Client.GRID_SIZE; y++)
                                    {
                                        if (_client2.CheckGridStatus(x, y) == 'S')
                                        {
                                            message = ((int)PacketAction.DISPLAYSHIP).ToString() + " " + IndexToMnemonic(x, y);
                                            _client1.SendPacket(message);
                                        }
                                    }
                                }

                                message = ((int)PacketAction.PLAYERLOSS).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                                _client1.SendPacket(message);
                            }
                        }
                        // if there is no enemy ship at the coordinates,
                        else
                        {
                            // send attack to client 1
                            string message = ((int)PacketAction.OPPONENTATTACK).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                            _client1.SendPacket(message);

                            //send feedback to client 2
                            message = ((int)PacketAction.PLAYERMISS).ToString() + " " + IndexToMnemonic(location.Item1, location.Item2);
                            _client2.SendPacket(message);
                        }
                    }
                    break;
                }

                default:
                    Program.DisconnectClient(client);
                    break;
                }
            }
        }
Example #18
0
        public PacketAction Defragment(int direction)
        {
            PacketAction result = PacketAction.NONE;

            bool LoopAgain = true;

            while (LoopAgain)
            {
                LoopAgain = false;
                foreach (TCPPacket packet in Packets[direction])
                {
                    if (packet.MinSequence <= Sequence[direction])
                    {
                        Packets[direction].Remove(packet);
                        if (packet.MaxSequence > Sequence[direction])  // i.e. if adds anything new
                        {
                            long srcIndex         = packet.DataStart + (Sequence[direction] - packet.MinSequence);
                            long length           = packet.MaxSequence - Sequence[direction];
                            long packetDataLength = packet.Packet.Length;

                            if (length > packetDataLength)
                            {
                                //ErrorLog("Unreasonable TCP/IP packet.Setting the packet length as received data length");

                                //Setting the packet length as received data length
                                //length = packetDataLength - srcIndex;
                                return(PacketAction.DEAD);
                            }
                            long stPos         = Position[direction];
                            long requiredLengh = stPos + length + 10;//10 is approximately added... because sometimes system is throwing exception
                            long arLength      = data[direction].Length;
                            if (requiredLengh > arLength)
                            {
                                Array.Resize(ref data[direction], (int)(arLength + (requiredLengh - arLength)));
                            }


                            Array.Copy(packet.Packet, srcIndex, data[direction], Position[direction], length);
                            Position[direction] += (uint)(packet.MaxSequence - Sequence[direction]);
                            Sequence[direction]  = packet.MaxSequence;
                            Times[direction].Add(new PacketTime(packet.TimeStamp, packet.MinSequence));
                            return(PacketAction.DATA);
                        }

                        if (packet.FIN)
                        {
                            State[direction] = States.FINISHED;
                            return(PacketAction.FIN);
                        }

                        if (packet.RST)
                        {
                            State[direction] = States.FINISHED;
                            return(PacketAction.RST);
                        }

                        LoopAgain = true; // here for repeats etc.
                        break;            // to restart iterator
                    }
                    else  // beyond current position
                    {
                        if (packet.MaxSequence > Sequence[direction] + packet.PTcp.WindowSize * 2 && Sequence[direction] != 0) // more than twice ahead of window means likely missed data
                        {
                            result = PacketAction.DEAD;
                        }
                    }
                }
            }


            return(result);
        }
Example #19
0
 /// <summary>
 /// Sets a PacketAction binding.
 /// </summary>
 /// <param name="type">The type of packet.</param>
 /// <param name="action">The action to bind.</param>
 public void SetAction(byte type, PacketAction action)
 {
     #if DEBUG
     if (!isSystem && type >= ReservedPacketTypeLower && type <= ReservedPacketTypeUpper)
         throw new Exception("Cannot assign to a reserved packet type.");
     #endif
     Actions[type] = action;
 }
Example #20
0
 public Packet(string name, PacketAction action)
 {
     this.name   = name;
     this.action = action;
 }
 public EOPacketHandler(PacketFamily family, PacketAction action, EOPacketChannel channel)
 {
     this.Family  = family;
     this.Action  = action;
     this.Channel = channel;
 }
Example #22
0
 public static ushort PID(PacketFamily family, PacketAction action)
 {
     return (ushort)((ushort)family | (ushort)action << 8);
 }
Example #23
0
 public Packet(PacketFamily family, PacketAction action)
 {
     data = new List<byte>(2) {(byte) action, (byte) family};
 }
 public IPacketHandler FindHandler(PacketFamily family, PacketAction action)
 {
     return(_handlers[new FamilyActionPair(family, action)]);
 }
Example #25
0
 // ReSharper disable once UnusedMember.Global
 public void SetID(PacketFamily family, PacketAction action)
 {
     data[0] = (byte)action;
     data[1] = (byte)family;
 }
Example #26
0
        // packet handler
        private void ProcessPacket(string allPacketString)
        {
            string[] allPackets = allPacketString.Split('\0');
            for (int i = 0; i < allPackets.Length; i++)
            {
                string[] packet = allPackets[i].Split(' ');

                if (string.IsNullOrEmpty(packet[0]))
                {
                    break;
                }

                // get packet type
                PacketAction action = (PacketAction)int.Parse(packet[0]);

                // handle packet based on type
                switch (action)
                {
                // opponent attacking player
                case PacketAction.OPPONENTATTACK:
                {
                    Tuple <int, int> coord = MnemonicToIndex(packet[1]);
                    ProcessOpponentAttack(coord.Item1, coord.Item2);
                    CurStage = Stage.PLAYERTURN;
                    break;
                }

                // opponent connected
                case PacketAction.OPPONENTREADY:
                    CurStage = Stage.PLACEBATTLESHIP;
                    break;

                // ship placement turn
                case PacketAction.PLACESHIP:
                    CurStage++;
                    break;

                // player's turn
                case PacketAction.PLAYERTURN:
                    CurStage = Stage.PLAYERTURN;
                    break;

                // opponent's turn
                case PacketAction.OPPONENTTURN:
                    CurStage = Stage.OPPONENTTURN;
                    break;

                // feedback for player's attack succeeding
                case PacketAction.PLAYERHIT:
                {
                    Tuple <int, int> coord = MnemonicToIndex(packet[1]);
                    _opponentTiles[coord.Item1][coord.Item2].Status = 'H';
                    statusBox.Invoke(new MethodInvoker(delegate() { statusBox.Text = "Hit at " + packet[1] + "."; }));
                    CurStage = Stage.OPPONENTTURN;
                    break;
                }

                // feedback for player's attack failing
                case PacketAction.PLAYERMISS:
                {
                    Tuple <int, int> coord = MnemonicToIndex(packet[1]);
                    _opponentTiles[coord.Item1][coord.Item2].Status = 'M';
                    statusBox.Invoke(new MethodInvoker(delegate() { statusBox.Text = "Miss at " + packet[1] + "."; }));
                    CurStage = Stage.OPPONENTTURN;
                    break;
                }

                // your opponent has been disconnected, disconnect player
                case PacketAction.OPPONENTFORFEIT:
                    CurStage = Stage.WIN;

                    // see results, but close connection.
                    _sock.Close();
                    _sock = null;
                    statusBox.Invoke(new MethodInvoker(delegate() { statusBox.Text = "Your opponent has disconnected and forfeited!"; }));
                    break;

                // server is full, disconnect
                case PacketAction.TOOMANYCONNECTIONS:
                    DisconnectClient();
                    statusBox.Invoke(new MethodInvoker(delegate() { statusBox.Text = "Error: Too many connections!"; }));
                    break;

                // display opponent's ships when lost.
                case PacketAction.DISPLAYSHIP:
                {
                    Tuple <int, int> coord = MnemonicToIndex(packet[1]);
                    if (_opponentTiles[coord.Item1][coord.Item2].Status == 'N')
                    {
                        _opponentTiles[coord.Item1][coord.Item2].Status = 'S';
                    }

                    break;
                }

                // player wins!
                case PacketAction.PLAYERWIN:
                {
                    Tuple <int, int> coord = MnemonicToIndex(packet[1]);
                    _opponentTiles[coord.Item1][coord.Item2].Status = 'H';
                    CurStage = Stage.WIN;

                    // see results, but close connection.
                    _sock.Close();
                    _sock = null;
                    statusBox.Invoke(new MethodInvoker(delegate() { statusBox.Text = "You won! To play again, please disconnect and reconnect to the server."; }));
                    break;
                }

                // player loses!
                case PacketAction.PLAYERLOSS:
                {
                    Tuple <int, int> coord = MnemonicToIndex(packet[1]);
                    _playerTiles[coord.Item1][coord.Item2].Status = 'H';
                    CurStage = Stage.LOSE;

                    // see results, but close connection.
                    _sock.Close();
                    _sock = null;
                    statusBox.Invoke(new MethodInvoker(delegate() { statusBox.Text = "You lost... To play again, please disconnect and reconnect to the server."; }));
                    break;
                }

                // error, disconnect
                default:
                    DisconnectClient(); break;
                }
            }
        }
Example #27
0
 public FamilyActionPair(PacketFamily family, PacketAction action)
 {
     fam = family;
     act = action;
 }
Example #28
0
// ReSharper disable once UnusedMember.Global
        public void SetID(PacketFamily family, PacketAction action)
        {
            data[0] = (byte)action;
            data[1] = (byte)family;
        }
Example #29
0
 public FamilyActionPair(PacketFamily family, PacketAction action)
 {
     fam = family;
     act = action;
 }
Example #30
0
 /// <summary>
 /// initiate a packet builder with pre-defined family and actions
 /// </summary>
 /// <param name="family"></param>
 /// <param name="action"></param>
 public PacketBuilder(PacketFamily family, PacketAction action)
 {
     _data = new byte[] { (byte)family, (byte)action };
 }