Exemple #1
0
        /// <summary>
        /// Encode the HandshakePacket to a byte array. Encode the Header then the payload with all the frames.
        /// </summary>
        /// <returns>The raw packet</returns>
        public override byte[] Encode()
        {
            List <byte> lpack = new List <byte>(base.Encode());

            Length.Value = (ulong)PacketNumberLength + (ulong)Payload.Length;
            lpack.AddRange(Length.Encode());

            int packetNumberBitsIndex_ = lpack.Count * 8;

            lpack.AddRange(new byte[PacketNumberLength]);
            lpack.AddRange(Payload);

            // Set packet type to "Handshake Packet"
            lpack[0] &= 0b11001111; // clear
            lpack[0] += 0b00100000;

            // Set packet number length
            lpack[0] &= 0b11111100; // clear
            lpack[0] += Convert.ToByte(PacketNumberLength - 1);

            // Set packet number
            byte[] packet = lpack.ToArray();
            BitUtils.WriteNByteFromInt(packetNumberBitsIndex_, packet, PacketNumber, (int)PacketNumberLength);

            return(packet);
        }
Exemple #2
0
        /// <summary>
        /// Encode the packet to a byte array. Encode the Header then the payload with all the frames.
        /// </summary>
        /// <returns>The raw packet</returns>
        public override byte[] Encode()
        {
            List <byte> lpack = new List <byte>(base.Encode());

            if (TokenLength.Value != (UInt64)Token.Length)
            {
                throw new CorruptedPacketException("mismatch between Token.Length and TokenLength");
            }

            lpack.AddRange(TokenLength.Encode());
            lpack.AddRange(Token);

            // Append padding frames so that the UDP datagram is at least 1200 bytes, per the spec
            // TODO: make this more efficient by computing the minimum number of padding frames needed
            byte[] padding = Enumerable.Repeat(new PaddingFrame().Type, 1200).ToArray();

            // TODO: use List<> everywhere instead of arrays?
            List <byte> PayloadList = new List <byte>(EncodeFrames());

            PayloadList.AddRange(padding);
            Payload = PayloadList.ToArray();

            Length.Value = (ulong)PacketNumberLength + (ulong)Payload.Length;
            lpack.AddRange(Length.Encode());

            int packetNumberBitsIndex_ = lpack.Count * 8;

            lpack.AddRange(new byte[PacketNumberLength]);
            lpack.AddRange(Payload);

            // Set packet type to "Initial Packet"
            lpack[0] &= 0b11001111;

            // Set packet number length
            lpack[0] &= 0b11111100; // clear
            lpack[0] += Convert.ToByte(PacketNumberLength - 1);

            // Set packet number
            byte[] packet = lpack.ToArray();
            BitUtils.WriteNByteFromInt(packetNumberBitsIndex_, packet, PacketNumber, (int)PacketNumberLength);

            return(packet);
        }