Beispiel #1
0
        public static IPEndPoint Parse(Stream s)
        {
            byte[] address;
            byte[] port = new byte[2];

            switch (s.ReadByte())
            {
            case 0:
                address = new byte[4];
                break;

            case 1:
                address = new byte[16];
                break;

            case -1:
                throw new EndOfStreamException();

            default:
                throw new NotSupportedException("AddressFamily not supported.");
            }

            OffsetStream.StreamRead(s, address, 0, address.Length);
            OffsetStream.StreamRead(s, port, 0, 2);

            return(new IPEndPoint(new IPAddress(address), BitConverter.ToUInt16(port, 0)));
        }
Beispiel #2
0
        public void WriteTest()
        {
            // Write one block
            using (MemoryStream memstream = new MemoryStream())
                using (OffsetStream offsetstream = new OffsetStream(memstream, this.offset)) {
                    Assert.AreEqual(0, memstream.Position);
                    Assert.AreEqual(this.offset, offsetstream.Position);
                    offsetstream.Write(this.content, 0, this.content.Length);
                    Assert.AreEqual(this.content.Length + this.offset, offsetstream.Position);
                    Assert.AreEqual(this.content, memstream.ToArray());
                }

            // Write single bytes
            using (MemoryStream memstream = new MemoryStream())
                using (OffsetStream offsetstream = new OffsetStream(memstream, this.offset)) {
                    Assert.AreEqual(0, memstream.Position);
                    Assert.AreEqual(this.offset, offsetstream.Position);
                    foreach (byte b in this.content)
                    {
                        offsetstream.WriteByte(b);
                    }

                    Assert.AreEqual(this.content.Length + this.offset, offsetstream.Position);
                    Assert.AreEqual(this.content, memstream.ToArray());
                }
        }
