Beispiel #1
0
        public TcpPacket(byte[] buffer)
        {
            try
            {
                SourcePort      = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 0));
                DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 2));

                var offsetAndFlags = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 12));
                DataOffset = (byte)((offsetAndFlags >> 12) * 4);
                Flags      = (TcpFlags)(offsetAndFlags & 511); // 0b111111111 = 511

                Payload = buffer.Skip(DataOffset).ToArray();

                IsValid = true;
            }
            catch (Exception ex)
            {
                SourcePort      = 0;
                DestinationPort = 0;
                DataOffset      = 0;
                Flags           = TcpFlags.NONE;

                Payload = null;
                IsValid = false;

                Locator.Current.GetService <ILogger>().Write(ex, "N: TCP Packet Parsing Error", LogLevel.Error);
            }
        }
Beispiel #2
0
        public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string login, string password,
                          ArraySegment <byte> data) : this(command, flags, correlationId, data)
        {
            if ((flags & TcpFlags.Authenticated) != 0)
            {
                Ensure.NotNull(login, nameof(login));
                Ensure.NotNull(password, nameof(password));
                if (Helper.UTF8NoBom.GetByteCount(login) > MaxLoginLength)
                {
                    throw new ArgumentException($"Login length must be less than {MaxLoginLength} bytes.",
                                                nameof(login));
                }

                if (Helper.UTF8NoBom.GetByteCount(password) > MaxPasswordLength)
                {
                    throw new ArgumentException($"Password length must be less than {MaxPasswordLength} bytes.",
                                                nameof(password));
                }
            }
            else
            {
                if (login != null)
                {
                    throw new ArgumentException("Login provided for non-authorized TcpPackage", nameof(login));
                }

                if (password != null)
                {
                    throw new ArgumentException("Password provided for non-authorized TcpPackage", nameof(password));
                }
            }

            _login    = login;
            _password = password;
        }
Beispiel #3
0
        public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string login, string password,
                          ArraySegment <byte> data)
        {
            if ((flags & TcpFlags.Authenticated) != 0)
            {
                Ensure.NotNull(login, "login");
                Ensure.NotNull(password, "password");
            }
            else
            {
                if (login != null)
                {
                    throw new ArgumentException("Login provided for non-authorized TcpPackage.");
                }
                if (password != null)
                {
                    throw new ArgumentException("Password provided for non-authorized TcpPackage.");
                }
            }

            Command       = command;
            Flags         = flags;
            CorrelationId = correlationId;
            Login         = login;
            Password      = password;
            Data          = data;
        }
Beispiel #4
0
        public TcpPacket(byte[] buffer)
        {
            try
            {
                SourcePort      = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 0));
                DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 2));

                var offsetAndFlags = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 12));
                DataOffset = (byte)((offsetAndFlags >> 12) * 4);
                Flags      = (TcpFlags)(offsetAndFlags & 511); // 0b111111111 = 511

                Payload = buffer.Skip(DataOffset).ToArray();

                IsValid = true;
            }
            catch (Exception ex)
            {
                SourcePort      = 0;
                DestinationPort = 0;
                DataOffset      = 0;
                Flags           = TcpFlags.NONE;

                Payload = null;

                IsValid = false;

                Logger.Exception(ex, "l-packet-error-tcp");
            }
        }
Beispiel #5
0
        internal virtual void Post(TcpFlags flags, uint ackno, uint seqno, uint length = 0, int retransmission = 0, bool timeout = false)
        {
            SegmentsContext segments = null;

            lock (this)
            {
                lock (this.SegmentsContexts)
                {
                    segments = new SegmentsContext()
                    {
                        AcknowledgeNo  = ackno,
                        SequenceNo     = seqno,
                        Flags          = flags,
                        Length         = length,
                        Stopwatch      = new Stopwatch(),
                        Retransmission = retransmission,
                        Pcb            = this,
                        Timeout        = timeout,
                    };
                    if (retransmission > 0)
                    {
                        long nackNo = segments.SequenceNo + segments.Length;
                        if (this.SegmentsContexts.TryAdd(nackNo, segments))
                        {
                            segments.Stopwatch.Start();
                        }
                    }
                }
            }
            TcpFrame frame = segments.CreateFrame(this);

            this.Locator.Tcp.Output(frame);
        }
Beispiel #6
0
 public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string login, string password, ArraySegment <byte> data)
 {
     Command       = command;
     Flags         = flags;
     CorrelationId = correlationId;
     Login         = login;
     Password      = password;
     Data          = data;
 }
