Example #1
0
 internal SmppHeader(ByteBuilder bb)
 {
     _CommandLength  = SmppConverter.FromByteArrayToInt32(bb.ToArray(0, 4));
     _CommandId      = SmppConverter.FromByteArrayToInt32(bb.ToArray(4, 4));
     _CommandStatus  = SmppConverter.FromByteArrayToInt32(bb.ToArray(8, 4));
     _SequenceNumber = SmppConverter.FromByteArrayToInt32(bb.ToArray(12, 4));
 }
Example #2
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(100);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SystemId)));
                return(builder.ToArray());
            }
    /// <summary>
    /// Waits until the connected client sends a SOCKS5 request.
    /// </summary>
    /// <returns>The SOCKS5 request sent by the client.</returns>
    /// <exception cref="Socks5Exception">The data sent by the client
    /// is not a valid SOCKS5 request.</exception>
    private SocksRequest WaitForRequest()
    {
        ByteBuilder b = new ByteBuilder();

        using (var r = new BinaryReader(stream, Encoding.UTF8, true))
        {
            byte[] bytes = r.ReadBytes(4);
            b.Append(bytes);
            ATyp atyp = (ATyp)bytes[3];
            switch (atyp)
            {
            case ATyp.IPv4:
            case ATyp.IPv6:
                b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16));
                break;

            case ATyp.Domain:
                byte length = r.ReadByte();
                b.Append(length).Append(r.ReadBytes(length));
                break;
            }
            b.Append(r.ReadBytes(2));
        }
        try
        {
            return(SocksRequest.Deserialize(b.ToArray()));
        }
        catch (Exception e)
        {
            throw new Socks5Exception("The request could not be serialized.", e);
        }
    }
Example #4
0
    /// <summary>
    /// Performs the specified SOCKS5 request.
    /// </summary>
    /// <param name="request">The SOCKS5 request to issue to the server.</param>
    /// <returns>The SOCKS5 reply sent by the server.</returns>
    /// <exception cref="ArgumentNullException">The request parameter is
    /// null.</exception>
    /// <exception cref="ObjectDisposedException">The object has been
    /// disposed.</exception>
    /// <exception cref="Socks5Exception">The request could not be performed.
    /// Consult the InnerException property of the Socks5Exception to learn
    /// the reason.</exception>
    public SocksReply Request(SocksRequest request)
    {
        AssertValid();
        try
        {
            byte[] bytes = request.Serialize();
            stream.Write(bytes, 0, bytes.Length);
            ByteBuilder b = new ByteBuilder();
            using (var r = new BinaryReader(stream, Encoding.UTF8, true))
            {
                bytes = r.ReadBytes(4);
                b.Append(bytes);
                ATyp atyp = (ATyp)bytes[3];
                switch (atyp)
                {
                case ATyp.IPv4:
                case ATyp.IPv6:
                    b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16));
                    break;

                case ATyp.Domain:
                    byte length = r.ReadByte();
                    b.Append(length).Append(r.ReadBytes(length));
                    break;
                }
                b.Append(r.ReadBytes(2));
            }
            return(SocksReply.Deserialize(b.ToArray()));
        }
        catch (Exception e)
        {
            throw new Socks5Exception("The request could not be performed.", e);
        }
    }
Example #5
0
        /// <summary>
        /// 解析一个数据包
        /// 不足一个封包时返回null
        /// </summary>
        /// <param name="builder">接收到的历史数据</param>
        /// <returns></returns>
        public static FastPacket GetPacket(ByteBuilder builder)
        {
            // 包头长度
            const int headLength = 12;

            // 不会少于12
            if (builder.Length < headLength)
            {
                return(null);
            }

            // 包长
            int totalLength = builder.ToInt32(0, Endians.Big);

            // 包长要小于等于数据长度
            if (totalLength > builder.Length || totalLength < headLength)
            {
                return(null);
            }

            // cmd
            int cmd = builder.ToInt32(4, Endians.Big);
            // 哈希值
            int hashCode = builder.ToInt32(8, Endians.Big);

            // 实体数据
            byte[] body = builder.ToArray(12, totalLength - headLength);

            // 清空本条数据
            builder.Remove(totalLength);
            return(new FastPacket(cmd, hashCode, body));
        }
