Ejemplo n.º 1
0
        private void CmdGUITurnMessage(ActorTurnSM actorTurnSM, int msgEnum, int extraData)
        {
            ActorData   actor = actorTurnSM.gameObject.GetComponent <ActorData>();
            TurnMessage msg   = (TurnMessage)msgEnum;

            if (!GameFlowData.Get().IsInDecisionState())
            {
                Log.Info($"Recieved CmdGuiTurnMessage not in desicion state! {actor.DisplayName} {msg} ({extraData})");
                return;
            }

            Log.Info($"CmdGuiTurnMessage {actor.DisplayName} {msg} ({extraData})");
            if (msg == TurnMessage.CANCEL_BUTTON_CLICKED)
            {
                // TODO distinguish CANCEL button and ability cancelling
                // actor.TeamSensitiveData_authority.SetToggledAction(actionType, false);
                // if (DONE) make undone
                // else if (targeting action) set toggled action(false)
                actorTurnSM.CallRpcTurnMessage((int)TurnMessage.CANCEL_BUTTON_CLICKED, 0);
            }
            else if (msg == TurnMessage.DONE_BUTTON_CLICKED)
            {
                actorTurnSM.CallRpcTurnMessage((int)TurnMessage.DONE_BUTTON_CLICKED, 0);
            }
            // TODO: Timebanks. Notice that client sends CANCEL msg when selecting ability after confirmed
            // (but we still should have a fallback if it doesn't) but doesn't send one when updating movement.
        }
Ejemplo n.º 2
0
 public void SetResponse(TurnMessage newResponse)
 {
     lock (sync)
     {
         response = newResponse;
     }
 }
