ReadByte() public method

public ReadByte ( ) : int
return int
        public byte[] Decompress(byte[] input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            var output = new List<byte>();

            using (var ms = new MemoryStream(input))
            {
                var gs = new GZipStream(ms, CompressionMode.Decompress);
                var readByte = gs.ReadByte();

                while (readByte != -1)
                {
                    output.Add((byte)readByte);
                    readByte = gs.ReadByte();
                }

                gs.Close();
                ms.Close();
            }

            return output.ToArray();
        }
Exemplo n.º 2
0
 static void UncompressFile(string inFilename, string outFilename)
 {
     FileStream sourceFile = File.OpenRead(inFilename);
     FileStream destFile = File.Create(outFilename);
     GZipStream compStream = new GZipStream(destFile, CompressionMode.Decompress);
     int theByte = compStream.ReadByte();
     while (theByte != -1)
     {
         destFile.WriteByte((byte)theByte);
         theByte = compStream.ReadByte();
     }
     sourceFile.Close();
     destFile.Close();
     compStream.Close();
 }
Exemplo n.º 3
0
        static void Main()
        {
            FileStream source = File.OpenRead(@"D:\archive.zip");
            FileStream destination = File.Create(@"D:\text_zip.txt");

            GZipStream deCompressor = new GZipStream(source, CompressionMode.Decompress);

            int theByte = deCompressor.ReadByte();
            while (theByte != -1)
            {
                destination.WriteByte((byte)theByte);
                theByte = deCompressor.ReadByte();
            }

            deCompressor.Close();
        }
        public async Task ConcatenatedEmptyGzipStreams()
        {
            const int copyToBufferSizeRequested = 0x8000;

            // we'll request a specific size buffer, but we cannot guarantee that's the size
            // that will be used since CopyTo will rent from the array pool
            // take advantage of this knowledge to find out what size it will actually use
            var rentedBuffer = ArrayPool <byte> .Shared.Rent(copyToBufferSizeRequested);

            int actualBufferSize = rentedBuffer.Length;

            ArrayPool <byte> .Shared.Return(rentedBuffer);

            // use 3 buffers-full so that we can prime the stream with the first buffer-full,
            // test that CopyTo successfully flushes this at the beginning of the operation,
            // then populates the second buffer-full and reads its entirety despite every
            // payload being 0 length before it reads the final buffer-full.
            int minCompressedSize = 3 * actualBufferSize;

            using (Stream compressedStream = new DerivedMemoryStream())
            {
                using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, leaveOpen: true))
                {
                    // write one byte in order to allow us to prime the inflater buffer
                    gz.WriteByte(3);
                }

                while (compressedStream.Length < minCompressedSize)
                {
                    using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, leaveOpen: true))
                    {
                        gz.Write(Array.Empty <byte>());
                    }
                }

                compressedStream.Seek(0, SeekOrigin.Begin);
                using (Stream gz = new GZipStream(compressedStream, CompressionMode.Decompress, leaveOpen: true))
                    using (Stream decompressedData = new DerivedMemoryStream())
                    {
                        // read one byte in order to fill the inflater bufffer before copy
                        Assert.Equal(3, gz.ReadByte());

                        gz.CopyTo(decompressedData, copyToBufferSizeRequested);
                        Assert.Equal(0, decompressedData.Length);
                    }

                compressedStream.Seek(0, SeekOrigin.Begin);
                using (Stream gz = new GZipStream(compressedStream, CompressionMode.Decompress, leaveOpen: true))
                    using (Stream decompressedData = new DerivedMemoryStream())
                    {
                        // read one byte in order to fill the inflater bufffer before copy
                        Assert.Equal(3, gz.ReadByte());

                        await gz.CopyToAsync(decompressedData, copyToBufferSizeRequested);

                        Assert.Equal(0, decompressedData.Length);
                    }
            }
        }