Example #6
0
        public byte[] ToByteArray()
        {
            var builder = new ByteBuilder(100);

            builder.AddRange(_Header.ToByteArray());
            builder.AddRange(_Body.ToByteArray());
            return(builder.ToArray());
        }
Example #7
0
		/// <summary>
		/// Serializes the instance into an array of bytes.
		/// </summary>
		/// <returns>An array of bytes representing the instance of the
		/// ClientGreeting class.</returns>
		public byte[] Serialize() {
			ByteBuilder b = new ByteBuilder()
				.Append(version)
				.Append((byte) methods.Count);
			foreach (AuthMethod m in Methods)
				b.Append((byte) m);
			return b.ToArray();
		}
Example #8
0
 public SmppTlv(byte[] Data)
 {
     Items = new ArrayList(10);
     if (Data != null)
     {
         short num3;
         var   builder = new ByteBuilder(Data);
         for (int i = 0; i < builder.Count; i += 4 + num3)
         {
             short tagId = SmppConverter.FromByteArrayToInt16(builder.ToArray(i, 2));
             num3 = SmppConverter.FromByteArrayToInt16(builder.ToArray(i + 2, 2));
             byte[] buffer = builder.ToArray(i + 4, num3);
             var    tag    = new Tag(tagId);
             tag.SetByteArray(buffer);
             Items.Add(tag);
         }
     }
 }
Example #9
0
 public static byte[] GetPacket(Colony colony)
 {
     using (ByteBuilder b = ByteBuilder.Get()) {
         b.Write(ClientMessageType.ReceiveConstructionLimits);
         b.Write(colony?.TemporaryData.GetAsOrDefault("pipliz.builderlimit", 0) ?? 0);
         b.Write(colony?.TemporaryData.GetAsOrDefault("pipliz.diggerlimit", 0) ?? 0);
         return(b.ToArray());
     }
 }
Example #10
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(30);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_MessageId)));
                builder.Add(_SourceAddressTon);
                builder.Add(_SourceAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SourceAddress)));
                return(builder.ToArray());
            }
Example #11
0
        public byte[] ToByteArray()
        {
            var builder = new ByteBuilder(0x10);

            builder.AddRange(SmppConverter.FromInt32ToByteArray(_CommandLength));
            builder.AddRange(SmppConverter.FromInt32ToByteArray(_CommandId));
            builder.AddRange(SmppConverter.FromInt32ToByteArray(_CommandStatus));
            builder.AddRange(SmppConverter.FromInt32ToByteArray(_SequenceNumber));
            return(builder.ToArray());
        }
Example #12
0
        public byte[] ToByteArray()
        {
            byte[] c = _Body.ToByteArray();
            _Header.CommandLength = 0x10 + c.Length;
            byte[] buffer2 = _Header.ToByteArray();
            var    builder = new ByteBuilder(_Header.CommandLength);

            builder.AddRange(buffer2);
            builder.AddRange(c);
            return(builder.ToArray());
        }
Example #13
0
        public byte[] ToByteArray()
        {
            var builder = new ByteBuilder(300);

            builder.AddRange(_Header.ToByteArray());
            builder.AddRange(_Body.ToByteArray());
            if (_Tlv != null)
            {
                builder.AddRange(_Tlv.ToByteArray());
            }
            return(builder.ToArray());
        }
Example #14
0
    /// <summary>
    /// Serializes the instance into an array of bytes.
    /// </summary>
    /// <returns>An array of bytes representing the instance of the
    /// ClientGreeting class.</returns>
    public byte[] Serialize()
    {
        ByteBuilder b = new ByteBuilder()
                        .Append(version)
                        .Append((byte)methods.Count);

        foreach (AuthMethod m in Methods)
        {
            b.Append((byte)m);
        }
        return(b.ToArray());
    }
