private void ReadHeaders(IStreamWrapper inputStream)
        {
            Console.WriteLine("readHeaders()");
            string line;

            while ((line = inputStream.StreamReadLine()) != null)
            {
                if (line.Equals(""))
                {
                    Console.WriteLine("got headers");
                    return;
                }

                var separator = line.IndexOf(':');
                if (separator == -1)
                {
                    throw new Exception("invalid http header line: " + line);
                }

                var name = line.Substring(0, separator);
                var pos  = separator + 1;
                while ((pos < line.Length) && (line[pos] == ' '))
                {
                    pos++; // strip any spaces
                }

                var value = line.Substring(pos, line.Length - pos);
                Console.WriteLine("header: {0}:{1}", name, value);
                httpHeaders[name] = value;
            }
        }
Example #2
0
        public CryptoProtocol(IStreamWrapper under, byte[] key, byte[] iv)
        {
            if (under == null)
            {
                throw new ArgumentNullException("under");
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }

            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("iv");
            }

            this.under = under;
            var aes = new AesManaged {
                Key = key, IV = iv
            };

            this.encryptor = aes.CreateEncryptor();
            this.decryptor = aes.CreateDecryptor();
        }
 /// <summary>
 /// Provides data for the specified data format and index (ISTREAM).
 /// </summary>
 /// <param name="dataFormat">Data format.</param>
 /// <param name="index">Index of data.</param>
 /// <param name="streamData">Action generating the data.</param>
 /// <remarks>
 /// Uses Stream instead of IEnumerable(T) because Stream is more likely
 /// to be natural for the expected scenarios.
 /// </remarks>
 public void SetData(short dataFormat, int index, Action <Stream> streamData)
 {
     _dataObjects.Add(
         new DataObject
     {
         FORMATETC = new FORMATETC
         {
             cfFormat = dataFormat,
             ptd      = IntPtr.Zero,
             dwAspect = DVASPECT.DVASPECT_CONTENT,
             lindex   = index,
             tymed    = TYMED.TYMED_ISTREAM
         },
         GetData = () =>
         {
             // Create IStream for data
             var ptr     = IntPtr.Zero;
             var iStream = NativeMethods.CreateStreamOnHGlobal(IntPtr.Zero, true);
             if (streamData != null)
             {
                 // Wrap in a .NET-friendly Stream and call provided code to fill it
                 using (var stream = new IStreamWrapper(iStream))
                 {
                     streamData(stream);
                 }
             }
             // Return an IntPtr for the IStream
             ptr = Marshal.GetComInterfaceForObject(iStream, typeof(IStream));
             Marshal.ReleaseComObject(iStream);
             return(new Tuple <IntPtr, int>(ptr, NativeMethods.S_OK));
         },
     });
 }
Example #4
0
 public void SetData(short dataFormat, int index, FileDescriptor descriptor)
 {
     _dataObjects.Add(
         new DataObject {
         FORMATETC = new FORMATETC {
             cfFormat = dataFormat,
             ptd      = IntPtr.Zero,
             dwAspect = DVASPECT.DVASPECT_CONTENT,
             lindex   = index,
             tymed    = TYMED.TYMED_ISTREAM
         },
         GetData = () => {
             // Create IStream for data
             var iStream = NativeMethods.CreateStreamOnHGlobal(IntPtr.Zero, true);
             if (descriptor.StreamContents != null)
             {
                 // Wrap in a .NET-friendly Stream and call provided code to fill it
                 using (var stream = new IStreamWrapper(iStream)) {
                     descriptor.StreamContents(descriptor.GrfData, descriptor.FilePath, stream, descriptor.Argument);
                 }
             }
             // Return an IntPtr for the IStream
             IntPtr ptr = Marshal.GetComInterfaceForObject(iStream, typeof(IStream));
             Marshal.ReleaseComObject(iStream);
             return(new Utilities.Extension.Tuple <IntPtr, int>(ptr, NativeMethods.S_OK));
         },
     });
 }
 /// <summary>
 /// The stream wrapper in use for document downloads/uploads
 /// </summary>
 /// <returns></returns>
 public virtual IStreamWrapper DefaultStreamWrapper()
 {
     if (defaultStreamWrapper == null)
     {
         defaultStreamWrapper = new CenterDeviceStreamWrapper();
     }
     return(defaultStreamWrapper);
 }