Exemplo n.º 5
0
 public static byte[] Decompress(byte[] input)
 {
     List<byte> result = new List<byte>();
     using (var ms2 = new MemoryStream(input))
     {
         using (GZipStream zs = new GZipStream(ms2, CompressionMode.Decompress))
         {
             int read = zs.ReadByte();
             while (read != -1)
             {
                 result.Add((byte)read);
                 read = zs.ReadByte();
             }
         }
         return result.ToArray();
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Decompresses the given byte array
        /// </summary>
        public byte[] Decompress(byte[] input)
        {
            using (var output = new MemoryStream(input))
            {
                using (var zip = new GZipStream(output, CompressionMode.Decompress))
                {
                    var bytes = new List<byte>();
                    var b = zip.ReadByte();
                    while (b != -1)
                    {
                        bytes.Add((byte)b);
                        b = zip.ReadByte();

                    }
                    return bytes.ToArray();
                }
            }
        }
Exemplo n.º 7
0
 private static void Assemble(List<string> files, string destinationDirectory,string extension)
 {
     FileStream writer = new FileStream(destinationDirectory + "assembled" + "." + extension,FileMode.Create);
     for (int i = 0; i < files.Count; i++)
     {
         FileStream reader = new FileStream(destinationDirectory + files[i],FileMode.Open,FileAccess.ReadWrite);
         GZipStream readerGzip = new GZipStream(reader,CompressionMode.Decompress);
         int readBytesVariable = readerGzip.ReadByte();
         while (readBytesVariable != -1)
         {
             writer.WriteByte((byte)readBytesVariable);
             readBytesVariable = readerGzip.ReadByte();
         }
         readerGzip.Dispose();
         reader.Dispose();
     }
     writer.Flush();
     writer.Dispose();
 }
Exemplo n.º 8
0
 /// <summary>
 /// 解压缩
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 public static byte[] Decompress(byte[] input)
 {
     List<byte> output = new List<byte>();
     using (MemoryStream ms = new MemoryStream(input))
     {
         using (GZipStream gs = new GZipStream(ms, CompressionMode.Decompress))
         {
             int readByte = gs.ReadByte();
             while (readByte != -1)
             {
                 output.Add((byte)readByte);
                 readByte = gs.ReadByte();
             }
             gs.Close();
         }
         ms.Close();
     }
     return output.ToArray();
 }
Exemplo n.º 9
0
 public static byte[] GZDecompress(byte[] source)
 {
     byte[] buffer2;
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     try
     {
         using (MemoryStream stream = new MemoryStream())
         {
             MemoryStream stream2 = new MemoryStream(source);
             stream2.Position = 0L;
             using (GZipStream stream3 = new GZipStream(stream2, CompressionMode.Decompress, true))
             {
                 bool flag2;
                 byte[] buffer = new byte[0x1000];
                 bool flag = false;
                 long num2 = 0L;
                 int num3 = 0;
                 goto Label_0096;
             Label_0052:
                 num3 = stream3.ReadByte();
                 if (num3 != -1)
                 {
                     if (!flag)
                     {
                         flag = true;
                     }
                     num2 += 1L;
                     stream.WriteByte((byte) num3);
                 }
                 else if (flag)
                 {
                     goto Label_009B;
                 }
             Label_0096:
                 flag2 = true;
                 goto Label_0052;
             Label_009B:
                 stream3.Close();
                 Console.WriteLine("Original size: {0}, DeCompressed size: {1}", source.Length, stream.Length);
             }
             buffer2 = stream.ToArray();
         }
     }
     catch (Exception exception)
     {
         LoggingService.Error("GZip解压缩时出错:", exception);
         buffer2 = source;
     }
     return buffer2;
 }
Exemplo n.º 10
0
        public static string UnZip(string value)
        {
            System.Text.StringBuilder sB = new StringBuilder();
            //Transform string into byte[]
            byte[] byteArray = new byte[value.Length];
            int    indexBA   = 0;

            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

            //Prepare for decompress
            System.IO.MemoryStream           ms = new System.IO.MemoryStream(byteArray);
            System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
                                                                                       System.IO.Compression.CompressionMode.Decompress);

            List <byte> byteList = new List <byte>();
            //Reset variable to collect uncompressed result
            //byteArray = new byte[byteArray.Length * 3 ];
            int data = sr.ReadByte();

            while (data != -1)
            {
                //sB.Append((char)data);
                byteList.Add((byte)data);
                data = sr.ReadByte();
            }
            //Decompress
            sB.Append(Encoding.UTF8.GetString(byteList.ToArray()));
            //Transform byte[] unzip data to string
            //Read the number of bytes GZipStream red and do not a for each bytes in
            sr.Close();
            ms.Close();
            sr.Dispose();
            ms.Dispose();
            return(sB.ToString());
        }
Exemplo n.º 11
0
        public override Map Load( string fileName ) {
            if ( fileName == null ) throw new ArgumentNullException( "fileName" );
            using ( FileStream mapStream = File.OpenRead( fileName ) ) {
                using ( var gs = new GZipStream( mapStream, CompressionMode.Decompress ) ) {

                    Map map = LoadHeaderInternal(gs);

                    map.Blocks = new byte[map.Volume];

                    int i = 0, b, s;
                    while ((b = gs.ReadByte()) != -1)
                    {
                        s = gs.ReadByte();

                        short val = BitConverter.ToInt16( new[] { ( byte ) b, ( byte ) s }, 0 );

                        if (val <= 65)
                        {
                            map.Blocks[i] = ( byte ) val;
                        }
                        else
                        {
                            map.Blocks[i] = Mapping[val];
                        }
                    }



                    // Read in the map data
                    map.Blocks = new byte[map.Volume];
                    BufferUtil.ReadAll(gs, map.Blocks);

                    map.ConvertBlockTypes(Mapping);

                    return map;
                }
            }
        }
Exemplo n.º 12
0
        public byte[] Decompress(byte[] fileBytes)
        {
            byte[] bytes;

            using (MemoryStream fileStream = new MemoryStream(fileBytes)) {
                using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Decompress)) {
                    using (MemoryStream decompressedStream = new MemoryStream()) {
                        int value;
                        while ((value = zipStream.ReadByte()) != -1) {
                            decompressedStream.WriteByte((byte) value);
                        }
                        zipStream.Close();
                        bytes = decompressedStream.ToArray();
                    }
                }
            }

            return bytes;
        }