Example #15
0
        public static PolicyPacket GetPacket(ByteBuilder builder)
        {
            if (builder.Length == 0)
            {
                return(null);
            }

            var bytes = builder.ToArray();

            builder.Clear();
            return(new PolicyPacket(bytes));
        }
Example #16
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(90);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SystemId)));
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_Password)));
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SystemType)));
                builder.Add(_InterfaceVersion);
                builder.Add(_AddressTon);
                builder.Add(_AddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_AddressRange)));
                return(builder.ToArray());
            }
Example #17
0
        public static void sendAllSilent(string message, ChatColour colour = ChatColour.white, ChatStyle style = ChatStyle.normal, Pipliz.Chatting.ChatSenderType sender = Pipliz.Chatting.ChatSenderType.Server)
        {
            ChatSenderType type         = ChatSenderType.Server;
            string         messageBuilt = buildMessage(message, colour, style);


            using (ByteBuilder byteBuilder = ByteBuilder.Get())
            {
                byteBuilder.Write((ushort)ClientMessageType.Chat);
                byteBuilder.Write((byte)type);
                byteBuilder.Write(messageBuilt);
                Players.SendToAll(byteBuilder.ToArray(), NetworkMessageReliability.ReliableWithBuffering);
            }
        }
Example #18
0
        /// <summary>
        /// Creates a new "multi-precision integer" from the specified array
        /// of bytes.
        /// </summary>
        /// <param name="data">A big-endian sequence of bytes forming the
        /// integer value of the multi-precision integer.</param>
        public Mpi(byte[] data)
        {
            byte[] b = new byte[data.Length];
            Array.Copy(data.Reverse().ToArray(), b, data.Length);
            ByteBuilder builder = new ByteBuilder().Append(b);

            // We append a null byte to the buffer which ensures the most
            // significant bit will never be set and the big integer value
            // always be positive.
            if (b.Last() != 0)
            {
                builder.Append(0);
            }
            Value = new BigInteger(builder.ToArray());
        }
Example #19
0
        public byte[] ToByteArray()
        {
            var builder = new ByteBuilder(100);

            if (Items != null)
            {
                foreach (Tag tag in Items)
                {
                    builder.AddRange(SmppConverter.FromInt16ToByteArray(tag.TagId));
                    builder.AddRange(SmppConverter.FromInt16ToByteArray(tag.Length));
                    builder.AddRange(tag.GetByteArray());
                }
            }
            return(builder.ToArray());
        }
Example #20
0
        private void UpdatePlayerVariables()
        {
            using (ByteBuilder bRaw = ByteBuilder.Get())
            {
                bRaw.Write(ClientMessageType.ReceiveServerPerClientSettings);
                using (ByteBuilder b = ByteBuilder.Get())
                {
                    b.Write(_playerVariables.ToString());
                    bRaw.WriteCompressed(b);
                }
                NetworkWrapper.Send(bRaw.ToArray(), Player.ID);
            }

            Player.SendHealthPacket();
        }
        public static void SendPacket(Players.Player player)
        {
            if (player.IsConnected)
            {
                int builder = player.GetTempValues(false).GetOrDefault("pipliz.builderlimit", 0);
                int digger  = player.GetTempValues(false).GetOrDefault("pipliz.diggerlimit", 0);

                using (ByteBuilder b = ByteBuilder.Get()) {
                    b.Write(General.Networking.ClientMessageType.ReceiveConstructionLimits);
                    b.Write(builder);
                    b.Write(digger);
                    NetworkWrapper.Send(b.ToArray(), player);
                }
            }
        }
