Read() public method

Read data from the stream.

If you wish to use the ZlibStream to compress data while reading, you can create a ZlibStream with CompressionMode.Compress, providing an uncompressed data stream. Then call Read() on that ZlibStream, and the data read will be compressed. If you wish to use the ZlibStream to decompress data while reading, you can create a ZlibStream with CompressionMode.Decompress, providing a readable compressed data stream. Then call Read() on that ZlibStream, and the data will be decompressed as it is read.

A ZlibStream can be used for Read() or Write(), but not both.

public Read ( byte buffer, int offset, int count ) : int
buffer byte /// The buffer into which the read data should be placed.
offset int /// the offset within that data array to put the first byte read.
count int the number of bytes to read.
return int
示例#1
0
        /// <summary>
        /// Uncompress a byte array into a single string.
        /// </summary>
        /// <seealso cref="ZlibStream.CompressString(String)"/>
        /// <param name="compressed">
        /// A buffer containing ZLIB-compressed data.
        /// </param>
        public static String UncompressString(byte[] compressed)
        {
            // workitem 8460
            byte[] working  = new byte[1024];
            var    encoding = System.Text.Encoding.UTF8;

            using (var output = new MemoryStream())
            {
                using (var input = new MemoryStream(compressed))
                {
                    using (Stream decompressor = new ZlibStream(input, CompressionMode.Decompress))
                    {
                        int n;
                        while ((n = decompressor.Read(working, 0, working.Length)) != 0)
                        {
                            output.Write(working, 0, n);
                        }
                    }
                    // reset to allow read from start
                    output.Seek(0, SeekOrigin.Begin);
                    var sr = new StreamReader(output, encoding);
                    return(sr.ReadToEnd());
                }
            }
        }
