Example #1
0
        public static uint CalculateCRCForChunk(string chunkType, byte[] chunkData)
        {
            byte[] chunkTypeBytes = Encoding.UTF8.GetBytes(chunkType);

            Ionic.Crc.CRC32 crc32calculator = new Ionic.Crc.CRC32();
            crc32calculator.SlurpBlock(chunkTypeBytes, 0, chunkTypeBytes.Length);
            crc32calculator.SlurpBlock(chunkData, 0, chunkData.Length);

            return((uint)crc32calculator.Crc32Result);
        }
Example #2
0
        public override void Write(System.Byte[] buffer, int offset, int count)
        {
#if !NETFX_CORE
            // workitem 7159
            // calculate the CRC on the unccompressed data  (before writing)
            if (crc != null)
            {
                crc.SlurpBlock(buffer, offset, count);
            }
#endif

            if (_streamMode == StreamMode.Undefined)
            {
                _streamMode = StreamMode.Writer;
            }
            else if (_streamMode != StreamMode.Writer)
            {
                throw new ZlibException("Cannot Write after Reading.");
            }

            if (count == 0)
            {
                return;
            }

            // first reference of z property will initialize the private var _z
            z.InputBuffer       = buffer;
            _z.NextIn           = offset;
            _z.AvailableBytesIn = count;
            bool done = false;
            do
            {
                _z.OutputBuffer      = workingBuffer;
                _z.NextOut           = 0;
                _z.AvailableBytesOut = _workingBuffer.Length;
                int rc = (_wantCompress)
                    ? _z.Deflate(_flushMode)
                    : _z.Inflate(_flushMode);
                if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
                {
                    throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message);
                }

                //if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
                _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);

                done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;

                // If GZIP and de-compress, we're done when 8 bytes remain.
                if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
                {
                    done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
                }
            }while (!done);
        }
Example #3
0
        public async Task <TcpMessage> Receive(CancellationToken token = default(CancellationToken))
        {
            var packetLengthBytes = new byte[4];

            if (await _stream.ReadAsync(packetLengthBytes, 0, 4, token).ConfigureAwait(false) != 4)
            {
                throw new InvalidOperationException("Couldn't read the packet length");
            }

            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            var seqBytes = new byte[4];

            if (await _stream.ReadAsync(seqBytes, 0, 4, token).ConfigureAwait(false) != 4)
            {
                throw new InvalidOperationException("Couldn't read the sequence");
            }

            int seq = BitConverter.ToInt32(seqBytes, 0);

            int readBytes    = 0;
            var body         = new byte[packetLength - 12];
            int neededToRead = packetLength - 12;

            do
            {
                var bodyByte       = new byte[packetLength - 12];
                var availableBytes = await _stream.ReadAsync(bodyByte, 0, neededToRead, token).ConfigureAwait(false);

                neededToRead -= availableBytes;
                Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
                readBytes += availableBytes;
            }while (readBytes != packetLength - 12);

            var crcBytes = new byte[4];

            if (await _stream.ReadAsync(crcBytes, 0, 4, token).ConfigureAwait(false) != 4)
            {
                throw new InvalidOperationException("Couldn't read the crc");
            }

            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return(new TcpMessage(seq, body));
        }
        public TcpMessage Receieve()
        {
            lock (_locker)
            {
                var stream = _tcpClient.GetStream();

                var packetLengthBytes = new byte[4];
                if (stream.Read(packetLengthBytes, 0, 4) != 4)
                {
                    throw new InvalidOperationException("Couldn't read the packet length");
                }
                int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

                var seqBytes = new byte[4];
                if (stream.Read(seqBytes, 0, 4) != 4)
                {
                    throw new InvalidOperationException("Couldn't read the sequence");
                }
                int seq = BitConverter.ToInt32(seqBytes, 0);

                int readBytes    = 0;
                var body         = new byte[packetLength - 12];
                int neededToRead = packetLength - 12;

                do
                {
                    var bodyByte       = new byte[packetLength - 12];
                    var availableBytes = stream.Read(bodyByte, 0, neededToRead);
                    neededToRead -= availableBytes;
                    Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
                    readBytes += availableBytes;
                }while (readBytes != packetLength - 12);

                var crcBytes = new byte[4];
                if (stream.Read(crcBytes, 0, 4) != 4)
                {
                    throw new InvalidOperationException("Couldn't read the crc");
                }
                int checksum = BitConverter.ToInt32(crcBytes, 0);

                byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];

                Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
                Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
                Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
                var crc32 = new Ionic.Crc.CRC32();
                crc32.SlurpBlock(rv, 0, rv.Length);
                var validChecksum = crc32.Crc32Result;

                if (checksum != validChecksum)
                {
                    throw new InvalidOperationException("invalid checksum! skip");
                }

                return(new TcpMessage(seq, body));
            }
        }
        private static bool IsValidChecksum(byte[] block, int checksum)
        {
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(block, 0, block.Length);
            var validChecksum = crc32.Crc32Result;

            return(checksum == validChecksum);
        }