Example #22
0
        /// <summary>
        /// Reads an ASCII-string of the specified length from this instance.
        /// </summary>
        /// <param name="reader">Extension method for the BinaryReader class.</param>
        /// <param name="count">The number of bytes to read from the underlying
        /// stream.</param>
        /// <returns>A string decoded from the bytes read from the underlying
        /// stream using the ASCII character set.</returns>
        public static string ReadASCIIString(this BinaryReader reader, int count)
        {
            ByteBuilder builder = new ByteBuilder();
            int         read    = 0;

            while (true)
            {
                if (read++ >= count)
                {
                    break;
                }
                byte b = reader.ReadByte();
                builder.Append(b);
            }
            return(Encoding.ASCII.GetString(builder.ToArray()).TrimEnd('\0'));
        }
Example #23
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(100);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ServiceType.Value)));
                builder.Add(_SourceAddressTon);
                builder.Add(_SourceAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SourceAddress)));
                builder.Add(_DestinationAddressTon);
                builder.Add(_DestinationAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_DestinationAddress)));
                builder.Add(_EsmClass.Value);
                builder.Add(_RegisteredDelivery.Value);
                builder.Add(_DataCoding.Value);
                return(builder.ToArray());
            }
Example #24
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(30);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_MessageId)));
                if (_FinalDate == null)
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(null));
                }
                else
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_FinalDate.SmppDate)));
                }
                builder.Add(_MessageState);
                builder.Add(_ErrorCode);
                return(builder.ToArray());
            }
Example #25
0
        public static void sendSilent(Players.Player player, string message, ChatColour colour = ChatColour.white, ChatStyle style = ChatStyle.normal, Pipliz.Chatting.ChatSenderType sender = Pipliz.Chatting.ChatSenderType.Server)
        {
            ChatSenderType type = ChatSenderType.Server;

            if (!(player.ID == NetworkID.Server))
            {
                string messageBuilt = buildMessage(message, colour, style);

                using (ByteBuilder byteBuilder = ByteBuilder.Get())
                {
                    byteBuilder.Write((ushort)ClientMessageType.Chat);
                    byteBuilder.Write((byte)type);
                    byteBuilder.Write(messageBuilt);
                    NetworkWrapper.Send(byteBuilder.ToArray(), player, NetworkMessageReliability.ReliableWithBuffering);
                }
            }
            //send(player, message, colour, style, sender);
        }
Example #26
0
        public byte[] ToByteArray()
        {
            byte[] c       = null;
            byte[] buffer2 = _Body.ToByteArray();
            byte[] buffer3 = null;
            _Header.CommandLength = 0x10 + buffer2.Length;
            if (_Tlv != null)
            {
                buffer3 = _Tlv.ToByteArray();
                _Header.CommandLength += buffer3.Length;
            }
            c = _Header.ToByteArray();
            var builder = new ByteBuilder(c.Length + buffer2.Length);

            builder.AddRange(c);
            builder.AddRange(buffer2);
            builder.AddRange(buffer3);
            return(builder.ToArray());
        }
Example #27
0
        /// <summary>
        /// 将参数序列化并写入为Body
        /// </summary>
        /// <param name="serializer">序列化工具</param>
        /// <param name="parameters">参数</param>
        /// <exception cref="SerializerException"></exception>
        public void SetBodyParameters(ISerializer serializer, params object[] parameters)
        {
            if (parameters == null || parameters.Length == 0)
            {
                return;
            }
            var builder = new ByteBuilder(Endians.Big);

            foreach (var item in parameters)
            {
                // 序列化参数为二进制内容
                var paramBytes = serializer.Serialize(item);
                // 添加参数内容长度
                builder.Add(paramBytes == null ? 0 : paramBytes.Length);
                // 添加参数内容
                builder.Add(paramBytes);
            }
            this.Body = builder.ToArray();
        }