Beispiel #7
0
 private TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, ArraySegment <byte> data)
 {
     Command       = command;
     Flags         = flags;
     CorrelationId = correlationId;
     Data          = data;
     _login        = null;
     _password     = null;
     _authToken    = null;
 }
 /// <summary>
 ///		Set or unset a particular flag.
 /// </summary>
 /// <param name="flag">
 ///		The flag to set or unset.
 ///	</param>
 /// <param name="flagValue">
 ///		true to set, false to unset.
 ///	</param>
 public void SetFlag(TcpFlags flag, bool flagValue)
 {
     if (flagValue)
     {
         m_flags |= (byte)flag;
     }
     else
     {
         m_flags &= (byte)(~((byte)flag));
     }
 }
Beispiel #9
0
 public TcpHeader(IPHeader ip)
 {
     if (ip.Protocol == IPProtocol.Tcp)
     {
         data            = ip.Data;
         headerOffset    = ip.DataOffset;
         sourcePort      = data[headerOffset] << 8 | data[headerOffset + 1];
         destinationPort = data[headerOffset + 2] << 8 | data[headerOffset + 3];
         flags           = (TcpFlags)(data[headerOffset + 13] & 0x3f);
         dataOffset      = headerOffset + ((data[headerOffset + 12] & 0xF0) >> 2);
         dataLength      = ip.DataLength - (dataOffset - headerOffset);
     }
     else
     {
         throw new PacketFormatException("Packet is not TCP");
     }
 }
Beispiel #10
0
        public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string login, string password, ArraySegment<byte> data)
        {
            if ((flags & TcpFlags.Authenticated) != 0)
            {
                Ensure.NotNull(login, "login");
                Ensure.NotNull(password, "password");
            }
            else
            {
                if (login != null) throw new ArgumentException("Login provided for non-authorized TcpPackage.");
                if (password != null) throw new ArgumentException("Password provided for non-authorized TcpPackage.");
            }

            Command = command;
            Flags = flags;
            CorrelationId = correlationId;
            Login = login;
            Password = password;
            Data = data;
        }
Beispiel #11
0
        public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string authToken,
                          ArraySegment <byte> data) : this(command, flags, correlationId, data)
        {
            if ((flags & TcpFlags.Authenticated) != 0)
            {
                Ensure.NotNull(authToken, nameof(authToken));

                if (Helper.UTF8NoBom.GetByteCount(authToken) > MaxTokenLength)
                {
                    throw new ArgumentException($"Token length must be smaller than {MaxTokenLength} bytes",
                                                nameof(authToken));
                }
            }

            if ((flags & TcpFlags.Authenticated) == 0 && authToken != null)
            {
                throw new ArgumentException("Token provided for non-authorized TcpPackage", nameof(authToken));
            }

            _authToken = authToken;
        }
Beispiel #12
0
 public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string login, string password, byte[] data)
     : this(command, flags, correlationId, login, password, new ArraySegment<byte>(data ?? Empty.ByteArray))
 {
 }
 /// <summary>
 ///		Check whether or not a certain TCP flag is set.
 /// </summary>
 /// <param name="flag">
 ///		The flag to check.
 ///	</param>
 /// <returns>
 ///		Returns true if the flag is set, false otherwise.
 ///	</returns>
 public bool IsFlagSet(TcpFlags flag)
 {
     return((m_flags & (byte)flag) == (byte)flag);
 }
Beispiel #14
0
 extern public static int uv_tcp_bind(IntPtr handle, /*[In] ref Sockaddr*/ IntPtr addr, TcpFlags flags);
Beispiel #15
0
 public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string login, string password,
                   byte[] data)
     : this(command, flags, correlationId, login, password, new ArraySegment <byte>(data ?? Empty.ByteArray))
 {
 }
