internal void HandleTcpReceived(uint sequenceNumber, ByteArraySegment data) { var dataPosition = SequenceNumberToBytesReceived(sequenceNumber); if (dataPosition == BytesReceived) { OnDataReceived(data); BytesReceived += data.Length; } else { var dataArray = new byte[data.Length]; Array.Copy(data.Bytes, data.Offset, dataArray, 0, data.Length); if (!_bufferedPackets.ContainsKey(dataPosition) || _bufferedPackets[dataPosition].Length < dataArray.Length) { _bufferedPackets[dataPosition] = dataArray; } } long firstBufferedPosition; while (_bufferedPackets.Any() && ((firstBufferedPosition = _bufferedPackets.Keys.First()) <= BytesReceived)) { var dataArray = _bufferedPackets[firstBufferedPosition]; _bufferedPackets.Remove(firstBufferedPosition); var alreadyReceivedBytes = BytesReceived - firstBufferedPosition; Debug.Assert(alreadyReceivedBytes >= 0); if (alreadyReceivedBytes >= dataArray.Length) continue; var count = dataArray.Length - alreadyReceivedBytes; OnDataReceived(new ByteArraySegment(dataArray, (int) alreadyReceivedBytes, (int) count)); BytesReceived += count; } }
/// <summary> /// Constructor /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment"/> /// </param> public ProbeRequestFrame (ByteArraySegment bas) { header = new ByteArraySegment (bas); FrameControl = new FrameControlField (FrameControlBytes); Duration = new DurationField (DurationBytes); DestinationAddress = GetAddress (0); SourceAddress = GetAddress (1); BssId = GetAddress (2); SequenceControl = new SequenceControlField (SequenceControlBytes); if(bas.Length > ProbeRequestFields.InformationElement1Position) { //create a segment that just refers to the info element section ByteArraySegment infoElementsSegment = new ByteArraySegment (bas.Bytes, (bas.Offset + ProbeRequestFields.InformationElement1Position), (bas.Length - ProbeRequestFields.InformationElement1Position)); InformationElements = new InformationElementList (infoElementsSegment); } else { InformationElements = new InformationElementList (); } //cant set length until after we have handled the information elements //as they vary in length header.Length = FrameSize; }
public TLV(byte[] bytes, int offset) { ByteArraySegment byteArraySegment = new ByteArraySegment(bytes, offset, 2); this.TypeLength = new TLVTypeLength(byteArraySegment); this.tlvData = new ByteArraySegment(bytes, offset, this.TypeLength.Length + 2); this.tlvData.Length = this.TypeLength.Length + 2; }
public void Test_Constructor_ConstructWithValues () { AckFrame frame = new AckFrame (PhysicalAddress.Parse ("111111111111")); frame.FrameControl.ToDS = false; frame.FrameControl.FromDS = true; frame.FrameControl.MoreFragments = true; frame.Duration.Field = 0x1234; frame.UpdateFrameCheckSequence (); UInt32 fcs = frame.FrameCheckSequence; //serialize the frame into a byte buffer var bytes = frame.Bytes; var bas = new ByteArraySegment (bytes); //create a new frame that should be identical to the original AckFrame recreatedFrame = MacFrame.ParsePacket (bas) as AckFrame; recreatedFrame.UpdateFrameCheckSequence (); Assert.AreEqual (FrameControlField.FrameSubTypes.ControlACK, recreatedFrame.FrameControl.SubType); Assert.IsFalse (recreatedFrame.FrameControl.ToDS); Assert.IsTrue (recreatedFrame.FrameControl.FromDS); Assert.IsTrue (recreatedFrame.FrameControl.MoreFragments); Assert.AreEqual ("111111111111", recreatedFrame.ReceiverAddress.ToString ().ToUpper ()); Assert.AreEqual (fcs, recreatedFrame.FrameCheckSequence); }
public FloodFiller(ByteArraySegment skin, int skinwidth, int skinheight) { _Skin = skin; _Width = skinwidth; _Height = skinheight; _Fifo = new floodfill_t[FLOODFILL_FIFO_SIZE]; _FillColor = _Skin.Data[_Skin.StartIndex]; // *skin; // assume this is the pixel to fill }
public void Test_Constructor_EmptyByteArray () { ByteArraySegment bas = new ByteArraySegment (new Byte[0]); InformationElementList ieList = new InformationElementList (bas); Assert.AreEqual (0, ieList.Count); Assert.AreEqual (0, ieList.Length); }
/// <summary> /// Create from a type and string value /// </summary> /// <param name="tlvType"> /// A <see cref="TLVTypes"/> /// </param> /// <param name="StringValue"> /// A <see cref="System.String"/> /// </param> public StringTLV(TLVTypes tlvType, string StringValue) { var bytes = new byte[TLVTypeLength.TypeLengthLength]; var offset = 0; tlvData = new ByteArraySegment(bytes, offset, bytes.Length); Type = tlvType; this.StringValue = StringValue; }
/// <summary> /// Constructor /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment"/> /// </param> public IGMPv2Packet(ByteArraySegment bas) { // set the header field, header field values are retrieved from this byte array header = new ByteArraySegment(bas); header.Length = UdpFields.HeaderLength; // store the payload bytes payloadPacketOrData = new PacketOrByteArraySegment(); payloadPacketOrData.TheByteArraySegment = header.EncapsulatedBytes(); }
public Decoder(int bufsize, long maxmsgsize) : base(bufsize) { m_maxmsgsize = maxmsgsize; m_tmpbuf = new ByteArraySegment(new byte[8]); // At the beginning, read one byte and go to one_byte_size_ready state. NextStep (m_tmpbuf, 1, OneByteSizeReadyState); }
/// <summary> /// Constructor /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment"/> /// </param> public CtsFrame (ByteArraySegment bas) { header = new ByteArraySegment (bas); FrameControl = new FrameControlField (FrameControlBytes); Duration = new DurationField (DurationBytes); ReceiverAddress = GetAddress(0); header.Length = FrameSize; }
/// <summary> /// Creates a System Capabilities TLV and sets the value /// </summary> /// <param name="capabilities"> /// A bitmap containing the available System Capabilities /// </param> /// <param name="enabled"> /// A bitmap containing the enabled System Capabilities /// </param> public SystemCapabilities(ushort capabilities, ushort enabled) { var length = TLVTypeLength.TypeLengthLength + SystemCapabilitiesLength + EnabledCapabilitiesLength; var bytes = new byte[length]; var offset = 0; tlvData = new ByteArraySegment(bytes, offset, length); Type = TLVTypes.SystemCapabilities; Capabilities = capabilities; Enabled = enabled; }
public void Test_Constructor_BufferTooShort () { //This IE will have and length of 5 but only three bytes of data Byte[] value = new Byte[] { 0x0, 0x5, 0x1, 0x2, 0x3 }; ByteArraySegment bas = new ByteArraySegment (value); InformationElement infoElement = new InformationElement (bas); Assert.AreEqual (3, infoElement.ValueLength); Assert.AreEqual (3, infoElement.Value.Length); }
/// <summary> /// Initializes a new instance of the <see cref="PacketDotNet.Ieee80211.NullDataFrame"/> class. /// </summary> /// <param name='bas'> /// A <see cref="ByteArraySegment"/> /// </param> public NullDataFrame (ByteArraySegment bas) { header = new ByteArraySegment (bas); FrameControl = new FrameControlField (FrameControlBytes); Duration = new DurationField (DurationBytes); SequenceControl = new SequenceControlField (SequenceControlBytes); ReadAddresses (); header.Length = FrameSize; }
public void Test_Constructor_BufferLongerThanElement () { //This IE will have and length of 2 but there are three bytes of data available, //the last one should be ignored Byte[] value = new Byte[] { 0x0, 0x2, 0x1, 0x2, 0x3 }; ByteArraySegment bas = new ByteArraySegment (value); InformationElement infoElement = new InformationElement (bas); Assert.AreEqual (2, infoElement.ValueLength); Assert.AreEqual (2, infoElement.Value.Length); }
/// <summary> /// Create a new V1Decoder with the given buffer-size, maximum-message-size and Endian-ness. /// </summary> /// <param name="bufsize">the buffer-size to give the contained buffer</param> /// <param name="maxMessageSize">the maximum message size. -1 indicates no limit.</param> /// <param name="endian">the Endianness to specify for it - either Big or Little</param> public V1Decoder(int bufsize, long maxMessageSize, Endianness endian) : base(bufsize, endian) { m_maxMessageSize = maxMessageSize; m_tmpbuf = new ByteArraySegment(new byte[8]); // At the beginning, read one byte and go to one_byte_size_ready state. NextStep(m_tmpbuf, 1, OneByteSizeReadyState); m_inProgress = new Msg(); m_inProgress.InitEmpty(); }
public PgmSender( IOThread ioThread, Options options, Address addr) : base(ioThread) { m_options = options; m_addr = addr; m_encoder = null; m_outBuffer = null; m_outBufferSize = 0; m_writeSize = 0; m_encoder = new V1Encoder(0, m_options.Endian); m_state = State.Idle; }
public void Dispose() { lock(this) { if (Data != null) { HttpPacket.BodyBufferPool.Push(Data); Data = null; } } }
public void device_OnPacketArrival(object sender, CaptureEventArgs eCap) { try { ByteArraySegment raw = new ByteArraySegment(eCap.Packet.Data); EthernetPacket ethernetPacket = new EthernetPacket(raw); IpPacket ipPacket = (IpPacket)ethernetPacket.PayloadPacket; TcpPacket tcp = (TcpPacket)ipPacket.PayloadPacket; if (ipPacket != null && tcp != null) { string destIp = ipPacket.DestinationAddress.ToString(); if (destIp == captureIp) { //Client -> Server MainWindow.pp.AppendClientData(tcp.PayloadData); // ReSharper disable CSharpWarnings::CS0642 while (MainWindow.pp.ProcessClientData()) ; // ReSharper restore CSharpWarnings::CS0642 } else { //Do a check for a new game Connection. Each handshake starts with a dword 1 packet from the server. byte[] test = { 0x01, 0x00, 0x00, 0x00 }; if (StructuralComparisons.StructuralEqualityComparer.Equals(test, tcp.PayloadData)) { //New Connection detected. //We should reset State and Security Info MainWindow.pp.Init(); MainWindow.pp.State = 0; MainWindow.ClearPackets(); } //Sever -> Client MainWindow.pp.AppendServerData(tcp.PayloadData); // ReSharper disable CSharpWarnings::CS0642 while (MainWindow.pp.ProcessServerData()) ; // ReSharper restore CSharpWarnings::CS0642 } } } catch (Exception ex) { MainWindow.SetText("device_OnPacketArrival failure. \n Message:" + ex); } }
public PgmSender([NotNull] IOThread ioThread, [NotNull] Options options, [NotNull] Address addr, bool delayedStart) : base(ioThread) { m_options = options; m_addr = addr; m_delayedStart = delayedStart; m_encoder = null; m_outBuffer = null; m_outBufferSize = 0; m_writeSize = 0; m_encoder = new V1Encoder(0, m_options.Endian); m_currentReconnectIvl = m_options.ReconnectIvl; m_state = State.Idle; }
/// <summary> /// Initializes a new instance of the <see cref="PacketDotNet.Ieee80211.DataDataFrame"/> class. /// </summary> /// <param name='bas'> /// Bas. /// </param> public DataDataFrame (ByteArraySegment bas) { header = new ByteArraySegment (bas); FrameControl = new FrameControlField (FrameControlBytes); Duration = new DurationField (DurationBytes); SequenceControl = new SequenceControlField (SequenceControlBytes); ReadAddresses (); //must do this after reading FrameControl header.Length = FrameSize; var availablePayloadLength = GetAvailablePayloadLength(); if(availablePayloadLength > 0) { payloadPacketOrData.TheByteArraySegment = header.EncapsulatedBytes (availablePayloadLength); } }
public void Init( PgmAddress pgmAddress) { m_pgmAddress = pgmAddress; m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Publisher, (PgmAddress)m_addr.Resolved); m_pgmSocket.Init(); m_socket = m_pgmSocket.Handle; var localEndpoint = new IPEndPoint(IPAddress.Any, 0); m_socket.Bind(localEndpoint); m_pgmSocket.InitOptions(); m_outBufferSize = Config.PgmMaxTPDU; m_outBuffer = new ByteArraySegment(new byte[m_outBufferSize]); }
public void LongLittleEndian() { ByteArraySegment byteArraySegment = new ByteArraySegment(new byte[8]); byteArraySegment.PutLong(Endianness.Little, 1, 0); Assert.AreEqual(byteArraySegment[0], 1); Assert.AreEqual(0, byteArraySegment[7]); long num = byteArraySegment.GetLong(Endianness.Little, 0); Assert.AreEqual(1, num); byteArraySegment.PutLong(Endianness.Little, 72057594037927936, 0); Assert.AreEqual(1, byteArraySegment[7]); Assert.AreEqual(0, byteArraySegment[0]); num = byteArraySegment.GetLong(Endianness.Little, 0); Assert.AreEqual(72057594037927936, num); }
public void IntLittleEndian() { ByteArraySegment byteArraySegment = new ByteArraySegment(new byte[4]); byteArraySegment.PutInteger(Endianness.Little, 1, 0); Assert.AreEqual(1, byteArraySegment[0]); Assert.AreEqual(0, byteArraySegment[3]); long num = byteArraySegment.GetInteger(Endianness.Little, 0); Assert.AreEqual(1, num); byteArraySegment.PutInteger(Endianness.Little, 16777216, 0); Assert.AreEqual(1, byteArraySegment[3]); Assert.AreEqual(0, byteArraySegment[0]); num = byteArraySegment.GetInteger(Endianness.Little, 0); Assert.AreEqual(16777216, num); }
/// <summary> /// Default constructor /// </summary> public ASExternalLink() { var b = new Byte[Length]; Header = new ByteArraySegment(b); }
/// <summary> /// This is called when socket input has been completed. /// </summary> /// <param name="socketError">This indicates the status of the input operation - whether Success or some error.</param> /// <param name="bytesTransferred">the number of bytes that were transferred</param> /// <exception cref="NetMQException">A non-recoverable socket-error occurred.</exception> public void InCompleted(SocketError socketError, int bytesTransferred) { switch (socketError) { case SocketError.Success: { // TODO: check TcpFilters var acceptedSocket = m_handle.GetAcceptedSocket(); acceptedSocket.NoDelay = true; if (m_options.TcpKeepalive != -1) { acceptedSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_options.TcpKeepalive); if (m_options.TcpKeepaliveIdle != -1 && m_options.TcpKeepaliveIntvl != -1) { var bytes = new ByteArraySegment(new byte[12]); Endianness endian = BitConverter.IsLittleEndian ? Endianness.Little : Endianness.Big; bytes.PutInteger(endian, m_options.TcpKeepalive, 0); bytes.PutInteger(endian, m_options.TcpKeepaliveIdle, 4); bytes.PutInteger(endian, m_options.TcpKeepaliveIntvl, 8); acceptedSocket.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null); } } // Create the engine object for this connection. var engine = new StreamEngine(acceptedSocket, m_options, m_endpoint); // Choose I/O thread to run connector in. Given that we are already // running in an I/O thread, there must be at least one available. IOThread ioThread = ChooseIOThread(m_options.Affinity); // Create and launch a session object. // TODO: send null in address parameter, is unneeded in this case SessionBase session = SessionBase.Create(ioThread, false, m_socket, m_options, new Address(m_handle.LocalEndPoint)); session.IncSeqnum(); LaunchChild(session); SendAttach(session, engine, false); m_socket.EventAccepted(m_endpoint, acceptedSocket); Accept(); break; } case SocketError.ConnectionReset: case SocketError.NoBufferSpaceAvailable: case SocketError.TooManyOpenSockets: { m_socket.EventAcceptFailed(m_endpoint, socketError.ToErrorCode()); Accept(); break; } default: { NetMQException exception = NetMQException.Create(socketError); m_socket.EventAcceptFailed(m_endpoint, exception.ErrorCode); throw exception; } } }
/// <summary> /// Constructor with parent packet /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment"/> /// </param> /// <param name="ParentPacket"> /// A <see cref="Packet"/> /// </param> public ICMPv6Packet(ByteArraySegment bas, Packet ParentPacket) : this(bas) { this.ParentPacket = ParentPacket; }
/// <summary> /// Constructor /// </summary> /// <param name="bas"></param> /// <param name="ParentPacket"></param> public DrdaPacket(ByteArraySegment bas, Packet ParentPacket) : this(bas) { log.DebugFormat("ParentPacket.GetType() {0}", ParentPacket.GetType()); this.ParentPacket = ParentPacket; }
public SctpSackChunk(ByteArraySegment bas, Packet parent) : this(bas) { this.ParentPacket = parent; }
/// <summary> /// Initializes a new instance of the <see cref="IPv6ExtensionHeader" /> class. /// </summary> /// <param name="header">The header.</param> /// <param name="byteArraySegment">The byte array segment.</param> public IPv6ExtensionHeader(ProtocolType header, ByteArraySegment byteArraySegment) { Header = header; ByteArraySegment = byteArraySegment; }
/// <summary> /// Creates an Option from a byte[] /// </summary> /// <param name="bytes"> /// A <see cref="T:System.Byte[]" /> /// </param> /// <param name="offset"> /// A <see cref="int" /> /// </param> /// <param name="length"> /// A <see cref="int" /> /// </param> protected Option(byte[] bytes, int offset, int length) { OptionData = new ByteArraySegment(bytes, offset, length); }
private void BeginSending() { Assumes.NotNull(m_outBuffer); // If write buffer is empty, try to read new data from the encoder. if (m_writeSize == 0) { Assumes.NotNull(m_encoder); Assumes.NotNull(m_session); // First two bytes (sizeof uint16_t) are used to store message // offset in following steps. Note that by passing our buffer to // the get data function we prevent it from returning its own buffer. ushort offset = 0xffff; var buffer = new ByteArraySegment(m_outBuffer, sizeof(ushort)); int bufferSize = m_outBufferSize - sizeof(ushort); int bytes = m_encoder.Encode(ref buffer, bufferSize); int lastBytes = bytes; while (bytes < bufferSize) { if (!m_moreFlag && offset == 0xffff) { offset = (ushort)bytes; } Msg msg = new Msg(); if (m_session.PullMsg(ref msg) != PullMsgResult.Ok) { break; } m_moreFlag = msg.HasMore; m_encoder.LoadMsg(ref msg); buffer = buffer !+lastBytes; lastBytes = m_encoder.Encode(ref buffer, bufferSize - bytes); bytes += lastBytes; } // If there are no data to write stop polling for output. if (bytes == 0) { m_state = State.ActiveSendingIdle; return; } // Put offset information in the buffer. m_writeSize = bytes + sizeof(ushort); m_outBuffer.PutUnsignedShort(m_options.Endian, offset, 0); } Assumes.NotNull(m_socket); try { m_socket.Send((byte[])m_outBuffer, m_outBuffer.Offset, m_writeSize, SocketFlags.None); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.ConnectionReset) { Error(); } else { throw NetMQException.Create(ex.SocketErrorCode, ex); } } }
/// <summary> /// Constructor /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment" /> /// </param> public ICMPv6Packet(ByteArraySegment bas) { log.Debug(""); this.header = new ByteArraySegment(bas); }
/// <summary> /// Constructs a packet from bytes and offset abd length /// </summary> /// <param name="packet"> /// A <see cref="System.Byte" /> /// </param> /// <param name="offset"> /// A <see cref="System.Int32" /> /// </param> /// <param name="length"> /// A <see cref="System.Int32" /> /// </param> public LinkStateRequest(Byte[] packet, Int32 offset, Int32 length) { Header = new ByteArraySegment(packet, offset, length); }
/// <summary> /// This method is called when a message Send operation has been completed. /// </summary> /// <param name="socketError">a SocketError value that indicates whether Success or an error occurred</param> /// <param name="bytesTransferred">the number of bytes that were transferred</param> /// <exception cref="NetMQException">A non-recoverable socket error occurred.</exception> /// <exception cref="NetMQException">If the socketError is not Success then it must be a valid recoverable error.</exception> public void OutCompleted(SocketError socketError, int bytesTransferred) { Assumes.NotNull(m_s); if (socketError != SocketError.Success) { m_ioObject.RemoveSocket(m_s); m_handleValid = false; Close(); // Try again to connect after a time, if (m_options.ReconnectIvl >= 0) { AddReconnectTimer(); } } else { m_ioObject.RemoveSocket(m_s); m_handleValid = false; try { m_s.NoDelay = true; } catch (ArgumentException) { // OSX sometime fail while the socket is still connecting } // As long as the TCP keep-alive option is not -1 (indicating no change), if (m_options.TcpKeepalive != -1) { // Set the TCP keep-alive option values to the underlying socket. m_s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_options.TcpKeepalive); if (m_options.TcpKeepaliveIdle != -1 && m_options.TcpKeepaliveIntvl != -1) { // Write the TCP keep-alive options to a byte-array, to feed to the IOControl method.. var bytes = new ByteArraySegment(new byte[12]); Endianness endian = BitConverter.IsLittleEndian ? Endianness.Little : Endianness.Big; bytes.PutInteger(endian, m_options.TcpKeepalive, 0); bytes.PutInteger(endian, m_options.TcpKeepaliveIdle, 4); bytes.PutInteger(endian, m_options.TcpKeepaliveIntvl, 8); m_s.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null); } } // Create the engine object for this connection. var engine = new StreamEngine(m_s, m_options, m_endpoint); m_socket.EventConnected(m_endpoint, m_s); m_s = null; // Attach the engine to the corresponding session object. SendAttach(m_session, engine); // Shut the connector down. Terminate(); } }
public void Test_Constructor_ConstructWithValues () { Byte[] BlockAckBitmap = new Byte[]{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}; BlockAcknowledgmentFrame frame = new BlockAcknowledgmentFrame (PhysicalAddress.Parse ("111111111111"), PhysicalAddress.Parse ("222222222222"), BlockAckBitmap); frame.FrameControl.ToDS = false; frame.FrameControl.FromDS = true; frame.FrameControl.MoreFragments = true; frame.Duration.Field = 0x1234; frame.BlockAcknowledgmentControl.Policy = BlockAcknowledgmentControlField.AcknowledgementPolicy.Delayed; frame.BlockAcknowledgmentControl.Tid = 0xF; frame.BlockAckStartingSequenceControl = 0x5678; frame.UpdateFrameCheckSequence (); UInt32 fcs = frame.FrameCheckSequence; //serialize the frame into a byte buffer var bytes = frame.Bytes; var bas = new ByteArraySegment (bytes); //create a new frame that should be identical to the original BlockAcknowledgmentFrame recreatedFrame = MacFrame.ParsePacket (bas) as BlockAcknowledgmentFrame; recreatedFrame.UpdateFrameCheckSequence(); Assert.AreEqual (FrameControlField.FrameSubTypes.ControlBlockAcknowledgment, recreatedFrame.FrameControl.SubType); Assert.IsFalse (recreatedFrame.FrameControl.ToDS); Assert.IsTrue (recreatedFrame.FrameControl.FromDS); Assert.IsTrue (recreatedFrame.FrameControl.MoreFragments); Assert.AreEqual (0x1234, recreatedFrame.Duration.Field); Assert.AreEqual (BlockAcknowledgmentControlField.AcknowledgementPolicy.Delayed, recreatedFrame.BlockAcknowledgmentControl.Policy); Assert.AreEqual (0xF, recreatedFrame.BlockAcknowledgmentControl.Tid); Assert.IsTrue (recreatedFrame.BlockAcknowledgmentControl.CompressedBitmap); Assert.AreEqual (0x5678, recreatedFrame.BlockAckStartingSequenceControl); Assert.AreEqual ("111111111111", recreatedFrame.TransmitterAddress.ToString ().ToUpper ()); Assert.AreEqual ("222222222222", recreatedFrame.ReceiverAddress.ToString ().ToUpper ()); CollectionAssert.AreEqual (BlockAckBitmap, recreatedFrame.BlockAckBitmap); Assert.AreEqual (fcs, recreatedFrame.FrameCheckSequence); }
/// <summary> /// Writes the current packet properties to the backing ByteArraySegment. /// </summary> public override void UpdateCalculatedValues () { if ((header == null) || (header.Length > (header.BytesLength - header.Offset)) || (header.Length < FrameSize)) { header = new ByteArraySegment (new Byte[FrameSize]); } this.FrameControlBytes = this.FrameControl.Field; this.DurationBytes = this.Duration.Field; SetAddress (0, ReceiverAddress); SetAddress (1, BssId); header.Length = FrameSize; }
/// <summary> /// Parses the <see cref="PacketDotNet.Utils.ByteArraySegment"/> into a MacFrame. /// </summary> /// <returns> /// The parsed MacFrame or null if it could not be parsed. /// </returns> /// <param name='bas'> /// The bytes of the packet. bas.Offset should point to the first byte in the mac frame. /// </param> /// <remarks>If the provided bytes contain the FCS then call <see cref="MacFrame.ParsePacketWithFcs"/> instead. The presence of the /// FCS is usually determined by configuration of the device used to capture the packets.</remarks> public static MacFrame ParsePacket(ByteArraySegment bas) { if (bas.Length < MacFields.FrameControlLength) { //there isn't enough data to even try and work out what type of packet it is return(null); } //this is a bit ugly as we will end up parsing the framecontrol field twice, once here and once //inside the packet constructor. Could create the framecontrol and pass it to the packet but I think that is equally ugly FrameControlField frameControl = new FrameControlField( EndianBitConverter.Big.ToUInt16(bas.Bytes, bas.Offset)); MacFrame macFrame = null; switch (frameControl.SubType) { case FrameControlField.FrameSubTypes.ManagementAssociationRequest: { macFrame = new AssociationRequestFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementAssociationResponse: { macFrame = new AssociationResponseFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementReassociationRequest: { macFrame = new ReassociationRequestFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementReassociationResponse: { macFrame = new AssociationResponseFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementProbeRequest: { macFrame = new ProbeRequestFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementProbeResponse: { macFrame = new ProbeResponseFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementReserved0: break; //TODO case FrameControlField.FrameSubTypes.ManagementReserved1: break; //TODO case FrameControlField.FrameSubTypes.ManagementBeacon: { macFrame = new BeaconFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementATIM: break; //TODO case FrameControlField.FrameSubTypes.ManagementDisassociation: { macFrame = new DisassociationFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementAuthentication: { macFrame = new AuthenticationFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementDeauthentication: { macFrame = new DeauthenticationFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementAction: { macFrame = new ActionFrame(bas); break; } case FrameControlField.FrameSubTypes.ManagementReserved3: break; //TODO case FrameControlField.FrameSubTypes.ControlBlockAcknowledgmentRequest: { macFrame = new BlockAcknowledgmentRequestFrame(bas); break; } case FrameControlField.FrameSubTypes.ControlBlockAcknowledgment: { macFrame = new BlockAcknowledgmentFrame(bas); break; } case FrameControlField.FrameSubTypes.ControlPSPoll: break; //TODO case FrameControlField.FrameSubTypes.ControlRTS: { macFrame = new RtsFrame(bas); break; } case FrameControlField.FrameSubTypes.ControlCTS: { macFrame = new CtsFrame(bas); break; } case FrameControlField.FrameSubTypes.ControlACK: { macFrame = new AckFrame(bas); break; } case FrameControlField.FrameSubTypes.ControlCFEnd: { macFrame = new ContentionFreeEndFrame(bas); break; } case FrameControlField.FrameSubTypes.ControlCFEndCFACK: break; //TODO case FrameControlField.FrameSubTypes.Data: case FrameControlField.FrameSubTypes.DataCFACK: case FrameControlField.FrameSubTypes.DataCFPoll: case FrameControlField.FrameSubTypes.DataCFAckCFPoll: { macFrame = new DataDataFrame(bas); break; } case FrameControlField.FrameSubTypes.DataNullFunctionNoData: case FrameControlField.FrameSubTypes.DataCFAckNoData: case FrameControlField.FrameSubTypes.DataCFPollNoData: case FrameControlField.FrameSubTypes.DataCFAckCFPollNoData: { macFrame = new NullDataFrame(bas); break; } case FrameControlField.FrameSubTypes.QosData: case FrameControlField.FrameSubTypes.QosDataAndCFAck: case FrameControlField.FrameSubTypes.QosDataAndCFPoll: case FrameControlField.FrameSubTypes.QosDataAndCFAckAndCFPoll: { macFrame = new QosDataFrame(bas); break; } case FrameControlField.FrameSubTypes.QosNullData: case FrameControlField.FrameSubTypes.QosCFAck: case FrameControlField.FrameSubTypes.QosCFPoll: case FrameControlField.FrameSubTypes.QosCFAckAndCFPoll: { macFrame = new QosNullDataFrame(bas); break; } default: //this is an unsupported (and unknown) packet type break; } return(macFrame); }
public void Test_Constructor_ConstructWithValues () { DisassociationFrame frame = new DisassociationFrame (PhysicalAddress.Parse ("111111111111"), PhysicalAddress.Parse ("222222222222"), PhysicalAddress.Parse ("333333333333")); frame.FrameControl.ToDS = false; frame.FrameControl.FromDS = true; frame.FrameControl.MoreFragments = true; frame.Duration.Field = 0x1234; frame.SequenceControl.SequenceNumber = 0x77; frame.SequenceControl.FragmentNumber = 0x1; frame.Reason = ReasonCode.LeavingToRoam; frame.UpdateFrameCheckSequence (); UInt32 fcs = frame.FrameCheckSequence; var bytes = frame.Bytes; var bas = new ByteArraySegment (bytes); //create a new frame that should be identical to the original DisassociationFrame recreatedFrame = MacFrame.ParsePacket (bas) as DisassociationFrame; recreatedFrame.UpdateFrameCheckSequence(); Assert.AreEqual (FrameControlField.FrameSubTypes.ManagementDisassociation, recreatedFrame.FrameControl.SubType); Assert.IsFalse (recreatedFrame.FrameControl.ToDS); Assert.IsTrue (recreatedFrame.FrameControl.FromDS); Assert.IsTrue (recreatedFrame.FrameControl.MoreFragments); Assert.AreEqual (0x1234, recreatedFrame.Duration.Field); Assert.AreEqual (0x77, recreatedFrame.SequenceControl.SequenceNumber); Assert.AreEqual (0x1, recreatedFrame.SequenceControl.FragmentNumber); Assert.AreEqual (ReasonCode.LeavingToRoam, recreatedFrame.Reason); Assert.AreEqual ("111111111111", recreatedFrame.SourceAddress.ToString ().ToUpper ()); Assert.AreEqual ("222222222222", recreatedFrame.DestinationAddress.ToString ().ToUpper ()); Assert.AreEqual ("333333333333", recreatedFrame.BssId.ToString ().ToUpper ()); Assert.AreEqual (fcs, recreatedFrame.FrameCheckSequence); }
/// <summary> /// Create a network address from byte data /// </summary> /// <param name="bytes"> /// A <see cref="T:System.Byte[]"/> /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> /// </param> /// <param name="length"> /// A <see cref="System.Int32"/> /// </param> public NetworkAddress(Byte[] bytes, Int32 offset, Int32 length) { data = new ByteArraySegment(bytes, offset, length); }
/// <summary> /// Called to ensure that field values are updated before /// the packet bytes are retrieved /// </summary> public override void UpdateCalculatedValues() { //If aligned is true then fields must all start on 32bit boundaries so we might need //to read some extra padding from the end of the header fields. bool aligned = ((Flags & HeaderFlags.Alignment32Bit) == HeaderFlags.Alignment32Bit); var totalFieldLength = Length; if ((header == null) || (totalFieldLength > header.Length)) { header = new ByteArraySegment (new Byte[totalFieldLength]); } header.Length = totalFieldLength; VersionBytes = Version; FlagsBytes = Flags; LengthBytes = (ushort)totalFieldLength; LinkTypeBytes = LinkType; MemoryStream ms = new MemoryStream(header.Bytes, header.Offset + PpiHeaderFields.FirstFieldPosition, totalFieldLength - PpiHeaderFields.FirstFieldPosition); BinaryWriter writer = new BinaryWriter(ms); foreach (var field in PpiFields) { writer.Write((ushort) field.FieldType); writer.Write((ushort) field.Length); writer.Write(field.Bytes); var paddingBytesRequired = GetDistanceTo32BitAlignment(field.Length); if(aligned && (paddingBytesRequired > 0)) { writer.Write(new byte[paddingBytesRequired]); } } }
/// <summary> /// Constructor /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment"/> /// </param> public ICMPv6Packet(ByteArraySegment bas) { //log.DEBUG(""); header = new ByteArraySegment(bas); }
public virtual void Initialise(ByteArraySegment buffer) { Texture = BaseTexture.FromBuffer(Device, Name, buffer, 128, 128, false, true, filter: "GL_NEAREST"); }
public void Test_Constructor_ConstructWithValues() { InformationElement ssidInfoElement = new InformationElement(InformationElement.ElementId.ServiceSetIdentity, new Byte[] { 0x68, 0x65, 0x6c, 0x6c, 0x6f }); InformationElement vendorElement = new InformationElement(InformationElement.ElementId.VendorSpecific, new Byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }); AssociationResponseFrame frame = new AssociationResponseFrame(PhysicalAddress.Parse("111111111111"), PhysicalAddress.Parse("222222222222"), PhysicalAddress.Parse("333333333333"), new InformationElementList() { ssidInfoElement, vendorElement }); frame.FrameControl.ToDS = false; frame.FrameControl.FromDS = true; frame.FrameControl.MoreFragments = true; frame.Duration.Field = 0x1234; frame.SequenceControl.SequenceNumber = 0x77; frame.SequenceControl.FragmentNumber = 0x1; frame.CapabilityInformation.Privacy = true; frame.CapabilityInformation.ChannelAgility = true; frame.StatusCode = AuthenticationStatusCode.Success; frame.AssociationId = 0x2; frame.UpdateFrameCheckSequence(); UInt32 fcs = frame.FrameCheckSequence; //serialize the frame into a byte buffer var bytes = frame.Bytes; var bas = new ByteArraySegment(bytes); //create a new frame that should be identical to the original AssociationResponseFrame recreatedFrame = MacFrame.ParsePacket(bas) as AssociationResponseFrame; recreatedFrame.UpdateFrameCheckSequence(); Assert.AreEqual(FrameControlField.FrameSubTypes.ManagementAssociationResponse, recreatedFrame.FrameControl.SubType); Assert.IsFalse(recreatedFrame.FrameControl.ToDS); Assert.IsTrue(recreatedFrame.FrameControl.FromDS); Assert.IsTrue(recreatedFrame.FrameControl.MoreFragments); Assert.AreEqual(0x77, recreatedFrame.SequenceControl.SequenceNumber); Assert.AreEqual(0x1, recreatedFrame.SequenceControl.FragmentNumber); Assert.IsTrue(recreatedFrame.CapabilityInformation.Privacy); Assert.IsTrue(recreatedFrame.CapabilityInformation.ChannelAgility); Assert.AreEqual(AuthenticationStatusCode.Success, recreatedFrame.StatusCode); Assert.AreEqual(0x2, recreatedFrame.AssociationId); Assert.AreEqual("111111111111", recreatedFrame.SourceAddress.ToString().ToUpper()); Assert.AreEqual("222222222222", recreatedFrame.DestinationAddress.ToString().ToUpper()); Assert.AreEqual("333333333333", recreatedFrame.BssId.ToString().ToUpper()); Assert.AreEqual(fcs, recreatedFrame.FrameCheckSequence); }
/// <summary> /// Constructs an OSPFv2 Hello packet from ByteArraySegment /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment" /> /// </param> public OSPFv2HelloPacket(ByteArraySegment bas) { Header = new ByteArraySegment(bas.Bytes); }
/// <summary> /// R_BuildLightMap /// Combine and scale multiple lightmaps into the 8.8 format in blocklights /// </summary> static void BuildLightMap(msurface_t surf, ByteArraySegment dest, int stride) { surf.cached_dlight = (surf.dlightframe == _FrameCount); int smax = (surf.extents[0] >> 4) + 1; int tmax = (surf.extents[1] >> 4) + 1; int size = smax * tmax; int srcOffset = surf.sampleofs; byte[] lightmap = surf.sample_base;// surf.samples; // set to full bright if no light data if (_FullBright.Value != 0 || Client.cl.worldmodel.lightdata == null) { for (int i = 0; i < size; i++) { _BlockLights[i] = 255 * 256; } } else { // clear to no light for (int i = 0; i < size; i++) { _BlockLights[i] = 0; } // add all the lightmaps if (lightmap != null) { for (int maps = 0; maps < BspFile.MAXLIGHTMAPS && surf.styles[maps] != 255; maps++) { int scale = _LightStyleValue[surf.styles[maps]]; surf.cached_light[maps] = scale; // 8.8 fraction for (int i = 0; i < size; i++) { _BlockLights[i] += (uint)(lightmap[srcOffset + i] * scale); } srcOffset += size; // lightmap += size; // skip to next lightmap } } // add all the dynamic lights if (surf.dlightframe == _FrameCount) { AddDynamicLights(surf); } } // bound, invert, and shift //store: int blOffset = 0; int destOffset = dest.StartIndex; byte[] data = dest.Data; switch (Drawer.LightMapFormat) { case PixelFormat.Rgba: stride -= (smax << 2); for (int i = 0; i < tmax; i++, destOffset += stride) // dest += stride { for (int j = 0; j < smax; j++) { uint t = _BlockLights[blOffset++]; // *bl++; t >>= 7; if (t > 255) { t = 255; } data[destOffset + 3] = (byte)(255 - t); //dest[3] = 255 - t; destOffset += 4; } } break; case PixelFormat.Alpha: case PixelFormat.Luminance: //case GL_INTENSITY: for (int i = 0; i < tmax; i++, destOffset += stride) { for (int j = 0; j < smax; j++) { uint t = _BlockLights[blOffset++]; // *bl++; t >>= 7; if (t > 255) { t = 255; } data[destOffset + j] = (byte)(255 - t); // dest[j] = 255 - t; } } break; default: Sys.Error("Bad lightmap format"); break; } }
/// <summary> /// Construct a TLVTypeLength for a TLV /// </summary> /// <param name="byteArraySegment"> /// A <see cref="ByteArraySegment"/> /// </param> public TLVTypeLength(ByteArraySegment byteArraySegment) { this.byteArraySegment = byteArraySegment; }
internal void OnDataReceived(ByteArraySegment data) { var dataReceived = DataReceived; dataReceived?.Invoke(this, data); }
/// <summary> /// Initializes a new instance of the <see cref="PacketDotNet.Ieee80211.InformationElement"/> class. /// </summary> /// <param name='bas'> /// The bytes of the information element. The Offset property should point to the first byte of the element, the Id byte /// </param> public InformationElement(ByteArraySegment bas) { bytes = bas; }
/// <summary> /// Constructs a packet from bytes and offset and length /// </summary> /// <param name="packet"> /// A <see cref="System.Byte" /> /// </param> /// <param name="offset"> /// A <see cref="System.Int32" /> /// </param> /// <param name="length"> /// A <see cref="System.Int32" /> /// </param> public ASExternalLink(Byte[] packet, Int32 offset, Int32 length) { Header = new ByteArraySegment(packet, offset, length); }
public Apdu(ByteArraySegment bas) : this(new TLV(bas)) { }
public SctpUnsupportedChunk(ByteArraySegment bas, Packet parent) : this(bas) { this.ParentPacket = parent; }
public Apdu(TLV tlv) : this() { base.Identifier = BerIdentifier.Encode(BerIdentifier.Application, BerIdentifier.Constructed, 1); base.Bytes = tlv.Bytes; ByteArraySegment pdu = tlv.Value.Bytes; pdu.Length = 0; TLV tmp = new TLV(pdu.EncapsulatedBytes()); gocbRef = new VisibleString(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); timeAllowedtoLive = new Integer(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); datSet = new VisibleString(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); if (IsGoIDTag(tmp.Tag.RawBytes)) { goID = new VisibleString(tmp); } pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); t = new UtcTime(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); stNum = new Integer(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); sqNum = new Integer(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); test = new TAsn1.Boolean(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); confRev = new Integer(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); ndsCom = new TAsn1.Boolean(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); numDatSetEntries = new Integer(tmp); pdu.Length += tmp.Bytes.Length; tmp = new TLV(pdu.EncapsulatedBytes()); int cnt = 0; // int len = tmp.Value.Bytes.Length; TLV data = new TLV(tmp.Value.Bytes); allData.Add(new Data(data)); cnt++; while (cnt < numDatSetEntries.Value) { data = new TLV(tmp.Value.Bytes.EncapsulatedBytes()); tmp.Value.Bytes.Length += data.Bytes.Length; //TLV data = new TLV(tmp.Value.Bytes); allData.Add(new Data(data)); cnt++; //tmp.Value.Bytes.Length += data.Bytes.Length; } }
/// <summary> /// Create a network address from byte data /// </summary> /// <param name="bytes"> /// A <see cref="System.Byte[]"/> /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> /// </param> /// <param name="length"> /// A <see cref="System.Int32"/> /// </param> public NetworkAddress(byte[] bytes, int offset, int length) { data = new ByteArraySegment(bytes, offset, length); }
public ByteArraySegmentEnumerator(ByteArraySegment segment) { _segment = segment; pos = segment.start; }
/// <summary> /// Writes the current packet properties to the backing ByteArraySegment. /// </summary> public override void UpdateCalculatedValues () { if ((header == null) || (header.Length > (header.BytesLength - header.Offset)) || (header.Length < FrameSize)) { header = new ByteArraySegment (new Byte[FrameSize]); } this.FrameControlBytes = this.FrameControl.Field; this.DurationBytes = this.Duration.Field; SetAddress (0, DestinationAddress); SetAddress (1, SourceAddress); SetAddress (2, BssId); this.SequenceControlBytes = this.SequenceControl.Field; this.CapabilityInformationBytes = this.CapabilityInformation.Field; //we now know the backing buffer is big enough to contain the info elements so we can safely copy them in this.InformationElements.CopyTo (header, header.Offset + ProbeResponseFields.InformationElement1Position); header.Length = FrameSize; }
/// <summary> /// Creates an Option from a byte[] /// </summary> /// <param name="bytes"> /// A <see cref="System.Byte[]"/> /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> /// </param> /// <param name="length"> /// A <see cref="System.Int32"/> /// </param> public Option(byte[] bytes, int offset, int length) { optionData = new ByteArraySegment(bytes, offset, length); }
/// <summary> /// Initializes a new instance of the <see cref="PacketDotNet.Ieee80211.PpiPacket"/> class. /// </summary> /// <param name='bas'> /// A <see cref="ByteArraySegment"/> /// </param> public PpiPacket (ByteArraySegment bas) { // slice off the header portion header = new ByteArraySegment (bas); Version = VersionBytes; Flags = FlagsBytes; // update the header size based on the headers packet length header.Length = LengthBytes; LinkType = LinkTypeBytes; PpiFields = ReadPpiFields(); PpiCommon commonField = FindFirstByType(PpiFieldType.PpiCommon) as PpiCommon; // parse the encapsulated bytes payloadPacketOrData = ParseEncapsulatedBytes (header, commonField); }
/// <summary> /// Default constructor /// </summary> public LinkStateRequest() { var b = new byte[Length]; _header = new ByteArraySegment(b); }
/// <summary> /// Used by the Ieee80211PpiPacket constructor. /// </summary> /// <param name="header"> /// A <see cref="ByteArraySegment"/> /// </param> /// <param name="commonField"> /// The <see cref="PpiCommon"/> object in the PPI packet or null if not available /// </param> /// <returns> /// A <see cref="PacketOrByteArraySegment"/> /// </returns> internal static PacketOrByteArraySegment ParseEncapsulatedBytes (ByteArraySegment header, PpiCommon commonField) { // slice off the payload var payload = header.EncapsulatedBytes (); var payloadPacketOrData = new PacketOrByteArraySegment (); MacFrame frame = null; if (commonField != null) { bool fcsPresent = ((commonField.Flags & PpiCommon.CommonFlags.FcsIncludedInFrame) == PpiCommon.CommonFlags.FcsIncludedInFrame); if (fcsPresent) { frame = MacFrame.ParsePacketWithFcs (payload); } else { frame = MacFrame.ParsePacket (payload); } } else { frame = MacFrame.ParsePacket (payload); } if (frame == null) { payloadPacketOrData.TheByteArraySegment = payload; } else { payloadPacketOrData.ThePacket = frame; } return payloadPacketOrData; }
/// <summary> /// Constructs a packet from bytes and offset abd length /// </summary> /// <param name="packet"> /// A <see cref="byte" /> /// </param> /// <param name="offset"> /// A <see cref="int" /> /// </param> /// <param name="length"> /// A <see cref="int" /> /// </param> public LinkStateRequest(byte[] packet, int offset, int length) { _header = new ByteArraySegment(packet, offset, length); }