Example #6
0
        public DataWriter(IStreamWrapper streamObj, IValue textEncoding, ByteOrderEnum?byteOrder, string lineSplitter, string convertibleSplitterOfLines, bool writeBOM)
        {
            ByteOrder    = byteOrder ?? ByteOrderEnum.LittleEndian;
            LineSplitter = lineSplitter ?? "\r\n";
            ConvertibleSplitterOfLines = convertibleSplitterOfLines;
            _writeBOM    = writeBOM;
            TextEncoding = textEncoding;

            _binaryWriter = new BinaryWriter(streamObj.GetUnderlyingStream(), _workingEncoding);
        }
Example #7
0
 public void Open(IStreamWrapper stream, string password = null, FileNamesEncodingInZipFile encoding = FileNamesEncodingInZipFile.Auto)
 {
     ZipFile.DefaultEncoding = Encoding.GetEncoding(866);
     // f**k non-russian encodings on non-ascii files
     _zip = ZipFile.Read(stream.GetUnderlyingStream(), new ReadOptions()
     {
         Encoding = ChooseEncoding(encoding)
     });
     _zip.Password = password;
 }
Example #8
0
 public ClientEndpoint(IServer server, IDataContext context, TcpClient client)
 {
     this.server = server;
     this.dataContext = context;
     this.Tcp = client;
     this.tcpStream = client.GetStream();
     this.messageFramer = new FramedProtocol(this.tcpStream);
     this.clientIpAddress = Utils.TCPClient2IPAddress(this.Tcp);
     this.tcpStream.ReadTimeout = 1000; // TODO: remove this from server
     this.CurrentStatus = Status.Uninitialized;
 }
Example #9
0
 public ClientEndpoint(IServer server, IDataContext context, TcpClient client)
 {
     this.server                = server;
     this.dataContext           = context;
     this.Tcp                   = client;
     this.tcpStream             = client.GetStream();
     this.messageFramer         = new FramedProtocol(this.tcpStream);
     this.clientIpAddress       = Utils.TCPClient2IPAddress(this.Tcp);
     this.tcpStream.ReadTimeout = 1000; // TODO: remove this from server
     this.CurrentStatus         = Status.Uninitialized;
 }
Example #10
0
        public void CopyTo(IValue targetStream, int bufferSize = 0)
        {
            IStreamWrapper sw = targetStream.GetRawValue() as IStreamWrapper;
            if (sw == null)
                throw RuntimeException.InvalidArgumentType("targetStream");

            var stream = sw.GetUnderlyingStream();
            if (bufferSize == 0)
                _underlyingStream.CopyTo(stream);
            else
                _underlyingStream.CopyTo(stream, bufferSize);
        }
Example #11
0
 public void Init(string _serv, int _prt, string _login, string _password)
 {
     this.Server   = _serv;
     this.portNum  = _prt;
     this.Login    = _login;
     this.password = _password;
     this.InitStaticDSA();
     this.FreeClient();
     this.client             = new TcpClient(this.Server, this.portNum);
     this.stream             = this.client.GetStream();
     this.stream.ReadTimeout = 7000;
     this.messageFramer      = new FramedProtocol(this.stream);
 }
 private static bool IsStream(object input, out IStreamWrapper wrapper)
 {
     wrapper = null;
     if (input is Поток)
     {
         var obj = input;
         if (obj is IStreamWrapper wrap)
         {
             wrapper = wrap;
             return(true);
         }
     }
     return(false);
 }
        private void ParseRequest(IStreamWrapper inputStream)
        {
            var request = inputStream.StreamReadLine();
            var tokens  = request.Split(' ');

            if (tokens.Length != 3)
            {
                throw new Exception("invalid http request line");
            }
            httpMethod = tokens[0].ToUpper();
            httpUrl    = tokens[1];

            Console.WriteLine("starting: " + request);
        }
