Пример #1
0
 public override ImageData Read(IBinaryStream stream, ImageMetaData info)
 {
     using (var proxy = new ProxyStream(stream.AsStream, true))
         using (var crypt = new InputCryptoStream(proxy, new TigTransform()))
             using (var input = new BinaryStream(crypt, stream.Name))
                 return(base.Read(input, info));
 }
Пример #2
0
        protected Handler(ProxyStream stream, CancellationToken token)
        {
            this.ProxyStream = stream;

            this.CancelSource = CancellationTokenSource.CreateLinkedTokenSource(token);
            this.CancelSource.Token.Register(stream.Close);
        }
Пример #3
0
        public async Task <HttpObj> ProcessAsync(ProcessItem item)
        {
            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(item.HttpRequest.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, item.HttpRequest.Body);
            var section = await reader.ReadNextSectionAsync();

            //body
            ValidateSection(section);
            var ms = new MemoryStream();
            await section.Body.CopyToAsync(ms);

            var body    = Encoding.UTF8.GetString(ms.ToArray());
            var dataObj = Helper.ToHttpDataObj(body, item.DataObjType !);

            //stream
            section = await reader.ReadNextSectionAsync();

            ValidateSection(section);
            var fileName = GetFileName(section.ContentDisposition);

            if (fileName == null)
            {
                throw new ArgumentNullException("", "File name is null.");
            }
            dataObj.TrySetStreamName(fileName);
            var proxyStream = new ProxyStream(section.Body, dataObj.StreamLength);

            return(new HttpObj {
                HttpDataObj = dataObj, ProxyStream = proxyStream
            });
        }
Пример #4
0
        public async Task <(HttpDataObj obj, ProxyStream stream)> GetFromFormDataAsync(Type dataObjType)
        {
            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(_context.Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, _context.Request.Body);
            var section = await reader.ReadNextSectionAsync();

            //body
            ValidateSection(section);
            MemoryStream ms = new MemoryStream();
            await section.Body.CopyToAsync(ms);

            var body    = Encoding.UTF8.GetString(ms.ToArray());
            var dataObj = Helper.ToHttpDataObj(body, dataObjType);

            //stream
            section = await reader.ReadNextSectionAsync();

            ValidateSection(section);
            var fileName = GetFileName(section.ContentDisposition);

            dataObj.TrySetStreamName(fileName);
            var proxyStream = new ProxyStream(section.Body, dataObj.StreamLength);

            return(dataObj, proxyStream);
        }
Пример #5
0
        public TunnelSslMitm(ProxyStream stream, CancellationToken token, X509Certificate2 certificate, SslProtocols sslProtocols, HandleFunc handler)
            : base(stream, token)
        {
            this.m_sslProtocols = sslProtocols;
            this.m_certificate  = certificate;

            this.m_handler = handler;
        }
Пример #6
0
        internal IBinaryStream OpenEncrypted(IBinaryStream stream, bool seekable = false)
        {
            Stream input = new ProxyStream(stream.AsStream, true);

            input = new InputCryptoStream(input, new TigTransform());
            if (seekable)
            {
                input = new SeekableStream(input);
            }
            return(new BinaryStream(input, stream.Name));
        }
Пример #7
0
        private void SocketThread(object socketObject)
        {
            using (var socket = (Socket)socketObject)
                using (var stream = new NetworkStream(socket))
                {
                    socket.ReceiveTimeout = 30 * 1000;
                    socket.SendTimeout    = 30 * 1000;

                    stream.ReadTimeout  = 30 * 1000;
                    stream.WriteTimeout = 30 * 1000;

                    var desc = $"{socket.LocalEndPoint} > {socket.RemoteEndPoint}";

                    LinkedListNode <Socket> socketNode;

                    this.m_connectionsBarrier.AddParticipant();
                    lock (this.m_connections)
                    {
                        socketNode = this.m_connections.AddLast(socket);
                        Console.WriteLine($"Connected {desc} ({this.m_connections.Count})");
                    }

                    try
                    {
                        using (var proxyStream = new ProxyStream(stream))
                            this.SocketThreadSub(proxyStream);
                    }
                    catch (Exception)
                    {
                    }

                    lock (this.m_connections)
                    {
                        this.m_connections.Remove(socketNode);
                        Console.WriteLine($"Disconnected {desc} {this.m_connections.Count}");
                    }
                    try
                    {
                        socket.Close();
                    }
                    catch
                    {
                    }

                    try
                    {
                        this.m_connectionsBarrier.RemoveParticipant();
                    }
                    catch
                    {
                    }
                }
        }
