Пример #1
0
 /// <summary>
 /// Reads a bounty from a stream.
 /// </summary>
 public static Bounty Read(InStream Stream)
 {
     return new Bounty
     {
         Base = Stream.ReadDouble(),
         Decay = Stream.ReadDouble()
     };
 }
Пример #2
0
        //////////////////////////////////////////////////////////////////////////
        // Constructor
        //////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Construct for input stream.
        /// </summary>
        public ObjDecoder(InStream @in, Map options)
        {
            tokenizer    = new Tokenizer(@in);
            this.options = options;
            consume();
        }
Пример #3
0
        /// <summary>
        /// Reads a packet from a stream with the given size in bytes or returns null if the packet cannot be parsed.
        /// </summary>
        public static Packet Read(InStream Stream, int Size)
        {
            Packet packet = new Packet();

            // Read flags and header
            if ((Size -= StreamSize.Byte + StreamSize.Int) < 0)
                return null;
            PacketFlags flags = (PacketFlags)Stream.ReadByte();
            packet.SequenceNumber = Stream.ReadInt();
            packet.PingRequest = (flags & PacketFlags.PingRequest) == PacketFlags.PingRequest;
            packet.PingResponse = (flags & PacketFlags.PingResponse) == PacketFlags.PingResponse;

            // Read additional information
            if ((flags & PacketFlags.Acknowledgement) == PacketFlags.Acknowledgement)
            {
                if ((Size -= StreamSize.Int) < 0)
                    return null;
                packet.AcknowledgementNumber = Stream.ReadInt();
            }
            if ((flags & PacketFlags.RoundTripTime) == PacketFlags.RoundTripTime)
            {
                if ((Size -= StreamSize.Double) < 0)
                    return null;
                packet.RoundTripTime = Stream.ReadDouble();
            }

            // Read chunk if any
            if ((flags & PacketFlags.Chunk) == PacketFlags.Chunk)
            {
                packet.ChunkInitial = (flags & PacketFlags.ChunkInitial) == PacketFlags.ChunkInitial;
                packet.ChunkFinal = (flags & PacketFlags.ChunkFinal) == PacketFlags.ChunkFinal;

                byte[] data = new byte[Size];
                Stream.Read(data, 0, data.Length);
                packet.ChunkData = data;

                return packet;
            }
            else
            {
                // A packet can only be a disconnect if it does not have a chunk
                packet.Disconnect = (flags & PacketFlags.Disconnect) == PacketFlags.Disconnect;

                // Make sure this is the end of the packet
                if (Size == 0)
                    return packet;
                else
                    return null;
            }
        }