Example #28
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(300);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ServiceType.Value)));
                builder.Add(_SourceAddressTon);
                builder.Add(_SourceAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SourceAddress)));
                builder.Add(_DestinationAddressTon);
                builder.Add(_DestinationAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_DestinationAddress)));
                builder.Add(_EsmClass.Value);
                builder.Add(_ProtocolId);
                builder.Add(_PriorityFlag);
                if (_ScheduleDeliveryTime == null)
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(null));
                }
                else
                {
                    builder.AddRange(
                        SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ScheduleDeliveryTime.SmppDate)));
                }
                if (_ValidityPeriod == null)
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(null));
                }
                else
                {
                    builder.AddRange(
                        SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ValidityPeriod.SmppDate)));
                }
                builder.Add(_RegisteredDelivery.Value);
                builder.Add(_ReplaceIfPresent);
                builder.Add(_ShortMessage.DataCoding.Value);
                builder.Add(_SmDefaultMessageId);
                builder.Add(Convert.ToByte(_ShortMessage.Length));
                builder.AddRange(_ShortMessage.Value);
                return(builder.ToArray());
            }
Example #29
0
        public byte[] ToByteArray()
        {
            byte[] c        = null;
            byte[] buffer2  = _Body.ToByteArray();
            byte[] arrayObj = null;
            _Header.CommandLength = 0x10 + buffer2.Length;
            if (_Tlv != null)
            {
                arrayObj = _Tlv.ToByteArray();
                _Header.CommandLength += arrayObj.Length;
            }
            c = _Header.ToByteArray();
            var builder = new ByteBuilder((c.Length + buffer2.Length) + SmppConverter.GetArrayLength(arrayObj));

            builder.AddRange(c);
            builder.AddRange(buffer2);
            if (arrayObj != null)
            {
                builder.AddRange(arrayObj);
            }
            return(builder.ToArray());
        }
Example #30
0
        /// <summary>
        /// 将数据作帧处理
        /// </summary>
        /// <param name="bytes">原始数据</param>
        /// <param name="frameType">帧类型</param>
        /// <returns></returns>
        protected byte[] FrameBuffer(byte[] bytes, FrameTypes frameType)
        {
            var builder = new ByteBuilder();

            builder.Add((byte)((byte)frameType + 128));

            if (bytes.Length > UInt16.MaxValue)
            {
                builder.Add((byte)127);
                builder.Add((ulong)bytes.Length, Endians.Big);
            }
            else if (bytes.Length > 125)
            {
                builder.Add((byte)126);
                builder.Add((ushort)bytes.Length, Endians.Big);
            }
            else
            {
                builder.Add((byte)bytes.Length);
            }
            builder.Add(bytes);
            return(builder.ToArray());
        }
Example #31
0
        internal static byte[] GetPduByteArray(ref SmppHeader Header, ISmppBasic Body, SmppTlv Tlv)
        {
            byte[] c        = null;
            byte[] buffer2  = null;
            byte[] arrayObj = null;
            buffer2 = Body.ToByteArray();
            Header.CommandLength = 0x10 + buffer2.Length;
            if (Tlv != null)
            {
                arrayObj              = Tlv.ToByteArray();
                Header.CommandLength += arrayObj.Length;
            }
            c = Header.ToByteArray();
            var builder = new ByteBuilder((c.Length + buffer2.Length) + GetArrayLength(arrayObj));

            builder.AddRange(c);
            builder.AddRange(buffer2);
            if (arrayObj != null)
            {
                builder.AddRange(arrayObj);
            }
            return(builder.ToArray());
        }
