コード例 #1
0
        public override System.IO.Stream Receive(TimeSpan timeout, Information options)
        {
            if (_disposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (!_connect) throw new ConnectionException();

            lock (_receiveLock)
            {
                Stream stream = null;

                try
                {
                    stream = _connection.Receive(timeout, options);

                    var version = (byte)stream.ReadByte();

                    Stream dataStream = null;

                    try
                    {
                        dataStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position);

                        if (version == (byte)0)
                        {
                            return dataStream;
                        }
                        else if (version == (byte)1)
                        {
                            BufferStream deflateBufferStream = null;

                            try
                            {
                                deflateBufferStream = new BufferStream(_bufferManager);

                                using (DeflateStream deflateStream = new DeflateStream(dataStream, CompressionMode.Decompress, true))
                                using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 4))
                                {
                                    int length;

                                    while ((length = deflateStream.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0)
                                    {
                                        deflateBufferStream.Write(safeBuffer.Value, 0, length);

                                        if (deflateBufferStream.Length > _maxReceiveCount) throw new ConnectionException();
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                if (deflateBufferStream != null)
                                {
                                    deflateBufferStream.Dispose();
                                }

                                throw e;
                            }

            #if DEBUG
                            Debug.WriteLine("Receive : {0}→{1} {2}",
                                NetworkConverter.ToSizeString(stream.Length),
                                NetworkConverter.ToSizeString(deflateBufferStream.Length),
                                NetworkConverter.ToSizeString(stream.Length - deflateBufferStream.Length));
            #endif

                            deflateBufferStream.Seek(0, SeekOrigin.Begin);
                            dataStream.Dispose();

                            return deflateBufferStream;
                        }
                        else
                        {
                            throw new ArgumentException("ArgumentException");
                        }
                    }
                    catch (ConnectionException e)
                    {
                        if (dataStream != null) dataStream.Dispose();

                        throw e;
                    }
                    catch (Exception e)
                    {
                        if (dataStream != null) dataStream.Dispose();

                        throw new ConnectionException(e.Message, e);
                    }
                }
                catch (ConnectionException e)
                {
                    if (stream != null) stream.Dispose();

                    throw e;
                }
                catch (Exception e)
                {
                    if (stream != null) stream.Dispose();

                    throw new ConnectionException(e.Message, e);
                }
            }
        }
コード例 #2
0
        public override void Send(System.IO.Stream stream, TimeSpan timeout, Information options)
        {
            if (_disposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (!_connect) throw new ConnectionException();
            if (stream == null) throw new ArgumentNullException(nameof(stream));
            if (stream.Length == 0) throw new ArgumentOutOfRangeException(nameof(stream));

            bool isCompress = true;

            if (options != null)
            {
                if (options.Contains("IsCompress")) isCompress = (bool)options["IsCompress"];
            }

            lock (_sendLock)
            {
                using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                {
                    try
                    {
                        var list = new List<KeyValuePair<byte, Stream>>();

                        if (isCompress)
                        {
                            if (_otherCompressAlgorithm.HasFlag(CompressAlgorithm.Deflate))
                            {
                                BufferStream deflateBufferStream = null;

                                try
                                {
                                    deflateBufferStream = new BufferStream(_bufferManager);

                                    using (DeflateStream deflateStream = new DeflateStream(deflateBufferStream, CompressionMode.Compress, true))
                                    using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 4))
                                    {
                                        int length;

                                        while ((length = targetStream.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0)
                                        {
                                            deflateStream.Write(safeBuffer.Value, 0, length);
                                        }
                                    }

                                    deflateBufferStream.Seek(0, SeekOrigin.Begin);

                                    list.Add(new KeyValuePair<byte, Stream>((byte)1, deflateBufferStream));
                                }
                                catch (Exception e)
                                {
                                    if (deflateBufferStream != null)
                                    {
                                        deflateBufferStream.Dispose();
                                    }

                                    throw e;
                                }
                            }
                        }

                        list.Add(new KeyValuePair<byte, Stream>((byte)0, new WrapperStream(targetStream, true)));

                        list.Sort((x, y) =>
                        {
                            int c = x.Value.Length.CompareTo(y.Value.Length);
                            if (c != 0) return c;

                            return x.Key.CompareTo(y.Key);
                        });

            #if DEBUG
                        if (list[0].Value.Length != targetStream.Length)
                        {
                            Debug.WriteLine("Send : {0}→{1} {2}",
                                NetworkConverter.ToSizeString(targetStream.Length),
                                NetworkConverter.ToSizeString(list[0].Value.Length),
                                NetworkConverter.ToSizeString(list[0].Value.Length - targetStream.Length));
                        }
            #endif

                        for (int i = 1; i < list.Count; i++)
                        {
                            list[i].Value.Dispose();
                        }

                        var headerStream = new BufferStream(_bufferManager);
                        headerStream.WriteByte((byte)list[0].Key);

                        using (var dataStream = new UniteStream(headerStream, list[0].Value))
                        {
                            _connection.Send(dataStream, timeout, options);
                        }
                    }
                    catch (ConnectionException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw new ConnectionException(e.Message, e);
                    }
                }
            }
        }
コード例 #3
0
        public override void Send(Stream stream, TimeSpan timeout, Information options)
        {
            if (_disposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (!_connect) throw new ConnectionException();
            if (stream == null) throw new ArgumentNullException(nameof(stream));
            if (stream.Length == 0) throw new ArgumentOutOfRangeException(nameof(stream));

            lock (_sendLock)
            {
                using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                {
                    try
                    {
                        _sendStopwatch.Restart();

                        Stream headerStream = new BufferStream(_bufferManager);
                        headerStream.Write(NetworkConverter.GetBytes((int)targetStream.Length), 0, 4);

                        using (Stream dataStream = new UniteStream(headerStream, new WrapperStream(targetStream, true)))
                        using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 32))
                        {
                            for (;;)
                            {
                                var sendLength = (int)Math.Min(dataStream.Length - dataStream.Position, safeBuffer.Value.Length);
                                if (sendLength == 0) break;

                                if (_bandwidthLimit != null && _bandwidthLimit.Out != 0)
                                {
                                    sendLength = _bandwidthLimit.GetOutBandwidth(this, sendLength);
                                    if (sendLength < 0) throw new ConnectionException();
                                }

                                dataStream.Read(safeBuffer.Value, 0, sendLength);

                                var time = Connection.CheckTimeout(_sendStopwatch.Elapsed, timeout);
                                time = (time < _sendTimeSpan) ? time : _sendTimeSpan;

                                _cap.Send(safeBuffer.Value, 0, sendLength, time);

                                _aliveStopwatch.Restart();
                                _sentByteCount.Add(sendLength);
                            }
                        }

                        _aliveTimer.Change(1000 * 30);
                    }
                    catch (ConnectionException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw new ConnectionException(e.Message, e);
                    }
                }
            }
        }
