Пример #1
0
    public override void OnSerializeData(BitStream bitStream, ulong guid, int packet_size)
    {
        CustomIDs packet_id = (CustomIDs)bitStream.ReadByte();//the first byte of the packet is id, the rest is data

        switch (packet_id)
        {
        case CustomIDs.CLIENT_DATA:
            Debug.Log("[Server] Received client data from " + peer.GetAddress(guid, true) + " with guid " + guid);

            //creating a client data structure and putting it in a dictionary
            Clients.Add(guid, new ClientData(guid, bitStream.ReadString()));

            /* we inform the client that his data is accepted, we send it via a reliable channel */
            using (PooledBitStream bsIn = BitStreamPool.GetBitStream())
            {
                //be sure to reset the bitstream! If you do not do this the old recorded data will be sent
                bsIn.Reset();

                //Write the packet id as a byte so that the client knows how to process the packet
                bsIn.Write((byte)CustomIDs.CLIENT_DATA_ACCEPTED);

                //As an example, we will send the text to the client in the load
                bsIn.Write("RakNet top... SosiPisos");

                //we send data from bitstream to the client using its unique guid
                SendToClient(bitStream, guid, PacketPriority.IMMEDIATE_PRIORITY, PacketReliability.RELIABLE, 0);
            }
            break;
        }
    }
Пример #2
0
    public override void OnConnected()
    {
        Debug.LogWarning("[Client] Connected to server");

        //example using poolable bitStream
        using (PooledBitStream bitStream = BitStreamPool.GetBitStream())
        {
            bitStream.Reset();
            bitStream.Write((byte)CustomIDs.CLIENT_DATA);
            bitStream.Write(username);

            SendToServer(bitStream, PacketPriority.IMMEDIATE_PRIORITY, PacketReliability.RELIABLE, 0);
        }
    }
        internal static BitStream WrapMessage(byte messageType, ulong clientID, BitStream messageBody, SecuritySendFlags flags)
        {
            try
            {
                bool encrypted     = ((flags & SecuritySendFlags.Encrypted) == SecuritySendFlags.Encrypted) && false;             //NetworkManager.Get().NetworkConfig.EnableEncryption;
                bool authenticated = (flags & SecuritySendFlags.Authenticated) == SecuritySendFlags.Authenticated && false;       //NetworkManager.Get().NetworkConfig.EnableEncryption;

                PooledBitStream outStream = PooledBitStream.Get();

                using (PooledBitWriter outWriter = PooledBitWriter.Get(outStream))
                {
                    outWriter.WriteBit(encrypted);
                    outWriter.WriteBit(authenticated);
                    outWriter.WriteBits(messageType, 6);
                    outStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length);
                }

                return(outStream);
            }
            catch (Exception e)
            {
                Debug.LogError("Error while wrapping headers");
                Debug.LogError(e.ToString());

                return(null);
            }
        }
Пример #4
0
        /// <summary>
        /// Encrypts a message with AES with a given key and a random salt that gets encoded as the first 16 bytes of the encrypted buffer
        /// </summary>
        /// <param name="clearStream">The stream to be encrypted</param>
        /// <param name="clientId">The clientId whose AES key to use</param>
        /// <returns>The encrypted stream with encoded salt</returns>
        public static Stream EncryptStream(Stream clearStream, uint clientId)
        {
            using (RijndaelManaged aes = new RijndaelManaged())
            {
                aes.Key = NetworkingManager.singleton.isServer ? NetworkingManager.singleton.ConnectedClients[clientId].AesKey : NetworkingManager.singleton.clientAesKey;
                aes.GenerateIV();

                using (CryptoStream cs = new CryptoStream(clearStream, aes.CreateEncryptor(), CryptoStreamMode.Read))
                {
                    using (PooledBitStream outStream = PooledBitStream.Get())
                    {
                        outStream.Write(aes.IV, 0, 16);
                        outStream.CopyFrom(cs);
                        return(outStream);
                    }
                }
            }
        }