Пример #8
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            // Init the python engine

            ProxyStream InputStream  = new ProxyStream(1000);
            ProxyStream OutputStream = new ProxyStream(1000);
            ProxyStream ErrorStream  = new ProxyStream(1000);

            ScriptEngine engine = Python.CreateEngine();
            ScriptScope  scope  = engine.CreateScope();

            StreamReader OutputReader = new StreamReader(OutputStream);
            StreamWriter InputWriter  = new StreamWriter(InputStream);

            engine.Runtime.IO.SetInput(InputStream, Encoding.ASCII);
            engine.Runtime.IO.SetOutput(OutputStream, Encoding.ASCII);
            engine.Runtime.IO.SetErrorOutput(ErrorStream, Encoding.ASCII);

            scope.SetVariable("Axis1", AXISID.AXIS1);
            scope.SetVariable("Axis2", AXISID.AXIS2);
            scope.SetVariable("Controller", DynamicHelpers.GetPythonTypeFromType(typeof(Controller)));

            while (true)
            {
                if (Locked)
                {
                    OutputStream.clean();
                    try
                    {
                        backgroundWorker1.ReportProgress(2, mShellCommands);
                        var code = engine.CreateScriptSourceFromString(mShellCommands);
                        code.Execute(scope);
                    }
                    catch (Exception ee)
                    {
                        backgroundWorker1.ReportProgress(1, ee.ToString());
                        //textBox2.AppendText(string.Format("{0}{1}", Environment.NewLine, ee));
                    }


                    Locked = false;

                    OutputStream.Position = 0;
                    backgroundWorker1.ReportProgress(0, OutputReader.ReadToEnd());
                }
            }
        }
Пример #9
0
 void RewriteSegment(NpkSegment segment, int chunk_size)
 {
     using (var proxy = new ProxyStream(m_archive, true))
         using (var encryptor = m_aes.CreateEncryptor())
             using (var output = new CryptoStream(proxy, encryptor, CryptoStreamMode.Write))
             {
                 if (m_remaining == chunk_size)
                 {
                     m_input.CopyTo(output);
                 }
                 else
                 {
                     chunk_size = m_input.Read(m_buffer, 0, chunk_size);
                     output.Write(m_buffer, 0, chunk_size);
                 }
             }
     segment.UnpackedSize = segment.Size = (uint)chunk_size;
     segment.AlignedSize  = (uint)(m_archive.Position - segment.Offset);
 }
Пример #10
0
    //gets stream for reading uncompressed data
    //only one stream can be used at the same time
    public Stream GetStream(string fileName)
    {
        CentralDirectory dir        = m_centralDirEntries.Where(d => d.fileName == fileName).First();
        LocalFileHeader  fileHeader = LocalFileHeader.Read(m_reader, dir);

        switch (fileHeader.compressionMethod)
        {
        //no compression
        case 0:
            return(new ProxyStream(m_stream, dir.compressedSize));

        //deflate
        case 8:
            var proxy = new ProxyStream(m_stream, dir.compressedSize);
            return(new DeflateStream(proxy, CompressionMode.Decompress, true));
        }

        throw new NotSupportedException("Compression method not supported. Method id: " + fileHeader.compressionMethod);
    }
Пример #11
0
        NpkSegment WriteSegment(int chunk_size, bool compress)
        {
            var segment = new NpkSegment {
                Offset = m_archive.Position
            };

            using (var proxy = new ProxyStream(m_archive, true))
                using (var encryptor = m_aes.CreateEncryptor())
                {
                    Stream output  = new CryptoStream(proxy, encryptor, CryptoStreamMode.Write);
                    var    measure = new CountedStream(output);
                    output = measure;
                    if (compress)
                    {
                        output = new DeflateStream(output, CompressionLevel.Optimal);
                    }
                    using (output)
                    {
                        if (m_remaining == chunk_size)
                        {
                            var file_pos = m_input.Position;
                            m_input.CopyTo(output);
                            m_input.Position = file_pos;
                            m_input.CopyTo(m_checksum_stream);
                        }
                        else
                        {
                            chunk_size = m_input.Read(m_buffer, 0, chunk_size);
                            output.Write(m_buffer, 0, chunk_size);
                            m_checksum_stream.Write(m_buffer, 0, chunk_size);
                        }
                    }
                    segment.UnpackedSize = (uint)chunk_size;
                    segment.Size         = (uint)measure.Count;
                    segment.AlignedSize  = (uint)(m_archive.Position - segment.Offset);
                    return(segment);
                }
        }
Пример #12
0
 private ProxyRequest(Stream stream)
 {
     this.m_proxyStream = new ProxyStream(stream);
 }