Example #14
0
 private static bool IsStream(IValue input, out IStreamWrapper wrapper)
 {
     wrapper = null;
     if (input.DataType == DataType.Object)
     {
         var obj = input.AsObject();
         if (obj is IStreamWrapper wrap)
         {
             wrapper = wrap;
             return(true);
         }
     }
     return(false);
 }
        private void OpenStream(IStreamWrapper streamObj, string encoding = null, string lineDelimiter = "\n", string eolDelimiter = null)
        {
            TextReader imReader;

            if (encoding == null)
            {
                imReader = FileOpener.OpenReader(streamObj.GetUnderlyingStream());
            }
            else
            {
                var enc = КодировкаТекста.GetEncoding(encoding);
                imReader = FileOpener.OpenReader(streamObj.GetUnderlyingStream(), enc);
            }
            _reader = GetCustomLineFeedReader(imReader, lineDelimiter, eolDelimiter, AnalyzeDefaultLineFeed);
        }
Example #16
0
        private void OpenStream(IStreamWrapper streamObj, IValue encoding = null, string lineDelimiter = "\n", string eolDelimiter = null)
        {
            TextReader imReader;

            if (encoding == null)
            {
                imReader = Environment.FileOpener.OpenReader(streamObj.GetUnderlyingStream(), Encoding.Default);
            }
            else
            {
                var enc = TextEncodingEnum.GetEncoding(encoding);
                imReader = Environment.FileOpener.OpenReader(streamObj.GetUnderlyingStream(), enc);
            }
            _reader = GetCustomLineFeedReader(imReader, lineDelimiter, eolDelimiter, AnalyzeDefaultLineFeed);
        }
        private void HandlePOSTRequest(IStreamWrapper inputStream, IStreamWriterWrapper outputStream)
        {
            // this post data processing just reads everything into a memory stream.
            // this is fine for smallish things, but for large stuff we should really
            // hand an input stream to the request processor. However, the input stream
            // we hand him needs to let him see the "end of the stream" at this content
            // length, because otherwise he won't know when he's seen it all!

            //Console.WriteLine("get post data start");

            using (var ms = streamFactory.GetMemoryStreamWrapper())
            {
                if (httpHeaders.ContainsKey("Content-Length"))
                {
                    var contentLen = Convert.ToInt32(httpHeaders["Content-Length"]);
                    if (contentLen > MaxPostSize)
                    {
                        throw new Exception($"POST Content-Length({contentLen}) too big for this server");
                    }
                    var buf    = new byte[BufSize];
                    var toRead = contentLen;
                    while (toRead > 0)
                    {
                        //Console.WriteLine("starting Read, to_read={0}", toRead);
                        var numread = inputStream.Read(buf, 0, Math.Min(BufSize, toRead));

                        //Console.WriteLine("read finished, numread={0}", numread);
                        if (numread == 0)
                        {
                            if (toRead == 0)
                            {
                                break;
                            }

                            throw new Exception("client disconnected during post");
                        }
                        toRead -= numread;
                        ms.Write(buf, 0, numread);
                    }
                    ms.Seek(0, SeekOrigin.Begin);
                }
                //Console.WriteLine("get post data end");

                postHandler(httpUrl, ms, outputStream);
            }
        }
        public void CopyTo(object targetStream, int bufferSize = 0)
        {
            IStreamWrapper sw = targetStream as IStreamWrapper;

            if (sw == null)
            {
                throw RuntimeException.InvalidArgumentType("targetStream");
            }

            var stream = sw.GetUnderlyingStream();

            if (bufferSize == 0)
            {
                _underlyingStream.CopyTo(stream);
            }
            else
            {
                _underlyingStream.CopyTo(stream, bufferSize);
            }
        }