Beispiel #16
0
 private unsafe void WriteTcpPacket(TcpFlags flags, ReadOnlySpan <byte> data, bool isResponse = false)
 {
     lock (_pcap)
     {
         ref PacketHeader packetHeader = ref (useIPv6 ? ref _packet6.packetHeader : ref _packet4.packetHeader);
         ref TcpHeader    tcpHeader    = ref (useIPv6 ? ref _packet6.tcpHeader : ref _packet4.tcpHeader);
Beispiel #17
0
        public static TcpFrame ParseFrame(IPFrame ip, bool checksum = true)
        {
            if (ip == null)
            {
                return(null);
            }

            TcpFrame      frame  = null;
            BufferSegment packet = ip.Payload;

            packet.UnsafeAddrOfPinnedArrayElement((p) =>
            {
                tcp_hdr *tcphdr = (tcp_hdr *)p;
                if (tcphdr == null)
                {
                    return;
                }

                int hdrlen_bytes = TCPH_HDRLEN_BYTES(tcphdr);
                if (hdrlen_bytes < TCP_HLEN || hdrlen_bytes > packet.Length) // 错误的数据报
                {
                    return;
                }

                int len = packet.Length - hdrlen_bytes;
                if (len < 0)
                {
                    return;
                }

                TcpFlags flags = (TcpFlags)TCPH_FLAGS(tcphdr);
                if (checksum && tcphdr->chksum != 0)
                {
                    uint pseudo_checksum = CheckSum.inet_chksum_pseudo((byte *)p.ToPointer(),
                                                                       (uint)ProtocolType.Tcp,
                                                                       (uint)packet.Length,
                                                                       ip.SourceAddressV4,
                                                                       ip.DestinationAddressV4);
                    if (pseudo_checksum != 0)
                    {
                        return;
                    }
                }

                long payload_offset = 0;
                fixed(byte *stream  = packet.Buffer)
                {
                    payload_offset = ((byte *)p + hdrlen_bytes) - stream;
                }

                BufferSegment message_data = new BufferSegment(packet.Buffer, unchecked ((int)payload_offset), len);
                BufferSegment options_data = null;
                int options_size           = hdrlen_bytes - sizeof(tcp_hdr);
                if (options_size <= 0)
                {
                    options_data = new BufferSegment(BufferSegment.Empty);
                }
                else
                {
                    options_data = new BufferSegment(packet.Buffer,
                                                     packet.Offset + sizeof(tcp_hdr), options_size);
                }
                frame = new TcpFrame(new IPEndPoint(ip.Source, CheckSum.ntohs(tcphdr->src)), new IPEndPoint(ip.Destination, CheckSum.ntohs(tcphdr->dest)), message_data)
                {
                    Ttl                   = ip.Ttl,
                    AcknowledgeNo         = CheckSum.ntohl(tcphdr->ackno),
                    SequenceNo            = CheckSum.ntohl(tcphdr->seqno),
                    WindowSize            = CheckSum.ntohs(tcphdr->wnd),
                    Flags                 = flags,
                    SourceMacAddress      = ip.SourceMacAddress,
                    DestinationMacAddress = ip.DestinationMacAddress,
                    Options               = options_data,
                    UrgentPointer         = CheckSum.ntohs(tcphdr->urgp)
                };
            });
            return(frame);
        }
Beispiel #18
0
		/// <summary>
		///		Check whether or not a certain TCP flag is set.
		/// </summary>
		/// <param name="flag">
		///		The flag to check.
		///	</param>
		/// <returns>
		///		Returns true if the flag is set, false otherwise.
		///	</returns>
		public bool IsFlagSet (TcpFlags flag)
		{
			return ((m_flags & (byte)flag) == (byte)flag);
		}
Beispiel #19
0
 public TcpHeader(IPHeader ip)
 {
     if (ip.Protocol == IPProtocol.Tcp) {
     data = ip.Data;
     headerOffset = ip.DataOffset;
     sourcePort = data[headerOffset] << 8 | data[headerOffset + 1];
     destinationPort = data[headerOffset + 2] << 8 | data[headerOffset + 3];
     flags = (TcpFlags)(data[headerOffset + 13] & 0x3f);
     dataOffset = headerOffset + ((data[headerOffset + 12] & 0xF0) >> 2);
     dataLength = ip.DataLength - (dataOffset - headerOffset);
       } else {
     throw new PacketFormatException("Packet is not TCP");
       }
 }
Beispiel #20
0
		/// <summary>
		///		Set or unset a particular flag.
		/// </summary>
		/// <param name="flag">
		///		The flag to set or unset.
		///	</param>
		/// <param name="flagValue">
		///		true to set, false to unset.
		///	</param>
		public void SetFlag (TcpFlags flag, bool flagValue)
		{
			if (flagValue)
			{
				m_flags |= (byte)flag;
			}
			else
			{
				m_flags &= (byte)(~((byte)flag));
			}
		}
Beispiel #21
0
 public TcpPackage(TcpCommand command, TcpFlags flags, Guid correlationId, string authToken,
                   byte[] data)
     : this(command, flags, correlationId, authToken, new ArraySegment <byte>(data ?? Empty.ByteArray))
 {
 }