Пример #5
0
        internal static void BufferMessageForNetworkId(ulong networkId, ulong sender, string channelName, float receiveTime, ArraySegment <byte> payload)
        {
            if (!bufferQueues.ContainsKey(networkId))
            {
                bufferQueues.Add(networkId, new Queue <BufferedMessage>());
            }

            Queue <BufferedMessage> queue = bufferQueues[networkId];

            PooledBitStream payloadStream = PooledBitStream.Get();

            payloadStream.Write(payload.Array, payload.Offset, payload.Count);
            payloadStream.Position = 0;

            queue.Enqueue(new BufferedMessage()
            {
                bufferTime  = Time.realtimeSinceStartup,
                channelName = channelName,
                payload     = payloadStream,
                receiveTime = receiveTime,
                sender      = sender
            });
        }
Пример #6
0
        internal static BitStream WrapMessage(byte messageType, uint clientId, BitStream messageBody, SecuritySendFlags flags)
        {
            try
            {
                bool encrypted     = ((flags & SecuritySendFlags.Encrypted) == SecuritySendFlags.Encrypted) && NetworkingManager.Singleton.NetworkConfig.EnableEncryption;
                bool authenticated = (flags & SecuritySendFlags.Authenticated) == SecuritySendFlags.Authenticated && NetworkingManager.Singleton.NetworkConfig.EnableEncryption;

                PooledBitStream outStream = PooledBitStream.Get();

                using (PooledBitWriter outWriter = PooledBitWriter.Get(outStream))
                {
                    outWriter.WriteBit(encrypted);
                    outWriter.WriteBit(authenticated);

#if !DISABLE_CRYPTOGRAPHY
                    if (authenticated || encrypted)
                    {
                        outWriter.WritePadBits();
                        long hmacWritePos = outStream.Position;

                        if (authenticated)
                        {
                            outStream.Write(HMAC_PLACEHOLDER, 0, HMAC_PLACEHOLDER.Length);
                        }

                        if (encrypted)
                        {
                            using (RijndaelManaged rijndael = new RijndaelManaged())
                            {
                                rijndael.GenerateIV();
                                rijndael.Padding = PaddingMode.PKCS7;

                                byte[] key = NetworkingManager.Singleton.IsServer ? CryptographyHelper.GetClientKey(clientId) : CryptographyHelper.GetServerKey();

                                if (key == null)
                                {
                                    if (LogHelper.CurrentLogLevel <= LogLevel.Error)
                                    {
                                        LogHelper.LogError("Failed to grab key");
                                    }
                                    return(null);
                                }

                                rijndael.Key = key;

                                outStream.Write(rijndael.IV);

                                using (CryptoStream encryptionStream = new CryptoStream(outStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write))
                                {
                                    encryptionStream.WriteByte(messageType);
                                    encryptionStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length);
                                }
                            }
                        }
                        else
                        {
                            outStream.WriteByte(messageType);
                            outStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length);
                        }

                        if (authenticated)
                        {
                            byte[] key = NetworkingManager.Singleton.IsServer ? CryptographyHelper.GetClientKey(clientId) : CryptographyHelper.GetServerKey();

                            if (key == null)
                            {
                                if (LogHelper.CurrentLogLevel <= LogLevel.Error)
                                {
                                    LogHelper.LogError("Failed to grab key");
                                }
                                return(null);
                            }

                            using (HMACSHA256 hmac = new HMACSHA256(key))
                            {
                                byte[] computedHmac = hmac.ComputeHash(outStream.GetBuffer(), 0, (int)outStream.Length);

                                outStream.Position = hmacWritePos;
                                outStream.Write(computedHmac, 0, computedHmac.Length);
                            }
                        }
                    }
                    else
                    {
#endif
                    outWriter.WriteBits(messageType, 6);
                    outStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length);
#if !DISABLE_CRYPTOGRAPHY
                }
#endif
                }

                return(outStream);
            }
            catch (Exception e)
            {
                if (LogHelper.CurrentLogLevel <= LogLevel.Normal)
                {
                    LogHelper.LogError("Error while wrapping headers");
                }
                if (LogHelper.CurrentLogLevel <= LogLevel.Error)
                {
                    LogHelper.LogError(e.ToString());
                }

                return(null);
            }
        }