コード例 #4
0
        public void Test_RangeStream()
        {
            using (MemoryStream memoryStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }))
            {
                byte[] mbyte = new byte[4];
                memoryStream.Seek(7, SeekOrigin.Begin);
                memoryStream.Read(mbyte, 0, mbyte.Length);
                memoryStream.Seek(5, SeekOrigin.Begin);

                using (RangeStream rangeStream = new RangeStream(memoryStream, 7, 4))
                {
                    Assert.AreEqual(memoryStream.Position, 7, "RangeStream #1");
                    Assert.AreEqual(rangeStream.Position, 0, "RangeStream #2");

                    byte[] rbyte = new byte[4];
                    rangeStream.Read(rbyte, 0, rbyte.Length);

                    Assert.AreEqual(rangeStream.Length, 4, "RangeStream #3");
                    Assert.IsTrue(CollectionUtilities.Equals(mbyte, rbyte), "RangeStream #4");
                }
            }
        }
コード例 #5
0
        public override void Send(System.IO.Stream stream, TimeSpan timeout, Information options)
        {
            if (_disposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (!_connect) throw new ConnectionException();
            if (stream == null) throw new ArgumentNullException(nameof(stream));
            if (stream.Length == 0) throw new ArgumentOutOfRangeException(nameof(stream));

            lock (_sendLock)
            {
                using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                {
                    try
                    {
                        using (MemoryStream crcStream = new MemoryStream(Crc32_Castagnoli.ComputeHash(targetStream)))
                        using (Stream dataStream = new UniteStream(new WrapperStream(targetStream, true), crcStream))
                        {
                            _connection.Send(dataStream, timeout, options);
                        }
                    }
                    catch (ConnectionException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw new ConnectionException(e.Message, e);
                    }
                }
            }
        }
コード例 #6
0
        public override void Send(Stream stream, TimeSpan timeout, Information options)
        {
            if (_disposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (stream == null) throw new ArgumentNullException("stream");
            if (stream.Length == 0) throw new ArgumentOutOfRangeException("stream");
            if (!_connect) throw new ConnectionException();

            lock (_sendLock)
            {
                try
                {
                    using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true))
                    {
                        if (_version.HasFlag(SecureConnectionVersion.Version3))
                        {
                            using (BufferStream bufferStream = new BufferStream(_bufferManager))
                            {
                                bufferStream.SetLength(8);
                                bufferStream.Seek(8, SeekOrigin.Begin);

                                if (_informationVersion3.CryptoAlgorithm.HasFlag(SecureVersion3.CryptoAlgorithm.Aes256))
                                {
                                    byte[] iv = new byte[16];
                                    _random.GetBytes(iv);
                                    bufferStream.Write(iv, 0, iv.Length);

                                    using (var aes = Aes.Create())
                                    {
                                        aes.KeySize = 256;
                                        aes.Mode = CipherMode.CBC;
                                        aes.Padding = PaddingMode.PKCS7;

                                        using (CryptoStream cs = new CryptoStream(new WrapperStream(bufferStream, true), aes.CreateEncryptor(_informationVersion3.MyCryptoKey, iv), CryptoStreamMode.Write))
                                        {
                                            byte[] sendBuffer = null;

                                            try
                                            {
                                                sendBuffer = _bufferManager.TakeBuffer(1024 * 4);

                                                int i = -1;

                                                while ((i = targetStream.Read(sendBuffer, 0, sendBuffer.Length)) > 0)
                                                {
                                                    cs.Write(sendBuffer, 0, i);
                                                }
                                            }
                                            finally
                                            {
                                                if (sendBuffer != null)
                                                {
                                                    _bufferManager.ReturnBuffer(sendBuffer);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    throw new ConnectionException();
                                }

                                _totalSendSize += (bufferStream.Length - 8);

                                bufferStream.Seek(0, SeekOrigin.Begin);

                                byte[] totalSendSizeBuff = NetworkConverter.GetBytes(_totalSendSize);
                                bufferStream.Write(totalSendSizeBuff, 0, totalSendSizeBuff.Length);

                                if (_informationVersion3.HashAlgorithm.HasFlag(SecureVersion3.HashAlgorithm.Sha256))
                                {
                                    bufferStream.Seek(0, SeekOrigin.Begin);
                                    byte[] hmacBuff = HmacSha256.ComputeHash(bufferStream, _informationVersion3.MyHmacKey);

                                    bufferStream.Seek(0, SeekOrigin.End);
                                    bufferStream.Write(hmacBuff, 0, hmacBuff.Length);
                                }
                                else
                                {
                                    throw new ConnectionException();
                                }

                                bufferStream.Seek(0, SeekOrigin.Begin);

                                _connection.Send(bufferStream, timeout, options);
                            }
                        }
                        else
                        {
                            throw new ConnectionException();
                        }
                    }
                }
                catch (ConnectionException e)
                {
                    throw e;
                }
                catch (Exception e)
                {
                    throw new ConnectionException(e.Message, e);
                }
            }
        }
コード例 #7
0
        private static Stream RemoveType(Stream stream, string type)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            Encoding encoding = new UTF8Encoding(false);

            byte[] lengthBuffer = new byte[4];
            if (stream.Read(lengthBuffer, 0, lengthBuffer.Length) != lengthBuffer.Length) throw new FormatException();
            int length = NetworkConverter.ToInt32(lengthBuffer);

            using (RangeStream rangeStream = new RangeStream(stream, stream.Position, length, true))
            {
                using (StreamReader reader = new StreamReader(rangeStream, encoding))
                {
                    if (type != reader.ReadToEnd()) throw new FormatException();
                }
            }

            return new RangeStream(stream, true);
        }
コード例 #8
0
        public override System.IO.Stream Receive(TimeSpan timeout, Information options)
        {
            if (_disposed) throw new ObjectDisposedException(this.GetType().FullName);
            if (!_connect) throw new ConnectionException();

            lock (_receiveLock)
            {
                Stream stream = null;
                RangeStream dataStream = null;

                try
                {
                    stream = _connection.Receive(timeout, options);

                    dataStream = new RangeStream(stream, 0, stream.Length - 4);
                    byte[] verifyCrc = Crc32_Castagnoli.ComputeHash(dataStream);
                    byte[] orignalCrc = new byte[4];

                    using (RangeStream crcStream = new RangeStream(stream, stream.Length - 4, 4, true))
                    {
                        crcStream.Read(orignalCrc, 0, orignalCrc.Length);
                    }

                    if (!Unsafe.Equals(verifyCrc, orignalCrc)) throw new ArgumentException("Crc Error");

                    dataStream.Seek(0, SeekOrigin.Begin);
                    return dataStream;
                }
                catch (ConnectionException e)
                {
                    if (stream != null) stream.Dispose();
                    if (dataStream != null) dataStream.Dispose();

                    throw e;
                }
                catch (Exception e)
                {
                    if (stream != null) stream.Dispose();
                    if (dataStream != null) dataStream.Dispose();

                    throw new ConnectionException(e.Message, e);
                }
            }
        }
コード例 #9
0
        private static Stream RemoveHash(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            byte type = (byte)stream.ReadByte();

            if (type == (byte)ConvertHashAlgorithm.Sha256)
            {
                Stream dataStream = null;

                try
                {
                    byte[] hash = new byte[32];

                    using (RangeStream hashStream = new RangeStream(stream, stream.Length - 32, 32, true))
                    {
                        hashStream.Read(hash, 0, hash.Length);
                    }

                    dataStream = new RangeStream(stream, 1, stream.Length - (1 + 32));
                    if (!Unsafe.Equals(hash, Sha256.ComputeHash(dataStream))) throw new FormatException();

                    dataStream.Seek(0, SeekOrigin.Begin);

                    return dataStream;
                }
                catch (Exception)
                {
                    if (dataStream != null)
                    {
                        dataStream.Dispose();
                    }

                    throw;
                }
            }

            throw new NotSupportedException();
        }
コード例 #10
0
        private static Stream Decrypt(Stream stream, IExchangeDecrypt privateKey)
        {
            if (stream == null) throw new ArgumentNullException("stream");
            if (privateKey == null) throw new ArgumentNullException("privateKey");

            try
            {
                byte type = (byte)stream.ReadByte();

                if (type == (byte)ConvertCryptoAlgorithm.Aes256)
                {
                    byte[] cryptoKey;

                    {
                        byte[] lengthBuffer = new byte[4];
                        if (stream.Read(lengthBuffer, 0, lengthBuffer.Length) != lengthBuffer.Length) throw new ArgumentException();
                        int length = NetworkConverter.ToInt32(lengthBuffer);

                        byte[] encryptedBuffer = new byte[length];
                        if (stream.Read(encryptedBuffer, 0, encryptedBuffer.Length) != encryptedBuffer.Length) throw new ArgumentException();

                        cryptoKey = Exchange.Decrypt(privateKey, encryptedBuffer);
                    }

                    BufferStream outStream = null;

                    try
                    {
                        outStream = new BufferStream(_bufferManager);

                        using (Stream dataStream = new WrapperStream(stream, true))
                        {
                            var iv = new byte[32];
                            dataStream.Read(iv, 0, iv.Length);

                            using (var rijndael = new RijndaelManaged() { KeySize = 256, BlockSize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
                            using (var inStream = new RangeStream(dataStream, dataStream.Position, dataStream.Length - dataStream.Position))
                            using (CryptoStream cs = new CryptoStream(inStream, rijndael.CreateDecryptor(cryptoKey, iv), CryptoStreamMode.Read))
                            {
                                byte[] buffer = null;

                                try
                                {
                                    buffer = _bufferManager.TakeBuffer(1024 * 4);

                                    int i = -1;

                                    while ((i = cs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        outStream.Write(buffer, 0, i);
                                    }
                                }
                                finally
                                {
                                    _bufferManager.ReturnBuffer(buffer);
                                }
                            }
                        }

                        outStream.Seek(0, SeekOrigin.Begin);
                    }
                    catch (Exception)
                    {
                        if (outStream != null)
                        {
                            outStream.Dispose();
                        }

                        throw;
                    }

                    return outStream;
                }

                throw new NotSupportedException();
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message, e);
            }
        }
コード例 #11
0
        private static Stream Decompress(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            try
            {
                var targetStream = new RangeStream(stream, true);

                byte type = (byte)targetStream.ReadByte();

                if (type == (byte)ConvertCompressionAlgorithm.None)
                {
                    return new RangeStream(targetStream);
                }
                else if (type == (byte)ConvertCompressionAlgorithm.Deflate)
                {
                    using (Stream dataStream = new WrapperStream(targetStream, true))
                    {
                        BufferStream deflateBufferStream = null;

                        try
                        {
                            deflateBufferStream = new BufferStream(_bufferManager);

                            using (DeflateStream deflateStream = new DeflateStream(dataStream, CompressionMode.Decompress, true))
                            {
                                byte[] decompressBuffer = null;

                                try
                                {
                                    decompressBuffer = _bufferManager.TakeBuffer(1024 * 4);

                                    int i = -1;

                                    while ((i = deflateStream.Read(decompressBuffer, 0, decompressBuffer.Length)) > 0)
                                    {
                                        deflateBufferStream.Write(decompressBuffer, 0, i);
                                    }
                                }
                                finally
                                {
                                    if (decompressBuffer != null)
                                    {
                                        _bufferManager.ReturnBuffer(decompressBuffer);
                                    }
                                }
                            }

                            deflateBufferStream.Seek(0, SeekOrigin.Begin);

            #if DEBUG
                            Debug.WriteLine("ContentConverter Decompress {3} : {0}→{1} {2}",
                                NetworkConverter.ToSizeString(dataStream.Length),
                                NetworkConverter.ToSizeString(deflateBufferStream.Length),
                                NetworkConverter.ToSizeString(dataStream.Length - deflateBufferStream.Length),
                                ConvertCompressionAlgorithm.Deflate);
            #endif

                            return deflateBufferStream;
                        }
                        catch (Exception)
                        {
                            if (deflateBufferStream != null)
                            {
                                deflateBufferStream.Dispose();
                            }
                        }
                    }
                }

                throw new ArgumentException("ArgumentException");
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message, e);
            }
        }
コード例 #12
0
        private static Stream Compress(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            var targetStream = new RangeStream(stream, true);

            List<KeyValuePair<byte, Stream>> list = new List<KeyValuePair<byte, Stream>>();

            try
            {
                targetStream.Seek(0, SeekOrigin.Begin);

                BufferStream deflateBufferStream = null;

                try
                {
                    deflateBufferStream = new BufferStream(_bufferManager);

                    using (DeflateStream deflateStream = new DeflateStream(deflateBufferStream, CompressionMode.Compress, true))
                    {
                        byte[] compressBuffer = null;

                        try
                        {
                            compressBuffer = _bufferManager.TakeBuffer(1024 * 4);

                            int i = -1;

                            while ((i = targetStream.Read(compressBuffer, 0, compressBuffer.Length)) > 0)
                            {
                                deflateStream.Write(compressBuffer, 0, i);
                            }
                        }
                        finally
                        {
                            if (compressBuffer != null)
                            {
                                _bufferManager.ReturnBuffer(compressBuffer);
                            }
                        }
                    }

                    deflateBufferStream.Seek(0, SeekOrigin.Begin);

                    list.Add(new KeyValuePair<byte, Stream>((byte)ConvertCompressionAlgorithm.Deflate, deflateBufferStream));
                }
                catch (Exception)
                {
                    if (deflateBufferStream != null)
                    {
                        deflateBufferStream.Dispose();
                    }
                }
            }
            catch (Exception)
            {

            }

            list.Add(new KeyValuePair<byte, Stream>((byte)ConvertCompressionAlgorithm.None, targetStream));

            list.Sort((x, y) =>
            {
                int c = x.Value.Length.CompareTo(y.Value.Length);
                if (c != 0) return c;

                return x.Key.CompareTo(y.Key);
            });

            #if DEBUG
            if (list[0].Value.Length != targetStream.Length)
            {
                Debug.WriteLine("ContentConverter Compress {3} : {0}→{1} {2}",
                    NetworkConverter.ToSizeString(targetStream.Length),
                    NetworkConverter.ToSizeString(list[0].Value.Length),
                    NetworkConverter.ToSizeString(list[0].Value.Length - targetStream.Length),
                    (ConvertCompressionAlgorithm)list[0].Key);
            }
            #endif

            for (int i = 1; i < list.Count; i++)
            {
                list[i].Value.Dispose();
            }

            BufferStream metadataStream = new BufferStream(_bufferManager);
            metadataStream.WriteByte((byte)list[0].Key);

            return new UniteStream(metadataStream, list[0].Value);
        }
コード例 #13
0
        private static Stream AddHash(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            try
            {
                var targetStream = new RangeStream(stream, true);

                BufferStream metadataStream = new BufferStream(_bufferManager);
                metadataStream.WriteByte((byte)ConvertHashAlgorithm.Sha256);

                targetStream.Seek(0, SeekOrigin.Begin);
                var hash = Sha256.ComputeHash(targetStream);

                BufferStream hashStream = new BufferStream(_bufferManager);
                hashStream.Write(hash, 0, hash.Length);

                return new UniteStream(metadataStream, targetStream, hashStream);
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message, e);
            }
        }