Пример #4
0
        public void Start()
        {
            Stop();
            Running = true;
            _cancellationTokenSource = new CancellationTokenSource();

            ReadFinished = false;
            _readTask    = Task.Run(async() =>
            {
                while (Running && _cancellationTokenSource?.IsCancellationRequested == false)
                {
                    try
                    {
                        if (InStream.CanRead)
                        {
                            AudioChunk chunk = new AudioChunk(BufferReadSize);

                            int bytesRead = await InStream.ReadAsync(chunk.Memory, _cancellationTokenSource.Token).ConfigureAwait(false);
                            if (bytesRead > 0)
                            {
                                chunk.Length = bytesRead;

                                // Wait for the dequeue, comparing in megabytes.
                                while (Running && (Queue.Count * (BufferReadSize * 0.000001)) > BufferLimit)
                                {
                                    await Task.Delay(100, _cancellationTokenSource?.Token ?? CancellationToken.None).ConfigureAwait(false);
                                }
                                Queue.Enqueue(chunk);
                            }
                            else
                            {
                                Log.Debug("AudioBuffer: Read EOF");
                                break;
                            }
                        }
                        else
                        {
                            Log.Error("AudioBuffer: Could not read InStream.");
                            await Task.Delay(25).ConfigureAwait(false);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"AudioBuffer | {ex}");
                    }
                }

                ReadFinished = true;
            }, _cancellationTokenSource.Token);

            _writeTask = Task.Run(async() =>
            {
                while (Running && _cancellationTokenSource?.IsCancellationRequested == false)
                {
                    if (ReadFinished && Queue.IsEmpty)
                    {
                        break;
                    }

                    try
                    {
                        if (Queue.TryDequeue(out var audioChunk))
                        {
                            using (audioChunk)
                            {
                                if (OutStream.CanWrite)
                                {
                                    // We're required to process the chunks in the write task, it's far slower which allows us to change the volume while it's still playing.
                                    if (ProcessBuffer != null)
                                    {
                                        var bytes = audioChunk.Memory;
                                        if (audioChunk.Length != audioChunk.Memory.Length)
                                        {
                                            bytes = audioChunk.Memory.Part(0, audioChunk.Length, false).ToArray();
                                        }
                                        var processedBytes = ProcessBuffer?.Invoke(bytes);
                                        processedBytes.CopyTo(audioChunk.Memory, 0);
                                        audioChunk.Length = processedBytes.Length;
                                    }

                                    await OutStream.WriteAsync(audioChunk.Memory, 0, audioChunk.Length, _cancellationTokenSource.Token);
                                }
                                else
                                {
                                    Log.Error("AudioBuffer: Could not write to OutStream.");
                                    await Task.Delay(25).ConfigureAwait(false);
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"AudioBuffer | {ex.Message}");
                        Log.Debug($"AudioBuffer | {ex}");
                        await Task.Delay(25).ConfigureAwait(false);
                    }
                }
            }, _cancellationTokenSource.Token);
        }
        private SignatureStatus DecryptFile()
        {
            if (InStream.CanSeek)
            {
                InStream.Seek(0, SeekOrigin.Begin);
            }
            var inputStream = PgpUtilities.GetDecoderStream(InStream);

            try
            {
                PgpObjectFactory     pgpF = new PgpObjectFactory(inputStream);
                PgpEncryptedDataList enc;

                PgpObject o = pgpF.NextPgpObject();
                //
                // the first object might be a PGP marker packet.
                //
                if (o is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)o;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
                }


                var privateKeys = GetAllPrivateKeys();
                //
                // find the secret key
                //
                PgpPrivateKey             sKey = null;
                PgpPublicKeyEncryptedData pbe  = null;

                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = FindPrivateKey(privateKeys, pked.KeyId);

                    if (sKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }

                if (sKey == null)
                {
                    throw new SecretKeyNotFound("secret key for message not found.");
                }

                Stream clear = pbe.GetDataStream(sKey);

                PgpLiteralData          pgpLiteralData       = null;
                PgpOnePassSignatureList onePassSignatureList = null;
                PgpSignatureList        signatureList        = null;

                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(clear);
                var pgpObject = pgpObjectFactory.NextPgpObject();
                while (pgpObject != null)
                {
                    if (pgpObject is PgpCompressedData)
                    {
                        var compressedData = (PgpCompressedData)pgpObject;
                        pgpObjectFactory = new PgpObjectFactory(compressedData.GetDataStream());
                        pgpObject        = pgpObjectFactory.NextPgpObject();
                    }

                    if (pgpObject is PgpLiteralData)
                    {
                        pgpLiteralData = pgpObject as PgpLiteralData;
                        //must read directly to continue reading next pgp objects
                        Stream unc = pgpLiteralData.GetInputStream();
                        Streams.PipeAll(unc, OutStream);
                    }
                    else if (pgpObject is PgpOnePassSignatureList)
                    {
                        onePassSignatureList = pgpObject as PgpOnePassSignatureList;
                    }
                    else if (pgpObject is PgpSignatureList)
                    {
                        signatureList = pgpObject as PgpSignatureList;
                    }

                    pgpObject = pgpObjectFactory.NextPgpObject();
                }

                if (pgpLiteralData == null)
                {
                    throw new PgpLitralDataNotFound("couldn't find pgp literal data");
                }



                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        throw new PgpIntegrityCheckFailed("message failed integrity check");
                    }
                }

                if (CheckSignature)
                {
                    if (onePassSignatureList == null || signatureList == null)
                    {
                        return(SignatureStatus.NoSignature);
                    }
                    else
                    {
                        return(VerifyFileSignature(OutStream, onePassSignatureList, signatureList));
                    }
                }
                else
                {
                    return(SignatureStatus.NotChecked);
                }
            }
            catch
            {
                throw;
            }
        }
