예제 #1
0
        public void BinarySendTask( )
        {
            byte sequence = 0;

            while (IsRunning)
            {
                if (SendQueue.TryDequeue(out SendDatagram datagram))
                {
                    byte [] data = datagram.ToBinary( );

                    UnderlyingStream.WriteByte(DatagramHeader);
                    UnderlyingStream.WriteByte(sequence);
                    UnderlyingStream.WriteByte(( byte )datagram.Type.BinaryType);
                    UnderlyingStream.WriteByte(data.CaluCrc8( ));
                    UnderlyingStream.WriteByte(Convert.ToByte(data.Length));
                    UnderlyingStream.Write(data, 0, data.Length);

                    sequence++;
                }
                else
                {
                    Thread.Sleep(20);
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Writes a fixed-length ASCII-encoded string value to the underlying stream. To fit (size), the string content is either truncated or padded with null characters.
        /// </summary>
        public void WriteAsciiFixed(string value, int size)
        {
            if (value == null)
            {
                Console.WriteLine("Network: Attempted to WriteAsciiFixed() with null value");
                value = string.Empty;
            }

            int length = value.Length;

            UnderlyingStream.SetLength(UnderlyingStream.Length + size);

            if (length >= size)
            {
                UnderlyingStream.Position += Encoding.ASCII.GetBytes(value, 0, size, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
            }
            else
            {
                Encoding.ASCII.GetBytes(value, 0, length, UnderlyingStream.GetBuffer(), (int)UnderlyingStream.Position);
                UnderlyingStream.Position += size;
            }

            /*byte[] buffer = Encoding.ASCII.GetBytes( value );
             *
             * if ( buffer.Length >= size )
             * {
             *      m_Stream.Write( buffer, 0, size );
             * }
             * else
             * {
             *      m_Stream.Write( buffer, 0, buffer.Length );
             *      Fill( size - buffer.Length );
             * }*/
        }
예제 #3
0
        /*public*/ bool TryAndFind(BlobChunkHeader signature, long findStartPosition = TypeExtensions.kNone)
        {
            Contract.Requires <ArgumentOutOfRangeException>(findStartPosition.IsNone() ||
                                                            findStartPosition < AssumedBlobSize);

            Util.MarkUnusedVariable(ref signature);

            bool blob_found = false;
            long orig_pos   = TypeExtensions.kNone;

            if (findStartPosition.IsNotNone())
            {
                orig_pos = UnderlyingStream.BaseStream.Position;
                UnderlyingStream.Seek(findStartPosition + StartPosition, System.IO.SeekOrigin.Begin);
            }

            // #TODO_IMPLEMENT
            Contract.Assert(false, "TODO");

            if (orig_pos.IsNotNone())
            {
                UnderlyingStream.Seek(orig_pos, System.IO.SeekOrigin.Begin);
            }

            return(blob_found);
        }
예제 #4
0
        /// <summary>
        /// Writes a 2-byte unsigned integer value to the underlying stream.
        /// </summary>
        public void Write(ushort value)
        {
            m_Buffer[0] = (byte)(value >> 8);
            m_Buffer[1] = (byte)value;

            UnderlyingStream.Write(m_Buffer, 0, 2);
        }
예제 #5
0
        BlobChunkVerificationResultInfo VerifyEof(bool streamFirst = true,
                                                  BlobTransportStreamAuthentication expectedAuthentication = BlobTransportStreamAuthentication.None)
        {
            var result = streamFirst ? VerifyEnoughBytesForChunkOrData(kFooterSize) : BlobChunkVerificationResultInfo.ValidResult;

            if (result.IsValid)
            {
                if (streamFirst)
                {
                    mFooterPosition = BaseStream.Position;
                    UnderlyingStream.Stream(ref mHeader);
                }
                long blob_size = AssumedBlobSize;

                result = mFooter.Verify(expectedAuthentication, blob_size);

                if (streamFirst && result.IsValid)
                {
                    mFooter.SerializeAuthenticationData(UnderlyingStream);
                }
            }

            if (result.IsInvalid)
            {
                result.Context = BlobChunkVerificationResultContext.Footer;
            }

            return(result);
        }
예제 #6
0
        public BulletinBoardSendPostSummaryPacket(BulletinBoard Board, BulletinBoardPost Post)
            : base(0x71)
        {
            // Set the maximum size
            EnsureCapacity(1024);

            // Fill the packet data
            UnderlyingStream.Write((byte)BulletinPacket.PacketSubType.SendPostSummary);
            int BoardSerial = Board.Serial;

            if ((Post.RootParent != null) && (Post.RootParent is BulletinBoard))
            {
                BoardSerial = (((Item)(Post.RootParent)).Serial);
            }
            UnderlyingStream.Write((int)BoardSerial); // Bulletin Board Serial
            UnderlyingStream.Write((int)Post.Serial); // Post Serial
            int ParentSerial = Board.Serial;

            if ((Post.Parent != null) && ((Post.Parent is BulletinBoard) || (Post.Parent is BulletinBoardPost)))
            {
                ParentSerial = (((Item)(Post.Parent)).Serial);
            }
            UnderlyingStream.Write((int)(ParentSerial == BoardSerial ? 0 : ParentSerial)); // Parent Serial (if it is a reply)
            UnderlyingStream.Write((byte)(Post.Author.Length + 1));
            UnderlyingStream.WriteAsciiNull(Post.Author);
            UnderlyingStream.Write((byte)(Post.Subject.Length + 1));
            UnderlyingStream.WriteAsciiNull(Post.Subject);
            UnderlyingStream.Write((byte)(Post.Date.Length + 1));
            UnderlyingStream.WriteAsciiNull(Post.Date);

            // Log the raw packet info
            BulletinPacket.LogPacket("BulletinBoardSendPostSummaryPacket", UnderlyingStream.ToArray());
        }
예제 #7
0
        BlobChunkVerificationResultInfo VerifyStart(bool streamFirst = true)
        {
            var result = streamFirst ? VerifyEnoughBytesForChunkOrData(kHeaderSize) : BlobChunkVerificationResultInfo.ValidResult;

            if (result.IsValid)
            {
                if (streamFirst)
                {
                    UnderlyingStream.Stream(ref mHeader);
                }

                bool requires_byteswap;
                result = mHeader.Verify(out requires_byteswap);

                if (result.IsValid && requires_byteswap)
                {
                    UnderlyingStream.ChangeByteOrder(UnderlyingStream.ByteOrder.Invert());
                }
            }

            if (result.IsInvalid)
            {
                result.Context = BlobChunkVerificationResultContext.Header;
            }

            return(result);
        }
예제 #8
0
 public void Dispose()
 {
     if (UnderlyingStream != null)
     {
         UnderlyingStream.Dispose();
         UnderlyingStream = null;
     }
 }
예제 #9
0
        /// <summary>
        /// Writes a 4-byte unsigned integer value to the underlying stream.
        /// </summary>
        public void Write(uint value)
        {
            m_Buffer[0] = (byte)(value >> 24);
            m_Buffer[1] = (byte)(value >> 16);
            m_Buffer[2] = (byte)(value >> 8);
            m_Buffer[3] = (byte)value;

            UnderlyingStream.Write(m_Buffer, 0, 4);
        }
예제 #10
0
 ///<inheritdoc />
 public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
 {
     ThrowIfDisposed();
     if (_memoryStatus == MemoryFlag.AutoOverFlowToDisk && _isInMemory && count + UnderlyingStream.Position > _threshholdSize)
     {
         OverflowToPersistentStream();
     }
     return(UnderlyingStream.WriteAsync(buffer, offset, count, cancellationToken));
 }
예제 #11
0
 ///<inheritdoc />
 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     ThrowIfDisposed();
     if (_memoryStatus == MemoryFlag.AutoOverFlowToDisk && _isInMemory && count + UnderlyingStream.Position > _threshholdSize)
     {
         OverflowToPersistentStream();
     }
     return(UnderlyingStream.BeginWrite(buffer, offset, count, callback, state));
 }
예제 #12
0
        ///<inheritdoc />
        public override void Write(byte[] buffer, int offset, int count)
        {
            ThrowIfDisposed();
            if (_memoryStatus == MemoryFlag.AutoOverFlowToDisk && _isInMemory && count + UnderlyingStream.Position > _threshholdSize)
            {
                OverflowToPersistentStream();
            }

            UnderlyingStream.Write(buffer, offset, count);
        }
예제 #13
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (Position >= Length || Length - Position < count)
            {
                throw new IOException("Attempt to write beyond the slice");
            }

            UnderlyingStream.Position = Position + Start;
            UnderlyingStream.Write(buffer, offset, count);
        }
예제 #14
0
        private void OverflowToPersistentStream()
        {
            Stream persistentStream = CreatePersistentStream(_forAsync);

            persistentStream.SetLength(UnderlyingStream.Length);

            UnderlyingStream.Position = 0;
            UnderlyingStream.CopyTo(persistentStream);
            UnderlyingStream = persistentStream;
            _isInMemory      = false;
        }
예제 #15
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (UnderlyingStream != null)
         {
             UnderlyingStream.Dispose();
             UnderlyingStream = null;
         }
     }
 }
 protected void TryDisposeUnderlyingStream()
 {
     try
     {
         UnderlyingStream?.Dispose();
     }
     catch (Exception)
     {
         // Well, at least we tried
     }
 }