Ejemplo n.º 3
0
        public void ParseTest2()
        {
            byte[] bytes = new byte[]
            {
                0x01, 0x01, 0x00, 0x3c,                 //     Response type and message length
                0x21, 0x12, 0xa4, 0x42,                 //     Magic cookie
                0xb7, 0xe7, 0xa7, 0x01,                 //  }
                0xbc, 0x34, 0xd6, 0x86,                 //  }  Transaction ID
                0xfa, 0x87, 0xdf, 0xae,                 //  }
                0x80, 0x22, 0x00, 0x0b,                 //     SOFTWARE attribute header
                0x74, 0x65, 0x73, 0x74,                 //  }
                0x20, 0x76, 0x65, 0x63,                 //  }  UTF-8 server name
                0x74, 0x6f, 0x72, 0x20,                 //  }
                0x00, 0x20, 0x00, 0x08,                 //     XOR-MAPPED-ADDRESS attribute header
                0x00, 0x01, 0xa1, 0x47,                 //     Address family (IPv4) and xor'd mapped port number
                0xe1, 0x12, 0xa6, 0x43,                 //     Xor'd mapped IPv4 address
                0x00, 0x08, 0x00, 0x14,                 //     MESSAGE-INTEGRITY attribute header
                0x2b, 0x91, 0xf5, 0x99,                 //  }
                0xfd, 0x9e, 0x90, 0xc3,                 //  }
                0x8c, 0x74, 0x89, 0xf9,                 //  }  HMAC-SHA1 fingerprint
                0x2a, 0xf9, 0xba, 0x53,                 //  }
                0xf0, 0x6b, 0xe7, 0xd7,                 //  }
                0x80, 0x28, 0x00, 0x04,                 //     FINGERPRINT attribute header
                0xc0, 0x7d, 0x4c, 0x96,                 //     CRC32 fingerprint
            };

            string password = @"VOkJxbRl1RmTxUk/WvJxBt";

            TurnMessage message = TurnMessage.Parse(bytes, TurnMessageRfc.Rfc5389);

            Assert.AreEqual(@"test vector", message.Software.Value);
            Assert.AreEqual(@"192.0.2.1", message.XorMappedAddress.IpAddress.ToString());
            Assert.AreEqual(32853, message.XorMappedAddress.Port);

            byte[] messageIntegrity = message.ComputeMessageIntegrity(password, false);

            Helpers.AreArrayEqual(messageIntegrity, message.MessageIntegrity.Value);
            Assert.AreEqual(0x3c, bytes[3]);

            uint fingerprint = message.ComputeFingerprint();

            Assert.AreEqual(fingerprint, message.Fingerprint.Value);

            byte[] actual = message.GetBytes(password, false, 0x20);
            Helpers.AreArrayEqual(bytes, actual);

            TurnMessage message2 = new TurnMessage()
            {
                MessageType      = MessageType.BindingResponse,
                TransactionId    = message.TransactionId,
                Software         = message.Software,
                XorMappedAddress = message.XorMappedAddress,
                MessageIntegrity = new MessageIntegrity(),
                Fingerprint      = new Fingerprint(),
            };

            byte[] actual2 = message2.GetBytes(password, false, 0x20);

            Helpers.AreArrayEqual(bytes, actual2);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 同步游戏
        /// </summary>
        /// <param name="self"></param>
        public static void SyncTurn(this GameController self)
        {
            Room room = self.GetParent <Room>();

            // 轮转消息
            TurnMessage msg = new TurnMessage();

            msg.CurrentSeat = self.CurrentSeat;
            msg.LastOpSeat  = self.LastOpSeat;

            // 最后操作的玩家
            Player lastPlayer = room.Players[self.LastOpSeat];

            msg.LastOp = (int)lastPlayer.Action;

            // 最后操作是出了牌的,才同步牌桌上的牌。
            if (lastPlayer.Action == PlayerAction.Play)
            {
                msg.DeskSeat  = self.DeskSeat;
                msg.DeskCards = self.DeskCards.Select(f => new CardProto {
                    Color = (int)f.Color, Weight = (int)f.Weight
                }).ToList();
                msg.DeskCardType = (int)self.DeskCardType;
            }

            for (int i = 0; i < room.Players.Length; i++)
            {
                var item = room.Players[i];
                room.SendActor(item, msg);
            }

            Log.Debug($"[Room:{self.GetParent<Room>().Num}] 轮转消息:{self.CurrentSeat}");
        }
Ejemplo n.º 5
0
        private TurnMessage ProcessSendRequest(Allocation allocation, TurnMessage request, ref ServerAsyncEventArgs e)
        {
            try
            {
                if (allocation == null)
                {
                    throw new TurnServerException(ErrorCode.NoBinding);
                }

                if (request.Data == null || request.DestinationAddress == null)
                {
                    throw new TurnServerException(ErrorCode.BadRequest);
                }

                allocation.Permissions.Permit(request.DestinationAddress.IpEndPoint);

                e.LocalEndPoint  = allocation.Alocated;
                e.RemoteEndPoint = request.DestinationAddress.IpEndPoint;
                e.Offset         = request.Data.ValueRefOffset;
                e.Count          = request.Data.ValueRefLength;
                e.ConnectionId   = ServerAsyncEventArgs.AnyNewConnectionId;

                peerServer.SendAsync(e);

                e = null;
            }
            catch (Exception ex)
            {
                logger.WriteWarning(ex.ToString());
            }

            // [MS-TURN] The server MUST NOT respond to a client with either
            // a Send response or a Send error response.
            return(null);
        }
Ejemplo n.º 6
0
        private TurnMessage ReceiveMessage(Socket socket)
        {
            byte[] buffer1 = new byte[4096];
            socket.ReceiveTimeout = 10000;
            int length1 = socket.Receive(buffer1);

            return(TurnMessage.Parse(buffer1, TcpFramingHeader.TcpFramingHeaderLength, length1 - TcpFramingHeader.TcpFramingHeaderLength, TurnMessageRfc.MsTurn));
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Get messages to send in response to a TurnMessage
 /// </summary>
 /// <param name="playerId"> The uid of the player </param>
 /// <param name="turnMessage"></param>
 /// <returns> List of messages to be sent </returns>
 public MessagePackets HandleTurn(string playerId, TurnMessage turnMessage)
 {
     lock (this)
     {
         GameManager gm = GetGameManager(playerId);
         return(Do(gm, () => gm.HandleTurn(turnMessage)));
     }
 }
Ejemplo n.º 8
0
        private ErrorCode?ValidateRequest(TurnMessage request)
        {
            if (request.MessageIntegrity == null)
            {
                return(ErrorCode.Unauthorized);
            }

            if (request.MessageType == MessageType.AllocateRequest)
            {
                if (request.Realm == null)
                {
                    return(ErrorCode.MissingRealm);
                }

                if (request.Nonce == null)
                {
                    return(ErrorCode.MissingNonce);
                }

                if (IsValidNonce(request.Nonce.Value) == false)
                {
                    return(ErrorCode.StaleNonce);
                }
            }

            if (request.MsUsername == null)
            {
                return(ErrorCode.MissingUsername);
            }

            if (request.IsValidMsUsername(Key1) == false)
            {
                return(ErrorCode.UnknownUsername);
            }


            if (request.Realm != null)
            {
                if (request.Realm.Value != Realm)
                {
                    return(ErrorCode.MissingRealm);
                }
            }
            else
            {
                request.Realm = realm;
            }


            if (request.IsValidMessageIntegrity(Key2) == false)
            {
                return(ErrorCode.IntegrityCheckFailure);
            }

            return(null);
        }
Ejemplo n.º 9
0
        private void SendTurn(TurnMessage message, ServerEndPoint local, IPEndPoint remote)
        {
            ServerAsyncEventArgs p;
            int offset;

            message.ComputeMessageLength();

            GetBuffer(local, remote, message.TotalMessageLength, out p, out offset);

            message.GetBytes(p.Buffer, offset, Authentificater.Key2);

            turnServer.SendAsync(p);
        }
Ejemplo n.º 10
0
        public void Message_Integrity_And_Fingerprint_With_Data_Offset_In_Array()
        {
            byte[] bytes = new byte[]
            {
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // } Dummy data for testing offset
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }
                0xFF, 0xFF, 0xFF, 0xFF,                 // }

                0x01, 0x01, 0x00, 0x48,                 //     Response type and message length
                0x21, 0x12, 0xa4, 0x42,                 //     Magic cookie
                0xb7, 0xe7, 0xa7, 0x01,                 //  }
                0xbc, 0x34, 0xd6, 0x86,                 //  }  Transaction ID
                0xfa, 0x87, 0xdf, 0xae,                 //  }
                0x80, 0x22, 0x00, 0x0b,                 //     SOFTWARE attribute header
                0x74, 0x65, 0x73, 0x74,                 //  }
                0x20, 0x76, 0x65, 0x63,                 //  }  UTF-8 server name
                0x74, 0x6f, 0x72, 0x20,                 //  }
                0x00, 0x20, 0x00, 0x14,                 //     XOR-MAPPED-ADDRESS attribute header
                0x00, 0x02, 0xa1, 0x47,                 //     Address family (IPv6) and xor'd mapped port number
                0x01, 0x13, 0xa9, 0xfa,                 //  }
                0xa5, 0xd3, 0xf1, 0x79,                 //  }  Xor'd mapped IPv6 address
                0xbc, 0x25, 0xf4, 0xb5,                 //  }
                0xbe, 0xd2, 0xb9, 0xd9,                 //  }
                0x00, 0x08, 0x00, 0x14,                 //     MESSAGE-INTEGRITY attribute header
                0xa3, 0x82, 0x95, 0x4e,                 //  }
                0x4b, 0xe6, 0x7b, 0xf1,                 //  }
                0x17, 0x84, 0xc9, 0x7c,                 //  }  HMAC-SHA1 fingerprint
                0x82, 0x92, 0xc2, 0x75,                 //  }
                0xbf, 0xe3, 0xed, 0x41,                 //  }
                0x80, 0x28, 0x00, 0x04,                 //     FINGERPRINT attribute header
                0xc8, 0xfb, 0x0b, 0x4c,                 //     CRC32 fingerprint
            };

            string password = @"VOkJxbRl1RmTxUk/WvJxBt";

            TurnMessage message = TurnMessage.Parse(bytes, 40, bytes.Length - 40, TurnMessageRfc.Rfc5389);

            byte[] messageIntegrity = message.ComputeMessageIntegrity(password, false);

            Helpers.AreArrayEqual(messageIntegrity, message.MessageIntegrity.Value);

            Assert.AreEqual(message.ComputeFingerprint(), message.Fingerprint.Value);
        }
Ejemplo n.º 11
0
        private void SendMessage(Socket socket, TurnMessage message)
        {
            byte[] buffer1 = new byte[4096];

            message.ComputeMessageLength();
            message.GetBytes(buffer1, TcpFramingHeader.TcpFramingHeaderLength, key2);

            TcpFramingHeader.GetBytes(buffer1, 0, TcpFrameType.ControlMessage, message.TotalMessageLength);

            int size = TcpFramingHeader.TcpFramingHeaderLength + message.TotalMessageLength;

            if (socket.Send(buffer1, size, SocketFlags.None) != size)
            {
                throw new Exception("Send failed!");
            }
        }
Ejemplo n.º 12
0
        public void ParseTest1()
        {
            byte[] bytes = new byte[]
            {
                0x00, 0x01, 0x00, 0x58,                 //     Request type and message length
                0x21, 0x12, 0xa4, 0x42,                 //     Magic cookie
                0xb7, 0xe7, 0xa7, 0x01,                 //  }
                0xbc, 0x34, 0xd6, 0x86,                 //  }  Transaction ID
                0xfa, 0x87, 0xdf, 0xae,                 //  }
                0x80, 0x22, 0x00, 0x10,                 //     SOFTWARE attribute header
                0x53, 0x54, 0x55, 0x4e,                 //  }
                0x20, 0x74, 0x65, 0x73,                 //  }  User-agent...
                0x74, 0x20, 0x63, 0x6c,                 //  }  ...name
                0x69, 0x65, 0x6e, 0x74,                 //  }
                0x00, 0x24, 0x00, 0x04,                 //     PRIORITY attribute header
                0x6e, 0x00, 0x01, 0xff,                 //     ICE priority value
                0x80, 0x29, 0x00, 0x08,                 //     ICE-CONTROLLED attribute header
                0x93, 0x2f, 0xf9, 0xb1,                 //  }  Pseudo-random tie breaker...
                0x51, 0x26, 0x3b, 0x36,                 //  }   ...for ICE control
                0x00, 0x06, 0x00, 0x09,                 //     USERNAME attribute header
                0x65, 0x76, 0x74, 0x6a,                 //  }
                0x3a, 0x68, 0x36, 0x76,                 //  }  Username (9 bytes) and padding (3 bytes)
                0x59, 0x20, 0x20, 0x20,                 //  }
                0x00, 0x08, 0x00, 0x14,                 //     MESSAGE-INTEGRITY attribute header
                0x9a, 0xea, 0xa7, 0x0c,                 //  }
                0xbf, 0xd8, 0xcb, 0x56,                 //  }
                0x78, 0x1e, 0xf2, 0xb5,                 //  }  HMAC-SHA1 fingerprint
                0xb2, 0xd3, 0xf2, 0x49,                 //  }
                0xc1, 0xb5, 0x71, 0xa2,                 //  }
                0x80, 0x28, 0x00, 0x04,                 //     FINGERPRINT attribute header
                0xe5, 0x7a, 0x3b, 0xcf,                 //     CRC32 fingerprint
            };

            TurnMessage message = TurnMessage.Parse(bytes, TurnMessageRfc.Rfc5389);

            Assert.AreEqual(@"evtj:h6vY", message.Username.Value);
            Assert.AreEqual(@"STUN test client", message.Software.Value);

            byte[] messageIntegrity = message.ComputeMessageIntegrity(@"VOkJxbRl1RmTxUk/WvJxBt", false);

            Helpers.AreArrayEqual(messageIntegrity, message.MessageIntegrity.Value);
            Assert.AreEqual(0x58, bytes[3]);

            uint fingerprint = message.ComputeFingerprint();

            Assert.AreEqual(fingerprint, message.Fingerprint.Value);
        }
Ejemplo n.º 13
0
        private void HandleTurnMessage(String address, AbstractMessage message)
        {
            GameScreen  gameScreen  = GameScreen.GetInstance();
            TurnMessage turnMessage = (TurnMessage)message;

            gameScreen.ActualTurn = turnMessage.Turn;
            gameScreen.Handlers.Peek().FillOptions();

            if (gameScreen.SelectedCharacter == null)
            {
                gameScreen.MapCursor.MapLocation = Camera.GetInstance().CenterLocation;
                gameScreen.MapCursor.IsVisible   = true;
            }
            else
            {
                Camera.GetInstance().FocusOn(gameScreen.SelectedCharacter.MapLocation);
                gameScreen.MapCursor.IsVisible = false;
            }
        }
Ejemplo n.º 14
0
        private TurnMessage GetErrorResponse(ErrorCode errorCode, SocketAsyncEventArgs e)
        {
            MessageType?  messageType = TurnMessage.SafeGetMessageType(e.Buffer, e.Offset, e.Count);
            TransactionId id          = TurnMessage.SafeGetTransactionId(e.Buffer, e.Offset, e.Count);

            if (messageType != null && id != null)
            {
                return(new TurnMessage()
                {
                    MessageType = ((MessageType)messageType).GetErrorResponseType(),
                    TransactionId = id,
                    ErrorCodeAttribute = new ErrorCodeAttribute()
                    {
                        ErrorCode = (int)errorCode,
                        ReasonPhrase = errorCode.GetReasonPhrase(),
                    },
                });
            }

            return(null);
        }
Ejemplo n.º 15
0
        public bool Process(TurnMessage request, out TurnMessage response)
        {
            lock (syncRoot)
            {
                ErrorCode?errorCode = ValidateRequest(request);

                if (errorCode != null)
                {
                    response = new TurnMessage()
                    {
                        MessageType        = request.MessageType.GetErrorResponseType(),
                        TransactionId      = request.TransactionId,
                        MagicCookie        = new MagicCookie(),
                        ErrorCodeAttribute = new ErrorCodeAttribute()
                        {
                            ErrorCode    = (int)errorCode,
                            ReasonPhrase = ((ErrorCode)errorCode).GetReasonPhrase(),
                        },
                        Realm = new Realm(TurnMessageRfc.MsTurn)
                        {
                            Value = Realm,
                        },
                        Nonce = new Nonce(TurnMessageRfc.MsTurn)
                        {
                            Value = NewNonce(),
                        },
                        MsVersion = new MsVersion()
                        {
                            Value = 1,
                        },
                    };
                }
                else
                {
                    response = null;
                }

                return(response == null);
            }
        }
Ejemplo n.º 16
0
        public void MS_Message_Integrity_With_Data_Offset_In_Array()
        {
            var key2 = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            var created = new TurnMessage()
            {
                MessageType   = MessageType.AllocateRequest,
                TransactionId = TransactionId.Generate(),
                MagicCookie   = new MagicCookie(),
                MsVersion     = new MsVersion()
                {
                    Value = 1,
                },
                MsUsername = new MsUsername()
                {
                    Value = new byte[52],
                },
                Nonce = new Nonce(TurnMessageRfc.MsTurn)
                {
                    Value = "17938999-C63D-41cd-87A4-FE80975F03BA",
                },
                Realm = new Realm(TurnMessageRfc.MsTurn)
                {
                    Value = "test.test",
                },
                MessageIntegrity = new MessageIntegrity(),
            };

            int offset = 120;
            var buffer = new byte[4096];

            created.ComputeMessageLength();
            created.GetBytes(buffer, offset, key2);

            var parsed = TurnMessage.Parse(buffer, offset, created.TotalMessageLength, TurnMessageRfc.MsTurn);

            Assert.IsTrue(parsed.IsValidMessageIntegrity(key2));
        }
Ejemplo n.º 17
0
        public void TestHandleJoinGameStart()
        {
            string         uid      = "uid";
            string         gameName = "fullGame";
            List <string>  uids     = new List <string>();
            MessagePackets messages = new MessagePackets();

            for (int i = 0; i < 4; i++)
            {
                string num = i.ToString();
                uids.Add(uid + num);
                messages = JoinGame(uid + num, num, gameName);
            }

            Assert.IsTrue(gm.HasStarted());
            Assert.AreEqual(gm.GetCurrentPlayerIndex(), 1);
            Assert.AreEqual(gm.GetDealerIndex(), 0);

            Assert.IsTrue(Utils.VerifyMessagePackets(messages, typeof(JoinResponse),
                                                     typeof(JoinMessage), typeof(JoinMessage), typeof(JoinMessage), typeof(JoinMessage),
                                                     typeof(StartMessage), typeof(StartMessage), typeof(StartMessage), typeof(StartMessage), typeof(TurnMessage)));

            List <Player> players = gm.GetPlayers();

            for (int i = 5; i < 9; i++)
            {
                Assert.AreEqual(messages.Messages[i].SendTo.Single(), uid + (i - 5).ToString());
                StartMessage sm = (StartMessage)messages.Messages[i].Message;
                Assert.AreEqual(sm.Cards.Length, 13);
                CollectionAssert.AreEqual(sm.Cards, players[i - 5].Cards);
            }
            CollectionAssert.AreEqual(messages.Messages[9].SendTo.ToList(), uids);
            TurnMessage tm = (TurnMessage)messages.Messages[9].Message;

            Assert.AreEqual(tm.PlayerName, "1");
            CollectionAssert.AreEqual(tm.ValidCards, ((StartMessage)messages.Messages[6].Message).Cards);
            Assert.IsTrue(tm.IsFirstCard);
        }
Ejemplo n.º 18
0
    private void HandleTurn(TurnMessage turnMessage)
    {
        ViewController.Instance.DoOnClear(() =>
        {
            if (turnMessage.IsFirstCard)
            {
                ViewController.Instance.UnHighlightNames();
                ViewController.Instance.HighlightName(turnMessage.PlayerName);
            }

            if (turnMessage.Card == null)
            {
                if (turnMessage.PlayerName == PlayerName)
                {
                    ViewController.Instance.EnablePlayCard(turnMessage.ValidCards);
                }
            }
            else
            {
                ViewController.Instance.ShowPlayedCard(turnMessage.Card, turnMessage.PlayerName, turnMessage.PlayerName == PlayerName);
            }
        });
    }
Ejemplo n.º 19
0
        public void DoubleTcpAllocationTest()
        {
            var msUsername = new MsUsername()
            {
                Value = new byte[52],
            };

            using (HMACSHA1 sha1 = new HMACSHA1(key1))
            {
                sha1.ComputeHash(msUsername.Value, 0, msUsername.TokenBlobLength);
                Array.Copy(sha1.Hash, 0, msUsername.Value, msUsername.TokenBlobLength, MsUsername.HashOfTokenBlobLength);
            }

            var allocate1 = new TurnMessage()
            {
                MessageType   = MessageType.AllocateRequest,
                TransactionId = TransactionId.Generate(),

                MagicCookie = new MagicCookie(),
                MsVersion   = new MsVersion()
                {
                    Value = 1,
                },
                MsUsername = msUsername,
            };

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(turnIp, tcpPort);

            var allocate1response = SendReceiveMessage(socket, allocate1);

            Assert.AreEqual(MessageType.AllocateErrorResponse, allocate1response.MessageType);
            Assert.AreEqual(401, allocate1response.ErrorCodeAttribute.ErrorCode);

            var allocate2 = new TurnMessage()
            {
                MessageType   = MessageType.AllocateRequest,
                TransactionId = TransactionId.Generate(),

                MagicCookie = new MagicCookie(),
                MsVersion   = new MsVersion()
                {
                    Value = 1,
                },
                MsUsername = msUsername,
                Nonce      = allocate1response.Nonce,
                Realm      = new Realm(TurnMessageRfc.MsTurn)
                {
                    Value = realm,
                },
                MessageIntegrity = new MessageIntegrity(),
            };

            var allocate2response = SendReceiveMessage(socket, allocate2);

            Assert.AreEqual(MessageType.AllocateResponse, allocate2response.MessageType);

            var allocate3response = SendReceiveMessage(socket, allocate2);

            Assert.AreEqual(MessageType.AllocateResponse, allocate3response.MessageType);
        }
Ejemplo n.º 20
0
        private void HandleConfirmUpdateMessage(String address, AbstractMessage message)
        {
            ConfirmUpdateMessage confirmUpdateMessage = (ConfirmUpdateMessage)message;
            Player       currentPlayer = controller.GetPlayer(IPAddress.Parse(address));
            BattleEngine battleEngine  = BattleEngine.GetInstance();

            if (serverStatus != ServerStatus.Game || currentPlayer.Ready)
            {
                return;
            }

            currentPlayer.Ready = true;

            bool ready = true;

            foreach (Player player in controller.GetPlayers())
            {
                if (!player.Ready)
                {
                    ready = false;
                    break;
                }
            }

            if (ready)
            {
                AbstractMessage returnMessage = null;

                if (confirmUpdateMessage.ConfirmationType == ConfirmationType.UpdateMessage)
                {
                    if (battleEngine.LastAction == LastAction.Walked)
                    {
                        returnMessage = new AffectsMessage();
                        ((AffectsMessage)returnMessage).Affects =
                            ConvertEffectsToArray(battleEngine.ProcessSpecialAbilities());
                        foreach (Player player in controller.GetPlayers())
                        {
                            player.Ready = false;
                        }
                    }

                    else if (battleEngine.LastAction == LastAction.Attacked ||
                             battleEngine.LastAction == LastAction.Passed)
                    {
                        if (battleEngine.IsGameOver())
                        {
                            returnMessage = CreateEndGameMessage();
                        }
                        else
                        {
                            battleEngine.FinalizeCharacterTurn();
                            battleEngine.NextCharacterTurn();

                            returnMessage = new AffectsMessage();
                            ((AffectsMessage)returnMessage).Affects =
                                ConvertEffectsToArray(battleEngine.ProcessSpecialAbilities());
                            ((AffectsMessage)returnMessage).Turn = new Turn(battleEngine.ActualCharacter.RootName,
                                                                            battleEngine.ActualPlayer, battleEngine.ActualCharacterHasWalked);

                            foreach (Player player in controller.GetPlayers())
                            {
                                player.Ready = false;
                            }
                        }
                    }
                }

                else if (confirmUpdateMessage.ConfirmationType == ConfirmationType.AffectsMessage)
                {
                    if (battleEngine.ActualCharacter.Health.IsDead)
                    {
                        if (battleEngine.IsGameOver())
                        {
                            returnMessage = CreateEndGameMessage();
                        }
                        else
                        {
                            returnMessage = new AffectsMessage();

                            battleEngine.FinalizeCharacterTurn();
                            battleEngine.NextCharacterTurn();

                            ((AffectsMessage)returnMessage).Affects =
                                ConvertEffectsToArray(battleEngine.ProcessSpecialAbilities());
                            ((AffectsMessage)returnMessage).Turn = new Turn(battleEngine.ActualCharacter.RootName,
                                                                            battleEngine.ActualPlayer, battleEngine.ActualCharacterHasWalked);

                            foreach (Player player in controller.GetPlayers())
                            {
                                player.Ready = false;
                            }
                        }
                    }
                    else
                    {
                        returnMessage = new TurnMessage();
                        ((TurnMessage)returnMessage).Turn = new Turn(battleEngine.ActualCharacter.RootName,
                                                                     battleEngine.ActualPlayer, battleEngine.ActualCharacterHasWalked);
                    }
                }
                controller.Server.SendToAll(returnMessage);
                battleEngine.ClearAffects();
            }
        }
Ejemplo n.º 21
0
        private TurnMessage ProcessSetActiveDestinationRequest(Allocation allocation, TurnMessage request, IPEndPoint reflexEndPoint)
        {
            if (allocation == null)
            {
                throw new TurnServerException(ErrorCode.NoBinding);
            }

            if (request.DestinationAddress == null)
            {
                throw new TurnServerException(ErrorCode.BadRequest);
            }

            allocation.ActiveDestination = request.DestinationAddress.IpEndPoint;
            allocation.Permissions.Permit(request.DestinationAddress.IpEndPoint);

            logger.WriteInformation(string.Format("Set Active Destination: {2} --> {0} <--> {1}", allocation.Alocated.ToString(), allocation.Reflexive.ToString(), allocation.ActiveDestination.ToString()));

            uint sequenceNumber = (request.MsSequenceNumber != null) ? request.MsSequenceNumber.SequenceNumber : 0;

            return(new TurnMessage()
            {
                IsAttributePaddingDisabled = true,
                MessageType = MessageType.SetActiveDestinationResponse,
                TransactionId = request.TransactionId,

                MagicCookie = new MagicCookie(),

                Realm = new Realm(TurnMessageRfc.MsTurn)
                {
                    Ignore = true,
                    Value = Authentificater.Realm,
                },
                MsUsername = new MsUsername()
                {
                    Ignore = true,
                    Value = request.MsUsername.Value,
                },
                //MsUsername = allocation.Username,
                MessageIntegrity = new MessageIntegrity(),

                MsSequenceNumber = new MsSequenceNumber()
                {
                    ConnectionId = allocation.ConnectionId,
                    SequenceNumber = sequenceNumber,//allocation.SequenceNumber,
                },
            });
        }
Ejemplo n.º 22
0
    private void HandleMessage(string message)
    {
        try
        {
            lock (MessageTasks)
            {
                ErrorResponse errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(message);
                if (errorResponse.IsValid())
                {
                    Debug.Log("ErrorResponse: " + errorResponse.ErrorMessage);
                    return;
                }

                DisconnectMessage disconnectMessage = JsonConvert.DeserializeObject <DisconnectMessage>(message);
                if (disconnectMessage.IsValid())
                {
                    HandleDisconnect(disconnectMessage);
                    return;
                }

                RestartMessage restartMessage = JsonConvert.DeserializeObject <RestartMessage>(message);
                if (restartMessage.IsValid())
                {
                    HandleRestart(restartMessage);
                    return;
                }

                GameTypeMessage gameTypeMessage = JsonConvert.DeserializeObject <GameTypeMessage>(message);
                if (gameTypeMessage.IsValid())
                {
                    ViewController.Instance.UpdateGameTypes(gameTypeMessage.GameTypes);
                    return;
                }

                JoinResponse joinResponse = JsonConvert.DeserializeObject <JoinResponse>(message);
                if (joinResponse.IsValid())
                {
                    HandleJoinResponse(joinResponse);
                    return;
                }

                AvailableGamesMessage gamesMessage = JsonConvert.DeserializeObject <AvailableGamesMessage>(message);
                if (gamesMessage.IsValid())
                {
                    ViewController.Instance.UpdateAvailableGames(gamesMessage.AvailableGames);
                    return;
                }

                JoinMessage joinMessage = JsonConvert.DeserializeObject <JoinMessage>(message);
                if (joinMessage.IsValid())
                {
                    HandleJoin(joinMessage);
                    return;
                }

                StartMessage startMessage = JsonConvert.DeserializeObject <StartMessage>(message);
                if (startMessage.IsValid())
                {
                    HandleStart(startMessage);
                    return;
                }

                BidMessage bidMessage = JsonConvert.DeserializeObject <BidMessage>(message);
                if (bidMessage.IsValid())
                {
                    HandleBid(bidMessage);
                    return;
                }

                KittyMessage kittyMessage = JsonConvert.DeserializeObject <KittyMessage>(message);
                if (kittyMessage.IsValid())
                {
                    HandleKitty(kittyMessage);
                    return;
                }

                TrumpMessage trumpMessage = JsonConvert.DeserializeObject <TrumpMessage>(message);
                if (trumpMessage.IsValid())
                {
                    HandleTrump(trumpMessage);
                    return;
                }

                MeldPointsMessage meldPointsMessage = JsonConvert.DeserializeObject <MeldPointsMessage>(message);
                if (meldPointsMessage.IsValid())
                {
                    HandleMeldPoints(meldPointsMessage);
                    return;
                }

                MeldMessage meldMessage = JsonConvert.DeserializeObject <MeldMessage>(message);
                if (meldMessage.IsValid())
                {
                    HandleMeld(meldMessage);
                    return;
                }

                PassMessage passMessage = JsonConvert.DeserializeObject <PassMessage>(message);
                if (passMessage.IsValid())
                {
                    HandlePass(passMessage);
                    return;
                }

                ScoreMessage scoreMessage = JsonConvert.DeserializeObject <ScoreMessage>(message);
                if (scoreMessage.IsValid())
                {
                    HandleScore(scoreMessage);
                    return;
                }

                TurnMessage turnMessage = JsonConvert.DeserializeObject <TurnMessage>(message);
                if (turnMessage.IsValid())
                {
                    HandleTurn(turnMessage);
                    return;
                }

                TrickMessage trickMessage = JsonConvert.DeserializeObject <TrickMessage>(message);
                if (trickMessage.IsValid())
                {
                    HandleTrick(trickMessage);
                    return;
                }

                TrickInfoMessage trickInfoMessage = JsonConvert.DeserializeObject <TrickInfoMessage>(message);
                if (trickInfoMessage.IsValid())
                {
                    HandleTrickInfo(trickInfoMessage);
                    return;
                }

                GameOverMessage gameOverMessage = JsonConvert.DeserializeObject <GameOverMessage>(message);
                if (gameOverMessage.IsValid())
                {
                    HandleGameOver(gameOverMessage);
                    return;
                }
            }
        }
        catch (Exception err)
        {
            Debug.Log("OnMessage error: " + err.Message);
            Debug.Log("OnMessage stack trace: " + err.StackTrace);
        }
    }
Ejemplo n.º 23
0
        /// <summary>
        /// Handle a TurnMessage.
        /// </summary>
        /// <param name="message"> The received turn message </param>
        /// <returns> List of messages to be sent </returns>
        public MessagePackets HandleTurn(TurnMessage message)
        {
            // Verify game state
            VerifyGameRunning();
            VerifyPlayer(message.PlayerName);

            // Broadcast turn to all players
            MessagePackets messages = new MessagePackets();

            messages.Add(GetBroadcastMessage(message));

            // Add card to current trick, and remove from player's hand
            CurTrick.Add(message.Card);
            Players[CurPlayer].Cards.Remove(message.Card);

            // Update CurPlayer
            NextPlayer();

            // Handle all players have played
            if (CurPlayer == Leader)
            {
                // Decide and score trick
                int winningPlayer = DecideTrick();
                messages.Add(ScoreTrick(winningPlayer));

                // Broadcast trick to all players
                messages.Add(GetBroadcastMessage(new TrickMessage(Players[winningPlayer].Name)));

                // Handle last trick
                if (Players.All(p => p.Cards.Count == 0))
                {
                    DoLastTrick(winningPlayer);

                    // Update, send, and clear scores
                    UpdateScores();
                    messages.Add(GetScoreMessages());
                    ClearPerHandScores();

                    // Handle game over
                    if (DoShouldGameEnd())
                    {
                        messages.Add(EndGame());
                    }
                    // Initiate next hand
                    else
                    {
                        NextDealer();
                        messages.Add(StartRound());
                    }
                }
                // Initiate next trick
                else
                {
                    messages.Add(StartTrick(winningPlayer));
                }
            }
            // Handle next turn
            else
            {
                messages.Add(NextTurn());
            }

            return(messages);
        }
Ejemplo n.º 24
0
        private bool TurnServer_Received(ServersManager <TurnConnection> s, TurnConnection c, ref ServerAsyncEventArgs e)
        {
            if (e.LocalEndPoint.Protocol == ServerProtocol.Udp)
            {
                if (TurnMessage.IsTurnMessage(e.Buffer, e.Offset, e.BytesTransferred))
                {
                    TurnServer_TurnDataReceived(ref e);
                }
                else
                {
                    TurnServer_PeerDataReceived(ref e);
                }
            }
            else if (e.LocalEndPoint.Protocol == ServerProtocol.Tcp)
            {
                if (c.Buffer.IsValid)
                {
                    c.Buffer.Resize(Math.Max(4096, c.BytesExpected));

                    if (c.Buffer.CopyTransferredFrom(e, 0) == false)
                    {
                        return(false);
                    }

                    if (c.Buffer.Count < c.BytesExpected)
                    {
                        return(true);
                    }
                }
                else
                {
                    if (e.BytesTransferred < c.BytesExpected)
                    {
                        return(c.Buffer.CopyTransferredFrom(e, 0));
                    }
                }

                int proccessed = 0;

                for (; ;)
                {
                    if (c.Buffer.IsValid)
                    {
                        if (e == null)
                        {
                            e = EventArgsManager.Get();
                            e.CopyAddressesFrom(c);
                        }

                        e.AttachBuffer(c.Buffer);
                        proccessed = 0;
                    }

                    if (e.BytesTransferred - proccessed < c.BytesExpected)
                    {
                        return(c.Buffer.CopyTransferredFrom(e, proccessed));
                    }

                    switch (c.Phase)
                    {
                    case TcpPhase.WaitingFirstXpacket:

                        if (pseudoTlsMessage.IsBeginOfClientHello(e.Buffer, e.Offset, FirstXpacketLength))
                        {
                            c.Phase         = TcpPhase.WaitingClientHello;
                            c.BytesExpected = PseudoTlsMessage.ClientHelloLength;
                        }
                        else
                        {
                            c.Phase         = TcpPhase.WaitingTcpFrame;
                            c.BytesExpected = TcpFramingHeader.TcpFramingHeaderLength;

                            if (FirstXpacketLength <= TcpFramingHeader.TcpFramingHeaderLength)
                            {
                                goto case TcpPhase.WaitingTcpFrame;
                            }
                        }
                        break;


                    case TcpPhase.WaitingClientHello:

                        if (pseudoTlsMessage.IsClientHello(e.Buffer, e.Offset) == false)
                        {
                            return(false);
                        }

                        var x = EventArgsManager.Get();

                        x.CopyAddressesFrom(e);
                        x.Count = PseudoTlsMessage.ServerHelloHelloDoneLength;

                        pseudoTlsMessage.GetServerHelloHelloDoneBytes(x.Buffer, x.Offset);

                        s.SendAsync(x);

                        proccessed     += c.BytesExpected;
                        c.Phase         = TcpPhase.WaitingTcpFrame;
                        c.BytesExpected = TcpFramingHeader.TcpFramingHeaderLength;

                        break;


                    case TcpPhase.WaitingTcpFrame:

                        TcpFramingHeader tcpHeader;
                        if (TcpFramingHeader.TryParse(e.Buffer, e.Offset, out tcpHeader) == false)
                        {
                            return(false);
                        }

                        proccessed += c.BytesExpected;
                        c.Phase     = (tcpHeader.Type == TcpFrameType.ControlMessage) ?
                                      TcpPhase.WaitingTurnControlMessage : TcpPhase.WaitingTurnEndToEndData;
                        c.BytesExpected = tcpHeader.Length;

                        break;



                    case TcpPhase.WaitingTurnEndToEndData:
                    case TcpPhase.WaitingTurnControlMessage:

                        if (e.BytesTransferred - proccessed < c.BytesExpected)
                        {
                            if (c.Buffer.CopyTransferredFrom(e, proccessed + c.BytesExpected) == false)
                            {
                                return(false);
                            }
                        }

                        e.Count           -= proccessed;
                        e.Offset          += proccessed;
                        e.BytesTransferred = c.BytesExpected;

                        if (c.Phase == TcpPhase.WaitingTurnEndToEndData)
                        {
                            TurnServer_PeerDataReceived(ref e);
                        }
                        else
                        {
                            TurnServer_TurnDataReceived(ref e);
                        }

                        proccessed = e.BytesTransferred;

                        c.Phase         = TcpPhase.WaitingTcpFrame;
                        c.BytesExpected = TcpFramingHeader.TcpFramingHeaderLength;

                        break;


                    default:
                        throw new NotImplementedException();
                    }
                }
            }
            else
            {
                throw new NotImplementedException();
            }

            return(true);
        }
Ejemplo n.º 25
0
 public void CallRpcTurnMessage(TurnMessage msg, int extraData)
 {
     CallRpcTurnMessage((int)msg, extraData);
 }
Ejemplo n.º 26
0
        private bool PeerServer_Received(ServersManager <PeerConnection> s, BaseConnection с, ref ServerAsyncEventArgs e)
        {
            //lock (syncRoot)
            {
                try
                {
                    Allocation allocation = allocations.Get(e.LocalEndPoint);

                    if (allocation != null)
                    {
                        if (allocation.Permissions.IsPermited(e.RemoteEndPoint))
                        {
                            allocation.TouchLifetime();

                            if (allocation.ActiveDestination.IsEqual(e.RemoteEndPoint))
                            {
                                if (e.LocalEndPoint.Protocol == ServerProtocol.Tcp)
                                {
                                    TcpFramingHeader.GetBytes(e.Buffer, e.Offset, TcpFrameType.EndToEndData, e.BytesTransferred);

                                    e.Count        = e.OffsetOffset + e.BytesTransferred;
                                    e.OffsetOffset = 0;
                                }
                                else
                                {
                                    e.Count = e.BytesTransferred;
                                }

                                e.LocalEndPoint  = allocation.Local;
                                e.RemoteEndPoint = allocation.Reflexive;
                                e.ConnectionId   = ServerAsyncEventArgs.AnyConnectionId;

                                turnServer.SendAsync(e);

                                e = null;
                            }
                            else
                            {
                                TurnMessage message = new TurnMessage()
                                {
                                    IsAttributePaddingDisabled = true,
                                    MessageType   = MessageType.DataIndication,
                                    TransactionId = TransactionServer.GenerateTransactionId(),

                                    MagicCookie = new MagicCookie(),

                                    RemoteAddress = new RemoteAddress()
                                    {
                                        IpAddress = e.RemoteEndPoint.Address,
                                        Port      = (UInt16)e.RemoteEndPoint.Port,
                                    },

                                    Data = new Data()
                                    {
                                        ValueRef       = e.Buffer,
                                        ValueRefOffset = e.Offset,
                                        ValueRefLength = e.BytesTransferred,
                                    },
                                };

                                SendTurn(message, allocation.Local, allocation.Reflexive);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.WriteWarning(ex.ToString());
                }
            }

            return(true);
        }
Ejemplo n.º 27
0
 public override void Deserialize(NetworkReader reader, GameObject context)
 {
     Msg       = (TurnMessage)reader.ReadPackedUInt32();
     ExtraData = (int)reader.ReadPackedUInt32();
 }
Ejemplo n.º 28
0
 private TurnMessage SendReceiveMessage(Socket socket, TurnMessage message)
 {
     SendMessage(socket, message);
     return(ReceiveMessage(socket));
 }
Ejemplo n.º 29
0
        private void TurnServer_TurnDataReceived(ref ServerAsyncEventArgs e)
        {
            //lock (syncRoot)
            {
                TurnMessage response = null;

                try
                {
                    if (true)//(TransactionServer.GetCachedResponse(e, out response) == false)
                    {
                        TurnMessage request = TurnMessage.Parse(e.Buffer, e.Offset, e.BytesTransferred, TurnMessageRfc.MsTurn);

                        if (Authentificater.Process(request, out response))
                        {
                            Allocation allocation = null;
                            if (request.MsSequenceNumber != null)
                            {
                                allocation = allocations.Get(request.MsSequenceNumber.ConnectionId);
                            }

                            if (allocation != null)
                            {
                                if (request.MsSequenceNumber != null)
                                {
                                    response = allocation.GetResponse(request.MsSequenceNumber.SequenceNumber);
                                }
                            }

                            if (response == null)
                            {
                                if (allocation != null)
                                {
                                    allocation.TouchLifetime();
                                }

                                switch (request.MessageType)
                                {
                                case MessageType.AllocateRequest:
                                    response = ProcessAllocateRequest(ref allocation, request, e.LocalEndPoint, e.RemoteEndPoint);
                                    break;

                                case MessageType.SendRequest:
                                    response = ProcessSendRequest(allocation, request, ref e);
                                    break;

                                case MessageType.SetActiveDestinationRequest:
                                    response = ProcessSetActiveDestinationRequest(allocation, request, e.RemoteEndPoint);
                                    break;
                                }

                                if (allocation != null && response != null)
                                {
                                    allocation.SetResponse(response);
                                }
                            }
                        }

                        //TransactionServer.CacheResponse(e, response);
                    }
                }
                catch (TurnMessageException ex)
                {
                    response = GetErrorResponse(ex.ErrorCode, e);
                }
                catch (TurnServerException ex)
                {
                    response = GetErrorResponse(ex.ErrorCode, e);
                }
                catch (Exception ex)
                {
                    response = GetErrorResponse(ErrorCode.ServerError, e);

                    logger.WriteError(ex.ToString());
                }

                if (response != null)
                {
                    SendTurn(response, e.LocalEndPoint, e.RemoteEndPoint);
                }
            }
        }
Ejemplo n.º 30
0
        private TurnMessage ProcessAllocateRequest(ref Allocation allocation, TurnMessage request, ServerEndPoint local, IPEndPoint remote)
        {
            uint sequenceNumber = (request.MsSequenceNumber != null) ? request.MsSequenceNumber.SequenceNumber : 0;

            {
                uint lifetime = (request.Lifetime != null) ? ((request.Lifetime.Value > MaxLifetime.Seconds) ? MaxLifetime.Seconds : request.Lifetime.Value) : DefaultLifetime.Seconds;

                if (allocation != null)
                {
                    allocation.Lifetime = lifetime;

                    if (lifetime == 0)
                    {
                        logger.WriteInformation(string.Format("Update Allocation: {2} seconds {0} <--> {1}", allocation.Alocated.ToString(), allocation.Reflexive.ToString(), lifetime));
                    }
                }
                else
                {
                    if (lifetime <= 0)
                    {
                        throw new TurnServerException(ErrorCode.NoBinding);
                    }

                    ProtocolPort pp = new ProtocolPort()
                    {
                        Protocol = local.Protocol,
                    };
                    if (peerServer.Bind(ref pp) != SocketError.Success)
                    {
                        throw new TurnServerException(ErrorCode.ServerError);
                    }

                    allocation = new Allocation()
                    {
                        TransactionId = request.TransactionId,
                        ConnectionId  = ConnectionIdGenerator.Generate(local, remote),

                        Local     = local,
                        Alocated  = new ServerEndPoint(pp, PublicIp),
                        Real      = new ServerEndPoint(pp, RealIp),
                        Reflexive = new IPEndPoint(remote.Address, remote.Port),

                        Lifetime = lifetime,
                    };

                    allocations.Replace(allocation);

                    logger.WriteInformation(string.Format("Allocated: {0} <--> {1} for {2} seconds", allocation.Alocated.ToString(), allocation.Reflexive.ToString(), allocation.Lifetime));
                }
            }

            return(new TurnMessage()
            {
                IsAttributePaddingDisabled = true,
                MessageType = MessageType.AllocateResponse,
                TransactionId = request.TransactionId,

                MagicCookie = new MagicCookie(),

                MappedAddress = new MappedAddress()
                {
                    IpAddress = allocation.Alocated.Address,
                    Port = (UInt16)allocation.Alocated.Port,
                },

                Lifetime = new Lifetime()
                {
                    Value = allocation.Lifetime,
                },
                Bandwidth = new Bandwidth()
                {
                    Value = 750,
                },

                XorMappedAddress = new XorMappedAddress(TurnMessageRfc.MsTurn)
                {
                    IpAddress = remote.Address,
                    Port = (UInt16)remote.Port,
                },

                Realm = new Realm(TurnMessageRfc.MsTurn)
                {
                    Ignore = true,
                    Value = Authentificater.Realm,
                },
                MsUsername = new MsUsername()
                {
                    Ignore = true,
                    Value = request.MsUsername.Value,
                },
                //MsUsername = allocation.Username,
                MessageIntegrity = new MessageIntegrity(),

                MsSequenceNumber = new MsSequenceNumber()
                {
                    ConnectionId = allocation.ConnectionId,
                    SequenceNumber = sequenceNumber,//allocation.SequenceNumber,
                },
            });
        }