Пример #6
0
        //////////////////////////////////////////////////////////////////////////
        // Construction
        //////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Construct for specified input stream.
        /// </summary>
        public Tokenizer(InStream @in)
        {
            m_in = @in;
            consume();
            consume();
        }
Пример #7
0
 public override int Read(byte[] buffer, int offset, int count) => InStream.Read(buffer, offset, count);
        public void runSeekTest(CompressionCodec codec)
        {
            TestInStream.OutputCollector collect = new TestInStream.OutputCollector();
            RunLengthIntegerWriterV2     @out    = new RunLengthIntegerWriterV2(
                new OutStream("test", 1000, codec, collect), true);

            TestInStream.PositionCollector[] positions =
                new TestInStream.PositionCollector[4096];
            Random random = new Random(99);

            int[] junk = new int[2048];
            for (int i = 0; i < junk.Length; ++i)
            {
                junk[i] = random.Next();
            }
            for (int i = 0; i < 4096; ++i)
            {
                positions[i] = new TestInStream.PositionCollector();
                @out.getPosition(positions[i]);
                // test runs, incrementing runs, non-runs
                if (i < 1024)
                {
                    @out.write(i / 4);
                }
                else if (i < 2048)
                {
                    @out.write(2 * i);
                }
                else
                {
                    @out.write(junk[i - 2048]);
                }
            }
            @out.flush();
            ByteBuffer inBuf = ByteBuffer.allocate(collect.buffer.size());

            collect.buffer.setByteBuffer(inBuf, 0, collect.buffer.size());
            inBuf.flip();
#pragma warning disable 612
            RunLengthIntegerReaderV2 @in =
                new RunLengthIntegerReaderV2(InStream.create
                                                 (null, "test", new ByteBuffer[] { inBuf },
                                                 new long[] { 0 }, inBuf.remaining(),
                                                 codec, 1000), true, false);
#pragma warning restore 612
            for (int i = 0; i < 2048; ++i)
            {
                int x = (int)@in.next();
                if (i < 1024)
                {
                    Assert.Equal(i / 4, x);
                }
                else if (i < 2048)
                {
                    Assert.Equal(2 * i, x);
                }
                else
                {
                    Assert.Equal(junk[i - 2048], x);
                }
            }
            for (int i = 2047; i >= 0; --i)
            {
                @in.seek(positions[i]);
                int x = (int)@in.next();
                if (i < 1024)
                {
                    Assert.Equal(i / 4, x);
                }
                else if (i < 2048)
                {
                    Assert.Equal(2 * i, x);
                }
                else
                {
                    Assert.Equal(junk[i - 2048], x);
                }
            }
        }
Пример #9
0
 public Message Read(InStream Stream)
 {
     return this._Read(Stream);
 }
Пример #10
0
 public static new Message Read(InStream Stream)
 {
     return new DataRequestMessage
     {
         Index = ID.Read(Stream),
         Region = DataRegion.Read(Stream),
         Bounty = Bounty.Read(Stream)
     };
 }
Пример #11
0
 /// <summary>
 /// Reads a message from a stream.
 /// </summary>
 public static Message Read(InStream Stream)
 {
     MessageType type = MessageType.ForID(Stream.ReadByte());
     return type.Read(Stream);
 }