Example #6
0
        public async Task <TcpMessage> Receieve()
        {
            // packet length
            var packetLengthBytes = new byte[4];

            if (!await ReadBuffer(stream, packetLengthBytes))
            {
                return(null);
            }

            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            // seq
            var seqBytes = new byte[4];

            if (!await ReadBuffer(stream, seqBytes))
            {
                return(null);
            }

            int seq = BitConverter.ToInt32(seqBytes, 0);

            // body
            var bodyBytes = new byte[packetLength - 12];

            if (!await ReadBuffer(stream, bodyBytes))
            {
                return(null);
            }

            // crc
            var crcBytes = new byte[4];

            if (!await ReadBuffer(stream, crcBytes))
            {
                return(null);
            }

            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + bodyBytes.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(bodyBytes, 0, rv, packetLengthBytes.Length + seqBytes.Length, bodyBytes.Length);
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return(new TcpMessage(seq, bodyBytes));
        }
        private void _DeflateOne(Object wi)
        {
            // compress one buffer
            WorkItem workitem = (WorkItem)wi;

            try
            {
                int             myItem = workitem.index;
                Ionic.Crc.CRC32 crc    = new Ionic.Crc.CRC32();

                // calc CRC on the buffer
                crc.SlurpBlock(workitem.buffer, 0, workitem.inputBytesAvailable);

                // deflate it
                DeflateOneSegment(workitem);

                // update status
                workitem.crc = crc.Crc32Result;
                TraceOutput(TraceBits.Compress,
                            "Compress          wi({0}) ord({1}) len({2})",
                            workitem.index,
                            workitem.ordinal,
                            workitem.compressedBytesAvailable
                            );

                lock (_latestLock)
                {
                    if (workitem.ordinal > _latestCompressed)
                    {
                        _latestCompressed = workitem.ordinal;
                    }
                }
                lock (_toWrite)
                {
                    _toWrite.Enqueue(workitem.index);
                }
                _newlyCompressedBlob.Set();
            }
            catch (System.Exception exc1)
            {
                lock (_eLock)
                {
                    // expose the exception to the main thread
                    if (_pendingException != null)
                    {
                        _pendingException = exc1;
                    }
                }
            }
        }