Пример #13
0
        public override void Create(Stream output, IEnumerable <Entry> list, ResourceOptions options,
                                    EntryCallback callback)
        {
            var npk_options = GetOptions <Npk2Options> (options);

            if (null == npk_options.Key)
            {
                throw new InvalidEncryptionScheme();
            }

            var enc          = DefaultEncoding.WithFatalFallback();
            int index_length = 0;
            var dir          = new List <NpkStoredEntry>();

            foreach (var entry in list)
            {
                var ext       = Path.GetExtension(entry.Name).ToLowerInvariant();
                var npk_entry = new NpkStoredEntry
                {
                    Name     = entry.Name,
                    RawName  = enc.GetBytes(entry.Name.Replace('\\', '/')),
                    IsSolid  = SolidFiles.Contains(ext),
                    IsPacked = !DisableCompression.Contains(ext),
                };
                int segment_count = 1;
                if (!npk_entry.IsSolid)
                {
                    segment_count = (int)(((long)entry.Size + DefaultSegmentSize - 1) / DefaultSegmentSize);
                }
                index_length += 3 + npk_entry.RawName.Length + 0x28 + segment_count * 0x14;
                dir.Add(npk_entry);
            }
            index_length = (index_length + 0xF) & ~0xF;

            int callback_count = 0;

            using (var aes = Aes.Create())
            {
                aes.Mode        = CipherMode.CBC;
                aes.Padding     = PaddingMode.PKCS7;
                aes.Key         = npk_options.Key;
                aes.IV          = GenerateAesIV();
                output.Position = 0x20 + index_length;
                foreach (var entry in dir)
                {
                    if (null != callback)
                    {
                        callback(callback_count++, entry, arcStrings.MsgAddingFile);
                    }

                    using (var writer = new NpkWriter(entry, output, aes))
                        writer.Write(DefaultSegmentSize);
                }
                output.Position = 0;
                var buffer = new byte[] { (byte)'N', (byte)'P', (byte)'K', (byte)'2', 1, 0, 0, 0 };
                output.Write(buffer, 0, 8);
                output.Write(aes.IV, 0, 0x10);
                LittleEndian.Pack(dir.Count, buffer, 0);
                LittleEndian.Pack(index_length, buffer, 4);
                output.Write(buffer, 0, 8);

                using (var encryptor = aes.CreateEncryptor())
                    using (var proxy = new ProxyStream(output, true))
                        using (var index_stream = new CryptoStream(proxy, encryptor, CryptoStreamMode.Write))
                            using (var index = new BinaryWriter(index_stream))
                            {
                                if (null != callback)
                                {
                                    callback(callback_count++, null, arcStrings.MsgWritingIndex);
                                }
                                foreach (var entry in dir)
                                {
                                    index.Write(entry.IsSolid); // 0 -> segmentation enabled, 1 -> no segmentation
                                    index.Write((short)entry.RawName.Length);
                                    index.Write(entry.RawName);
                                    index.Write(entry.UnpackedSize);
                                    index.Write(entry.CheckSum);
                                    index.Write(entry.Segments.Count);
                                    foreach (var segment in entry.Segments)
                                    {
                                        index.Write(segment.Offset);
                                        index.Write(segment.AlignedSize);
                                        index.Write(segment.Size);
                                        index.Write(segment.UnpackedSize);
                                    }
                                }
                            }
            }
        }
Пример #14
0
 public HandlerPlain(ProxyStream stream, CancellationToken token, HandleFunc handler)
     : base(stream, token)
 {
     this.m_handler = handler;
 }
Пример #15
0
        private void SocketThreadSub(ProxyStream proxyStream)
        {
            // https 연결인지, plain 인지 확인하는 과정
            // ContentType type
            // https://tools.ietf.org/html/rfc5246#page-41
            var buff = new byte[1];
            var read = proxyStream.Peek(buff, 0, buff.Length);

            if (read != buff.Length)
            {
                throw new NotSupportedException();
            }

            if (buff[0] == 22)
            {
                var ssl = new SslStream(proxyStream, false);
                ssl.AuthenticateAsServer(Certificates.Client, false, SslProtocol, false);

                proxyStream = new ProxyStream(ssl);
            }

            Handler handler = null;

            if (!ProxyRequest.TryParse(proxyStream, false, out var req))
            {
                return;
            }

            using (req)
            {
                // HTTPS
                if (req.Method == "CONNECT")
                {
                    // 호스트 확인하고 처리
                    switch (req.RemoteHost)
                    {
                    case "userstream.twitter.com":
                    case "api.twitter.com":
                    case "localhost":
                    case "127.0.0.1":
                        handler = new TunnelSslMitm(proxyStream, this.m_tunnelCancel.Token, Certificates.Client, SslProtocol, this.HandleContext);
                        break;

                    default:
                        handler = new TunnelSslForward(proxyStream, this.m_tunnelCancel.Token);
                        break;
                    }
                }

                // HTTP
                else
                {
                    // 호스트 확인하고 처리
                    switch (req.RemoteHost)
                    {
                    case "localhost":
                    case "127.0.0.1":
                        handler = new HandlerPlain(proxyStream, this.m_tunnelCancel.Token, this.HandleContext);
                        break;

                    default:
                        handler = new TunnelPlain(proxyStream, this.m_tunnelCancel.Token);
                        break;
                    }
                }

                using (handler)
                    handler.Handle(req);
            }
        }
Пример #16
0
 public TunnelPlain(ProxyStream stream, CancellationToken token)
     : base(stream, token)
 {
 }
Пример #17
0
        Stream OpenStream(IBinaryStream input, uint key)
        {
            var proxy = new ProxyStream(input.AsStream, true);

            return(new InputCryptoStream(proxy, new Ags32Transform(key)));
        }
Пример #18
0
 public TunnelSslForward(ProxyStream stream, CancellationToken token)
     : base(stream, token)
 {
 }