Пример #12
0
        public void testUncompressedDisjointBuffers()
        {
            OutputCollector collect = new OutputCollector();
            OutStream       @out    = new OutStream("test", 400, null, collect);

            PositionCollector[] positions = new PositionCollector[1024];
            DataOutput          stream    = new DataOutputStream(@out);

            for (int i = 0; i < 1024; ++i)
            {
                positions[i] = new PositionCollector();
                @out.getPosition(positions[i]);
                stream.writeInt(i);
            }
            @out.Flush();
            Assert.Equal("test", @out.ToString());
            Assert.Equal(4096, collect.buffer.size());
            ByteBuffer[] inBuf = new ByteBuffer[3];
            inBuf[0] = ByteBuffer.allocate(1100);
            inBuf[1] = ByteBuffer.allocate(2200);
            inBuf[2] = ByteBuffer.allocate(1100);
            collect.buffer.setByteBuffer(inBuf[0], 0, 1024);
            collect.buffer.setByteBuffer(inBuf[1], 1024, 2048);
            collect.buffer.setByteBuffer(inBuf[2], 3072, 1024);

            for (int i = 0; i < inBuf.Length; ++i)
            {
                inBuf[i].flip();
            }
            InStream @in = InStream.create(null, "test", inBuf,
                                           new long[] { 0, 1024, 3072 }, 4096, null, 400);

            Assert.Equal("uncompressed stream test position: 0 length: 4096" +
                         " range: 0 offset: 0 limit: 0",
                         @in.ToString());
            DataInputStream inStream = new DataInputStream(@in);

            for (int i = 0; i < 1024; ++i)
            {
                int x = inStream.readInt();
                Assert.Equal(i, x);
            }
            Assert.Equal(0, @in.available());
            for (int i = 1023; i >= 0; --i)
            {
                @in.seek(positions[i]);
                Assert.Equal(i, inStream.readInt());
            }

            @in = InStream.create(null, "test", new ByteBuffer[] { inBuf[1], inBuf[2] },
                                  new long[] { 1024, 3072 }, 4096, null, 400);
            inStream = new DataInputStream(@in);
            positions[256].reset();
            @in.seek(positions[256]);
            for (int i = 256; i < 1024; ++i)
            {
                Assert.Equal(i, inStream.readInt());
            }

            @in = InStream.create(null, "test", new ByteBuffer[] { inBuf[0], inBuf[2] },
                                  new long[] { 0, 3072 }, 4096, null, 400);
            inStream = new DataInputStream(@in);
            positions[768].reset();
            for (int i = 0; i < 256; ++i)
            {
                Assert.Equal(i, inStream.readInt());
            }
            @in.seek(positions[768]);
            for (int i = 768; i < 1024; ++i)
            {
                Assert.Equal(i, inStream.readInt());
            }
        }