Example #8
0
        public async Task<TcpMessage> Receieve()
        {
            var stream = _tcpClient.GetStream();

            var packetLengthBytes = new byte[4];
            if (await stream.ReadAsync(packetLengthBytes, 0, 4) != 4)
                throw new InvalidOperationException("Couldn't read the packet length");
            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            var seqBytes = new byte[4];
            if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
                throw new InvalidOperationException("Couldn't read the sequence");
            int seq = BitConverter.ToInt32(seqBytes, 0);

            int readBytes = 0;
            var body = new byte[packetLength - 12];
            int neededToRead = packetLength - 12;

            do
            {
                var bodyByte = new byte[packetLength - 12];
                var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);
                neededToRead -= availableBytes;
                Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
                readBytes += availableBytes;
            }
            while (readBytes != packetLength - 12);

            var crcBytes = new byte[4];
            if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
                throw new InvalidOperationException("Couldn't read the crc");
            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
            var crc32 = new Ionic.Crc.CRC32();
            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return new TcpMessage(seq, body);
        }
        private void _DeflateOne(Object wi)
        {
            // compress one buffer
            WorkItem workitem = (WorkItem) wi;
            try
            {
                int myItem = workitem.index;
                Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32();

                // calc CRC on the buffer
                crc.SlurpBlock(workitem.buffer, 0, workitem.inputBytesAvailable);

                // deflate it
                DeflateOneSegment(workitem);

                // update status
                workitem.crc = crc.Crc32Result;
                TraceOutput(TraceBits.Compress,
                            "Compress          wi({0}) ord({1}) len({2})",
                            workitem.index,
                            workitem.ordinal,
                            workitem.compressedBytesAvailable
                            );

                lock(_latestLock)
                {
                    if (workitem.ordinal > _latestCompressed)
                        _latestCompressed = workitem.ordinal;
                }
                lock (_toWrite)
                {
                    _toWrite.Enqueue(workitem.index);
                }
                _newlyCompressedBlob.Set();
            }
            catch (System.Exception exc1)
            {
                lock(_eLock)
                {
                    // expose the exception to the main thread
                    if (_pendingException!=null)
                        _pendingException = exc1;
                }
            }
        }
Example #10
0
        public async Task <TcpMessage> Receieve()
        {
            logger.Trace($"Wait for answer {_tcpClient.Available} ...");
            var stream = _tcpClient.GetStream();

            var packetLengthBytes = new byte[4];

            if (await stream.ReadAsync(packetLengthBytes, 0, 4) != 4)
            {
                throw new InvalidOperationException("Couldn't read the packet length");
            }
            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            logger.Debug("[IN] Packet length: {0}", packetLength);

            var seqBytes = new byte[4];

            if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
            {
                throw new InvalidOperationException("Couldn't read the sequence");
            }
            int seq = BitConverter.ToInt32(seqBytes, 0);

            logger.Debug("[IN] Sequence: {0}", seq);

            int readBytes    = 0;
            var body         = new byte[packetLength - 12];
            int neededToRead = packetLength - 12;

            do
            {
                var bodyByte       = new byte[packetLength - 12];
                var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);

                neededToRead -= availableBytes;
                Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
                readBytes += availableBytes;
            }while (readBytes != packetLength - 12);

            var crcBytes = new byte[4];

            if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
            {
                throw new InvalidOperationException("Couldn't read the crc");
            }
            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return(new TcpMessage(seq, body));
        }
Example #11
0
        public async Task <TcpMessage> Receieve(int timeoutms)
        {
            logger.Trace($"Wait for event {_tcpClient.Available} ...");
            var stream = _tcpClient.GetStream();

            var packetLengthBytes = new byte[4];
            var token             = tokenSource.Token;

            stream.ReadTimeout = timeoutms;
            int bytes = 0;

            try
            {
                bytes = stream.Read(packetLengthBytes, 0, 4);
            } catch (System.IO.IOException io)
            {
                var socketError = io.InnerException as SocketException;
                if (socketError != null && socketError.SocketErrorCode == SocketError.TimedOut)
                {
                    throw new OperationCanceledException();
                }
                throw io;
            }
            if (bytes != 4)
            {
                throw new InvalidOperationException("Couldn't read the packet length");
            }
            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            logger.Debug("[IN]* Packet length: {0}", packetLength);

            var seqBytes = new byte[4];

            if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
            {
                throw new InvalidOperationException("Couldn't read the sequence");
            }
            int seq = BitConverter.ToInt32(seqBytes, 0);

            logger.Debug("[IN]* sequence: {0}", seq);

            int readBytes    = 0;
            var body         = new byte[packetLength - 12];
            int neededToRead = packetLength - 12;

            do
            {
                var bodyByte       = new byte[packetLength - 12];
                var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);

                neededToRead -= availableBytes;
                Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
                readBytes += availableBytes;
            }while (readBytes != packetLength - 12);

            var crcBytes = new byte[4];

            if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
            {
                throw new InvalidOperationException("Couldn't read the crc");
            }
            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return(new TcpMessage(seq, body));
        }