Exemplo n.º 13
0
        void IOLoop()
        {
            byte[] loginPacket = CreateLoginPacket(migratedUsername ?? _username, _ver);
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                if(EndPoint.Port > IPEndPoint.MaxPort || EndPoint.Port < IPEndPoint.MinPort) throw new SocketException(-1);
                //Do not continue if the user attempts to connect on a port larger than possible.
                ServerSocket.Connect(EndPoint);
                ServerSocket.Send(loginPacket);
            } catch( SocketException ex ) {
                Log( LogType.Error, HandleSocketError( ex.ErrorCode ), ex.ToString() );
                return;
            }

            BinaryReader reader = new BinaryReader(new NetworkStream(ServerSocket));

            while (true)
            {
                try
                {
                    byte OpCode = reader.ReadByte();
                    PacketEventArgs opcodeEvent = new PacketEventArgs((ServerPackets)OpCode);
                    Events.RaisePacketReceived(opcodeEvent);

                    switch ((ServerPackets)OpCode)
                    {
                        case ServerPackets.ServerIdentification://0x00
                            {
                                ProtocolVersion = reader.ReadByte(); // Protocol version should be seven.
                                string Name = Encoding.ASCII.GetString(reader.ReadBytes(64)).Trim();
                                string MOTD = Encoding.ASCII.GetString(reader.ReadBytes(64)).Trim();
                                if(!serverLoaded)
                                {
                                    ServerName = Name;
                                    ServerMOTD = MOTD;
                                    serverLoaded = true;
                                }
                                UserType = reader.ReadByte();//Get the type. 0x64 = Op, 0x00 = Normal user.
                            }
                            break;

                        case ServerPackets.Ping://0x01
                            break; // Server only requires we read the packet ID.

                        case ServerPackets.LevelInitialize://0x02
                            Players.Clear();
                            if(_savemap) mapStream = new MemoryStream();
                            CanReconnectAfterKick = true;
                            break;

                        case ServerPackets.LevelDataChunk://0x03
                            {
                                int chunkLength = IPAddress.HostToNetworkOrder(reader.ReadInt16()); // Length of non padded data.
                                byte[] chunkData = reader.ReadBytes(1024); // May be padded with extra data.
                                byte progress = reader.ReadByte();
                                if(_savemap) {
                                    mapStream.Write( chunkData, 0, chunkLength );
                                }
                                MapProgressEventArgs e = new MapProgressEventArgs(progress);
                                Events.RaiseMapProgress(e);
                            }
                            break;

                        case ServerPackets.LevelFinalize://0x04:
                            {
                                MapSizeX = IPAddress.HostToNetworkOrder(reader.ReadInt16());
                                MapSizeZ = IPAddress.HostToNetworkOrder(reader.ReadInt16());
                                MapSizeY = IPAddress.HostToNetworkOrder(reader.ReadInt16());
                                Connected = true; //At this state, we've loaded the map and we're ready to send chat etc.
                                if(_savemap) {
                                    Log( LogType.BotActivity, "Beginning to save map.." );
                                    mapStream.Seek(0, SeekOrigin.Begin);
                                    Map map = new Map(MapSizeX, MapSizeY, MapSizeZ);
                                    using (GZipStream decompressed = new GZipStream( mapStream,CompressionMode.Decompress ) ) {
                                        decompressed.Read( new byte[4], 0, 4 ); //Ignore size of stream.
                                        int sizeX = MapSizeX, sizeY = MapSizeY, sizeZ = MapSizeZ;
                                        for( int z = 0; z < sizeZ; z++ ) {
                                            for( int y = 0; y < sizeY; y++ ) {
                                                for( int x = 0; x < sizeX; x++ ) {
                                                    byte next = (byte)decompressed.ReadByte();
                                                    map.SetBlock( x, y, z, next );
                                                }
                                            }
                                        }
                                    }
                                    mapStream.Dispose();
                                    map.Save("map_" + DateTime.Now.ToString("ddHHmmssfffffff")); //Formatting for DateTime.
                                    map.Dispose();
                                    Log( LogType.BotActivity, "Saved map" );
                                }
                                MapLoadedEventArgs e = new MapLoadedEventArgs();
                                Events.RaiseMapLoaded(e);
                            }
                            break;

                        case ServerPackets.SetBlock://0x06:
                            {
                                int blockX = IPAddress.HostToNetworkOrder(reader.ReadInt16());
                                int blockZ = IPAddress.HostToNetworkOrder(reader.ReadInt16());
                                int blockY = IPAddress.HostToNetworkOrder(reader.ReadInt16());
                                byte blockType = reader.ReadByte();
                                BlockPlacedEventArgs e = new BlockPlacedEventArgs(blockX, blockY, blockZ, blockType);
                                Events.RaiseBlockPlaced(e);
                                if(marksLeft > 0 && blockType == 39 && CubID != null)
                                {
                                    byte id = CubID.Value;
                                    if(Players[id].X < 0 || Players[id].Y < 0 || Players[id].Z < 0) {
                                        SendMessagePacket("Error: You are too far away from the bot.");
                                        break;
                                    }

                                    if(new Vector3I(blockX, blockY, blockZ).DistanceTo(new Vector3I(
                                        (int)Players[id].X, (int)Players[id].Y, (int)Players[id].Z)) > 11) {
                                        break; //Another player probably tried placing a block somewhere else.
                                    }
                                    marks[marks.Length - marksLeft] = new Vector3I(blockX, blockY, blockZ);
                                    marksLeft--; //Go from smallest to largest.
                                    if(marksLeft == 0 && QueuedDrawer != null) {
                                        Draw(QueuedDrawer, marks, cuboidType);
                                    }
                                }
                            }
                            break;

                        case ServerPackets.SpawnPlayer://0x07:
                            {
                                byte pID = reader.ReadByte();
                                string playername = Encoding.ASCII.GetString(reader.ReadBytes(64)).Trim();
                                Players[pID] = new Player();
                                Players[pID].Name = playername;
                                Players[pID].X = IPAddress.HostToNetworkOrder(reader.ReadInt16()) / 32f;
                                Players[pID].Z = IPAddress.HostToNetworkOrder(reader.ReadInt16()) / 32f;
                                Players[pID].Y = IPAddress.HostToNetworkOrder(reader.ReadInt16()) / 32f;
                                Players[pID].Yaw = reader.ReadByte();
                                Players[pID].Pitch = reader.ReadByte();
                                PositionEventArgs e = new PositionEventArgs(pID, Players[pID]);
                                Events.RaisePlayerMoved(e);
                            }
                            break;

                        case ServerPackets.PlayerTeleport://0x08
                            {
                                byte pID = reader.ReadByte();
                                Players[pID].X = IPAddress.HostToNetworkOrder(reader.ReadInt16()) / 32f;
                                Players[pID].Z = IPAddress.HostToNetworkOrder(reader.ReadInt16()) / 32f;
                                Players[pID].Y = IPAddress.HostToNetworkOrder(reader.ReadInt16()) / 32f;
                                Players[pID].Yaw = reader.ReadByte();
                                Players[pID].Pitch = reader.ReadByte();
                                PositionEventArgs e = new PositionEventArgs(pID, Players[pID]);
                                Events.RaisePlayerMoved(e);
                            }
                            break;

                        case ServerPackets.PositionandOrientationUpdate://0x09
                            {
                                byte pID = reader.ReadByte();
                                Players[pID].X += reader.ReadSByte() / 32f;
                                Players[pID].Z += reader.ReadSByte() / 32f;
                                Players[pID].Y += reader.ReadSByte() / 32f;
                                Players[pID].Yaw = reader.ReadByte();
                                Players[pID].Pitch = reader.ReadByte();
                                PositionEventArgs e = new PositionEventArgs(pID, Players[pID]);
                                Events.RaisePlayerMoved(e);
                            }
                            break;

                        case ServerPackets.PositionUpdate://0x0a
                            {
                                byte pID = reader.ReadByte();
                                Players[pID].X += (reader.ReadSByte() / 32f);
                                Players[pID].Z += (reader.ReadSByte() / 32f);
                                Players[pID].Y += (reader.ReadSByte() / 32f);
                                PositionEventArgs e = new PositionEventArgs(pID, Players[pID]);
                                Events.RaisePlayerMoved(e);
                            }
                            break;

                        case ServerPackets.OrientationUpdate://0x0b
                            {
                                byte pID = reader.ReadByte();
                                Players[pID].Yaw = reader.ReadByte();
                                Players[pID].Pitch = reader.ReadByte();
                                PositionEventArgs e = new PositionEventArgs(pID, Players[pID]);
                                Events.RaisePlayerMoved(e);
                            }
                            break;

                        case ServerPackets.DespawnPlayer://0x0c
                            {
                                byte playerID = reader.ReadByte();
                                Players.Remove(playerID); // Also sent when the player joins another map.
                            }
                            break;

                        case ServerPackets.Message://0x0d
                            {
                                reader.ReadByte(); // Most servers don't send the ID.
                                string Line = Encoding.ASCII.GetString(reader.ReadBytes(64)).Trim();
                                MessageEventArgs e = new MessageEventArgs(Line); //Raise the event, let the event handler take care of splitting.
                                Events.RaiseChatMessage(e);
                                Log( LogType.Chat, Line );

                                if (Line.Contains(_delimiter.ToString())) { //Most servers use : as the delimiter.
                                    string[] lineSplit = Line.Split(new char[] { _delimiter }, 2);
                                    string Message = Extensions.StripColors(lineSplit[1]).TrimStart(' ');
                                    string User = Extensions.StripColors(lineSplit[0]);

                                    if (!IgnoredUserList.Contains(User)) {
                                        string strippedcommandheader = Message.Split(' ')[0].ToLower();
                                        foreach(KeyValuePair<string,CommandDelegate> command in RegisteredCommands)
                                        {
                                            if(strippedcommandheader == "." + command.Key.ToLower()) {
                                                if(_requiresop) {
                                                    if(Users.Contains(User)) {
                                                        EnqueueCommand(command.Value,Line);
                                                        break;
                                                    } else {
                                                        SendMessagePacket(User +", you are not allowed to use the bot.");
                                                    }
                                                } else {
                                                    EnqueueCommand(command.Value,Line);
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                ProcessCommandQueue();
                            }
                            break;

                        case ServerPackets.DisconnectSelf://0x0e
                            {
                                string reason = Encoding.ASCII.GetString(reader.ReadBytes(64)).Trim();
                                KickedEventArgs e = new KickedEventArgs(reason, CanReconnectAfterKick);
                                Events.RaiseGotKicked(e);
                                if( _reconnectonkick == true && CanReconnectAfterKick == true ) {
                                    Log( LogType.BotActivity, "Kicked from the server. Reconnecting.", reason );
                                    CanReconnectAfterKick = false;
                                    Thread thread = new Thread(IOLoop);
                                    thread.Name = "LibClassicBotIO";
                                    thread.IsBackground = true;
                                    thread.Start();
                                } else if(_reconnectonkick == false) {
                                    Log( LogType.Warning, "Kicked from the server. Not attempting to reconnect.", reason );
                                } else {
                                    ServerSocket.Close();
                                    Log( LogType.Error, "The bot was prevented from reconnecting.", "(Kick packet received before a LevelBegin packet.)" );
                                }
                                return;
                            }

                        case ServerPackets.SetPermission://0x0f
                            UserType = reader.ReadByte();//Issued in Vanilla when someone calls /op, used in fCraft for bedrock permission checking.
                            break;

                        default:
                            throw new IOException("Unrecognised packet. Opcode: " + OpCode.ToString());
                    }
                } catch ( IOException ex ) {
                    if( _reconnectonkick == true && CanReconnectAfterKick == true ) {
                        CancelDrawer();
                        CanReconnectAfterKick = false;
                        Thread thread = new Thread(IOLoop);
                        thread.Name = "LibClassicBotIO";
                        thread.IsBackground = true;
                        thread.Start();
                    } else {
                        Log( LogType.Error, "An I/O error has occured. The connection have been closed uncleanly. Exiting the bot.", ex.ToString() );
                    }
                    return;

                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Adds the xml files provided to the provider.
        /// </summary>
        /// <param name="provider">The provider to be modified.</param>
        /// <param name="files">List of files to be processed.</param>
        public static void Add(Provider provider, IList<string> files)
        {
            var streams = new List<Stream>();
            try
            {
                foreach (string file in files)
                {
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.Exists)
                    {
                        if (Detection.Constants.CompressedFileExtensions.Contains(fileInfo.Extension))
                        {
                            // This is a compressed file. It needs to be copied to a memory stream
                            // to enable multiple passed of the data.
                            var ms = new MemoryStream();
                            var temp = new GZipStream(
                                new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read),
                                CompressionMode.Decompress);
                            
                            // Copy the data to the memory stream.
                            int value = temp.ReadByte();
                            while (value > 0)
                            {
                                ms.WriteByte((byte)value);
                                value = temp.ReadByte();
                            }

                            streams.Add(ms);
                        }
                        else
                            streams.Add(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read));
                    }
                }
                Add(provider, streams);
            }
            finally
            {
                foreach (var stream in streams)
                    stream.Dispose();
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Wraps the given stream in a decompression stream.
 /// </summary>
 /// <param name="input">Stream to wrap.</param>
 /// <returns>Decompression stream from which decompressed data can be read.</returns>
 public static Stream DecompressStream(Stream input)
 {
     Stream result = new GZipStream(input, CompressionMode.Decompress);
     int magic = result.ReadByte() << 24 | result.ReadByte() << 16 | result.ReadByte() << 8 | result.ReadByte();
     if (magic != MagicNumber)
         throw new Exception("Unsupported compression scheme or bad magic number.");
     return result;
 }
Exemplo n.º 16
0
 /// <summary>
 /// UnZip zippedBuffer
 /// </summary>
 /// <param name="zippedbuffer">The zippedbuffer.</param>
 /// <returns></returns>
 public static string UnGZip(this byte[] zippedbuffer)
 {
     string result = null;
     int blockSize = 512;
     using (var compressedStream = new System.IO.MemoryStream(zippedbuffer, false))
     {
         if (compressedStream.CanSeek)
         {
             compressedStream.Seek(0, SeekOrigin.Begin);
         }
         using (var uncompressedStream = new System.IO.MemoryStream())
         {
             using (var unzip = new System.IO.Compression.GZipStream(compressedStream, CompressionMode.Decompress))
             {
                 var bf = new byte[blockSize];
                 while (true)
                 {
                     // Bug ! if zippedbuffer smaller than 4096 bytes, read byte one by one
                     if (zippedbuffer.Length <= 4096)
                     {
                         var pos = unzip.ReadByte();
                         if (pos == -1)
                         {
                             break;
                         }
                         uncompressedStream.WriteByte((byte)pos);
                     }
                     else
                     {
                         var count = unzip.Read(bf, 0, blockSize);
                         if (count == 0)
                         {
                             break;
                         }
                         uncompressedStream.Write(bf, 0, count);
                     }
                 }
                 result = System.Text.Encoding.UTF8.GetString(uncompressedStream.ToArray());
                 unzip.Close();
             }
             uncompressedStream.Close();
         }
         compressedStream.Close();
     }
     return result;
 }
Exemplo n.º 17
0
        public static DictRadix<MorphData> LoadDictionaryFromHSpellFolder(string path, bool bLoadMorphData)
        {
            if (path[path.Length - 1] != Path.DirectorySeparatorChar)
                path += Path.DirectorySeparatorChar;

            if (bLoadMorphData)
            {
                // Load the count of morphological data slots required
                string sizesFile = File.ReadAllText(path + HSpell.Constants.SizesFile);
                int lookupLen = sizesFile.IndexOf(' ', sizesFile.IndexOf('\n'));
                lookupLen = Convert.ToInt32(sizesFile.Substring(lookupLen + 1));
                string[] lookup = new string[lookupLen + 1];

                using (GZipStream fdict = new GZipStream(File.OpenRead(path + HSpell.Constants.DictionaryFile), CompressionMode.Decompress))
                {
                    char[] sbuf = new char[HSpell.Constants.MaxWordLength];
                    int c = 0, n, slen = 0, i = 0;
                    while ((c = fdict.ReadByte()) > -1)
                    {
                        if (c >= '0' && c <= '9') // No conversion required for chars < 0xBE
                        {
                            /* new word - finalize and save old word */
                            lookup[i++] = new string(sbuf, 0, slen);

                            /* and read how much to go back */
                            n = 0;
                            do
                            {
                                /* base 10... */
                                n *= 10;
                                n += (c - '0');
                            } while ((c = fdict.ReadByte()) > -1 && c >= '0' && c <= '9');
                            slen -= n;
                        }
                        sbuf[slen++] = ISO8859_To_Unicode(c);
                    }
                }

                using (MorphDataLoader dataLoader = new MorphDataLoader(path + HSpell.Constants.DescFile,
                        path + HSpell.Constants.StemsFile))
                {
                    using (GZipStream fprefixes = new GZipStream(File.OpenRead(path + HSpell.Constants.PrefixesFile), CompressionMode.Decompress))
                    {
                        DictRadix<MorphData> ret = new DictRadix<MorphData>();

                        for (int i = 0; lookup[i] != null; i++)
                        {
                            MorphData data = new MorphData();
                            data.Prefixes = Convert.ToByte(fprefixes.ReadByte()); // Read prefix hint byte
                            data.DescFlags = dataLoader.ReadDescFile();

                            List<int> stemReferences = dataLoader.ReadStemFile();
                            data.Lemmas = new string[stemReferences.Count];
                            int stemPosition = 0;
                            foreach (int r in stemReferences)
                            {
                                // This is a bypass for the psuedo-stem "שונות", as defined by hspell
                                // TODO: Try looking into changing this in hspell itself
                                if (lookup[r].Equals("שונות") && !lookup[r].Equals(lookup[i]))
                                {
                                    data.Lemmas[stemPosition++] = null;
                                }
                                else
                                {
                                    data.Lemmas[stemPosition++] = lookup[r];
                                }
                            }
                            ret.AddNode(lookup[i], data);
                        }

                        return ret;
                    }
                }
            }
            else // Use optimized version for loading HSpell's dictionary files
            {
                using (GZipStream fdict = new GZipStream(File.OpenRead(path + HSpell.Constants.DictionaryFile), CompressionMode.Decompress))
                {
                    using (GZipStream fprefixes = new GZipStream(File.OpenRead(path + HSpell.Constants.PrefixesFile), CompressionMode.Decompress))
                    {
                        DictRadix<MorphData> ret = new DictRadix<MorphData>();

                        char[] sbuf = new char[HSpell.Constants.MaxWordLength];
                        int c = 0, n, slen = 0;
                        while ((c = fdict.ReadByte()) > -1)
                        {
                            if (c >= '0' && c <= '9') // No conversion required for chars < 0xBE
                            {
                                /* new word - finalize old word first (set value) */
                                sbuf[slen] = '\0';

                                // TODO: Avoid creating new MorphData object, and enhance DictRadix to store
                                // the prefixes mask in the node itself
                                MorphData data = new MorphData();
                                data.Prefixes = Convert.ToByte(fprefixes.ReadByte()); // Read prefix hint byte
                                ret.AddNode(sbuf, data);

                                /* and read how much to go back */
                                n = 0;
                                do
                                {
                                    /* base 10... */
                                    n *= 10;
                                    n += (c - '0');
                                } while ((c = fdict.ReadByte()) > -1 && c >= '0' && c <= '9');
                                slen -= n;
                            }
                            sbuf[slen++] = ISO8859_To_Unicode(c);
                        }

                        return ret;
                    }
                }
            }
        }
Exemplo n.º 18
0
        public bool Load(string filename)
        {
            try
            {
                this.filename = filename;
                GZipStream gzin = new GZipStream(new FileStream("maps/" + filename, FileMode.Open), CompressionMode.Decompress);

                byte[] magicnumbytes = new byte[4];
                gzin.Read(magicnumbytes, 0, 4);
                if (!(BitConverter.ToUInt32(magicnumbytes, 0) == 0xebabefac))
                {
                    Program.server.logger.log("Wrong magic number in level file: " + BitConverter.ToUInt32(magicnumbytes, 0), Logger.LogType.Error);
                    return false;
                }

                byte[] leveldimensions = new byte[6];
                gzin.Read(leveldimensions, 0, 6);
                this.width = BitConverter.ToInt16(leveldimensions, 0);
                this.height = BitConverter.ToInt16(leveldimensions, 2);
                this.depth = BitConverter.ToInt16(leveldimensions, 4);

                byte[] spawnpoint = new byte[6];
                gzin.Read(spawnpoint, 0, 6);
                this.spawnx = BitConverter.ToInt16(spawnpoint, 0);
                this.spawny = BitConverter.ToInt16(spawnpoint, 2);
                this.spawnz = BitConverter.ToInt16(spawnpoint, 4);

                this.srotx = (byte)gzin.ReadByte();
                this.sroty = (byte)gzin.ReadByte();

                this.blocks = new byte[this.width * this.height * this.depth];
                gzin.Read(blocks, 0, this.width * this.height * this.depth);

                //gzin.BaseStream.Close();
                gzin.Close();

                this.name = filename.Substring(0, filename.IndexOf(".umw"));
                this.messageBlocks = new Dictionary<int, string>();
                this.teleportBlocks = new Dictionary<int, int>();

                if (File.Exists("maps/" + this.name + ".mb"))
                {
                    StreamReader mBlocksIn = new StreamReader(File.Open("maps/" + this.name + ".mb", FileMode.Open));
                    string line = "";
                    while (!mBlocksIn.EndOfStream)
                    {
                        line = mBlocksIn.ReadLine();
                        if (!line.Contains(" ")) break;
                        int index = Int32.Parse(line.Substring(0, line.IndexOf(" ")));
                        string msg = line.Substring(line.IndexOf(" ") + 1);
                        this.messageBlocks.Add(index, msg);
                    }
                    mBlocksIn.Close();
                }

                if (File.Exists("maps/" + this.name + ".tb"))
                {
                    StreamReader tBlocksIn = new StreamReader(File.Open("maps/" + this.name + ".tb", FileMode.Open));
                    string line = "";
                    while (!tBlocksIn.EndOfStream)
                    {
                        line = tBlocksIn.ReadLine();
                        if (!line.Contains(" ")) break;
                        int index = Int32.Parse(line.Substring(0, line.IndexOf(" ")));
                        int value = Int32.Parse(line.Substring(line.IndexOf(" ") + 1));
                        this.teleportBlocks.Add(index, value);
                    }
                    tBlocksIn.Close();
                }

                Program.server.logger.log("Loaded world from " + filename);
                return true;
            }
            catch (Exception e)
            {
                Program.server.logger.log("Error occurred while loading map", Logger.LogType.Error);
                Program.server.logger.log(e);
                return false;
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// 解压文件
        /// </summary>
        internal static string DerFileZip(string sourcefile, string filepath)
        {                
            string filename = System.IO.Path.GetFileNameWithoutExtension(filepath);//获取文件名

            using (var sourcestream = System.IO.File.OpenRead(sourcefile))
            {
                var CompressedStream = new GZipStream(sourcestream, CompressionMode.Decompress, true);
                var bs = new List<byte>();
                var b = CompressedStream.ReadByte();
                while(b != -1)
                {
                    bs.Add((byte)b);
                    b = CompressedStream.ReadByte();
                }
                using (var file = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    file.Write(bs.ToArray(), 0,bs.Count);
                }
            }
            return "成功";           
        }
Exemplo n.º 20
0
        public static Sprite Load(string inpath)
        {
            Sprite spr = new Sprite(inpath);

            if (inpath == null) return spr;
            spr.seeds.Clear();//LoadSeeds
            {
                if (System.IO.Path.DirectorySeparatorChar == '\\')
                    inpath = inpath.Replace("/", "\\");
                else
                    inpath = inpath.Replace("\\", "/");
                string file = System.IO.Path.Combine(inpath, "seeds.bin.bytes");
                using (System.IO.Stream os = TitleContainer.OpenStream(file))
                {
            #if USECompression
                    using (GZipStream s = new GZipStream(os, CompressionMode.Decompress))
            #else
                    var s = os;
            #endif
                    {
                        byte[] bb = new byte[256];

                        s.Read(bb, 0, 2);
                        UInt16 len = BitConverter.ToUInt16(bb, 0);
                        for (int i = 0; i < len; i++)
                        {
                            int slen = s.ReadByte();
                            s.Read(bb, 0, slen);
                            Seed seed = new Seed();
                            seed.Read(s);
                            string name = System.Text.Encoding.UTF8.GetString(bb, 0, slen);
                            spr.seeds[name] = seed;
                        }
                    }
                }
            }
            string[] files = null;
            {
                using (System.IO.Stream s = TitleContainer.OpenStream(System.IO.Path.Combine( inpath , "anims.txt")))
                {
                    byte[] buf = new byte[65536];
                    int buflen = (int)s.Read(buf, 0, 65536);
                    //byte[] b = new byte[s.Length];
                    //s.Read(b, 0, b.Length);
                    string txt = System.Text.Encoding.UTF8.GetString(buf,0,buflen);
                    files = txt.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    while(!char.IsLetter(files[0][0]))
                    {
                        files[0]=files[0].Substring(1);
                    }
                }
            }
            //string[] files = System.IO.Directory.GetFiles(inpath, "*.anim.bin");
            foreach (var _f in files)
            {
                string f =_f;
                if(System.IO.Path.DirectorySeparatorChar=='/')
                {
                    f=f.Replace('\\','/');
                }
                string fname =System.IO.Path.GetFileName(f);
                fname = System.IO.Path.Combine(inpath,fname);
                using (System.IO.Stream ss = TitleContainer.OpenStream(fname))
                {
                    Anim ani = new Anim(spr);
                    ani.Read(ss);
                    string name = System.IO.Path.GetFileNameWithoutExtension(f);
                    name = System.IO.Path.GetFileNameWithoutExtension(name);
                    spr.anims[name] = ani;
                }
            }
            return spr;
        }
Exemplo n.º 21
0
        /// <summary>
        /// GZipStream解压文件
        /// </summary>
        /// <param name="inFileName">源文件</param>
        /// <param name="outFileName">新文件</param>
        public static void GZipDecompress(string inFileName, string outFileName) {
            if (!FileExists(inFileName)) return;
            FileStream sourceFile = File.OpenRead(inFileName);
            FileStream destFile = File.Create(outFileName);
            GZipStream compStream = new GZipStream(sourceFile, CompressionMode.Decompress);
            int theByte = compStream.ReadByte();

            while (theByte != -1) {
                destFile.WriteByte((byte)theByte);
                theByte = compStream.ReadByte();
            }

            destFile.Close();
            compStream.Close();
            sourceFile.Close();
        }
Exemplo n.º 22
0
        public static Level Load(string name, string file, bool loadTexturesConfig = true) {
            using (Stream fs = File.OpenRead(file),
                   gs = new GZipStream(fs, CompressionMode.Decompress, true))
            {
                byte[] header = new byte[16];
                gs.Read(header, 0, 2);
                ushort[] vars = new ushort[6];
                vars[0] = BitConverter.ToUInt16(header, 0);

                int offset = 0;
                if (vars[0] == 1874) { // version field, width is next ushort
                    gs.Read(header, 0, 16);
                    vars[0] = BitConverter.ToUInt16(header, 0);
                    offset = 2;
                } else {
                    gs.Read(header, 0, 12);
                }
                vars[1] = BitConverter.ToUInt16(header, offset);
                vars[2] = BitConverter.ToUInt16(header, offset + 2);

                Level level = new Level(name, vars[0], vars[2], vars[1],
                                        "full_empty", 0, loadTexturesConfig);
                level.spawnx = BitConverter.ToUInt16(header, offset + 4);
                level.spawnz = BitConverter.ToUInt16(header, offset + 6);
                level.spawny = BitConverter.ToUInt16(header, offset + 8);
                level.rotx = header[offset + 10];
                level.roty = header[offset + 11];
                
                gs.Read(level.blocks, 0, level.blocks.Length);
                if (gs.ReadByte() != 0xBD) 
                    return level;
                
                int index = 0;
                for (int y = 0; y < level.ChunksY; y++)
                	for (int z = 0; z < level.ChunksZ; z++)
                		for (int x = 0; x < level.ChunksX; x++)
                {
                    if (gs.ReadByte() == 1) {
                        byte[] chunk = new byte[16 * 16 * 16];
                        gs.Read(chunk, 0, chunk.Length);
                        level.CustomBlocks[index] = chunk;
                    }
                    index++;
                }
                return level;
            }
        }
Exemplo n.º 23
0
 public void ungzip(string path, string decomPath, bool overwrite)
 {
     if (File.Exists(decomPath))
     {
         if (overwrite)
         {
             File.Delete(decomPath);
         }
         else
         {
             throw new IOException("The decompressed path you specified already exists and cannot be overwritten.");
         }
     }
     GZipStream stream = new GZipStream(new FileStream(path, FileMode.Open, FileAccess.ReadWrite), CompressionMode.Decompress);
     FileStream decompressedFile = new FileStream(decomPath, FileMode.OpenOrCreate, FileAccess.Write);
     int data;
     while ((data = stream.ReadByte()) != -1)
     {
         decompressedFile.WriteByte((byte)data);
     }
     decompressedFile.Close();
     stream.Close();
 }
Exemplo n.º 24
0
        public static Sprite LoadUnity(string inpath, byte[] seeddata)
        {
            Sprite spr = new Sprite(inpath);

            if (inpath == null) return spr;
            using (System.IO.Stream os = new System.IO.MemoryStream(seeddata))
            {
            #if USECompression
                using (GZipStream s = new GZipStream(os, CompressionMode.Decompress))
            #else
                var s = os;
            #endif
                {
                    byte[] bb = new byte[256];

                    s.Read(bb, 0, 2);
                    UInt16 len = BitConverter.ToUInt16(bb, 0);
                    for (int i = 0; i < len; i++)
                    {
                        int slen = s.ReadByte();
                        s.Read(bb, 0, slen);
                        Seed seed = new Seed();
                        seed.Read(s);
                        string name = System.Text.Encoding.UTF8.GetString(bb, 0, slen);
                        spr.seeds[name] = seed;
                    }
                }
            }
            //foreach (var ani in anis)
            {
                //using (System.IO.Stream ss = TitleContainer.OpenStream(fname))
                //{
                //    Anim ani = new Anim(spr);
                //    ani.Read(ss);
                //    string name = System.IO.Path.GetFileNameWithoutExtension(f);
                //    name = System.IO.Path.GetFileNameWithoutExtension(name);
                //    spr.anims[name] = ani;
                //}
            }
            return spr;
        }
Exemplo n.º 25
0
        public void TestBasicRequestHandling()
        {
            var store = 1024 * 1024;
            var instance = new HttpServer(ProgramServersTests.Port, new HttpServerOptions { StoreFileUploadInFileAtSize = store })
            {
                Handler = new UrlResolver(
                    new UrlMapping(handlerStatic, path: "/static"),
                    new UrlMapping(handlerDynamic, path: "/dynamic"),
                    new UrlMapping(handler64KFile, path: "/64kfile")
                ).Handle
            };
            try
            {
                instance.StartListening();

                testRequest("GET test #1", store, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 404 Not Found", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/html; charset=utf-8"));
                    Assert.IsTrue(headers.Any(x => x.StartsWith("Content-Length: ")));
                    Assert.IsTrue(content.FromUtf8().Contains("404"));
                });

                testRequest("GET test #2", store, "GET /static?x=y&z=%20&zig=%3D%3d HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                    Assert.IsTrue(headers.Contains("Content-Length: 41"));
                    Assert.AreEqual("GET:\nx => [\"y\"]\nz => [\" \"]\nzig => [\"==\"]\n", content.FromUtf8());
                });

                testRequest("GET test #3", store, "GET /static?x[]=1&x%5B%5D=%20&x%5b%5d=%3D%3d HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                    Assert.IsTrue(headers.Contains("Content-Length: 29"));
                    Assert.AreEqual("GET:\nx[] => [\"1\", \" \", \"==\"]\n", content.FromUtf8());
                });

                testRequest("GET test #4", store, "GET /dynamic?x=y&z=%20&zig=%3D%3d HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                    Assert.IsFalse(headers.Any(x => x.ToLowerInvariant().StartsWith("content-length:")));
                    Assert.IsFalse(headers.Any(x => x.ToLowerInvariant().StartsWith("accept-ranges:")));
                    Assert.AreEqual("GET:\nx => [\"y\"]\nz => [\" \"]\nzig => [\"==\"]\n", content.FromUtf8());
                });

                testRequest("GET test #5 (actually a POST)", store, "POST /static HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 411 Length Required", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/html; charset=utf-8"));
                    Assert.IsTrue(headers.Contains("Connection: close"));
                    Assert.IsTrue(headers.Contains("Content-Length: " + content.Length));
                    Assert.IsTrue(content.FromUtf8().Contains("411"));
                });

                testRequest("GET test #6", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: application/octet-stream"));
                    Assert.IsTrue(headers.Contains("Content-Length: 65536"));
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.AreEqual(65536, content.Length);
                    for (int i = 0; i < content.Length; i++)
                        Assert.AreEqual(content[i], (byte) (i % 256));
                });

                testRequest("GET test #7", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\nRange: bytes=23459-38274\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 206 Partial Content", headers[0]);
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.IsTrue(headers.Contains("Content-Range: bytes 23459-38274/65536"));
                    Assert.IsTrue(headers.Contains("Content-Type: application/octet-stream"));
                    Assert.IsTrue(headers.Contains("Content-Length: 14816"));
                    for (int i = 0; i < content.Length; i++)
                        Assert.AreEqual((byte) ((163 + i) % 256), content[i]);
                });

                testRequest("GET test #8", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\nRange: bytes=65-65,67-67\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 206 Partial Content", headers[0]);
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.IsTrue(headers.Any(x => Regex.IsMatch(x, @"^Content-Type: multipart/byteranges; boundary=[0-9A-F]+$")));
                    string boundary = headers.First(x => Regex.IsMatch(x, @"^Content-Type: multipart/byteranges; boundary=[0-9A-F]+$")).Substring(45);
                    Assert.IsTrue(headers.Contains("Content-Length: 284"));
                    byte[] expectedContent = ("--" + boundary + "\r\nContent-Range: bytes 65-65/65536\r\n\r\nA\r\n--" + boundary + "\r\nContent-Range: bytes 67-67/65536\r\n\r\nC\r\n--" + boundary + "--\r\n").ToUtf8();
                    Assert.AreEqual(expectedContent.Length, content.Length);
                    for (int i = 0; i < expectedContent.Length; i++)
                        Assert.AreEqual(expectedContent[i], content[i]);
                });

                testRequest("GET test #9", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.IsTrue(headers.Contains("Content-Type: application/octet-stream"));
                    Assert.IsTrue(headers.Contains("Content-Encoding: gzip"));
                    Assert.IsTrue(headers.Any(h => h.StartsWith("Content-Length")));
                    GZipStream gz = new GZipStream(new MemoryStream(content), CompressionMode.Decompress);
                    for (int i = 0; i < 65536; i++)
                        Assert.AreEqual(i % 256, gz.ReadByte());
                    Assert.AreEqual(-1, gz.ReadByte());
                });

                testRequest("GET test #10", store, "GET /dynamic HTTP/1.1\r\n\r\n", (headers, content) => Assert.AreEqual("HTTP/1.1 400 Bad Request", headers[0]));
                testRequest("GET test #11", store, "INVALID /request HTTP/1.1\r\n\r\n", (headers, content) => Assert.AreEqual("HTTP/1.1 400 Bad Request", headers[0]));
                testRequest("GET test #12", store, "GET  HTTP/1.1\r\n\r\n", (headers, content) => Assert.AreEqual("HTTP/1.1 400 Bad Request", headers[0]));
                testRequest("GET test #13", store, "!\r\n\r\n", (headers, content) => Assert.AreEqual("HTTP/1.1 400 Bad Request", headers[0]));
            }
            finally
            {
                instance.StopListening();
            }

            foreach (var storeFileUploadInFileAtSize in new[] { 5, 1024 })
            {
                instance = new HttpServer(ProgramServersTests.Port, new HttpServerOptions { StoreFileUploadInFileAtSize = storeFileUploadInFileAtSize })
                {
                    Handler = new UrlResolver(
                        new UrlMapping(handlerStatic, path: "/static"),
                        new UrlMapping(handlerDynamic, path: "/dynamic")
                    ).Handle
                };
                try
                {
                    instance.StartListening();

                    testRequest("POST test #1", storeFileUploadInFileAtSize, "POST /static HTTP/1.1\r\nHost: localhost\r\nContent-Length: 48\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\nx=y&z=%20&zig=%3D%3d&a[]=1&a%5B%5D=2&%61%5b%5d=3", (headers, content) =>
                    {
                        Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                        Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                        Assert.IsTrue(headers.Contains("Content-Length: 66"));
                        Assert.AreEqual("\nPOST:\nx => [\"y\"]\nz => [\" \"]\nzig => [\"==\"]\na[] => [\"1\", \"2\", \"3\"]\n", content.FromUtf8());
                    });

                    testRequest("POST test #2", storeFileUploadInFileAtSize, "POST /dynamic HTTP/1.1\r\nHost: localhost\r\nContent-Length: 20\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\nx=y&z=%20&zig=%3D%3d", (headers, content) =>
                    {
                        Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                        Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                        Assert.IsFalse(headers.Any(x => x.ToLowerInvariant().StartsWith("content-length:")));
                        Assert.IsFalse(headers.Any(x => x.ToLowerInvariant().StartsWith("accept-ranges:")));
                        Assert.AreEqual("\nPOST:\nx => [\"y\"]\nz => [\" \"]\nzig => [\"==\"]\n", content.FromUtf8());
                    });

                    string postContent = "--abc\r\nContent-Disposition: form-data; name=\"x\"\r\n\r\ny\r\n--abc\r\nContent-Disposition: form-data; name=\"z\"\r\n\r\n%3D%3d\r\n--abc\r\nContent-Disposition: form-data; name=\"y\"; filename=\"z\"\r\nContent-Type: application/weirdo\r\n\r\n%3D%3d\r\n--abc--\r\n";
                    string expectedResponse = "\nPOST:\nx => [\"y\"]\nz => [\"%3D%3d\"]\n\nFiles:\ny => { application/weirdo, z, \"%3D%3d\" (" + (storeFileUploadInFileAtSize < 6 ? "localfile" : "data") + ") }\n";

                    testRequest("POST test #3", storeFileUploadInFileAtSize, "POST /static HTTP/1.1\r\nHost: localhost\r\nContent-Length: " + postContent.Length + "\r\nContent-Type: multipart/form-data; boundary=abc\r\n\r\n" + postContent, (headers, content) =>
                    {
                        Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                        Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                        Assert.AreEqual(expectedResponse, content.FromUtf8());
                        Assert.IsTrue(headers.Contains("Content-Length: " + expectedResponse.Length));
                    });

                    testRequest("POST test #4", storeFileUploadInFileAtSize, "POST /dynamic HTTP/1.1\r\nHost: localhost\r\nContent-Length: " + postContent.Length + "\r\nContent-Type: multipart/form-data; boundary=abc\r\n\r\n" + postContent, (headers, content) =>
                    {
                        Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                        Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                        Assert.IsFalse(headers.Any(x => x.StartsWith("Content-Length: ")));
                        Assert.IsFalse(headers.Any(x => x.StartsWith("Accept-Ranges: ")));
                        Assert.AreEqual(expectedResponse, content.FromUtf8());
                    });

                    // Test that the server doesn't crash if a field name is missing
                    postContent = "--abc\r\nContent-Disposition: form-data; name=\"x\"\r\n\r\n\r\n--abc\r\nContent-Disposition: form-data\r\n\r\n%3D%3d\r\n--abc\r\nContent-Disposition: form-data; filename=\"z\"\r\nContent-Type: application/weirdo\r\n\r\n%3D%3d\r\n--abc--\r\n";
                    expectedResponse = "\nPOST:\nx => [\"\"]\n";

                    testRequest("POST test #5", storeFileUploadInFileAtSize, "POST /static HTTP/1.1\r\nHost: localhost\r\nContent-Length: " + postContent.Length + "\r\nContent-Type: multipart/form-data; boundary=abc\r\n\r\n" + postContent, (headers, content) =>
                    {
                        Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                        Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                        Assert.IsTrue(headers.Any(x => x.StartsWith("Content-Length: ")));
                        Assert.IsFalse(headers.Any(x => x.StartsWith("Accept-Ranges: ")));
                        Assert.AreEqual(expectedResponse, content.FromUtf8());
                    });

                    testRequest("POST test #6", storeFileUploadInFileAtSize, "POST /dynamic HTTP/1.1\r\nHost: localhost\r\nContent-Length: " + postContent.Length + "\r\nContent-Type: multipart/form-data; boundary=abc\r\n\r\n" + postContent, (headers, content) =>
                    {
                        Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                        Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                        Assert.IsFalse(headers.Any(x => x.StartsWith("Content-Length: ")));
                        Assert.IsFalse(headers.Any(x => x.StartsWith("Accept-Ranges: ")));
                        Assert.AreEqual(expectedResponse, content.FromUtf8());
                    });
                }
                finally
                {
                    instance.StopListening();
                }
            }
        }