Пример #13
0
        public void testDisjointBuffers()
        {
            OutputCollector  collect = new OutputCollector();
            CompressionCodec codec   = new ZlibCodec();
            OutStream        @out    = new OutStream("test", 400, codec, collect);

            PositionCollector[] positions = new PositionCollector[1024];
            DataOutput          stream    = new DataOutputStream(@out);

            for (int i = 0; i < 1024; ++i)
            {
                positions[i] = new PositionCollector();
                @out.getPosition(positions[i]);
                stream.writeInt(i);
            }
            @out.Flush();
            Assert.Equal("test", @out.ToString());
            Assert.Equal(1674, collect.buffer.size());
            ByteBuffer[] inBuf = new ByteBuffer[3];
            inBuf[0] = ByteBuffer.allocate(500);
            inBuf[1] = ByteBuffer.allocate(1200);
            inBuf[2] = ByteBuffer.allocate(500);
            collect.buffer.setByteBuffer(inBuf[0], 0, 483);
            collect.buffer.setByteBuffer(inBuf[1], 483, 1625 - 483);
            collect.buffer.setByteBuffer(inBuf[2], 1625, 1674 - 1625);

            for (int i = 0; i < inBuf.Length; ++i)
            {
                inBuf[i].flip();
            }
            InStream @in = InStream.create(null, "test", inBuf,
                                           new long[] { 0, 483, 1625 }, 1674, codec, 400);

            Assert.Equal("compressed stream test position: 0 length: 1674 range: 0" +
                         " offset: 0 limit: 0 range 0 = 0 to 483;" +
                         "  range 1 = 483 to 1142;  range 2 = 1625 to 49",
                         @in.ToString());
            DataInputStream inStream = new DataInputStream(@in);

            for (int i = 0; i < 1024; ++i)
            {
                int x = inStream.readInt();
                Assert.Equal(i, x);
            }
            Assert.Equal(0, @in.available());
            for (int i = 1023; i >= 0; --i)
            {
                @in.seek(positions[i]);
                Assert.Equal(i, inStream.readInt());
            }

            @in = InStream.create(null, "test", new ByteBuffer[] { inBuf[1], inBuf[2] },
                                  new long[] { 483, 1625 }, 1674, codec, 400);
            inStream = new DataInputStream(@in);
            positions[303].reset();
            @in.seek(positions[303]);
            for (int i = 303; i < 1024; ++i)
            {
                Assert.Equal(i, inStream.readInt());
            }

            @in = InStream.create(null, "test", new ByteBuffer[] { inBuf[0], inBuf[2] },
                                  new long[] { 0, 1625 }, 1674, codec, 400);
            inStream = new DataInputStream(@in);
            positions[1001].reset();
            for (int i = 0; i < 300; ++i)
            {
                Assert.Equal(i, inStream.readInt());
            }
            @in.seek(positions[1001]);
            for (int i = 1001; i < 1024; ++i)
            {
                Assert.Equal(i, inStream.readInt());
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            Console.Title = "Test3";

            /*if (args.Length == 0)
             *      args = new string[] { "maps_q3.pk3" };*/

            int TargetVer = 0;
            int StartIdx  = 0;

            if (args.Length == 0)
            {
                Console.WriteLine("bspconv [version] file(.bsp|.pk3) [file2(.bsp|.pk3)]+");
                Console.WriteLine();
                Console.WriteLine("\tversion - 46 (Quake 3) or 47 (Quake Live), output version. Input version any.");
                return;
            }

            if (args.Length > 1 && int.TryParse(args[0], out TargetVer))
            {
                StartIdx = 1;
            }
            else
            {
                TargetVer = 47;
                StartIdx  = 0;
            }


            Console.WriteLine("Converting to IBSP {0}", TargetVer);


            for (int i = StartIdx; i < args.Length; i++)
            {
                string FileNameExt = args[i];

                if (!File.Exists(FileNameExt))
                {
                    Console.WriteLine("Could not find {0}", FileNameExt);
                    continue;
                }

                string FileName  = Path.GetFileNameWithoutExtension(FileNameExt);
                string Extension = Path.GetExtension(FileNameExt);
                string OutName   = FileName + "_IBSP" + TargetVer + Extension;

                if (Extension == ".bsp")
                {
                    Console.WriteLine("Converting {0}", FileNameExt);

                    BSP Map = BSP.FromFile(FileNameExt);
                    Map.Version = TargetVer;

                    File.WriteAllBytes(OutName, Map.ToByteArray());
                }
                else if (Extension == ".pk3")
                {
                    OpenZip(FileNameExt, true, (In) => {
                        OpenZip(OutName, false, (Out) => {
                            int EntryNum = 0;
                            int Count    = In.Entries.Count;

                            foreach (var Entry in In.Entries)
                            {
                                Console.Title = string.Format("{0:0}%", ((float)EntryNum / Count) * 100);
                                EntryNum++;

                                if (Entry.Length == 0)
                                {
                                    continue;
                                }

                                string EntryExt          = Path.GetExtension(Entry.FullName);
                                ZipArchiveEntry OutEntry = Out.CreateEntry(Entry.FullName, CompressionLevel.Optimal);

                                OpenEntry(Entry, true, (InStream) => {
                                    if (EntryExt == ".bsp")
                                    {
                                        Console.WriteLine("Converting {0}", Entry.FullName);

                                        BSP Map     = BSP.FromStream(InStream);
                                        Map.Version = TargetVer;

                                        OpenEntry(OutEntry, false, (OutStream) => Map.Serialize(OutStream));
                                    }
                                    else
                                    {
                                        OpenEntry(OutEntry, false, (OutStream) => InStream.CopyTo(OutStream));
                                    }
                                });
                            }
                        });
                    });
                }
                else
                {
                    Console.WriteLine("Skipping {0}, unknown extension type {1}", FileNameExt, Extension);
                }
            }
        }
Пример #15
0
 public override abstract void Deserialize(InStream inStream);
Пример #16
0
 public abstract void Deserialize(InStream inStream);