예제 #17
0
        ///<inheritdoc />
        public override void SetLength(long length)
        {
            ThrowIfDisposed();

            if (_memoryStatus == MemoryFlag.AutoOverFlowToDisk && _isInMemory && length > _threshholdSize)
            {
                OverflowToPersistentStream();
            }

            UnderlyingStream.SetLength(length);
        }
예제 #18
0
 /// <summary>
 /// Writes a number of 0x00 byte values to the underlying stream.
 /// </summary>
 public void Fill(int length)
 {
     if (UnderlyingStream.Position == UnderlyingStream.Length)
     {
         UnderlyingStream.SetLength(UnderlyingStream.Length + length);
         UnderlyingStream.Seek(0, SeekOrigin.End);
     }
     else
     {
         UnderlyingStream.Write(new byte[length], 0, length);
     }
 }
예제 #19
0
파일: PartialStream.cs 프로젝트: radtek/PSD
        public override void Write(byte[] buffer, int offset, int count)
        {
            long remaining     = Length - (UnderlyingStream.Position - PartialStart);
            int  actuallyWrite = (int)Math.Min(remaining, count);

            if (actuallyWrite < 0)
            {
                return;
            }

            UnderlyingStream.Write(buffer, offset, actuallyWrite);
        }
예제 #20
0
파일: PartialStream.cs 프로젝트: radtek/PSD
        public override int Read(byte[] buffer, int offset, int count)
        {
            long remaining    = Length - (UnderlyingStream.Position - PartialStart);
            int  actuallyRead = (int)Math.Min(remaining, count);

            if (actuallyRead < 0)
            {
                return(0);
            }

            return(UnderlyingStream.Read(buffer, offset, actuallyRead));
        }