Exemplo n.º 26
0
 private string DecodeResponseStream(Stream stream)
 {
     using (var gzipStream = new GZipStream(stream, CompressionMode.Decompress))
     {
         var decompressed = new List<byte>();
         int i;
         while ((i = gzipStream.ReadByte()) != -1)
             decompressed.Add((byte)i);
         return Encoding.UTF8.GetString(decompressed.ToArray());
     }
 }
Exemplo n.º 27
0
        public HttpWebResponse GetData(HttpWebRequest httpWebRequest, out string responseText)
        {
            ServicePointManager.Expect100Continue = false; //Resolve http 417 issue

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            Encoding encoding = GetEncoding(httpWebResponse.ContentType);

            using (Stream outStream = httpWebResponse.GetResponseStream())
            {
                string contentEncoding = httpWebResponse.ContentEncoding;

                if (contentEncoding.StartsWith("gzip"))
                {
                    MemoryStream ms = new MemoryStream();

                    using (Stream stream = new GZipStream(outStream, CompressionMode.Decompress))
                    {
                        int bit = stream.ReadByte();

                        while (bit > -1)
                        {
                            ms.WriteByte((byte)bit);
                            bit = stream.ReadByte();
                        }

                        responseText = encoding.GetString(ms.ToArray());
                    }
                }
                else if (contentEncoding.StartsWith("deflate"))
                {
                    MemoryStream ms = new MemoryStream();

                    using (Stream stream = new DeflateStream(outStream, CompressionMode.Decompress))
                    {
                        int bit = stream.ReadByte();

                        while (bit > -1)
                        {
                            ms.WriteByte((byte)bit);
                            bit = stream.ReadByte();
                        }

                        responseText = encoding.GetString(ms.ToArray());
                    }
                }
                else
                {
                    using (StreamReader sr = new StreamReader(outStream, encoding))
                    {
                        responseText = sr.ReadToEnd();
                    }
                }
            }

            return httpWebResponse;
        }