示例#2
0
        public static string UncompressString(byte[] compressed)
        {
            string str;

            byte[]   buffer   = new byte[0x400];
            Encoding encoding = Encoding.UTF8;

            using (MemoryStream stream = new MemoryStream())
            {
                using (MemoryStream stream2 = new MemoryStream(compressed))
                {
                    using (Stream stream3 = new ZlibStream(stream2, CompressionMode.Decompress))
                    {
                        int num;
                        while ((num = stream3.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            stream.Write(buffer, 0, num);
                        }
                    }
                    stream.Seek(0L, SeekOrigin.Begin);
                    str = new StreamReader(stream, encoding).ReadToEnd();
                }
            }
            return(str);
        }
        public Stream GetStream()
        {
            byte[] data = new byte[Data.Size];
            long offset = Packfile.DataOffset + Data.Start;
            Packfile.DataStream.Seek(offset, SeekOrigin.Begin);
            if (Data.Flags.HasFlag(PackfileEntryFlags.Compressed))
            {
                byte[] compressedData = new byte[Data.CompressedSize];
                Packfile.DataStream.Read(compressedData, 0, (int)Data.CompressedSize);
                using (MemoryStream tempStream = new MemoryStream(compressedData))
                {
                    using (Stream s = new ZlibStream(tempStream, CompressionMode.Decompress, true))
                    {
                        s.Read(data, 0, (int)Data.Size);
                    }
                }
            }
            else
            {
                Packfile.DataStream.Read(data, 0, (int)Data.Size);
            }

            MemoryStream ms = new MemoryStream(data);
            return ms;
        }
        public Packfile(Stream stream, bool isStr2)
        {
            IsStr2 = isStr2;
            stream.Seek(0, SeekOrigin.Begin);
            FileData = stream.ReadStruct<PackfileFileData>();

            m_Files = new List<IPackfileEntry>();

            uint runningPosition = 0;
            List<PackfileEntryFileData> entryFileData = new List<PackfileEntryFileData>();
            for (int i = 0; i < FileData.NumFiles; i++)
            {
                PackfileEntryFileData data = stream.ReadStruct<PackfileEntryFileData>();

                if (IsCondensed && IsCompressed)
                {
                    data.Flags = 0;
                    data.Start = runningPosition;
                    runningPosition += data.Size;
                }
                else if (IsCondensed)
                {
                    data.Start = runningPosition;
                    runningPosition += data.Size.Align(16);
                }

                entryFileData.Add(data);
            }

            for (int i = 0; i < FileData.NumFiles; i++)
            {
                stream.Align(2);
                string filename = stream.ReadAsciiNullTerminatedString();
                stream.Seek(1, SeekOrigin.Current);
                m_Files.Add(new PackfileEntry(this, entryFileData[i], filename));
                stream.Align(2);
            }

            if (IsCondensed && IsCompressed)
            {
                DataOffset = 0;
                byte[] compressedData = new byte[FileData.CompressedDataSize];
                stream.Read(compressedData, 0, (int)FileData.CompressedDataSize);
                using (MemoryStream tempStream = new MemoryStream(compressedData))
                {
                    using (Stream s = new ZlibStream(tempStream, CompressionMode.Decompress, true))
                    {
                        byte[] uncompressedData = new byte[FileData.DataSize];
                        s.Read(uncompressedData, 0, (int)FileData.DataSize);
                        DataStream = new MemoryStream(uncompressedData);
                    }
                }
                
            }
            else
            {
                DataStream = stream;
                DataOffset = stream.Position;
            }
        }
        public static void DeCompressBuffToFile(byte[] bytes, string strOutFile)
        {
            try
            {
                byte[] working = new byte[10240];
                using (var input = new MemoryStream(bytes))
                {
                    using (var raw = System.IO.File.Create(strOutFile))
                    {
                        Stream decompressor =
                            new ZlibStream(input, CompressionMode.Decompress);

                        using (decompressor)
                        {
                            int n;
                            while ((n = decompressor.Read(working, 0, working.Length)) != 0)
                            {
                                raw.Write(working, 0, n);
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                if (System.IO.File.Exists(strOutFile))
                {
                    System.IO.File.Delete(strOutFile);
                }
            }
        }
        /// <summary>
        /// Decompress a byte array into another byte array of the specified size
        /// </summary>
        /// <param name="to_decompress">Data to decompress</param>
        /// <param name="size_uncompressed">Size of the data once decompressed</param>
        /// <returns>Decompressed data as a byte array</returns>

        public static byte[] Decompress(byte[] to_decompress, int size_uncompressed)
        {
            ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_decompress, false), CompressionMode.Decompress);
            byte[] packetData_decompressed = new byte[size_uncompressed];
            stream.Read(packetData_decompressed, 0, size_uncompressed);
            stream.Close();
            return packetData_decompressed;
        }
示例#7
0
        public static byte[] Decompress(MemoryStream data, int size)
        {
            byte[] msDecompressed = new byte[size];
            var    zOut           = new ZlibStream(data, CompressionMode.Decompress);

            zOut.Read(msDecompressed, 0, msDecompressed.Length);
            zOut.Close();
            return(msDecompressed);
        }
示例#8
0
        public void DecompressResponse()
        {
            if (string.IsNullOrEmpty(this.ZNO))
            {
                return;
            }

            MemoryStream compressMetadataCollection = null;
            MemoryStream decompressedMetadataCollection = null;
            ZlibStream decompressStream = null;

            try
            {
                byte[] compressedMetadataCollectionBytes = Convert.FromBase64String(this.ZNO);
                compressMetadataCollection = new MemoryStream(compressedMetadataCollectionBytes);
                byte[] buffer = new byte[1024];
                int numBytesRead = 0;
                bool start = true;

                decompressedMetadataCollection = new MemoryStream();

                using (decompressStream = new ZlibStream(compressMetadataCollection, CompressionMode.Decompress))
                {
                    while (start || numBytesRead > 0)
                    {
                        numBytesRead = decompressStream.Read(buffer, 0, buffer.Length);

                        if (numBytesRead > 0)
                        {
                            decompressedMetadataCollection.Write(buffer, 0, numBytesRead);
                        }

                        start = false;
                    }
                }

                decompressedMetadataCollection.Position = 0;

                DataContractSerializer deserializer = new DataContractSerializer(typeof(CompressedResponseTuple));

                CompressedResponseTuple responseTuple = deserializer.ReadObject(decompressedMetadataCollection) as CompressedResponseTuple;

                Nodes = responseTuple.Nodes;
                Relationships = responseTuple.Relationships;
            }
            finally
            {
                if (decompressedMetadataCollection != null)
                {
                    decompressedMetadataCollection.Dispose();
                    decompressedMetadataCollection = null;
                }
            }
        }
        /// <summary>
        /// Compress a byte array into another bytes array using Zlib compression
        /// </summary>
        /// <param name="to_compress">Data to compress</param>
        /// <returns>Compressed data as a byte array</returns>

        public static byte[] Compress(byte[] to_compress)
        {
            ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_compress, false), CompressionMode.Compress);
            List<byte> temp_compression_list = new List<byte>();
            byte[] b = new byte[1];
            while (true)
            {
                int read = stream.Read(b, 0, 1);
                if (read > 0) { temp_compression_list.Add(b[0]); }
                else break;
            }
            stream.Close();
            return temp_compression_list.ToArray();
        }
示例#10
0
        public UInt16 pktID2; //packet id again

        #endregion Fields

        #region Constructors

        public Gunz2Packet(byte[] buf, byte[] _cryptKey)
        {
            flagsraw = BitConverter.ToUInt32(buf, 0);
            flags = new Gunz2Flags();
            flags.keepalive = (byte)((flagsraw >> 0) & 1) == 1;
            flags.isping = (byte)((flagsraw >> 1) & 1) == 1; //used for keepalive. Normal is set to false for keepalive packets.
            flags.unkFlag3 = (byte)((flagsraw >> 2) & 1) == 1;
            flags.encrypted = (byte)((flagsraw >> 3) & 1) == 1;
            flags.compressed = (byte)((flagsraw >> 4) & 1) == 1;
            flags.size = (uint)(0x7FFFFF & (flagsraw >> 5));
            // how to check if it it's encrypted.
            if (flags.encrypted)
            {
                Decrypt(buf, 12, (uint)buf.Length - 12, _cryptKey);
            }

            if (flags.compressed && flags.encrypted && flags.size < 65535)
            {
                uint fullSize = BitConverter.ToUInt32(buf, 12);
                byte[] decompressedBuffer = new byte[fullSize - 12];
                byte[] cpyArray = new byte[flags.size - 16];
                Buffer.BlockCopy(buf, 16, cpyArray, 0, buf.Length - 16);
                //Console.WriteLine("This packet is compressed. Length: {0}", fullSize - 12);
                using (ZlibStream zlib = new ZlibStream(new MemoryStream(cpyArray), CompressionMode.Decompress))
                {
                    zlib.Read(decompressedBuffer, 0, (int)fullSize - 12);
                }
                Array.Resize(ref buf, (int)fullSize);
                Buffer.BlockCopy(decompressedBuffer, 0, buf, 12, (int)fullSize - 12);
            }
            data = buf;
            if (!flags.isping)
            {
                pktCounter = BitConverter.ToUInt32(data, 0);
                pktID = BitConverter.ToUInt16(data, 8);
                checksum = BitConverter.ToUInt16(data, 10);
                datalen = BitConverter.ToUInt32(data, 12);
                pktID2 = BitConverter.ToUInt16(data, 16);
            }
            else
            {
                //pingpong
            }
        }
示例#11
0
 /// <summary>
 /// Uncompress a byte array into a byte array.
 /// </summary>
 /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
 /// <seealso cref="ZlibStream.UncompressString(byte[])"/>
 /// <param name="compressed">
 /// A buffer containing ZLIB-compressed data.
 /// </param>
 public static byte[] UncompressBuffer(byte[] compressed)
 {
     // workitem 8460
     byte[] working = new byte[1024];
     using (var output = new MemoryStream())
     {
         using (var input = new MemoryStream(compressed))
         {
             using (Stream decompressor = new ZlibStream(input, CompressionMode.Decompress))
             {
                 int n;
                 while ((n = decompressor.Read(working, 0, working.Length)) != 0)
                 {
                     output.Write(working, 0, n);
                 }
             }
             return(output.ToArray());
         }
     }
 }
示例#12
0
 public static byte[] UncompressBuffer(byte[] compressed)
 {
     byte[] buffer2;
     byte[] buffer = new byte[0x400];
     using (MemoryStream stream = new MemoryStream())
     {
         using (MemoryStream stream2 = new MemoryStream(compressed))
         {
             using (Stream stream3 = new ZlibStream(stream2, CompressionMode.Decompress))
             {
                 int num;
                 while ((num = stream3.Read(buffer, 0, buffer.Length)) != 0)
                 {
                     stream.Write(buffer, 0, num);
                 }
             }
             buffer2 = stream.ToArray();
         }
     }
     return(buffer2);
 }
        public void ExecuteServiceByName(string correlationId, string repositoryName, string serviceName, ExecutionOptions options, System.IO.Stream inStream, System.IO.Stream outStream)
        {
            ParsedReceivePack receivedPack = null;

            if (serviceName == "receive-pack" && inStream.Length > 0)
            {
                // PARSING RECEIVE-PACK THAT IS OF THE FOLLOWING FORMAT:
                // (NEW LINES added for ease of reading)
                // (LLLL is length of the line (expressed in HEX) until next LLLL value)
                //
                // LLLL------ REF LINE -----------\0------- OHTER DATA -----------
                // LLLL------ REF LINE ----------------
                // ...
                // ...
                // 0000PACK------- REST OF PACKAGE --------
                //

                var pktLines = new List<ReceivePackPktLine>();

                var buff1 = new byte[1];
                var buff4 = new byte[4];
                var buff20 = new byte[20];
                var buff16K = new byte[1024 * 16];

                while (true)
                {
                    ReadStream(inStream, buff4);
                    var len = Convert.ToInt32(Encoding.UTF8.GetString(buff4), 16);
                    if (len == 0)
                    {
                        break;
                    }
                    len = len - buff4.Length;

                    var accum = new LinkedList<byte>();

                    while (len > 0)
                    {
                        len -= 1;
                        ReadStream(inStream, buff1);
                        if (buff1[0] == 0)
                        {
                            break;
                        }
                        accum.AddLast(buff1[0]);
                    }
                    if (len > 0)
                    {
                        inStream.Seek(len, SeekOrigin.Current);
                    }
                    var pktLine = Encoding.UTF8.GetString(accum.ToArray());
                    var pktLineItems = pktLine.Split(' ');

                    var fromCommit = pktLineItems[0];
                    var toCommit = pktLineItems[1];
                    var refName = pktLineItems[2];

                    pktLines.Add(new ReceivePackPktLine(fromCommit, toCommit, refName));
                }

                // parse PACK contents
                var packCommits = new List<ReceivePackCommit>();

                // PACK format
                // https://www.kernel.org/pub/software/scm/git/docs/technical/pack-format.html
                // http://schacon.github.io/gitbook/7_the_packfile.html

                if (inStream.Position < inStream.Length)
                {
                    ReadStream(inStream, buff4);
                    if (Encoding.UTF8.GetString(buff4) != "PACK")
                    {
                        throw new Exception("Unexpected receive-pack 'PACK' content.");
                    }
                    ReadStream(inStream, buff4);
                    Array.Reverse(buff4);
                    var versionNum = BitConverter.ToInt32(buff4, 0);

                    ReadStream(inStream, buff4);
                    Array.Reverse(buff4);
                    var numObjects = BitConverter.ToInt32(buff4, 0);

                    while (numObjects > 0)
                    {
                        numObjects -= 1;

                        ReadStream(inStream, buff1);
                        var type = (GIT_OBJ_TYPE)((buff1[0] >> 4) & 7);
                        long len = buff1[0] & 15;

                        var shiftAmount = 4;
                        while ((buff1[0] >> 7) == 1)
                        {
                            ReadStream(inStream, buff1);
                            len = len | ((long)(buff1[0] & 127) << shiftAmount);

                            shiftAmount += 7;
                        }

                        if (type == GIT_OBJ_TYPE.OBJ_REF_DELTA)
                        {
                            // read ref name
                            ReadStream(inStream, buff20);
                        }
                        if (type == GIT_OBJ_TYPE.OBJ_OFS_DELTA)
                        {
                            // read negative offset
                            ReadStream(inStream, buff1);
                            while ((buff1[0] >> 7) == 1)
                            {
                                ReadStream(inStream, buff1);
                            }
                        }

                        var origPosition = inStream.Position;
                        long offsetVal = 0;

                        using (var zlibStream = new ZlibStream(inStream, CompressionMode.Decompress, true))
                        {
                            // read compressed data max 16KB at a time
                            var readRemaining = len;
                            do
                            {
                                var bytesUncompressed = zlibStream.Read(buff16K, 0, buff16K.Length);
                                readRemaining -= bytesUncompressed;
                            } while (readRemaining > 0);

                            if (type == GIT_OBJ_TYPE.OBJ_COMMIT)
                            {
                                var parsedCommit = ParseCommitDetails(buff16K, len);
                                packCommits.Add(parsedCommit);
                            }
                            offsetVal = zlibStream.TotalIn;
                        }
                        // move back position a bit because ZLibStream reads more than needed for inflating
                        inStream.Seek(origPosition + offsetVal, SeekOrigin.Begin);
                    }
                }
                // -------------------

                var user = HttpContext.Current.User.Identity.Name;
                receivedPack = new ParsedReceivePack(correlationId, repositoryName, pktLines, user, DateTime.Now, packCommits);

                inStream.Seek(0, SeekOrigin.Begin);

                receivePackHandler.PrePackReceive(receivedPack);
            }

            GitExecutionResult execResult = null;
            using (var capturedOutputStream = new MemoryStream())
            {
                gitService.ExecuteServiceByName(correlationId, repositoryName, serviceName, options, inStream, new ReplicatingStream(outStream, capturedOutputStream));

                // parse captured output
                capturedOutputStream.Seek(0, SeekOrigin.Begin);
                execResult = resultParser.ParseResult(capturedOutputStream);
            }

            if(receivedPack != null)
            {
                receivePackHandler.PostPackReceive(receivedPack, execResult);
            }
        }
        private BulkOperations DecompressBulkOperations(string compressedOperations)
        {
            MemoryStream compressedOperationsStream = null;
            MemoryStream decompressedOperationsStream = null;
            ZlibStream decompressionStream = null;

            try
            {
                byte[] compressedOperationsBytes = Convert.FromBase64String(compressedOperations);
                compressedOperationsStream = new MemoryStream(compressedOperationsBytes);
                byte[] buffer = new byte[1024];
                int numBytesRead = 0;
                bool start = true;

                decompressedOperationsStream = new MemoryStream();

                using (decompressionStream = new ZlibStream(compressedOperationsStream, CompressionMode.Decompress))
                {
                    while (start || numBytesRead > 0)
                    {
                        numBytesRead = decompressionStream.Read(buffer, 0, buffer.Length);

                        if (numBytesRead > 0)
                        {
                            decompressedOperationsStream.Write(buffer, 0, numBytesRead);
                        }

                        start = false;
                    }
                }

                decompressedOperationsStream.Position = 0;

                DataContractSerializer deserializer = new DataContractSerializer(typeof(BulkOperations));

                BulkOperations operations = deserializer.ReadObject(decompressedOperationsStream) as BulkOperations;

                return operations;
            }
            finally
            {
                if (decompressedOperationsStream != null)
                {
                    decompressedOperationsStream.Dispose();
                    decompressedOperationsStream = null;
                }
            }
        }
示例#15
0
        private byte[] InternalExtract()
        {
            _stream.Position = _manifest.Offset;

            var sizeBytes = new byte[4];
            _stream.Read(sizeBytes, 0, 4);

            int uncompressedSize = BitConverter.ToInt32(sizeBytes, 0);
            if (uncompressedSize <= 0)
            {
                return new byte[0];
            }

            _stream.Position += 4;

            var buffer = new byte[_manifest.UncompressedSize];

            var zlibStream = new ZlibStream(_stream, CompressionMode.Decompress, true);

            zlibStream.Read(buffer, 0, buffer.Length);

            zlibStream.Close();
            zlibStream.Dispose();

            return buffer;
        }
示例#16
0
        /// <summary>
        /// Decompresses the provided data, returning the inflated result.
        /// </summary>
        /// <param name="data">the deflated picture data.</param>
        /// <returns>the inflated picture data.</returns>
        private static byte[] InflatePictureData(byte[] data)
        {
            MemoryStream out1 = new MemoryStream();
            ZlibStream in1 = null;
            try
            {
                in1 = new ZlibStream(
                    new MemoryStream(data), CompressionMode.Decompress);

                byte[] buf = new byte[4096];
                int ReadBytes;
                while ((ReadBytes = in1.Read(buf, 0, buf.Length)) > 0)
                {
                    out1.Write(buf, 0, ReadBytes);
                }
                return out1.ToArray();
            }
            catch (IOException e)
            {
                log.Log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
                return data;
            }
            finally
            {
                out1.Close();
                if (in1 != null)
                {
                    in1.Close();
                }
            }
        }
        public static byte[] DecompressZlib(Stream input)
        {
            using (var decompressor = new ZlibStream(input, CompressionMode.Decompress))
            {
                var buffer = new byte[BufferSize];

                using (var output = new MemoryStream())
                {
                    int read;
                    while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, read);
                    }
                    return output.ToArray();
                }
            }
        }