Example #32
0
		/// <summary>
		/// Performs the specified SOCKS5 request.
		/// </summary>
		/// <param name="request">The SOCKS5 request to issue to the server.</param>
		/// <returns>The SOCKS5 reply sent by the server.</returns>
		/// <exception cref="ArgumentNullException">The request parameter is
		/// null.</exception>
		/// <exception cref="ObjectDisposedException">The object has been
		/// disposed.</exception>
		/// <exception cref="Socks5Exception">The request could not be performed.
		/// Consult the InnerException property of the Socks5Exception to learn
		/// the reason.</exception>
		public SocksReply Request(SocksRequest request) {
			request.ThrowIfNull("request");
			AssertValid();
			try {
				byte[] bytes = request.Serialize();
				stream.Write(bytes, 0, bytes.Length);
				ByteBuilder b = new ByteBuilder();
				using (var r = new BinaryReader(stream, Encoding.UTF8, true)) {
					bytes = r.ReadBytes(4);
					b.Append(bytes);
					ATyp atyp = (ATyp) bytes[3];
					switch (atyp) {
						case ATyp.IPv4:
						case ATyp.IPv6:
							b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16));
							break;
						case ATyp.Domain:
							byte length = r.ReadByte();
							b.Append(length).Append(r.ReadBytes(length));
							break;
					}
					b.Append(r.ReadBytes(2));
				}
				return SocksReply.Deserialize(b.ToArray());
			} catch (Exception e) {
				throw new Socks5Exception("The request could not be performed.", e);
			}
		}
Example #33
0
 /// <summary>
 /// 将参数序列化并写入为Body
 /// </summary>
 /// <param name="serializer">序列化工具</param>
 /// <param name="parameters">参数</param>
 /// <exception cref="SerializerException"></exception>
 public void SetBodyParameters(ISerializer serializer, params object[] parameters)
 {
     if (parameters == null || parameters.Length == 0)
     {
         return;
     }
     var builder = new ByteBuilder(Endians.Big);
     foreach (var item in parameters)
     {
         // 序列化参数为二进制内容
         var paramBytes = serializer.Serialize(item);
         // 添加参数内容长度
         builder.Add(paramBytes == null ? 0 : paramBytes.Length);
         // 添加参数内容
         builder.Add(paramBytes);
     }
     this.Body = builder.ToArray();
 }
Example #34
0
		/// <summary>
		/// Performs the initial greeting.
		/// </summary>
		/// <exception cref="Socks5Exception">The client sent invalid data, or
		/// requires authentication.</exception>
		/// <exception cref="IOException">The stream could not be read, or the
		/// operation timed out.</exception>
		void PerformGreeting() {
			ByteBuilder b = new ByteBuilder();
			using (var r = new BinaryReader(stream, Encoding.UTF8, true)) {
				byte[] bytes = r.ReadBytes(2);
				b.Append(bytes);
				// The number of method-bytes following is contained in the second byte.
				b.Append(r.ReadBytes(bytes[1]));
			}
			ClientGreeting greeting = ClientGreeting.Deserialize(b.ToArray());
			// We only accept an authentication method of 'none'.
			if (!greeting.Methods.Contains(AuthMethod.None)) {
				Dispose();
				throw new Socks5Exception("Client requires authentication.");
			}
			// Send back our greeting response.
			var response = new ServerGreeting(AuthMethod.None).Serialize();
			stream.Write(response, 0, response.Length);
		}
Example #35
0
		/// <summary>
		/// Waits until the connected client sends a SOCKS5 request.
		/// </summary>
		/// <returns>The SOCKS5 request sent by the client.</returns>
		/// <exception cref="Socks5Exception">The data sent by the client
		/// is not a valid SOCKS5 request.</exception>
		SocksRequest WaitForRequest() {
			ByteBuilder b = new ByteBuilder();
			using (var r = new BinaryReader(stream, Encoding.UTF8, true)) {
				byte[] bytes = r.ReadBytes(4);
				b.Append(bytes);
				ATyp atyp = (ATyp) bytes[3];
				switch (atyp) {
					case ATyp.IPv4:
					case ATyp.IPv6:
						b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16));
						break;
					case ATyp.Domain:
						byte length = r.ReadByte();
						b.Append(length).Append(r.ReadBytes(length));
						break;
				}
				b.Append(r.ReadBytes(2));
			}
			try {
				return SocksRequest.Deserialize(b.ToArray());
			} catch (Exception e) {
				throw new Socks5Exception("The request could not be serialized.", e);
			}
		}