Beispiel #3
0
        public async Task DownloadLogAsync(HttpListenerRequest request, HttpListenerResponse response, string logName, long limit)
        {
            string logFileName = logName + ".log";

            using (FileStream fS = new FileStream(Path.Combine(ConvertToAbsolutePath(_logFolder), logFileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                response.ContentType = "text/plain";
                response.AddHeader("Content-Disposition", "attachment;filename=" + logFileName);

                if ((limit > fS.Length) || (limit < 1))
                {
                    limit = fS.Length;
                }

                OffsetStream oFS = new OffsetStream(fS, 0, limit);

                using (Stream s = WebService.GetOutputStream(request, response))
                {
                    await oFS.CopyToAsync(s);

                    if (fS.Length > limit)
                    {
                        byte[] buffer = Encoding.UTF8.GetBytes("####___TRUNCATED___####");
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
Beispiel #4
0
        public static void DownloadLog(HttpListenerResponse response, string logFile, long limit)
        {
            using (FileStream fS = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                response.ContentType = "text/plain";
                response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(logFile));

                if ((limit > fS.Length) || (limit < 1))
                {
                    limit = fS.Length;
                }

                OffsetStream oFS = new OffsetStream(fS, 0, limit);

                using (Stream s = response.OutputStream)
                {
                    oFS.CopyTo(s);

                    if (fS.Length > limit)
                    {
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes("####___TRUNCATED___####");
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
        public SecureChannelPacket(Stream s)
        {
            _code = (SecureChannelCode)s.ReadByte();

            if (_code == SecureChannelCode.None)
            {
                byte[] buffer = new byte[2];
                OffsetStream.StreamRead(s, buffer, 0, 2);
                ushort dataLen = BitConverter.ToUInt16(buffer, 0);

                if (dataLen > 0)
                {
                    _data = new byte[dataLen];
                    OffsetStream.StreamRead(s, _data, 0, _data.Length);
                }
                else
                {
                    _data = new byte[] { };
                }
            }
            else
            {
                throw new SecureChannelException(SecureChannelCode.RemoteError, null, null, "Error packet received from remote.", new SecureChannelException(_code, null, null));
            }
        }
        /// <summary>
        ///     Obtains a stream which can be used to read and write a cache file's meta in realtime.
        ///     The stream will be set up such that offsets in the stream correspond to meta pointers in the cache file.
        /// </summary>
        /// <param name="cacheFile">The cache file to get a stream for.</param>
        /// <returns>The stream if it was opened successfully, or null otherwise.</returns>
        public IStream GetMetaStream(ICacheFile cacheFile)
        {
            if (string.IsNullOrEmpty(ExecutableName))
            {
                throw new InvalidOperationException("No gameExecutable value found in Engines.xml for engine " + _buildInfo.Name + ".");
            }
            if (_buildInfo.Poking == null)
            {
                throw new InvalidOperationException("No poking definitions found in Engines.xml for engine " + _buildInfo.Name + ".");
            }

            Process gameProcess = FindGameProcess();

            if (gameProcess == null)
            {
                return(null);
            }

            string version = gameProcess.MainModule.FileVersionInfo.FileVersion;
            long   pointer = _buildInfo.Poking.RetrievePointer(version);

            if (pointer == -1)
            {
                throw new InvalidOperationException("Game version " + version + " does not have a pointer defined in the Formats folder.");
            }

            var gameMemory = new ProcessMemoryStream(gameProcess);
            var mapInfo    = new H2VistaMapPointerReader(gameMemory, pointer);

            long metaAddress;

            if (cacheFile.Type != CacheFileType.Shared)
            {
                metaAddress = mapInfo.CurrentMetaAddress;

                // The map isn't shared, so make sure the map names match
                if (mapInfo.MapName != cacheFile.InternalName)
                {
                    gameMemory.Close();
                    return(null);
                }
            }
            else
            {
                metaAddress = mapInfo.SharedMetaAddress;

                // Make sure the shared and current map pointers are different,
                // or that the current map is the shared map
                if (mapInfo.MapType != CacheFileType.Shared && mapInfo.CurrentMetaAddress == mapInfo.SharedMetaAddress)
                {
                    gameMemory.Close();
                    return(null);
                }
            }

            var metaStream = new OffsetStream(gameMemory, metaAddress - cacheFile.MetaArea.BasePointer);

            return(new EndianStream(metaStream, BitConverter.IsLittleEndian ? Endian.LittleEndian : Endian.BigEndian));
        }
 public void Encrypt(Stream clearText, Stream cipherText, int bufferSize = 128 * 1024)
 {
     using (CryptoStream cW = new CryptoStream(cipherText, _symAlgo.CreateEncryptor(), CryptoStreamMode.Write))
     {
         OffsetStream.StreamCopy(clearText, cW, bufferSize);
         cW.FlushFinalBlock();
     }
 }
        public async Task WriteToTcpAsync(Stream s, MemoryStream sharedBuffer)
        {
            OffsetStream sharedBufferOffset = new OffsetStream(sharedBuffer);

            if ((_question.Count > 0) && (_question[0].Type == DnsResourceRecordType.AXFR))
            {
                int iQD = 0;
                int iAN = 0;
                int QDCOUNT;
                int ANCOUNT;
                List <DnsDomainOffset> domainEntries = new List <DnsDomainOffset>(1);

                do
                {
                    sharedBuffer.SetLength(0);
                    sharedBufferOffset.Reset(2, 12, 12);

                    QDCOUNT = 0;
                    ANCOUNT = 0;
                    domainEntries.Clear();

                    for (; iQD < _question.Count; iQD++, QDCOUNT++)
                    {
                        _question[iQD].WriteTo(sharedBufferOffset, domainEntries);
                    }

                    for (; iAN < _answer.Count; iAN++, ANCOUNT++)
                    {
                        _answer[iAN].WriteTo(sharedBufferOffset, domainEntries);

                        if (sharedBuffer.Length >= 16384)
                        {
                            break;
                        }
                    }

                    sharedBuffer.Position = 0;
                    WriteUInt16NetworkOrder(Convert.ToUInt16(sharedBuffer.Length - 2), sharedBuffer);
                    WriteHeaders(sharedBuffer, QDCOUNT, ANCOUNT, 0, 0);

                    sharedBuffer.Position = 0;
                    await sharedBuffer.CopyToAsync(s, 512);
                }while (iAN < _answer.Count);
            }
            else
            {
                sharedBuffer.SetLength(0);
                sharedBufferOffset.Reset(2, 0, 0);
                WriteDatagram(sharedBufferOffset);

                sharedBuffer.Position = 0;
                WriteUInt16NetworkOrder(Convert.ToUInt16(sharedBuffer.Length - 2), sharedBuffer);

                sharedBuffer.Position = 0;
                await sharedBuffer.CopyToAsync(s, 512);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Geats a stream for reading from the cabinet file. For use by subclasses.
        /// </summary>
        protected internal Stream GetCabinetReadStream()
        {
            Stream stream = this.fileInfo.OpenRead();
            long   offset = Cabinet.FindCabinetOffset(new DuplicateStream(stream));

            if (offset > 0)
            {
                stream = new OffsetStream(stream, offset);
            }
            return(stream);
        }
        public BinaryID(Stream s)
        {
            int length = s.ReadByte();

            if (length < 0)
            {
                throw new EndOfStreamException();
            }

            _id = new byte[length];
            OffsetStream.StreamRead(s, _id, 0, length);
        }
Beispiel #11
0
        public void SeekTest()
        {
            using (MemoryStream memstream = new MemoryStream(this.content))
                using (OffsetStream offsetstream = new OffsetStream(memstream, this.offset))
                {
                    Assert.True(offsetstream.CanSeek);
                    Assert.AreEqual(memstream.CanSeek, offsetstream.CanSeek);
                    Assert.AreEqual(memstream.Position + this.offset, offsetstream.Position);
                    long pos = offsetstream.Seek(10, SeekOrigin.Begin);
                    Assert.AreEqual(110, pos);
                    Assert.AreEqual(10, memstream.Position);
                    pos = offsetstream.Seek(0, SeekOrigin.End);
                    Assert.AreEqual(offsetstream.Length, pos);
                    Assert.AreEqual(memstream.Length, memstream.Position);
                    pos = offsetstream.Seek(0, SeekOrigin.Current);
                    Assert.AreEqual(offsetstream.Length, pos);
                    Assert.AreEqual(memstream.Length, memstream.Position);
                    offsetstream.Seek(10, SeekOrigin.Begin);
                    pos = offsetstream.Seek(10, SeekOrigin.Current);
                    Assert.AreEqual(this.offset + 20, pos);
                    Assert.AreEqual(20, memstream.Position);

                    // negative seek
                    pos = offsetstream.Seek(-10, SeekOrigin.Current);
                    Assert.AreEqual(this.offset + 10, pos);
                    Assert.AreEqual(10, memstream.Position);
                    pos = offsetstream.Seek(-10, SeekOrigin.Current);
                    Assert.AreEqual(this.offset, pos);
                    Assert.AreEqual(0, memstream.Position);

                    // seek into illegal areas
                    try
                    {
                        pos = offsetstream.Seek(-10, SeekOrigin.Current);
                        Assert.Fail();
                    }
                    catch (IOException)
                    {
                    }

                    Assert.AreEqual(this.offset, pos);
                    Assert.AreEqual(0, memstream.Position);
                }

            // Using an unseekable stream should return CanSeek = false
            var mockstream = new Mock <Stream>();

            mockstream.SetupGet(s => s.CanSeek).Returns(false);
            using (OffsetStream offsetstream = new OffsetStream(mockstream.Object)) {
                Assert.False(offsetstream.CanSeek);
            }
        }
Beispiel #12
0
        /// <summary>
        ///     Obtains a stream which can be used to read and write a cache file's meta in realtime.
        ///     The stream will be set up such that offsets in the stream correspond to meta pointers in the cache file.
        /// </summary>
        /// <param name="cacheFile">The cache file to get a stream for.</param>
        /// <returns>The stream if it was opened successfully, or null otherwise.</returns>
        public IStream GetMetaStream(ICacheFile cacheFile)
        {
            if (string.IsNullOrEmpty(_buildInfo.PokingExecutable))
            {
                throw new InvalidOperationException("No gameExecutable value found in Engines.xml for engine " + _buildInfo.Name + ".");
            }
            if (_buildInfo.Poking == null)
            {
                throw new InvalidOperationException("No poking definitions found in Engines.xml for engine " + _buildInfo.Name + ".");
            }

            Process gameProcess = FindGameProcess();

            if (gameProcess == null)
            {
                return(null);
            }

            string version = gameProcess.MainModule.FileVersionInfo.FileVersion;

            PokingInformation info = _buildInfo.Poking.RetrieveInformation(version);

            if (info == null)
            {
                throw new InvalidOperationException("Game version " + version + " does not have poking information defined in the Formats folder.");
            }

            if (!info.HeaderAddress.HasValue)
            {
                throw new NotImplementedException("First Generation poking requires a HeaderAddress value.");
            }
            if (!info.MagicAddress.HasValue)
            {
                throw new NotImplementedException("First Generation poking requires a MagicAddress value.");
            }

            var gameMemory = new ProcessMemoryStream(gameProcess);
            var mapInfo    = new FirstGenMapPointerReader(gameMemory, _buildInfo, info);

            long metaAddress = mapInfo.CurrentCacheAddress;

            if (mapInfo.MapName != cacheFile.InternalName)
            {
                gameMemory.Close();
                return(null);
            }

            var metaStream = new OffsetStream(gameMemory, metaAddress - cacheFile.MetaArea.BasePointer);

            return(new EndianStream(metaStream, BitConverter.IsLittleEndian ? Endian.LittleEndian : Endian.BigEndian));
        }
Beispiel #13
0
        public PeerInfo(Stream s)
        {
            byte[] buffer = new byte[s.ReadByte()];
            OffsetStream.StreamRead(s, buffer, 0, buffer.Length);
            _peerEmail = Encoding.UTF8.GetString(buffer);

            int count = s.ReadByte();

            _peerEPList = new List <IPEndPoint>(count);

            for (int i = 0; i < count; i++)
            {
                _peerEPList.Add(IPEndPointParser.Parse(s));
            }
        }
Beispiel #14
0
            public KeyExchange(Stream s)
            {
                byte[] buffer = new byte[2];
                ushort length;

                OffsetStream.StreamRead(s, buffer, 0, 2);
                length     = BitConverter.ToUInt16(buffer, 0);
                _publicKey = new byte[length];
                OffsetStream.StreamRead(s, _publicKey, 0, length);

                OffsetStream.StreamRead(s, buffer, 0, 2);
                length     = BitConverter.ToUInt16(buffer, 0);
                _signature = new byte[length];
                OffsetStream.StreamRead(s, _signature, 0, length);
            }
        public SharedFileMetaData(Stream s)
        {
            switch (s.ReadByte()) //version
            {
            case 1:
                int    length;
                byte[] buffer = new byte[255];

                length = s.ReadByte();
                OffsetStream.StreamRead(s, buffer, 0, length);
                _fileName = Encoding.UTF8.GetString(buffer, 0, length);

                length = s.ReadByte();
                OffsetStream.StreamRead(s, buffer, 0, length);
                _contentType = new ContentType(Encoding.UTF8.GetString(buffer, 0, length));

                OffsetStream.StreamRead(s, buffer, 0, 8);
                _lastModified = _epoch.AddSeconds(BitConverter.ToInt64(buffer, 0));

                OffsetStream.StreamRead(s, buffer, 0, 8);
                _fileSize = BitConverter.ToInt64(buffer, 0);

                OffsetStream.StreamRead(s, buffer, 0, 4);
                _blockSize = BitConverter.ToInt32(buffer, 0);

                length = s.ReadByte();
                OffsetStream.StreamRead(s, buffer, 0, length);
                _hashAlgo = Encoding.ASCII.GetString(buffer, 0, length);

                int totalBlocks = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((double)_fileSize / _blockSize)));

                _blockHash = new byte[totalBlocks][];

                int hashLength = s.ReadByte();

                for (int i = 0; i < totalBlocks; i++)
                {
                    _blockHash[i] = new byte[hashLength];
                    OffsetStream.StreamRead(s, _blockHash[i], 0, hashLength);
                }

                _fileID = ComputeFileID();
                break;

            default:
                throw new BitChatException("FileMetaData format version not supported.");
            }
        }
Beispiel #16
0
 public void ReadTest()
 {
     // Read block
     byte[] buffer = new byte[this.contentLength];
     using (MemoryStream memstream = new MemoryStream(this.content))
         using (OffsetStream offsetstream = new OffsetStream(memstream, this.offset)) {
             Assert.AreEqual(0, memstream.Position);
             Assert.AreEqual(this.offset, offsetstream.Position);
             int len = offsetstream.Read(buffer, 0, buffer.Length);
             Assert.AreEqual(this.contentLength, len);
             Assert.AreEqual(this.contentLength + this.offset, offsetstream.Position);
             Assert.AreEqual(this.content, buffer);
             len = offsetstream.Read(buffer, 0, buffer.Length);
             Assert.AreEqual(0, len);
         }
 }
Beispiel #17
0
        public static byte[] ReadData(Stream s)
        {
            int dataLen = Convert.ToInt32(s.Length - s.Position);

            if (dataLen > 0)
            {
                byte[] buffer = new byte[dataLen];
                OffsetStream.StreamRead(s, buffer, 0, dataLen);

                return(buffer);
            }
            else
            {
                return(new byte[] { });
            }
        }
Beispiel #18
0
        /// <summary>
        ///  Uploads the file.
        ///  Resumes an upload if the given localFileStream.Position is larger than zero.
        /// </summary>
        /// <returns>
        ///  The new CMIS document.
        /// </returns>
        /// <param name='remoteDocument'>
        ///  Remote document where the local content should be uploaded to.
        /// </param>
        /// <param name='localFileStream'>
        ///  Local file stream.
        /// </param>
        /// <param name='status'>
        ///  Transmission status where the uploader should report its uploading status.
        /// </param>
        /// <param name='hashAlg'>
        ///  Hash alg which should be used to calculate a checksum over the uploaded content.
        /// </param>
        /// <param name='overwrite'>
        ///  If true, the local content will overwrite the existing content.
        /// </param>
        /// <exception cref="CmisSync.Lib.Tasks.UploadFailedException">
        /// Contains the last successful remote document state. This is needed for continue a failed upload.
        /// </exception>
        public override IDocument UploadFile(IDocument remoteDocument, Stream localFileStream, FileTransmissionEvent status, HashAlgorithm hashAlg, bool overwrite = true)
        {
            IDocument result = remoteDocument;

            for (long offset = localFileStream.Position; offset < localFileStream.Length; offset += this.ChunkSize)
            {
                bool isFirstChunk = offset == 0;
                bool isLastChunk  = (offset + this.ChunkSize) >= localFileStream.Length;
                using (NonClosingHashStream hashstream = new NonClosingHashStream(localFileStream, hashAlg, CryptoStreamMode.Read))
                    using (ChunkedStream chunkstream = new ChunkedStream(hashstream, this.ChunkSize))
                        using (OffsetStream offsetstream = new OffsetStream(chunkstream, offset))
                            using (ProgressStream progressstream = new ProgressStream(offsetstream, status))
                            {
                                status.Status.Length         = localFileStream.Length;
                                status.Status.ActualPosition = offset;
                                chunkstream.ChunkPosition    = offset;

                                ContentStream contentStream = new ContentStream();
                                contentStream.FileName = remoteDocument.Name;
                                contentStream.MimeType = Cmis.MimeType.GetMIMEType(remoteDocument.Name);
                                if (isLastChunk)
                                {
                                    contentStream.Length = localFileStream.Length - offset;
                                }
                                else
                                {
                                    contentStream.Length = this.ChunkSize;
                                }

                                contentStream.Stream = progressstream;
                                try {
                                    if (isFirstChunk && result.ContentStreamId != null && overwrite)
                                    {
                                        result.DeleteContentStream(true);
                                    }

                                    result.AppendContentStream(contentStream, isLastChunk, true);
                                } catch (Exception e) {
                                    throw new UploadFailedException(e, result);
                                }
                            }
            }

            hashAlg.TransformFinalBlock(new byte[0], 0, 0);
            return(result);
        }
Beispiel #19
0
        /// <summary>
        /// Geats a stream for writing to the cabinet file. For use by subclasses.
        /// </summary>
        protected internal Stream GetCabinetWriteStream()
        {
            Stream stream = this.fileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite);
            long   offset = Cabinet.FindCabinetOffset(new DuplicateStream(stream));

            // If this is not a cabinet file, append the cab to it.
            if (offset < 0)
            {
                offset = stream.Length;
            }

            if (offset > 0)
            {
                stream = new OffsetStream(stream, offset);
            }
            return(stream);
        }
        /// <summary>
        ///     Obtains a stream which can be used to read and write a cache file's meta in realtime.
        ///     The stream will be set up such that offsets in the stream correspond to meta pointers in the cache file.
        /// </summary>
        /// <param name="cacheFile">The cache file to get a stream for.</param>
        /// <returns>The stream if it was opened successfully, or null otherwise.</returns>
        public override IStream GetMetaStream(ICacheFile cacheFile = null)
        {
            if (!CheckBuildInfo())
            {
                return(null);
            }

            Process gameProcess = FindGameProcess();

            if (gameProcess == null)
            {
                return(null);
            }

            PokingInformation info = RetrieveInformation(gameProcess);

            if (!info.HeaderPointer.HasValue && (!info.HeaderAddress.HasValue || !info.MagicAddress.HasValue))
            {
                throw new NotImplementedException("Poking information is missing required values.");
            }

            var gameMemory = new ProcessModuleMemoryStream(gameProcess, _buildInfo.GameModule);
            var mapInfo    = new ThirdGenMapPointerReader(gameMemory, _buildInfo, info);

            long metaMagic = mapInfo.CurrentCacheAddress;

            if (gameMemory.BaseModule == null)
            {
                return(null);
            }

            if (mapInfo.MapName != cacheFile.InternalName)
            {
                gameMemory.Close();
                return(null);
            }

            if (metaMagic == 0)
            {
                return(null);
            }

            var metaStream = new OffsetStream(gameMemory, metaMagic);

            return(new EndianStream(metaStream, BitConverter.IsLittleEndian ? Endian.LittleEndian : Endian.BigEndian));
        }
Beispiel #21
0
            public DiscoveryPacket(Stream s)
            {
                switch (s.ReadByte())
                {
                case 5:     //query
                {
                    byte[] bufferChallenge = new byte[32];
                    byte[] bufferHmac      = new byte[32];

                    OffsetStream.StreamRead(s, bufferChallenge, 0, 32);
                    OffsetStream.StreamRead(s, bufferHmac, 0, 32);

                    _isResponse = false;
                    _challenge  = new BinaryNumber(bufferChallenge);
                    _hmac       = new BinaryNumber(bufferHmac);
                }
                break;

                case 6:     //response
                {
                    byte[] bufferServicePort = new byte[2];
                    byte[] bufferChallenge   = new byte[32];
                    byte[] bufferHmac        = new byte[32];

                    OffsetStream.StreamRead(s, bufferServicePort, 0, 2);
                    OffsetStream.StreamRead(s, bufferChallenge, 0, 32);
                    OffsetStream.StreamRead(s, bufferHmac, 0, 32);

                    _isResponse  = true;
                    _servicePort = BitConverter.ToUInt16(bufferServicePort, 0);
                    _challenge   = new BinaryNumber(bufferChallenge);
                    _hmac        = new BinaryNumber(bufferHmac);
                }
                break;

                case -1:
                    throw new EndOfStreamException();

                default:
                    throw new IOException("Invalid local discovery packet.");
                }
            }
Beispiel #22
0
        /// <summary>
        ///     Obtains a stream which can be used to read and write a cache file's meta in realtime.
        ///     The stream will be set up such that offsets in the stream correspond to meta pointers in the cache file.
        /// </summary>
        /// <param name="cacheFile">The cache file to get a stream for.</param>
        /// <returns>The stream if it was opened successfully, or null otherwise.</returns>
        public IStream GetMetaStream(ICacheFile cacheFile)
        {
            Process gameProcess = FindGameProcess();

            if (gameProcess == null)
            {
                return(null);
            }

            var gameMemory = new ProcessMemoryStream(gameProcess);
            var mapInfo    = new H2VistaMapPointerReader(gameMemory);

            long metaAddress;

            if (cacheFile.Type != CacheFileType.Shared)
            {
                metaAddress = mapInfo.CurrentMetaAddress;

                // The map isn't shared, so make sure the map names match
                if (mapInfo.MapName != cacheFile.InternalName)
                {
                    gameMemory.Close();
                    return(null);
                }
            }
            else
            {
                metaAddress = mapInfo.SharedMetaAddress;

                // Make sure the shared and current map pointers are different,
                // or that the current map is the shared map
                if (mapInfo.MapType != CacheFileType.Shared && mapInfo.CurrentMetaAddress == mapInfo.SharedMetaAddress)
                {
                    gameMemory.Close();
                    return(null);
                }
            }

            var metaStream = new OffsetStream(gameMemory, metaAddress - cacheFile.MetaArea.BasePointer);

            return(new EndianStream(metaStream, BitConverter.IsLittleEndian ? Endian.LittleEndian : Endian.BigEndian));
        }
Beispiel #23
0
            internal void FeedReadBuffer(Stream s, int timeout)
            {
                int count     = Convert.ToInt32(s.Length - s.Position);
                int readCount = _readBuffer.Length;

                while (count > 0)
                {
                    lock (this)
                    {
                        if (_disposed)
                        {
                            throw new ObjectDisposedException("ChannelStream");
                        }

                        if (_readBufferCount > 0)
                        {
                            if (!Monitor.Wait(this, timeout))
                            {
                                throw new IOException("Channel FeedReadBuffer timed out.");
                            }

                            if (_readBufferCount > 0)
                            {
                                throw new IOException("Channel FeedReadBuffer failed. Buffer not empty.");
                            }
                        }

                        if (count < readCount)
                        {
                            readCount = count;
                        }

                        OffsetStream.StreamRead(s, _readBuffer, 0, readCount);
                        _readBufferOffset = 0;
                        _readBufferCount  = readCount;
                        count            -= readCount;

                        Monitor.Pulse(this);
                    }
                }
            }
Beispiel #24
0
        public void LengthTest()
        {
            // static length test
            using (MemoryStream memstream = new MemoryStream(this.content))
                using (OffsetStream offsetstream = new OffsetStream(memstream, this.offset)) {
                    Assert.AreEqual(this.offset + this.content.Length, offsetstream.Length);
                }

            // dynamic length test
            using (MemoryStream memstream = new MemoryStream())
                using (OffsetStream offsetstream = new OffsetStream(memstream, this.offset)) {
                    Assert.AreEqual(0, memstream.Length);
                    Assert.AreEqual(this.offset, offsetstream.Length);
                    offsetstream.SetLength(200);
                    Assert.AreEqual(200, offsetstream.Length);
                    Assert.AreEqual(200 - this.offset, memstream.Length);
                    Assert.Throws <ArgumentOutOfRangeException>(() => offsetstream.SetLength(50));
                    Assert.AreEqual(200, offsetstream.Length);
                    Assert.AreEqual(200 - this.offset, memstream.Length);
                }
        }
Beispiel #25
0
        private List <string> ReadFileList(Stream s, TocEntry e)
        {
            var strings = new List <string>();

            using (var os = new OffsetStream(s, e.offset + 2, e.uncompressedSize - 2))
                using (var ds = new DeflateStream(os, CompressionMode.Decompress))
                {
                    var bytes = new byte[e.uncompressedSize];
                    ds.Read(bytes, 0, (int)e.uncompressedSize);
                    using (var ms = new MemoryStream(bytes))
                        using (var textReader = new StreamReader(ms))
                        {
                            while (!textReader.EndOfStream)
                            {
                                strings.Add(textReader.ReadLine());
                            }
                        }
                }

            return(strings);
        }
Beispiel #26
0
        private int DownloadNextChunk(IDocument remoteDocument, long offset, long remainingBytes, FileTransmissionEvent status, Stream outputstream, HashAlgorithm hashAlg)
        {
            lock (this.disposeLock)
            {
                if (this.disposed)
                {
                    status.ReportProgress(new TransmissionProgressEventArgs()
                    {
                        Aborted = true
                    });
                    throw new ObjectDisposedException(status.Path);
                }

                IContentStream contentStream = remoteDocument.GetContentStream(remoteDocument.ContentStreamId, offset, remainingBytes);
                status.ReportProgress(new TransmissionProgressEventArgs {
                    Length         = remoteDocument.ContentStreamLength,
                    ActualPosition = offset,
                    Resumed        = offset > 0
                });

                using (Stream remoteStream = contentStream.Stream)
                    using (ForwardReadingStream forwardstream = new ForwardReadingStream(remoteStream))
                        using (OffsetStream offsetstream = new OffsetStream(forwardstream, offset))
                            using (ProgressStream progress = new ProgressStream(offsetstream, status))
                            {
                                byte[] buffer = new byte[8 * 1024];
                                int    result = 0;
                                int    len;
                                while ((len = progress.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    outputstream.Write(buffer, 0, len);
                                    hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
                                    result += len;
                                    outputstream.Flush();
                                }

                                return(result);
                            }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Writes your PKG to the given stream.
        /// Assumes exclusive use of the stream (writes are absolute, relative to 0)
        /// </summary>
        /// <param name="s"></param>
        /// <returns>Completed Pkg structure</returns>
        public Pkg Write(Stream s)
        {
            var pkg    = BuildPkg();
            var writer = new PkgWriter(s);

            // Write PFS first, to get stream length
            s.Position = (long)pkg.Header.pfs_image_offset;
            var pfsStream = new OffsetStream(s, s.Position);

            new PFS.PfsBuilder().BuildPfs(new PFS.PfsProperties
            {
                BlockSize = 65536,
                output    = pfsStream,
                proj      = project,
                projDir   = projectDir,
            });
            var align = s.Length % 65536;

            if (align != 0)
            {
                s.SetLength(s.Length + 65536 - align);
            }

            // TODO: Encrypt PFS (could also be done while writing image)
            // TODO: Generate hashes in Entries (body)
            // TODO: Calculate keys in entries (image key, etc)

            // Write body now because it will make calculating hashes easier.
            writer.WriteBody(pkg);

            CalcHeaderHashes(pkg, s);

            // Update header sizes now that we know how big things are...
            UpdateHeaderInfo(pkg, s.Length, pfsStream.Length);

            // Now write header
            s.Position = 0;
            writer.WritePkg(pkg);
            return(pkg);
        }
Beispiel #28
0
        public void ResumeTest()
        {
            byte[] inputContent = new byte[100];
            long   offset       = 100;

            using (Stream stream = new MemoryStream(inputContent))
                using (OffsetStream offsetstream = new OffsetStream(stream, offset))
                {
                    FileTransmissionEvent transmissionEvent = new FileTransmissionEvent(this.transmissionType, this.filename);
                    transmissionEvent.TransmissionStatus += delegate(object sender, TransmissionProgressEventArgs args) {
                        if (args.ActualPosition != null && args.Percent != null)
                        {
                            this.position = (long)args.ActualPosition;
                            this.percent  = (double)args.Percent;
                        }
                    };
                    using (ProgressStream progress = new ProgressStream(offsetstream, transmissionEvent)) {
                        progress.Seek(0, SeekOrigin.Begin);
                        Assert.AreEqual(offset, this.position);
                        Assert.AreEqual(50, this.percent);
                        progress.Seek(10, SeekOrigin.Current);
                        Assert.AreEqual(offset + 10, this.position);
                        progress.Seek(0, SeekOrigin.End);
                        Assert.AreEqual(100, this.percent);
                        Assert.AreEqual(offset + inputContent.Length, this.position);
                        progress.Seek(0, SeekOrigin.Begin);
                        progress.WriteByte(0);
                        Assert.AreEqual(offset + 1, this.position);
                        Assert.AreEqual(50.5, this.percent);
                        progress.WriteByte(0);
                        Assert.AreEqual(offset + 2, this.position);
                        Assert.AreEqual(51, this.percent);
                        progress.Write(new byte[10], 0, 10);
                        Assert.AreEqual(56, this.percent);
                    }
                }
        }
Beispiel #29
0
        public override Stream OpenArchiveWriteStream(int archiveNumber, string archiveName, bool truncate, CompressionEngine compressionEngine)
        {
            if (string.IsNullOrEmpty(archiveName))
            {
                throw new ArgumentNullException("archiveName");
            }
            string path = Path.Combine(Path.GetDirectoryName(ArchiveFiles[0]), archiveName);

            if (truncate)
            {
                if (!DictionaryStringMemoryStream.ContainsKey(path))
                {
                    DictionaryStringMemoryStream[path] = new MemoryStream();
                }
            }

            Stream stream = DictionaryStringMemoryStream[path];

            if (EnableOffsetOpen)
            {
                long num = compressionEngine.FindArchiveOffset(new DuplicateStream(stream));
                if (num < 0L)
                {
                    num = stream.Length;
                }
                if (num > 0L)
                {
                    stream = new OffsetStream(stream, num);
                }
                stream.Seek(0L, SeekOrigin.Begin);
            }
            if (truncate)
            {
                stream.SetLength(0L);
            }
            return(stream);
        }
Beispiel #30
0
        public override Stream OpenArchiveReadStream(int archiveNumber, string archiveName, CompressionEngine compressionEngine)
        {
            if (archiveNumber >= ArchiveFiles.Count)
            {
                return(null);
            }

            string path   = ArchiveFiles[archiveNumber];
            Stream stream = DictionaryStringMemoryStream[path];

            if (EnableOffsetOpen)
            {
                long num = compressionEngine.FindArchiveOffset(new DuplicateStream(stream));
                if (num > 0L)
                {
                    stream = new OffsetStream(stream, num);
                }
                else
                {
                    stream.Seek(0L, SeekOrigin.Begin);
                }
            }
            return(stream);
        }
Beispiel #31
0
        public static Extractor FromFile([NotNull] string path, [NotNull] string target, [CanBeNull] string mimeType = null, long startOffset = 0)
        {
            if (string.IsNullOrEmpty(mimeType)) mimeType = Archive.GuessMimeType(path);

            // MSI Extractor does not support Stream-based access
            if (mimeType == Archive.MimeTypeMsi) return new MsiExtractor(path, target);

            Stream stream = File.OpenRead(path);
            if (startOffset != 0) stream = new OffsetStream(stream, startOffset);

            try
            {
                return FromStream(stream, target, mimeType);
            }
            catch
            {
                stream.Dispose();
                throw;
            }
        }