예제 #21
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (Position >= Length)
            {
                return(0);
            }

            int toRead = (int)Math.Min(Length - Position, count);

            UnderlyingStream.Position = Position + Start;
            int bytesRead = UnderlyingStream.Read(buffer, offset, toRead);

            Position += bytesRead;
            return(bytesRead);
        }
예제 #22
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            int  bytesRead = count;
            long max       = Length - Position;

            if (max < bytesRead)
            {
                bytesRead = (int)max;
            }

            UnderlyingStream.Read(buffer, offset, bytesRead);
            InternalPosition += bytesRead;

            return(bytesRead);
        }
예제 #23
0
        public void BinaryListenTask( )
        {
            try
            {
                byte currentSequence = 0;
                while (IsRunning)
                {
                    if (UnderlyingStream.ReadByte( ) == DatagramHeaderInt)
                    {
                        byte sequence = ( byte )UnderlyingStream.ReadByte( );

                        if (sequence == currentSequence)
                        {
                            currentSequence++;
                        }
                        else
                        {
                            //Todo:???
                        }

                        BinaryDatagramType type = ( BinaryDatagramType )( byte )UnderlyingStream.ReadByte( );                               //todo:if not throw

                        byte crc = ( byte )UnderlyingStream.ReadByte( );

                        byte length = ( byte )UnderlyingStream.ReadByte( );

                        byte [] data = new byte[length];

                        UnderlyingStream.Read(data, 0, length);

                        if (data.CaluCrc8( ) == crc)
                        {
                            if (Datagram.Parse(type, data) is ReceiveDatagram datagram)
                            {
                                ReceiveQueue.Enqueue(datagram);
                            }
                        }
                        else
                        {
                            //todo:Warning?
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
        }
예제 #24
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            try
            {
                int bytes = UnderlyingStream.Read(buffer, offset, count);
                _Position += bytes;

                Logger?.LogDebug($"StreamRequestWrapper: Read(buffer, {offset}, {count}) returned {bytes} Position: {this.Position} Length: {this.Length}");

                return(bytes);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #25
0
        BlobChunkVerificationResultInfo EnumerateOneChunk <T>(
            out BlobChunkHeader header, ref T resultValue,
            Func <BlobTransportStream, BlobChunkHeader, T> getResultValue, bool getResultValueConsumesChunk,
            out bool isEof)
        {
            header = BlobChunkHeader.Null;
            isEof  = false;
            var result = VerifyEnoughBytesForChunkOrData(BlobChunkHeader.kSizeOf);

            if (result.IsValid)
            {
                UnderlyingStream.Stream(ref header);
                result = header.VerifyVersionIsPositive()
                         .And(header, h => h.VerifyDataSize(0))
                         .And(header, h => h.VerifyFlagsIsPostive())
                         .And(header, this, (h, s) => s.VerifyEnoughBytesForChunkOrData(h.DataSize));

                isEof = header.Signature == StreamFooter.kSignature.ID;

                if (result.IsValid)
                {
                    if (isEof)
                    {
                        mFooterPosition = BaseStream.Position - BlobChunkHeader.kSizeOf;
                        mFooter.SerializeSansHeader(UnderlyingStream, header);
                        mFooter.SerializeAuthenticationData(UnderlyingStream);
                    }
                    else
                    {
                        resultValue = getResultValue(this, header);

                        if (!getResultValueConsumesChunk)
                        {
                            header.StreamSkipData(BaseStream);
                        }
                    }
                }
                else
                {
                    if (isEof)
                    {
                        result.Context = BlobChunkVerificationResultContext.Footer;
                    }
                }
            }
            return(result);
        }
예제 #26
0
        public async override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            try
            {
                int bytes = await UnderlyingStream.ReadAsync(buffer, offset, count);

                _Position += bytes;

                Logger?.LogDebug($"StreamRequestWrapper: Read(buffer, {offset}, {count}) returned {bytes} Position: {this.Position} Length: {this.Length}");

                return(bytes);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #27
0
        public BulletinBoardOpenPacket(BulletinBoard Board)
            : base(0x71)
        {
            // Don't need much room here (just enough to take into account a
            // non-default bulletin board name)
            EnsureCapacity(256);

            // Get the name of the bulletin board
            string BoardName = Board.Name == null ? "Bulletin Board" : Board.Name;

            // Fill the packet data
            UnderlyingStream.Write((byte)BulletinPacket.PacketSubType.DisplayBoard);
            UnderlyingStream.Write((int)Board.Serial);
            UnderlyingStream.WriteAsciiNull(BoardName);

            // Log the raw packet info
            BulletinPacket.LogPacket("BulletinBoardOpenPacket", UnderlyingStream.ToArray());
        }
예제 #28
0
        /// <summary>
        /// Obtains an element from the collection.
        /// </summary>
        /// <param name="index">The index of the element to extract.</param>
        /// <returns>The requested element from the collection.</returns>
        public TreeNode this[int index]
        {
            get
            {
                if (StorageType == StorageTypes.List)
                {
                    return(InternalStorage[index]);
                }
                else
                {
                    int correspIndex = TreeIndexCorrespondence[index];
                    if (correspIndex >= 0)
                    {
                        UnderlyingStream.Seek(TreeAddresses[correspIndex], SeekOrigin.Begin);
                        return(UnderlyingReader.ReadTree(GlobalNames, AllNames, AllAttributes));
                    }
                    else
                    {
                        return(InternalStorage[-correspIndex - 1]);
                    }
                }
            }

            set
            {
                if (StorageType == StorageTypes.List)
                {
                    InternalStorage[index] = value;
                }
                else
                {
                    int correspIndex = TreeIndexCorrespondence[index];
                    if (correspIndex >= 0)
                    {
                        InternalStorage.Add(value);
                        TreeIndexCorrespondence[index] = -InternalStorage.Count;
                    }
                    else
                    {
                        InternalStorage[-correspIndex - 1] = value;
                    }
                }
            }
        }
예제 #29
0
        public object Clone()
        {
            Stream clonedStream;

            if (_isInMemory)
            {
                clonedStream = new MemoryStream((int)UnderlyingStream.Length);
            }
            else
            {
                clonedStream = CreatePersistentStream(_forAsync);
                clonedStream.SetLength(this.Length);
            }

            UnderlyingStream.CopyTo(clonedStream);
            clonedStream.Position = 0L;

            return(new VirtualStream(_threshholdSize, _memoryStatus, clonedStream, _forAsync));
        }
예제 #30
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     if (Direction == Direction.Read)
     {
         throw new InvalidOperationException("Incorrect direction");
     }
     byte[] underlying = new byte[count];
     for (int i = 0; i < count; i++)
     {
         if (Mode == EncryptionMode.Encrypt)
         {
             underlying[i] = encryptByte(buffer[i + offset]);
         }
         else
         {
             underlying[i] = decryptByte(buffer[i + offset]);
         }
     }
     UnderlyingStream.Write(underlying, 0, count);
 }