Example #19
0
        public void SetUpSecureChannel()
        {
            try
            {
                var ecdh1 = new ECDHWrapper(AgreementLength);
                this.messageFramer.Send(ecdh1.PubData);
                var    serverPublicKey = this.messageFramer.Receive();
                byte[] agreement       = ecdh1.calcAgreement(serverPublicKey);

                const int AESKeyLength = 32;
                byte[]    aesKey       = new byte[AESKeyLength];
                Array.Copy(agreement, 0, aesKey, 0, AESKeyLength);

                this.cryptoWrapper = new CryptoProtocol(this.messageFramer, aesKey, Iv1);
            }
            catch (Exception ex)
            {
                Logger.Debug(string.Format("Error while stting up secure channel: {0}{1}", Environment.NewLine, ex));
                throw new ServerSendInvalidDataException(string.Empty, ex);
            }
        }
Example #20
0
        public CryptoProtocol(IStreamWrapper under, byte[] key, byte[] iv)
        {
            if (under == null)
            {
                throw new ArgumentNullException("under");
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }

            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("iv");
            }

            this.under = under;
            var aes = new AesManaged { Key = key, IV = iv };
            this.encryptor = aes.CreateEncryptor();
            this.decryptor = aes.CreateDecryptor();
        }
Example #21
0
        /// <summary>
        /// Init secure channel (this.Cryptor)
        /// </summary>
        /// <returns></returns>
        private void SetUpSecureChannel()
        {
            try
            {
                var ecdh1     = new ECDHWrapper(AgreementLength);
                var recCliPub = this.messageFramer.Receive();
                this.messageFramer.Send(ecdh1.PubData);
                var agr = ecdh1.calcAgreement(recCliPub);

                const int AESKeyLength = 32;
                var       aeskey       = new byte[AESKeyLength];
                Array.Copy(agr, 0, aeskey, 0, AESKeyLength);

                this.cryptoWrapper = new CryptoProtocol(this.messageFramer, aeskey, CryptoIv1);
            }
            catch (Exception ex)
            {
                Log.DebugFormat("Error while completing agreement: {0}{1}", Environment.NewLine, ex);
                this.cryptoWrapper = null;
                throw new SecureChannelInitFailedException(string.Empty, ex);
            }
        }
Example #22
0
 public ShapeLoaderAdapter(IShapeLoader loader, IStreamWrapper wrapper)
 {
     loader_  = loader;
     wrapper_ = wrapper;
 }
 public DocumentsRestClient(IOAuthInfoProvider oauthInfoProvider, IRestClientConfiguration configuration, IRestClientErrorHandler errorHandler, IStreamWrapper streamWrapper, string apiVersionPrefix) : base(oauthInfoProvider, configuration, errorHandler, apiVersionPrefix)
 {
     this.streamWrapper = streamWrapper;
 }
 internal static Stream WrapDownloadStream(Stream stream, IStreamWrapper streamWrapper)
 {
     return(streamWrapper?.WrapDownloadStream(stream) ?? stream);
 }
 internal static void AddFileToUpload(IRestRequest uploadRequest, string fileName, string filePath, IStreamWrapper streamWrapper, CancellationToken cancellationToken)
 {
     uploadRequest.Files.Add(new FileParameter()
     {
         Name          = fileName,
         FileName      = Path.GetFileName(filePath),
         ContentLength = new FileInfo(filePath).Length,
         ContentType   = null,
         Writer        = uploadStream =>
         {
             using (var fileStream = WrapUploadStream(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete), streamWrapper))
             {
                 CopyTo(fileStream, uploadStream, cancellationToken);
             }
         }
     });
 }
Example #26
0
 public Disposed(IStreamWrapper wrapper)
     : base(wrapper)
 {
 }
Example #27
0
 internal AfterRead(IStreamWrapper wrapper, byte[] buf, int ofs, int count)
     : base(wrapper)
 {
     Buffer = new ArraySegment <byte>(buf, ofs, count);
 }
Example #28
0
 internal BeforeWrite(IStreamWrapper wrapper, byte[] buf, int ofs, int count)
     : base(wrapper)
 {
     Buffer = new ArraySegment <byte>(buf, ofs, count);
 }