Example #12
0
        public static void SetModded()
        {
            try {
                if (global::Rust.Global.SteamServer == null)
                    return;
                
                using (TimeWarning.New("UpdateServerInformation", 0.1f)) {
                    var steamServer = global::Rust.Global.SteamServer;

                    System.Reflection.Assembly assembly = typeof(ServerMgr).Assembly;
                    byte[] byteArray = System.IO.File.ReadAllBytes(assembly.Location);
                    Ionic.Crc.CRC32 cRC = new Ionic.Crc.CRC32();

                    cRC.SlurpBlock(byteArray, 0, byteArray.Length);

                    string _AssemblyHash = cRC.Crc32Result.ToString("x");

                    steamServer.ServerName = ConVar.Server.hostname;
                    steamServer.MaxPlayers = ConVar.Server.maxplayers;
                    steamServer.Passworded = false;
                    steamServer.MapName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;

                    string gameTags = string.Format("mp{0},cp{1},qp{5},v{2}{3},h{4}", new object[] {
                        ConVar.Server.maxplayers,
                        BasePlayer.activePlayerList.Count,
                        global::Rust.Protocol.network,
                        ConVar.Server.pve ? ",pve" : string.Empty,
                        pluton.enabled ? ",modded,pluton" : string.Empty,
                        _AssemblyHash,
                        ServerMgr.Instance.connectionQueue.Queued
                    });

                    steamServer.GameTags = gameTags;

                    string[] array = ConVar.Server.description.SplitToChunks(100).ToArray();

                    for (int i = 0; i < 16; i++) {
                        if (i < array.Length) {
                            steamServer.SetKey(string.Format("description_{0:00}", i), array[i]);
                        } else {
                            steamServer.SetKey(string.Format("description_{0:00}", i), string.Empty);
                        }
                    }

                    steamServer.SetKey("hash", _AssemblyHash);
                    steamServer.SetKey("world.seed", global::World.Seed.ToString());
                    steamServer.SetKey("world.size", global::World.Size.ToString());
                    steamServer.SetKey("pve", ConVar.Server.pve.ToString());
                    steamServer.SetKey("headerimage", ConVar.Server.headerimage);
                    steamServer.SetKey("url", ConVar.Server.url);
                    steamServer.SetKey("uptime", ((int)Time.realtimeSinceStartup).ToString());
                    steamServer.SetKey("mem_ws", Performance.report.usedMemoryWorkingSetMB.ToString());
                    steamServer.SetKey("mem_pv", Performance.report.usedMemoryPrivateMB.ToString());
                    steamServer.SetKey("gc_mb", Performance.report.memoryAllocations.ToString());
                    steamServer.SetKey("gc_cl", Performance.report.memoryCollections.ToString());
                    steamServer.SetKey("fps", Performance.report.frameRate.ToString());
                    steamServer.SetKey("fps_avg", Performance.report.frameRateAverage.ToString("0.00"));
                    steamServer.SetKey("ent_cnt", BaseNetworkable.serverEntities.Count.ToString());
                    steamServer.SetKey("build", BuildInformation.VersionStampDays.ToString());
                }
            } catch (Exception ex) {
                Logger.LogError("[Hooks] Error while setting the server modded.");
                Logger.LogException(ex);
            }
        }