示例#18
0
        public static Firmware ProcessFirmware(string path)
        {
            

           // JavaScriptSerializer serializer = new JavaScriptSerializer();

            Console.WriteLine("Read File " + path);

            // read the file
            StreamReader f = new StreamReader(File.OpenRead(path));
            //fw = serializer.Deserialize<Firmware>(f.ReadToEnd());
            fw = JSON.Instance.ToObject<Firmware>(f.ReadToEnd());
            f.Close();
            
            byte[] data = Convert.FromBase64String(fw.image);

            MemoryStream imagems = new MemoryStream(data, true);

            ZlibStream decompressionStream = new ZlibStream(imagems, CompressionMode.Decompress);


            int size = fw.image_size + (fw.image_size % 4);
            fw.imagebyte = new byte[size];

            for (int a = 0; a < fw.imagebyte.Length; a++)
            {
                fw.imagebyte[a] = 0xff;
            }

            try
            {
                decompressionStream.Read(fw.imagebyte, 0, fw.image_size);
            }
            catch { Console.WriteLine("Possible bad file - usualy safe to ignore"); }

            Console.WriteLine("image_size {0} size {1}",fw.image_size,size);

            
            BinaryWriter sw = new BinaryWriter(File.Open("px4fw.bin", FileMode.Create));

            foreach (byte by in fw.imagebyte)
            {
                sw.Write(by);
                //   Console.Write("{0:x2}", by);
            }

            sw.Close();
            
            // pad image to 4-byte length
            //while ((fw.imagebyte.Length % 4) != 0) {
            //fw.imagebyte. += b'\x00'

            return fw;
        }
示例#19
0
 /// <summary>
 /// Decompresses a byte array using the specified compression type.
 /// </summary>
 /// <param name="bytes">The byte array to be decompressed.</param>
 /// <param name="type">Type of compression to use.</param>
 /// <returns>Decompressed byte array.</returns>
 public static byte[] Decompress(this byte[] bytes, CompressionType type)
 {
     int size = 4096;
     byte[] buffer = new byte[size];
     using (MemoryStream memory = new MemoryStream())
     {
         using (MemoryStream memory2 = new MemoryStream(bytes))
             switch (type)
             {
                 case CompressionType.Zlib:
                     using (ZlibStream stream = new ZlibStream(memory2, CompressionMode.Decompress))
                     {
                         int count = 0;
                         while ((count = stream.Read(buffer, 0, size)) > 0)
                             memory.Write(buffer, 0, count);
                     }
                     break;
                 case CompressionType.GZip:
                     using (GZipStream stream = new GZipStream(memory2, CompressionMode.Decompress))
                     {
                         int count = 0;
                         while ((count = stream.Read(buffer, 0, size)) > 0)
                             memory.Write(buffer, 0, count);
                     }
                     break;
                 default:
                     throw new ArgumentException("Unknown compression type.");
             }
         return memory.ToArray();
     }
 }