Example #29
0
        /// <summary>
        /// Init secure channel (this.Cryptor)
        /// </summary>
        /// <returns></returns>
        private void SetUpSecureChannel()
        {
            try
            {
                var ecdh1 = new ECDHWrapper(AgreementLength);
                var recCliPub = this.messageFramer.Receive();
                this.messageFramer.Send(ecdh1.PubData);
                var agr = ecdh1.calcAgreement(recCliPub);

                const int AESKeyLength = 32;
                var aeskey = new byte[AESKeyLength];
                Array.Copy(agr, 0, aeskey, 0, AESKeyLength);

                this.cryptoWrapper = new CryptoProtocol(this.messageFramer, aeskey, CryptoIv1);
            }
            catch (Exception ex)
            {
                Log.DebugFormat("Error while completing agreement: {0}{1}", Environment.NewLine, ex);
                this.cryptoWrapper = null;
                throw new SecureChannelInitFailedException(string.Empty, ex);
            }
        }
Example #30
0
 protected StreamEvent(IStreamWrapper wrapper)
 {
     Wrapper = wrapper;
 }
		public void SetData(short dataFormat, int index, FileDescriptor descriptor) {
			_dataObjects.Add(
				new DataObject {
					FORMATETC = new FORMATETC {
						cfFormat = dataFormat,
						ptd = IntPtr.Zero,
						dwAspect = DVASPECT.DVASPECT_CONTENT,
						lindex = index,
						tymed = TYMED.TYMED_ISTREAM
					},
					GetData = () => {
						// Create IStream for data
						var iStream = NativeMethods.CreateStreamOnHGlobal(IntPtr.Zero, true);
						if (descriptor.StreamContents != null) {
							// Wrap in a .NET-friendly Stream and call provided code to fill it
							using (var stream = new IStreamWrapper(iStream)) {
								descriptor.StreamContents(descriptor.GrfData, descriptor.FilePath, stream, descriptor.Argument);
							}
						}
						// Return an IntPtr for the IStream
						IntPtr ptr = Marshal.GetComInterfaceForObject(iStream, typeof(IStream));
						Marshal.ReleaseComObject(iStream);
						return new Tuple<IntPtr, int>(ptr, NativeMethods.S_OK);
					},
				});
		}
Example #32
0
 public void Init(string _serv, int _prt, string _login, string _password)
 {
     this.Server = _serv;
     this.portNum = _prt;
     this.Login = _login;
     this.password = _password;
     this.InitStaticDSA();
     this.FreeClient();
     this.client = new TcpClient(this.Server, this.portNum);
     this.stream = this.client.GetStream();
     this.stream.ReadTimeout = 7000;
     this.messageFramer = new FramedProtocol(this.stream);
 }
Example #33
0
 public IStreamWriterWrapper GetStreamWriterWrapper(IStreamWrapper streamWrapper)
 {
     return(new StreamWriterWrapper(streamWrapper));
 }
Example #34
0
        public void SetUpSecureChannel()
        {
            try
            {
                var ecdh1 = new ECDHWrapper(AgreementLength);
                this.messageFramer.Send(ecdh1.PubData);
                var serverPublicKey = this.messageFramer.Receive();
                byte[] agreement = ecdh1.calcAgreement(serverPublicKey);

                const int AESKeyLength = 32;
                byte[] aesKey = new byte[AESKeyLength];
                Array.Copy(agreement, 0, aesKey, 0, AESKeyLength);

                this.cryptoWrapper = new CryptoProtocol(this.messageFramer, aesKey, Iv1);
            }
            catch (Exception ex)
            {
                Logger.Debug(string.Format("Error while stting up secure channel: {0}{1}", Environment.NewLine, ex));
                throw new ServerSendInvalidDataException(string.Empty, ex);
            }
        }
Example #35
0
 public ZipReader(IStreamWrapper stream, string password = null)
 {
     Open(stream, password);
 }
Example #36
0
 public AdapterLoaderPacker(IStreamWrapper wrapper)
 {
     wrapper_ = wrapper;
 }