Example #13
0
        public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
        {
            // According to MS documentation, any implementation of the IO.Stream.Read function must:
            // (a) throw an exception if offset & count reference an invalid part of the buffer,
            //     or if count < 0, or if buffer is null
            // (b) return 0 only upon EOF, or if count = 0
            // (c) if not EOF, then return at least 1 byte, up to <count> bytes

            if (_streamMode == StreamMode.Undefined)
            {
                if (!this._stream.CanRead)
                {
                    throw new ZlibException("The stream is not readable.");
                }
                // for the first read, set up some controls.
                _streamMode = StreamMode.Reader;
                // (The first reference to _z goes through the private accessor which
                // may initialize it.)
                z.AvailableBytesIn = 0;
                if (_flavor == ZlibStreamFlavor.GZIP)
                {
                    _gzipHeaderByteCount = _ReadAndValidateGzipHeader();
                    // workitem 8501: handle edge case (decompress empty stream)
                    if (_gzipHeaderByteCount == 0)
                    {
                        return(0);
                    }
                }
            }

            if (_streamMode != StreamMode.Reader)
            {
                throw new ZlibException("Cannot Read after Writing.");
            }

            if (count == 0)
            {
                return(0);
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }
            if (offset < buffer.GetLowerBound(0))
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if ((offset + count) > buffer.GetLength(0))
            {
                throw new ArgumentOutOfRangeException("count");
            }

            int rc = 0;

            // set up the output of the deflate/inflate codec:
            _z.OutputBuffer      = buffer;
            _z.NextOut           = offset;
            _z.AvailableBytesOut = count;

            // This is necessary in case _workingBuffer has been resized. (new byte[])
            // (The first reference to _workingBuffer goes through the private accessor which
            // may initialize it.)
            _z.InputBuffer = workingBuffer;

            do
            {
                // need data in _workingBuffer in order to deflate/inflate.  Here, we check if we have any.
                if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
                {
                    // No data available, so try to Read data from the captive stream.
                    _z.NextIn           = 0;
                    _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
                    if (_z.AvailableBytesIn == 0)
                    {
                        nomoreinput = true;
                    }
                }
                // we have data in InputBuffer; now compress or decompress as appropriate
                rc = _z.Inflate(_flushMode);

                if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
                {
                    return(0);
                }

                if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
                {
                    throw new ZlibException(String.Format(CultureInfo.InvariantCulture, "inflating:  rc={0}  msg={1}", rc, _z.Message));
                }

                if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
                {
                    break; // nothing more to read
                }
            }
            //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
            while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);


            // workitem 8557
            // is there more room in output?
            if (_z.AvailableBytesOut > 0)
            {
                if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
                {
                    // deferred
                }
            }


            rc = (count - _z.AvailableBytesOut);

            // calculate CRC after reading
            if (crc != null)
            {
                crc.SlurpBlock(buffer, offset, rc);
            }

            return(rc);
        }
Example #14
0
        public async Task <TcpMessage> Receieve()
        {
            //var stream = _tcpClient.GetStream();

            //var packetLengthBytes = new byte[4];
            //if (await stream.ReadAsync(packetLengthBytes, 0, 4) != 4)
            //    throw new InvalidOperationException("Couldn't read the packet length");
            //int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            //var seqBytes = new byte[4];
            //if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
            //    throw new InvalidOperationException("Couldn't read the sequence");
            //int seq = BitConverter.ToInt32(seqBytes, 0);

            //int readBytes = 0;
            //var body = new byte[packetLength - 12];
            //int neededToRead = packetLength - 12;

            //do
            //{
            //    var bodyByte = new byte[packetLength - 12];
            //    var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);
            //    neededToRead -= availableBytes;
            //    Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
            //    readBytes += availableBytes;
            //}
            //while (readBytes != packetLength - 12);

            //var crcBytes = new byte[4];
            //if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
            //    throw new InvalidOperationException("Couldn't read the crc");
            //int checksum = BitConverter.ToInt32(crcBytes, 0);

            // packet length
            var packetLengthBytes = new byte[4];

            if (!await ReadBuffer(_stream, packetLengthBytes))
            {
                return(null);
            }

            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            // seq
            var seqBytes = new byte[4];

            if (!await ReadBuffer(_stream, seqBytes))
            {
                return(null);
            }

            int seq = BitConverter.ToInt32(seqBytes, 0);

            // body
            var bodyBytes = new byte[packetLength - 12];

            if (!await ReadBuffer(_stream, bodyBytes))
            {
                return(null);
            }

            // crc
            var crcBytes = new byte[4];

            if (!await ReadBuffer(_stream, crcBytes))
            {
                return(null);
            }

            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + bodyBytes.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(bodyBytes, 0, rv, packetLengthBytes.Length + seqBytes.Length, bodyBytes.Length);
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return(new TcpMessage(seq, bodyBytes));
        }