示例#20
0
        public void run()
        {
            try
            {
                for (;;)
                {
                    if (!this.client.connectionAlive)
                    {
                        this.client.forceDisconnect(direction, "Connection no longer alive");
                        return;
                    }

                    if (this.client.kickTargetTimestamp != 0)
                    {
                        if (this.client.kickTargetTimestamp < Utils.getTimestamp())
                        {
                            this.client.closeConnection();
                            return;
                        }
                        continue;
                    }

                    #region Process Packet
                    //Packet ID and Vaildity Check.
                    uint temp = this.incoming.ReadVarUInt32();
                    if (temp < 1 || temp > 48)
                    {
                        this.client.forceDisconnect(direction, "Sent invalid packet ID [" + temp + "].");
                        return;
                    }
                    Packet packetID = (Packet)temp;

                    //Packet Size and Compression Check.
                    bool compressed = false;
                    int packetSize = this.incoming.ReadVarInt32();
                    if (packetSize < 0)
                    {
                        packetSize = -packetSize;
                        compressed = true;
                    }

                    //Create buffer for forwarding
                    byte[] dataBuffer = this.incoming.ReadFully(packetSize);

                    //Do decompression
                    MemoryStream ms = new MemoryStream();
                    if (compressed)
                    {
                        ZlibStream compressedStream = new ZlibStream(new MemoryStream(dataBuffer), CompressionMode.Decompress);
                        byte[] buffer = new byte[32768];
                        for (;;)
                        {
                            int read = compressedStream.Read(buffer, 0, buffer.Length);
                            if (read <= 0)
                                break;
                            ms.Write(buffer, 0, read);
                        }
                        ms.Seek(0, SeekOrigin.Begin);
                    }
                    else
                    {
                        ms = new MemoryStream(dataBuffer);
                    }

                    //Create packet parser
                    BinaryReader packetData = new BinaryReader(ms);
                    #endregion

                    //Return data for packet processor
                    object returnData = true;

                    if (packetID != Packet.Heartbeat && packetID != Packet.UniverseTimeUpdate)
                    {
                        if (direction == Direction.Client)
                        #region Handle Client Packets
                        {
                            #region Protocol State Security
                            ClientState curState = this.client.state;
                            if (curState != ClientState.Connected)
                            {
                                if (curState == ClientState.PendingConnect && packetID != Packet.ClientConnect)
                                {
                                    this.client.rejectPreConnected("Violated PendingConnect protocol state with " + packetID);
                                    return;
                                }
                                else if (curState == ClientState.PendingAuthentication && packetID != Packet.HandshakeResponse)
                                {
                                    this.client.rejectPreConnected("Violated PendingAuthentication protocol state with " + packetID);
                                    return;
                                }
                                else if (curState == ClientState.PendingConnectResponse)
                                {
                                    int startTime = Utils.getTimestamp();
                                    while (true)
                                    {
                                        if (this.client.state == ClientState.Connected) break;
                                        if (Utils.getTimestamp() > startTime + StarryboundServer.config.connectTimeout)
                                        {
                                            this.client.rejectPreConnected("Connection Failed: Server did not respond in time.");
                                            return;
                                        }
                                    }
                                }
                            }
                            #endregion

                            if (packetID == Packet.ChatSend)
                            {
                                returnData = new Packet11ChatSend(this.client, packetData, this.direction).onReceive();
                            }
                            else if (packetID == Packet.ClientConnect)
                            {
                                this.client.state = ClientState.PendingAuthentication;
                                returnData = new Packet7ClientConnect(this.client, packetData, this.direction).onReceive();
                                MemoryStream packet = new MemoryStream();
                                BinaryWriter packetWrite = new BinaryWriter(packet);

                                passwordSalt = Utils.GenerateSecureSalt();
                                packetWrite.WriteStarString("");
                                packetWrite.WriteStarString(passwordSalt);
                                packetWrite.WriteBE(StarryboundServer.config.passwordRounds);
                                this.client.sendClientPacket(Packet.HandshakeChallenge, packet.ToArray());
                            }
                            else if (packetID == Packet.HandshakeResponse)
                            {
                                string claimResponse = packetData.ReadStarString();
                                string passwordHash = packetData.ReadStarString();

                                string verifyHash = Utils.StarHashPassword(StarryboundServer.config.proxyPass, this.client.playerData.account + passwordSalt, StarryboundServer.config.passwordRounds);
                                if (passwordHash != verifyHash)
                                {
                                    this.client.rejectPreConnected("Your password was incorrect.");
                                    return;
                                }

                                this.client.state = ClientState.PendingConnectResponse;
                                returnData = false;
                            }
                            else if (packetID == Packet.WarpCommand)
                            {
                                WarpType cmd = (WarpType)packetData.ReadUInt32BE();
                                WorldCoordinate coord = packetData.ReadStarWorldCoordinate();
                                string player = packetData.ReadStarString();
                                if (cmd == WarpType.WarpToPlayerShip)
                                {
                                    Client target = StarryboundServer.getClient(player);
                                    if (target != null)
                                    {
                                        if (!this.client.playerData.canAccessShip(target.playerData))
                                        {
                                            this.client.sendChatMessage("^#5dc4f4;You cannot access this player's ship due to their ship access settings.");
                                            StarryboundServer.logDebug("ShipAccess", "Preventing " + this.client.playerData.name + " from accessing " + target.playerData.name + "'s ship.");
                                            MemoryStream packetWarp = new MemoryStream();
                                            BinaryWriter packetWrite = new BinaryWriter(packetWarp);
                                            packetWrite.WriteBE((uint)WarpType.WarpToOwnShip);
                                            packetWrite.Write(new WorldCoordinate());
                                            packetWrite.WriteStarString("");
                                            client.sendServerPacket(Packet.WarpCommand, packetWarp.ToArray());
                                            returnData = false;
                                        }
                                    }
                                }
                                StarryboundServer.logDebug("WarpCommand", "[" + this.client.playerData.client + "][" + cmd + "]" + (coord != null ? "[" + coord.ToString() + "]" : "") + "[" + player + "]");
                            }
                            else if (packetID == Packet.ModifyTileList || packetID == Packet.DamageTileGroup || packetID == Packet.DamageTile || packetID == Packet.ConnectWire || packetID == Packet.DisconnectAllWires)
                            {
                                if(!this.client.playerData.canIBuild()) returnData = false;
                            }
                            else if (packetID == Packet.EntityCreate)
                            {
                                while(true)
                                {
                                    EntityType type = (EntityType)packetData.Read();
                                    if(type == EntityType.EOF) break;
                                    byte[] entityData = packetData.ReadStarByteArray();
                                    int entityId = packetData.ReadVarInt32();
                                    if(type == EntityType.Projectile)
                                    {
                                        BinaryReader entity = new BinaryReader(new MemoryStream(entityData));
                                        string projectileKey = entity.ReadStarString();
                                        object projParams = entity.ReadStarVariant();
                                        if (StarryboundServer.config.projectileBlacklist.Contains(projectileKey))
                                        {
                                            MemoryStream packet = new MemoryStream();
                                            BinaryWriter packetWrite = new BinaryWriter(packet);
                                            packetWrite.WriteVarInt32(entityId);
                                            packetWrite.Write(false);
                                            this.client.sendClientPacket(Packet.EntityDestroy, packet.ToArray());
                                            returnData = false;
                                        }
                                        if (StarryboundServer.serverConfig.useDefaultWorldCoordinate && StarryboundServer.config.spawnWorldProtection)
                                        {
                                            if (this.client.playerData.loc != null)
                                            {
                                                if (StarryboundServer.config.projectileBlacklistSpawn.Contains(projectileKey) && StarryboundServer.spawnPlanet.Equals(this.client.playerData.loc) && !this.client.playerData.group.hasPermission("admin.spawnbuild") && !this.client.playerData.inPlayerShip)
                                                {
                                                    MemoryStream packet = new MemoryStream();
                                                    BinaryWriter packetWrite = new BinaryWriter(packet);
                                                    packetWrite.WriteVarInt32(entityId);
                                                    packetWrite.Write(false);
                                                    this.client.sendClientPacket(Packet.EntityDestroy, packet.ToArray());
                                                    returnData = false;
                                                }
                                            }
                                            else
                                            {
                                                MemoryStream packet = new MemoryStream();
                                                BinaryWriter packetWrite = new BinaryWriter(packet);
                                                packetWrite.WriteVarInt32(entityId);
                                                packetWrite.Write(false);
                                                this.client.sendClientPacket(Packet.EntityDestroy, packet.ToArray());
                                                returnData = false;
                                            }
                                        }
                                    }
                                    else if (type == EntityType.Object || type == EntityType.Plant || type == EntityType.PlantDrop || type == EntityType.Monster)
                                    {
                                        if (!this.client.playerData.canIBuild())
                                        {
                                            MemoryStream packet = new MemoryStream();
                                            BinaryWriter packetWrite = new BinaryWriter(packet);
                                            packetWrite.WriteVarInt32(entityId);
                                            packetWrite.Write(false);
                                            this.client.sendClientPacket(Packet.EntityDestroy, packet.ToArray());
                                            returnData = false;
                                        }
                                    }
                                }
                            }
                            else if (packetID == Packet.SpawnEntity)
                            {
                                while(true)
                                {
                                    EntityType type = (EntityType)packetData.Read();
                                    if (type == EntityType.EOF) break;
                                    byte[] entityData = packetData.ReadStarByteArray();
                                    if (type == EntityType.Projectile)
                                    {
                                        BinaryReader entity = new BinaryReader(new MemoryStream(entityData));
                                        string projectileKey = entity.ReadStarString();
                                        object projParams = entity.ReadStarVariant();
                                        if (StarryboundServer.config.projectileBlacklist.Contains(projectileKey))
                                        {
                                            returnData = false;
                                        }
                                        if (StarryboundServer.serverConfig.useDefaultWorldCoordinate && StarryboundServer.config.spawnWorldProtection)
                                        {
                                            if (this.client.playerData.loc != null)
                                            {
                                                if (StarryboundServer.config.projectileBlacklistSpawn.Contains(projectileKey) ^ StarryboundServer.config.projectileSpawnListIsWhitelist)
                                                {
                                                    if (StarryboundServer.spawnPlanet.Equals(this.client.playerData.loc) && !this.client.playerData.group.hasPermission("admin.spawnbuild") && !this.client.playerData.inPlayerShip)
                                                    {
                                                        returnData = false;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                returnData = false;
                                            }
                                        }
                                    }
                                    else if (type == EntityType.Object || type == EntityType.Plant || type == EntityType.PlantDrop || type == EntityType.Monster)
                                    {
                                        if (!this.client.playerData.canIBuild()) returnData = false;
                                    }
                                }
                            }
                        }
                        #endregion
                        else
                        #region Handle Server Packets
                        {
                            if (packetID == Packet.ChatReceive)
                            {
                                returnData = new Packet5ChatReceive(this.client, packetData, this.direction).onReceive();
                            }
                            else if (packetID == Packet.ProtocolVersion)
                            {
                                uint protocolVersion = packetData.ReadUInt32BE();
                                if (protocolVersion != StarryboundServer.ProtocolVersion)
                                {
                                    MemoryStream packet = new MemoryStream();
                                    BinaryWriter packetWrite = new BinaryWriter(packet);
                                    packetWrite.WriteBE(protocolVersion);
                                    this.client.sendClientPacket(Packet.ProtocolVersion, packet.ToArray());

                                    this.client.rejectPreConnected("Connection Failed: Unable to handle parent server protocol version.");
                                    return;
                                }
                            }
                            else if (packetID == Packet.HandshakeChallenge)
                            {
                                string claimMessage = packetData.ReadString();
                                string passwordSalt = packetData.ReadStarString();
                                int passwordRounds = packetData.ReadInt32BE();

                                MemoryStream packet = new MemoryStream();
                                BinaryWriter packetWrite = new BinaryWriter(packet);
                                string passwordHash = Utils.StarHashPassword(StarryboundServer.privatePassword, passwordSalt, passwordRounds);
                                packetWrite.WriteStarString("");
                                packetWrite.WriteStarString(passwordHash);
                                this.client.sendServerPacket(Packet.HandshakeResponse, packet.ToArray());

                                returnData = false;
                            }
                            else if (packetID == Packet.ConnectResponse)
                            {
                                int startTime = Utils.getTimestamp();
                                while (true)
                                {
                                    if (this.client.state == ClientState.PendingConnectResponse) break;
                                    if (Utils.getTimestamp() > startTime + StarryboundServer.config.connectTimeout)
                                    {
                                        this.client.rejectPreConnected("Connection Failed: Client did not respond with handshake.");
                                        return;
                                    }
                                }
                                returnData = new Packet2ConnectResponse(this.client, packetData, this.direction).onReceive();
                            }
                            else if (packetID == Packet.WorldStart)
                            {
                                if (!this.client.playerData.sentMotd)
                                {
                                    this.client.sendChatMessage(Config.GetMotd());

                                    if (!this.client.playerData.group.hasPermission("world.build"))
                                        this.client.sendChatMessage("^#f75d5d;" + StarryboundServer.config.buildErrorMessage);

                                    this.client.playerData.sentMotd = true;
                                }

                                byte[] planet = packetData.ReadStarByteArray();
                                byte[] worldStructure = packetData.ReadStarByteArray();
                                byte[] sky = packetData.ReadStarByteArray();
                                byte[] serverWeather = packetData.ReadStarByteArray();
                                float spawnX = packetData.ReadSingleBE();
                                float spawnY = packetData.ReadSingleBE();
                                uint mapParamsSize = packetData.ReadVarUInt32();
                                Dictionary<string, object> mapParams = new Dictionary<string, object>();
                                int isPlayerShip = 0;
                                for (int i = 0; i < mapParamsSize; i++)
                                {
                                    string key = packetData.ReadStarString();
                                    var value = packetData.ReadStarVariant();
                                    mapParams.Add(key, value);
                                    if(key == "fuel.level")
                                    {
                                        isPlayerShip++;
                                    }
                                    else if(key == "fuel.max")
                                    {
                                        isPlayerShip++;
                                    }
                                }
                                this.client.playerData.inPlayerShip = (isPlayerShip == 2);
                                uint clientID = packetData.ReadUInt32BE();
                                bool bool1 = packetData.ReadBoolean();
                                WorldCoordinate coords = Utils.findGlobalCoords(sky);
                                if (coords != null)
                                {
                                    this.client.playerData.loc = coords;
                                    StarryboundServer.logDebug("WorldStart", "[" + this.client.playerData.client + "][" + bool1 + ":" + clientID + "] CurLoc:[" + this.client.playerData.loc.ToString() + "][" + this.client.playerData.inPlayerShip + "]");
                                }
                                else
                                    StarryboundServer.logDebug("WorldStart", "[" + this.client.playerData.client + "][" + bool1 + ":" + clientID + "] InPlayerShip:[" + this.client.playerData.inPlayerShip + "]");
                            }
                            else if (packetID == Packet.WorldStop)
                            {
                                string status = packetData.ReadStarString();
                            }
                            else if (packetID == Packet.GiveItem)
                            {
                                string name = packetData.ReadStarString();
                                uint count = packetData.ReadVarUInt32();
                                var itemDesc = packetData.ReadStarVariant();
                            }
                            else if (packetID == Packet.EnvironmentUpdate)
                            {
                                byte[] sky = packetData.ReadStarByteArray();
                                byte[] serverWeather = packetData.ReadStarByteArray();
                                if (this.client.playerData.loc == null)
                                {
                                    WorldCoordinate coords = Utils.findGlobalCoords(sky);
                                    if (coords != null)
                                    {
                                        this.client.playerData.loc = coords;
                                        StarryboundServer.logDebug("EnvUpdate", "[" + this.client.playerData.client + "] CurLoc:[" + this.client.playerData.loc.ToString() + "]");
                                    }
                                }
                            }
                            else if (packetID == Packet.ClientContextUpdate)
                            {
                                try
                                {
                                    byte[] clientContextData = packetData.ReadStarByteArray();
                                    if (clientContextData.Length != 0)
                                    {
                                        BinaryReader clientContextReader = new BinaryReader(new MemoryStream(clientContextData));
                                        byte[] data = clientContextReader.ReadStarByteArray();
                                        if (data.Length > 8) //Should at least be more than 8 bytes for it to contain the data we want.
                                        {
                                            BinaryReader dataReader = new BinaryReader(new MemoryStream(data));
                                            byte dataBufferLength = dataReader.ReadByte();
                                            if (dataBufferLength == 2)
                                            {
                                                byte arrayLength = dataReader.ReadByte();
                                                if (arrayLength == 2 || arrayLength == 4) //Only observed these being used so far for what we want.
                                                {
                                                    byte dataType = dataReader.ReadByte(); //04 = String, 0E = CelestialLog
                                                    if (dataType == 4)
                                                    {
                                                        string string1 = dataReader.ReadStarString();
                                                        if (dataReader.BaseStream.Position != dataReader.BaseStream.Length)
                                                        {
                                                            if (string1 == "null")
                                                            {
                                                                byte[] worldHeader = dataReader.ReadStarByteArray(); //0008020A000C
                                                                byte[] worldData = dataReader.ReadStarByteArray();
                                                                byte typeByte = dataReader.ReadByte(); //0E = CelestialLog
                                                                if (typeByte == 14)
                                                                {
                                                                    Dictionary<string, WorldCoordinate> log = dataReader.ReadStarCelestialLog();
                                                                    log.TryGetValue("loc", out this.client.playerData.loc);
                                                                    if (!log.TryGetValue("home", out this.client.playerData.home))
                                                                        this.client.playerData.home = this.client.playerData.loc;
                                                                    StarryboundServer.logDebug("ClientContext", "[" + this.client.playerData.client + "] CurLoc:[" + this.client.playerData.loc.ToString() + "][" + this.client.playerData.inPlayerShip + "]");
                                                                    StarryboundServer.logDebug("ClientContext", "[" + this.client.playerData.client + "] CurHome:[" + this.client.playerData.home.ToString() + "]");
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else if (dataType == 14)
                                                    {
                                                        Dictionary<string, WorldCoordinate> log = dataReader.ReadStarCelestialLog();
                                                        log.TryGetValue("loc", out this.client.playerData.loc);
                                                        if (!log.TryGetValue("home", out this.client.playerData.home))
                                                            this.client.playerData.home = this.client.playerData.loc;
                                                        StarryboundServer.logDebug("ClientContext", "[" + this.client.playerData.client + "] CurLoc:[" + this.client.playerData.loc.ToString() + "][" + this.client.playerData.inPlayerShip + "]");
                                                        StarryboundServer.logDebug("ClientContext", "[" + this.client.playerData.client + "] CurHome:[" + this.client.playerData.home.ToString() + "]");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    StarryboundServer.logDebug("ClientContext", "[" + this.client.playerData.client + "] Failed to parse ClientContextUpdate from Server: " + e.ToString());
                                }
                            }
                            else if (packetID == Packet.EntityCreate)
                            {
                                MemoryStream sendStream = new MemoryStream();
                                BinaryWriter sendWriter = new BinaryWriter(sendStream);
                                bool test = true;
                                while (true)
                                {
                                    EntityType type = (EntityType)packetData.Read();
                                    if (type == EntityType.EOF) break;
                                    byte[] entityData = packetData.ReadStarByteArray();
                                    int entityId = packetData.ReadVarInt32();
                                    if (type == EntityType.Player)
                                    {
                                        byte[] buffer = new byte[16];
                                        Buffer.BlockCopy(entityData, 0, buffer, 0, 16);
                                        buffer = Utils.HashUUID(buffer);
                                        Buffer.BlockCopy(buffer, 0, entityData, 0, 16);
                                        returnData = test = false;
                                    }
                                    sendWriter.Write((byte)type);
                                    sendWriter.WriteVarUInt64((ulong)entityData.Length);
                                    sendWriter.Write(entityData);
                                    sendWriter.WriteVarInt32(entityId);
                                }
                                if(test == false)
                                {
                                    this.outgoing.WriteVarUInt32((uint)packetID);
                                    this.outgoing.WriteVarInt32((int)sendStream.Length);
                                    this.outgoing.Write(sendStream.ToArray());
                                    this.outgoing.Flush();
                                }
                            }
                        }
                        #endregion
                    }

                    //Check return data
                    if (returnData is Boolean)
                    {
                        if ((Boolean)returnData == false) continue;
                    }
                    else if (returnData is int)
                    {
                        if ((int)returnData == -1)
                        {
                            this.client.forceDisconnect(direction, "Command processor requested to drop client");
                            return;
                        }
                    }

                    #region Forward Packet
                    //Write data to dest
                    this.outgoing.WriteVarUInt32((uint)packetID);
                    if (compressed)
                    {
                        this.outgoing.WriteVarInt32(-packetSize);
                        this.outgoing.Write(dataBuffer, 0, packetSize);
                    }
                    else
                    {
                        this.outgoing.WriteVarInt32(packetSize);
                        this.outgoing.Write(dataBuffer, 0, packetSize);
                    }
                    this.outgoing.Flush();
                    #endregion

                    //If disconnect was forwarded to client, lets disconnect.
                    if(packetID == Packet.ServerDisconnect && direction == Direction.Server)
                    {
                        this.client.closeConnection();
                    }
                }
            }
            catch (ThreadAbortException) { }
            catch (EndOfStreamException)
            {
                this.client.forceDisconnect(direction, "End of stream");
            }
            catch (Exception e)
            {
                if(e.InnerException != null)
                {
                    if(e.InnerException is System.Net.Sockets.SocketException)
                    {
                        this.client.forceDisconnect(direction, e.InnerException.Message);
                        return;
                    }

                }
                this.client.forceDisconnect(direction, "ForwardThread Exception: " + e.ToString());
            }
        }
示例#21
0
        private void FillImageContent()
          {
            byte[] rawContent = GetRawContent();

            // HACK: Detect compressed images.  In reality there should be some way to determine
            //       this from the first 32 bytes, but I can't see any similarity between all the
            //       samples I have obtained, nor any similarity in the data block contents.
            if (MatchSignature(rawContent, COMPRESSED1, 32) || MatchSignature(rawContent, COMPRESSED2, 32))
            {
              try
              {

                  ZlibStream gzip = new ZlibStream(new MemoryStream(rawContent, 33, rawContent.Length - 33), CompressionMode.Decompress);
                MemoryStream out1 = new MemoryStream();
                byte[] buf = new byte[4096];
                int readBytes;
                while ((readBytes = gzip.Read(buf,0,4096)) > 0)
                {
                    out1.Write(buf, 0, readBytes);
                }
                content = out1.ToArray();
              }
              catch (IOException)
              {
                // Problems Reading from the actual MemoryStream should never happen
                // so this will only ever be a ZipException.
                //log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
              }
            } else {
              // Raw data is not compressed.
              content = rawContent;
            }
          }
示例#22
0
文件: Disk.cs 项目: DanielKeep/0x10c
        private void readFromStreamOld(Stream s)
        {
            using (var tr = new StreamReader(s, System.Text.Encoding.ASCII))
            {
                // Defaults
                bool deflate = true;
                bool base64 = true;
                _readOnly = false;
                int contLength = -1;

                // These are used to control big/little endian reading mode.
                int lb = 0, hb = 1;

                string line;
                while ((line = tr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.Length == 0)
                        break;

                    var parts = line.Split(headerSeps, 2, StringSplitOptions.None);

                    switch (parts[0].ToLower())
                    {
                        case "access":
                            if (parts.Length > 1)
                            {
                                switch (parts[1].ToLower())
                                {
                                    case "read-only":
                                        _readOnly = true;
                                        break;

                                    case "read-write":
                                        _readOnly = false;
                                        break;
                                }
                            }
                            break;

                        case "byte-order":
                                if (parts.Length > 1)
                                {
                                    switch (parts[1].ToLower())
                                    {
                                        case "little-endian":
                                            lb = 0;
                                            hb = 1;
                                            break;

                                        case "big-endian":
                                            lb = 1;
                                            hb = 0;
                                            break;
                                    }
                                }
                                break;

                        case "compression":
                                if (parts.Length > 1)
                                {
                                    switch (parts[1].ToLower())
                                    {
                                        case "none":
                                            deflate = false;
                                            break;

                                        case "zlib":
                                            deflate = true;
                                            break;
                                    }
                                }
                                break;

                        case "encoding":
                                if (parts.Length > 1)
                                {
                                    switch (parts[1].ToLower())
                                    {
                                        case "none":
                                            base64 = false;
                                            break;

                                        case "base64":
                                            base64 = true;
                                            break;
                                    }
                                }
                                break;

                        case "content-length":
                                if (parts.Length > 1)
                                {
                                    if (!int.TryParse(parts[1], out contLength))
                                        contLength = -1;
                                }
                                break;
                    }
                }

                byte[] cbytes, bytes;

                if (base64)
                {
                    if (contLength >= 0)
                    {
                        var chs = new char[contLength];
                        tr.Read(chs, 0, contLength);
                        cbytes = Convert.FromBase64CharArray(chs, 0, contLength);
                    }
                    else
                    {
                        var encoded = tr.ReadToEnd();
                        cbytes = Convert.FromBase64String(encoded);
                    }
                }
                else
                {
                    if (contLength >= 0)
                    {
                        var chs = new char[contLength];
                        tr.Read(chs, 0, contLength);
                        cbytes = new byte[contLength];
                        for (var i = 0; i < contLength; ++i)
                            cbytes[i] = (byte)chs[i];
                    }
                    else
                    {
                        var encoded = tr.ReadToEnd();
                        cbytes = new byte[encoded.Length];
                        for (var i = 0; i < encoded.Length; ++i)
                            cbytes[i] = (byte)encoded[i];
                    }
                }

                bytes = new byte[1440 * 1024];

                if (deflate)
                {
                    using (var cmpr = new ZlibStream(new MemoryStream(cbytes), CompressionMode.Decompress))
                    {
                        if (cmpr.Read(bytes, 0, bytes.Length) != bytes.Length)
                            throw new NotImplementedException("lazy programmer");
                    }
                }
                else
                {
                    bytes = cbytes;
                }

                if ((bytes.Length & 1) == 1)
                    throw new InvalidDataException("malformed disk image: last word is incomplete");

                if ((bytes.Length != (_words.Length * 2)))
                    throw new InvalidDataException("disk image not expected size");

                for (int i = 0; i < _words.Length; ++i)
                {
                    var j = 2*i;
                    _words[i] = (ushort)(bytes[j + lb] + (bytes[j + hb] << 8));
                }
            }
        }
示例#23
0
        public void Deflate(string outputPath)
        {
            using (ZlibStream input = new ZlibStream(File.Open(m_Path, FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
            {
                int maxBlockSize;
                logger.Trace("Opening registry key to find MaxBlockSize");
                RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Bit Thicket\\Git\\Streams");
                try
                {
                    maxBlockSize = Convert.ToInt32(key.GetValue("MaxBlockSize"));
                }
                catch (Exception e)
                {
                    logger.LogException(LogLevel.Info, "MaxBlockSize not specified.  Using default of 4k", e);
                    maxBlockSize = 4096;
                }

                using (var t0 = new TransferStream(File.Open(outputPath, FileMode.Create, FileAccess.Write)))
                {
                    byte[] buffer = new byte[maxBlockSize];
                    int readCount = 0;
                    input.Read(buffer, 0, (int)m_HeaderLen);
                    while (maxBlockSize == (readCount = input.Read(buffer, 0, maxBlockSize)))
                    {
                        logger.Trace("read {0} bytes", readCount);
                        t0.Write(buffer, 0, readCount);
                    }
                    logger.Trace("writing final block of {0} bytes", readCount);
                    t0.Write(buffer, 0, readCount);
                }
            }
        }
示例#24
0
        public static IObject CreateObject(string path)
        {
            logger.Trace("creating new Object from path {0}", path);            

            string digestString = Path.GetFileName(Path.GetDirectoryName(path)) + Path.GetFileName(path);
            logger.Trace("filename indicates digest of: {0}", digestString);
            byte[] digest = Encoding.ASCII.GetBytes(digestString.ToCharArray());
            
            byte[] buffer = new byte[MaxHeaderLength];
            using (ZlibStream input = new ZlibStream(File.Open(path, FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
            {
                logger.Trace("reading {0} bytes", MaxHeaderLength);
                input.Read(buffer, 0, MaxHeaderLength);
            }

            string[] header = null;
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == 0)
                {
                    header = new String(Encoding.ASCII.GetChars(buffer, 0, i)).Split(' ');
                    break;
                }   
            }

            logger.Trace("got header: {0} {1}", header[0], header[1]);           
            

            logger.Debug("got object of type {0}", header[0]);
            // TODO use header to create appropriate object
            Object result = null;            

            switch (header[0])
            {
                case "blob":
                    var blob = new Blob();                    
                    blob.m_Type = ObjectType.Blob;                    
                    result = blob;
                    break;
                case "tree":
                    var tree = new Tree();                    
                    tree.m_Type = ObjectType.Tree;                    
                    result = tree;
                    break;
                case "commit":
                    var commit = new Commit();
                    commit.m_Type = ObjectType.Commit;                    
                    result = commit;
                    break;
                case "tag":
                    break;
                default:
                    break;
            }

            result.m_Path = path;
            result.m_Digest = digest;
            result.m_Size = Convert.ToUInt64(header[1]);
            result.m_HeaderLen = header[0].Length + header[1].Length + 2; // + 2 to account for the ' ' and '\0'.
   
            return result;
        }
        public void run()
        {
            try
            {
                for (;;)
                {
                    if (!this.mParent.connectionAlive)
                    {
                        this.mParent.forceDisconnect("Connection Lost");
                        return;
                    }

                    if (this.mParent.kickTargetTimestamp != 0)
                    {
                        if (this.mParent.kickTargetTimestamp < Utils.getTimestamp())
                        {
                            this.mParent.forceDisconnect("Kicked from server");
                            return;
                        }
                        continue;
                    }

                    #region Process Packet
                    //Packet ID and Vaildity Check.
                    uint temp = this.mInput.ReadVarUInt32();
                    if (temp < 1 || temp > 48)
                    {
                        this.mParent.errorDisconnect(mDirection, "Sent invalid packet ID [" + temp + "].");
                        return;
                    }
                    Packet packetID = (Packet)temp;

                    //Packet Size and Compression Check.
                    bool compressed = false;
                    int packetSize = this.mInput.ReadVarInt32();
                    if (packetSize < 0)
                    {
                        packetSize = -packetSize;
                        compressed = true;
                    }

                    //Create buffer for forwarding
                    byte[] dataBuffer = this.mInput.ReadFully(packetSize);

                    //Do decompression
                    MemoryStream ms = new MemoryStream();
                    if (compressed)
                    {
                        ZlibStream compressedStream = new ZlibStream(new MemoryStream(dataBuffer), CompressionMode.Decompress);
                        byte[] buffer = new byte[32768];
                        for (;;)
                        {
                            int read = compressedStream.Read(buffer, 0, buffer.Length);
                            if (read <= 0)
                                break;
                            ms.Write(buffer, 0, read);
                        }
                        ms.Seek(0, SeekOrigin.Begin);
                    }
                    else
                    {
                        ms = new MemoryStream(dataBuffer);
                    }

                    //Create packet parser
                    BinaryReader packetData = new BinaryReader(ms);
                    #endregion

                    //Return data for packet processor
                    object returnData = true;

                    if (packetID != Packet.Heartbeat && packetID != Packet.UniverseTimeUpdate)
                    {
                        if (mDirection == Direction.Client)
                        #region Handle Client Packets
                        {
                            #region Protocol State Security
                            ClientState curState = this.mParent.clientState;
                            if (curState != ClientState.Connected)
                            {
                                if (curState == ClientState.PendingConnect && packetID != Packet.ClientConnect)
                                {
                                    this.mParent.forceDisconnect("Violated PendingConnect protocol state with " + packetID);
                                }
                                else if (curState == ClientState.PendingAuthentication && packetID != Packet.HandshakeResponse)
                                {
                                    this.mParent.forceDisconnect("Violated PendingAuthentication protocol state with " + packetID);
                                }
                                else if (curState == ClientState.PendingConnectResponse)
                                {
                                    this.mParent.forceDisconnect("Violated PendingConnectResponse protocol state with " + packetID);
                                }
                            }
                            #endregion

                            if (packetID == Packet.ChatSend)
                            {
                                returnData = new Packet11ChatSend(this.mParent, packetData, this.mDirection).onReceive();
                            }
                            else if (packetID == Packet.ClientConnect)
                            {
                                this.mParent.clientState = ClientState.PendingAuthentication;
                                returnData = new Packet7ClientConnect(this.mParent, packetData, this.mDirection).onReceive();
                                MemoryStream packet = new MemoryStream();
                                BinaryWriter packetWrite = new BinaryWriter(packet);

                                passwordSalt = Utils.GenerateSecureSalt();
                                packetWrite.WriteStarString("");
                                packetWrite.WriteStarString(passwordSalt);
                                packetWrite.WriteBE(StarryboundServer.config.passwordRounds);
                                this.mParent.sendClientPacket(Packet.HandshakeChallenge, packet.ToArray());
                            }
                            else if (packetID == Packet.HandshakeResponse)
                            {
                                string claimResponse = packetData.ReadStarString();
                                string passwordHash = packetData.ReadStarString();

                                string verifyHash = Utils.StarHashPassword(StarryboundServer.config.proxyPass, this.mParent.playerData.account + passwordSalt, StarryboundServer.config.passwordRounds);
                                if (passwordHash != verifyHash)
                                {
                                    this.mParent.rejectPreConnected("Your password was incorrect.");
                                }

                                this.mParent.clientState = ClientState.PendingConnectResponse;
                                returnData = false;
                            }
                            else if (packetID == Packet.WarpCommand)
                            {
                                uint warp = packetData.ReadUInt32BE();
                                WorldCoordinate coord = packetData.ReadStarWorldCoordinate();
                                string player = packetData.ReadStarString();
                                WarpType cmd = (WarpType)warp;
                                if (cmd == WarpType.WarpToHomePlanet)
                                {
                                    this.mParent.playerData.inPlayerShip = false;
                                }
                                else if (cmd == WarpType.WarpToOrbitedPlanet)
                                {
                                    this.mParent.playerData.inPlayerShip = false;
                                }
                                else if (cmd == WarpType.WarpToOwnShip)
                                {
                                    this.mParent.playerData.inPlayerShip = true;
                                }
                                else if (cmd == WarpType.WarpToPlayerShip)
                                {
                                    this.mParent.playerData.inPlayerShip = true;
                                }

                                StarryboundServer.logDebug("WarpCommand", "[" + this.mParent.playerData.client + "][" + warp + "]" + (coord != null ? "[" + coord.ToString() + "]" : "") + "[" + player + "]");
                            }
                            else if (packetID == Packet.ModifyTileList || packetID == Packet.DamageTileGroup || packetID == Packet.DamageTile || packetID == Packet.ConnectWire || packetID == Packet.DisconnectAllWires)
                            {
                                if (!this.mParent.playerData.canBuild) continue;
                                if (this.mParent.playerData.loc != null)
                                {
                                    string planetCheck = this.mParent.playerData.loc.ToString();
                                    string spawnPlanet = StarryboundServer.serverConfig.defaultWorldCoordinate;

                                    if (StarryboundServer.serverConfig.defaultWorldCoordinate.Split(':').Length == 5) spawnPlanet = spawnPlanet + ":0";

                                    if ((planetCheck == spawnPlanet) && !this.mParent.playerData.group.hasPermission("admin.spawnbuild") && !this.mParent.playerData.inPlayerShip)
                                    {
                                        continue;
                                    }
                                }
                            }
                        }
                        #endregion
                        else
                        #region Handle Server Packets
                        {
                            if (packetID == Packet.ChatReceive)
                            {
                                returnData = new Packet5ChatReceive(this.mParent, packetData, this.mDirection).onReceive();
                            }
                            else if (packetID == Packet.ProtocolVersion)
                            {
                                uint protocolVersion = packetData.ReadUInt32BE();
                                if (protocolVersion != StarryboundServer.ProtocolVersion)
                                {
                                    MemoryStream packet = new MemoryStream();
                                    BinaryWriter packetWrite = new BinaryWriter(packet);
                                    packetWrite.WriteBE(protocolVersion);
                                    this.mParent.sendClientPacket(Packet.ProtocolVersion, packet.ToArray());

                                    this.mParent.rejectPreConnected("Starrybound Server was unable to handle the parent server protocol version.");
                                    returnData = false;
                                }
                            }
                            else if (packetID == Packet.HandshakeChallenge)
                            {
                                string claimMessage = packetData.ReadString();
                                string passwordSalt = packetData.ReadStarString();
                                int passwordRounds = packetData.ReadInt32BE();

                                MemoryStream packet = new MemoryStream();
                                BinaryWriter packetWrite = new BinaryWriter(packet);
                                string passwordHash = Utils.StarHashPassword(StarryboundServer.config.serverPass, StarryboundServer.config.serverAccount + passwordSalt, passwordRounds);
                                packetWrite.WriteStarString("");
                                packetWrite.WriteStarString(passwordHash);
                                this.mParent.sendServerPacket(Packet.HandshakeResponse, packet.ToArray());

                                returnData = false;
                            }
                            else if (packetID == Packet.ConnectResponse)
                            {
                                while (this.mParent.clientState != ClientState.PendingConnectResponse) { } //TODO: needs timeout
                                returnData = new Packet2ConnectResponse(this.mParent, packetData, this.mDirection).onReceive();
                            }
                            else if (packetID == Packet.WorldStart)
                            {
                                if (!this.mParent.playerData.sentMotd)
                                {
                                    this.mParent.sendChatMessage(Config.GetMotd());
                                    this.mParent.playerData.sentMotd = true;
                                }

                                byte[] planet = packetData.ReadStarByteArray();
                                byte[] worldStructure = packetData.ReadStarByteArray();
                                byte[] sky = packetData.ReadStarByteArray();
                                byte[] serverWeather = packetData.ReadStarByteArray();
                                float spawnX = packetData.ReadSingleBE();
                                float spawnY = packetData.ReadSingleBE();
                                uint mapParamsSize = packetData.ReadVarUInt32();
                                Dictionary<string, object> mapParams = new Dictionary<string, object>();
                                for (int i = 0; i < mapParamsSize; i++)
                                {
                                    mapParams.Add(packetData.ReadStarString(), packetData.ReadStarVariant());
                                }
                                uint clientID = packetData.ReadUInt32BE();
                                bool bool1 = packetData.ReadBoolean();
                                WorldCoordinate coords = Utils.findGlobalCoords(sky);
                                if (coords != null)
                                {
                                    this.mParent.playerData.loc = coords;
                                    StarryboundServer.logDebug("WorldStart", "[" + this.mParent.playerData.client + "][" + bool1 + ":" + clientID + "] CurLoc:[" + this.mParent.playerData.loc.ToString() + "][" + this.mParent.playerData.inPlayerShip + "]");
                                }
                            }
                            else if (packetID == Packet.WorldStop)
                            {
                                string status = packetData.ReadStarString();
                            }
                            else if (packetID == Packet.GiveItem)
                            {
                                string name = packetData.ReadStarString();
                                uint count = packetData.ReadVarUInt32();
                                List<object> itemDesc = packetData.ReadStarVariant();
                            }
                            else if (packetID == Packet.EnvironmentUpdate)
                            {
                                byte[] sky = packetData.ReadStarByteArray();
                                byte[] serverWeather = packetData.ReadStarByteArray();
                                /*WorldCoordinate coords = Utils.findGlobalCoords(sky);
                                if (coords != null)
                                {
                                    this.mParent.playerData.loc = coords;
                                    StarryboundServer.logDebug("EnvUpdate", "[" + this.mParent.playerData.client + "] CurLoc:[" + this.mParent.playerData.loc.ToString() + "]");
                                }*/
                            }
                            else if (packetID == Packet.ClientContextUpdate)
                            {
                                try
                                {
                                    byte[] clientContextData = packetData.ReadStarByteArray();
                                    if (clientContextData.Length != 0)
                                    {
                                        BinaryReader clientContextReader = new BinaryReader(new MemoryStream(clientContextData));
                                        byte[] data = clientContextReader.ReadStarByteArray();
                                        if (data.Length > 8) //Should at least be more than 8 bytes for it to contain the data we want.
                                        {
                                            BinaryReader dataReader = new BinaryReader(new MemoryStream(data));
                                            byte dataBufferLength = dataReader.ReadByte();
                                            if (dataBufferLength == 2)
                                            {
                                                byte arrayLength = dataReader.ReadByte();
                                                if (arrayLength == 2 || arrayLength == 4) //Only observed these being used so far for what we want.
                                                {
                                                    byte dataType = dataReader.ReadByte(); //04 = String, 0E = CelestialLog
                                                    if (dataType == 4)
                                                    {
                                                        string string1 = dataReader.ReadStarString();
                                                        if (dataReader.BaseStream.Position != dataReader.BaseStream.Length)
                                                        {
                                                            if (string1 == "null")
                                                            {
                                                                byte[] worldHeader = dataReader.ReadStarByteArray(); //0008020A000C
                                                                byte[] worldData = dataReader.ReadStarByteArray();
                                                                byte typeByte = dataReader.ReadByte(); //0E = CelestialLog
                                                                if (typeByte == 14)
                                                                {
                                                                    Dictionary<string, WorldCoordinate> log = dataReader.ReadStarCelestialLog();
                                                                    log.TryGetValue("loc", out this.mParent.playerData.loc);
                                                                    if (!log.TryGetValue("home", out this.mParent.playerData.home))
                                                                        this.mParent.playerData.home = this.mParent.playerData.loc;
                                                                    StarryboundServer.logDebug("ClientContext", "[" + this.mParent.playerData.client + "] CurLoc:[" + this.mParent.playerData.loc.ToString() + "][" + this.mParent.playerData.inPlayerShip + "]");
                                                                    StarryboundServer.logDebug("ClientContext", "[" + this.mParent.playerData.client + "] CurHome:[" + this.mParent.playerData.home.ToString() + "]");
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else if (dataType == 14)
                                                    {
                                                        Dictionary<string, WorldCoordinate> log = dataReader.ReadStarCelestialLog();
                                                        log.TryGetValue("loc", out this.mParent.playerData.loc);
                                                        if (!log.TryGetValue("home", out this.mParent.playerData.home))
                                                            this.mParent.playerData.home = this.mParent.playerData.loc;
                                                        StarryboundServer.logDebug("ClientContext", "[" + this.mParent.playerData.client + "] CurLoc:[" + this.mParent.playerData.loc.ToString() + "][" + this.mParent.playerData.inPlayerShip + "]");
                                                        StarryboundServer.logDebug("ClientContext", "[" + this.mParent.playerData.client + "] CurHome:[" + this.mParent.playerData.home.ToString() + "]");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    StarryboundServer.logException("[" + this.mParent.playerData.client + "] Failed to parse ClientContextUpdate from Server: " + e.Message);
                                }
                            }
                        }
                        #endregion
                    }

                    #if DEBUG
                    if(packetID != Packet.Heartbeat)
                    {
                        //if (ms.Position != ms.Length)
                            //StarryboundServer.logDebug("ForwardThread", "[" + this.mParent.playerData.client + "] [" + this.mDirection.ToString() + "][" + packetID + "] failed parse (" + ms.Position + " != " + ms.Length + ")");
                        //StarryboundServer.logDebug("ForwardThread", "[" + this.mParent.playerData.client + "] [" + this.mDirection.ToString() + "][" + packetID + "] Dumping " + ms.Length + " bytes: " + Utils.ByteArrayToString(ms.ToArray()));
                    }
                    #endif

                    //Check return data
                    if (returnData is Boolean)
                    {
                        if ((Boolean)returnData == false) continue;
                    }
                    else if (returnData is int)
                    {
                        if ((int)returnData == -1)
                        {
                            this.mParent.forceDisconnect("Command processor requested to drop client");
                        }
                    }

                    #region Forward Packet
                    //Write data to dest
                    this.mOutput.WriteVarUInt32((uint)packetID);
                    if (compressed)
                    {
                        this.mOutput.WriteVarInt32(-packetSize);
                        this.mOutput.Write(dataBuffer, 0, packetSize);
                    }
                    else
                    {
                        this.mOutput.WriteVarInt32(packetSize);
                        this.mOutput.Write(dataBuffer, 0, packetSize);
                    }
                    this.mOutput.Flush();
                    #endregion

                    //If disconnect was forwarded to client, lets disconnect.
                    if(packetID == Packet.ServerDisconnect && mDirection == Direction.Server)
                    {
                        this.mParent.forceDisconnect();
                    }
                }
            }
            catch (EndOfStreamException)
            {
                this.mParent.forceDisconnect();
            }
            catch (Exception e)
            {
                this.mParent.errorDisconnect(mDirection, "ForwardThread Exception: " + e.ToString());
            }
        }
示例#26
0
 public slot ReadSlot()
 {
     short temp_b = ReadShort();
     if (temp_b <= -1)
     {
         return new slot(temp_b);
     }
     else if(slot.IsGziped(temp_b))
     {
         byte[] buffer = ReadBytes(temp_b);
         slot temp_slot = new slot(temp_b);
         ZlibStream decompress = new ZlibStream(reader, CompressionMode.Decompress);
         decompress.Read(temp_slot.GZipData,0 ,buffer.Length);
         return temp_slot;
     }
     return new slot(temp_b);
 }