示例#1
0
        private static void ForwardClientToProxy(TcpClient tcpClient, TcpClient tcpProxy)
        {
            string firstLine;
            string method;
            string version;
            string url;
            string sslTunnelDomain = null;

            Stream clientStream = tcpClient.GetStream();
            Stream proxyStream  = tcpProxy.GetStream();

            firstLine = clientStream.ReadLine();
            ParseHttpCommand(firstLine, out method, out url, out version);
            if (method == "CONNECT")
            {
                //client wants to ssl tunnel through the proxy
                clientStream = GetSslTunnelStream(clientStream, version);
                if (clientStream == null)
                {
                    return;
                }
                firstLine       = clientStream.ReadLine();
                sslTunnelDomain = url;
            }

            //request
            CopyHttpStream(clientStream, proxyStream, firstLine, sslTunnelDomain);
            //response
            CopyHttpStream(proxyStream, clientStream);
            firstLine = "";
            clientStream.Close();
            proxyStream.Close();
        }
示例#2
0
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (_chunkLength == null)
            {
                string rawLength = _stream.ReadLine();

                int length = Int32.Parse(rawLength, NumberStyles.HexNumber, CultureInfo.InvariantCulture);

                if (length == 0)
                {
                    return(0);
                }

                _chunkLength = length;
            }

            int maxRead = Math.Min(count - offset, _chunkLength.Value - _consumed);

            int read = await _stream.ReadAsync(buffer, offset, maxRead, cancellationToken);

            _consumed += read;

            if (_consumed >= _chunkLength)
            {
                _stream.ReadLine();

                _chunkLength = null;

                _consumed = 0;
            }

            return(read);
        }
示例#3
0
        public static Task<FormData> ParseMultipart(Stream stream, string boundary) {
            if (stream == null) {
                throw new ArgumentNullException("stream");
            }
            if (boundary == null) {
                throw new ArgumentNullException("boundary");
            }
            if (boundary.Length == 0) {
                throw new ArgumentException("Boundary cannot be empty", "boundary");
            }
            var form = new FormData();

            boundary = "--" + boundary;
            var boundaryBytes = Encoding.UTF8.GetBytes("\r\n" + boundary);

            string currentLine = stream.ReadLine(Encoding.UTF8);
            if (currentLine != boundary) {
                form.IsValid = false;
                return TaskHelper.Completed(form);
            }
            while (true) {
                currentLine = stream.ReadLine(Encoding.UTF8);
                // parse ContentDisposition line
                var match = ContentDispositionFormDataRegex.Match(currentLine);
                if (!match.Success) {
                    form.IsValid = false;
                    return TaskHelper.Completed(form);
                }
                string fieldName = match.Groups[1].Value;
                string fileName = match.Groups[2].Success ? match.Groups[3].Value : null;

                if (fileName != null) {
                    if (!ParseMultipartFile(stream, form, fieldName, fileName, boundaryBytes)) {
                        form.IsValid = false;
                        return TaskHelper.Completed(form);
                    }
                }
                else {
                    if (!ParseMultipartField(stream, form, fieldName, boundaryBytes)) {
                        form.IsValid = false;
                        return TaskHelper.Completed(form);
                    }
                }

                // check end or next
                currentLine = stream.ReadLine(Encoding.UTF8);
                // --boundary-- end
                if (currentLine == "--") {
                    break;
                }
                // --boundary between
                if (currentLine != string.Empty) {
                    form.IsValid = false;
                    return TaskHelper.Completed(form);
                }
            }
            return TaskHelper.Completed(form);
        }
示例#4
0
        private static (MergeTag, string) ReadMergeTag(byte[] hash, Stream stream)
        {
            var output = new MergeTag
            {
                Object = hash.AsShaToCid()
            };

            while (true)
            {
                var(line, eof) = stream.ReadLine();
                if (eof)
                {
                    break;
                }

                if (line == " ")
                {
                    while (true)
                    {
                        var(line2, eof2) = stream.ReadLine();
                        if (eof2)
                        {
                            break;
                        }

                        if (line2[0] != ' ')
                        {
                            return(output, line);
                        }

                        output.Text += line2 + '\n';
                    }
                }
                else if (line.StartsWith(" type "))
                {
                    output.Type = line.Substring(6);
                }
                else if (line.StartsWith(" tag "))
                {
                    output.Tag = line.Substring(5);
                }
                else if (line.StartsWith(" tagger "))
                {
                    var tagger = ParsePersonInfo(line.Substring(1));
                    if (tagger == null)
                    {
                        return(null, string.Empty);
                    }

                    output.Tagger = tagger;
                }
            }

            return(output, string.Empty);
        }
示例#5
0
        private void ParseMime(Stream reader, string boundary, int maxLength)
        {
            var    maxLengthSpecified = maxLength > 0;
            string data,
                   bounderInner = "--" + boundary,
                   bounderOuter = bounderInner + "--";

            do
            {
                data = reader.ReadLine(ref maxLength, Encoding);
            } while (data != null && !data.StartsWith(bounderInner));

            while (data != null && !data.StartsWith(bounderOuter) && (maxLength > 0 || !maxLengthSpecified))
            {
                data = reader.ReadLine(ref maxLength, Encoding);
                var a = new Attachment {
                    Encoding = Encoding
                };

                var part = new StringBuilder();
                // read part header
                while (!data.StartsWith(bounderInner) && data != string.Empty)
                {
                    part.AppendLine(data);
                    data = reader.ReadLine(ref maxLength, Encoding);
                }
                a.RawHeaders = part.ToString();
                // header body

                data = reader.ReadLine(ref maxLength, Encoding);
                var body = new StringBuilder();
                while (data != null && !data.StartsWith(bounderInner))
                {
                    body.AppendLine(data);
                    data = reader.ReadLine(ref maxLength, Encoding);
                }
                // check for nested part
                string nestedboundary = a.Headers.GetBoundary();
                if (!string.IsNullOrEmpty(nestedboundary))
                {
                    ParseMime(body.ToString(), nestedboundary);
                }
                else // nested
                {
                    a.SetBody(body.ToString());
                    (a.IsAttachment ? Attachments : AlternateViews).Add(a);
                }
            }

            if (maxLength > 0)
            {
                data = reader.ReadToEnd(maxLength, Encoding);
            }
        }
示例#6
0
        private void ParserASCII(PlyObjectHeader header, Stream sr)
        {
            Point3D[] vertices = new Point3D[header.Elements["vertex"].Count];
            ;
            PointerToVertex[] pointersToVertex = new PointerToVertex[header.Elements["face"].Count];
            //int headerLength = header.Count + 1;
            //while (sr.ReadLine().ToLower() != "end_header") { } //Pass header...
            NumberFormatInfo nfi = new NumberFormatInfo();

            nfi.NumberDecimalSeparator = ".";
            nfi.NumberGroupSeparator   = ",";
            String[] str;


            //for number of vertices readed in header do...
            for (int i = 0; i < vertices.Length; i++)
            {
                str         = sr.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                vertices[i] = new Point3D(float.Parse(str[0], nfi), float.Parse(str[1], nfi), float.Parse(str[2], nfi));
                //Adjusting BoundBox...
                this.BoundBox.Include(vertices[i]);
                //Reporting progress
                int percent = (int)(((float)i / vertices.Length) * 100.0f);
                if ((percent % 20) == 0)
                {
                    this.OnElementLoaded(percent, ElementMesh.Vertex);
                }
            }

            for (int i = 0; i < this.triangles.Length; i++)
            {
                str = sr.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                pointersToVertex[i] = new PointerToVertex(Int32.Parse(str[1], nfi), Int32.Parse(str[2], nfi),
                                                          Int32.Parse(str[3], nfi));
                this.triangles[i] = new Triangle(vertices[pointersToVertex[i].Vertex1],
                                                 vertices[pointersToVertex[i].Vertex2],
                                                 vertices[pointersToVertex[i].Vertex3]);
                int percent = (int)(((float)i / this.triangles.Length) * 100.0f);
                if ((percent % 20) == 0)
                {
                    this.OnElementLoaded(percent, ElementMesh.Triangle);
                }
            }
            //System.Windows.Forms.MessageBox.Show("Degenerate Triangles: " + RemoveDegenerateTriangles(ref pointersToVertex));
            //RemoveUnusedVertices(ref vertices, pointersToVertex);

            this.ProcessNormalsPerVertex(pointersToVertex, vertices.Length);

            vertices         = null;
            pointersToVertex = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
示例#7
0
        private static void ParseMime(Stream reader, string boundary, ref int maxLength, ICollection <Attachment> attachments, Encoding encoding, char?termChar)
        {
            var    maxLengthSpecified = maxLength > 0;
            string data,
                   bounderInner = "--" + boundary,
                   bounderOuter = bounderInner + "--";

            do
            {
                data = reader.ReadLine(ref maxLength, encoding, termChar);
            } while (data != null && !data.StartsWith(bounderInner));

            while (data != null && !data.StartsWith(bounderOuter) && !(maxLengthSpecified && maxLength == 0))
            {
                data = reader.ReadLine(ref maxLength, encoding, termChar);
                var a = new Attachment {
                    Encoding = encoding
                };

                var part = new StringBuilder();
                // read part header
                while (!data.StartsWith(bounderInner) && data != string.Empty && !(maxLengthSpecified && maxLength == 0))
                {
                    part.AppendLine(data);
                    data = reader.ReadLine(ref maxLength, encoding, termChar);
                }
                a.RawHeaders = part.ToString();
                // header body

                // check for nested part
                var nestedboundary = a.Headers.GetBoundary();
                if (!string.IsNullOrEmpty(nestedboundary))
                {
                    ParseMime(reader, nestedboundary, ref maxLength, attachments, encoding, termChar);
                }
                else
                {
                    data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
                    var body = new StringBuilder();
                    while (!data.StartsWith(bounderInner) && !(maxLengthSpecified && maxLength == 0))
                    {
                        body.AppendLine(data);
                        data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
                    }
                    a.SetBody(body.ToString());
                    attachments.Add(a);
                }
            }
        }
        public T[][] LoadArrayJagged <T>()
        {
            // Get dimensions of data.
            var rowCount = 0;

            while (Stream.ReadLine() != null)
            {
                rowCount++;
            }

            var t = new T[rowCount][];

            // Reset stream and populate array.
            Stream.BaseStream.Seek(0, SeekOrigin.Begin);
            string line;
            var    row = 0;

            while ((line = Stream.ReadLine()) != null)
            {
                var values = line.Split(Delimiter);
                t[row] = new T[values.Length];
                for (var col = 0; col < values.Length; col++)
                {
                    t[row][col] = (T)Converter.ConvertFromString(values[col]);
                }

                row++;
            }

            Dispose();

            return(t);
        }
        public T[] LoadArray1D <T>()
        {
            // Get dimensions of data.
            var length = 0;

            while (Stream.ReadLine() != null)
            {
                length++;
            }

            var t = new T[length];

            // Reset stream and populate array.
            Stream.BaseStream.Seek(0, SeekOrigin.Begin);
            string line;
            var    i = 0;

            while ((line = Stream.ReadLine()) != null)
            {
                t[i] = (T)Converter.ConvertFromString(line);
                i++;
            }

            Dispose();

            return(t);
        }
示例#10
0
        private static String[] GetHeaderLines(Stream stream, Encoding encoding)
        {
            List <string> headers = new List <string>();

            while (true)
            {
                String header;
                try
                {
                    header = stream.ReadLine(encoding);
                }
                catch (Exception)
                {
                    break;
                }

                if (header.Length == 0)
                {
                    // Empty Line.  End of headers
                    break;
                }
                // Else we add the header to our list.
                headers.Add(header);
            }
            return(headers.ToArray());
        }
示例#11
0
        private static bool ParseMultipartFile(Stream stream, FormData form, string fieldName, string fileName, byte[] boundaryBytes)
        {
            string contentType = null;
            string headerLine;

            while ((headerLine = stream.ReadLine(Encoding.UTF8)) != string.Empty)
            {
                // parse 'Content-" headers
                var match = ContentTypeFileRegex.Match(headerLine);
                if (match.Success)
                {
                    contentType = match.Groups[1].Value.Trim();
                }
            }
            if (contentType == null)
            {
                //todo: infer from file type (extension)
                contentType = "application/octet-stream";
            }

            byte[] data;
            if (!stream.ReadTo(boundaryBytes, out data))
            {
                return(false);
            }
            form.Files.Add(new PostedFile(fieldName, fileName, data, contentType));
            return(true);
        }
示例#12
0
        public static INode ReadCommit(Stream stream)
        {
            var size = stream.ReadString(0);

            if (size.Length == 0)
            {
                return(null);
            }

            var output = new Commit
            {
                DataSize = size.Substring(0, size.Length - 1)
            };

            while (true)
            {
                var(line, eof) = stream.ReadLine();
                if (eof)
                {
                    break;
                }

                if (!ParseCommitLine(output, line, stream))
                {
                    return(null);
                }
            }

            output.cid = HashObject(output.RawData());

            return(output);
        }
示例#13
0
        private static Stream GetSslTunnelStream(Stream stream, string version = "HTTP/1.1")
        {
            SslStream sslStream = null;

            //Browser wants to create a secure tunnel
            //read and ignore headers
            while (!String.IsNullOrEmpty(stream.ReadLine()))
            {
                ;
            }
            //tell the client that a tunnel has been established
            LogMessage(string.Format("Doing CONNECT"));
            var connectStreamWriter = new BinaryWriter(stream);

            connectStreamWriter.WriteLine(version + " 200 Connection established");
            connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
            connectStreamWriter.WriteLine("Proxy-agent: buskerproxy");
            connectStreamWriter.WriteLine();
            connectStreamWriter.Flush();

            //open a decrypting stream
            sslStream = new SslStream(stream, false);
            try
            {
                sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
            }
            catch (Exception ex)
            {
                stream.Close();
                sslStream.Close();
                return(null);
            }
            return(sslStream);
        }
示例#14
0
        /// <summary>
        /// Merge program from ascii or utf8 (if utf8_files is True) stream.
        /// </summary>
        /// <param name="stream">ASCII program stream to be merged</param>
        private void Merge(Stream stream)
        {
            while (true)
            {
                var line = stream.ReadLine();
                if (string.IsNullOrEmpty(line))
                {
                    break;
                }

                var tokenizedLine = Tokeniser.Tokenise(line);
                if (tokenizedLine.Length > 0 && tokenizedLine[0] == '\0')
                {
                    // line starts with a number, add to program memory; store_line seeks to 1 first
                    StoreLine(tokenizedLine.AsStream());
                }
                else
                {
                    // we have read the :
                    var next = stream.SkipWhitespace();
                    if (next != -1 && next != '\0')
                    {
                        throw new ReplRuntimeException(ReplExceptionCode.DirectStatementInFile);
                    }
                }
            }
        }
示例#15
0
        protected static IList<KeyValuePair<string, string>> ReadHeaders(Stream stream)
        {
            var headers = new List<KeyValuePair<string, string>>();
            var line = stream.ReadLine();
            while (line.Trim() != "")
            {
                var parts = line.Split(new[] { ':' }, 2);
                if (parts.Length != 2)
                    throw new Exception("Invalid HttpHeader");
                var name = parts[0].Trim();
                var value = parts[1].Trim();
                headers.Add(new KeyValuePair<string, string>(name, value));
                line = stream.ReadLine();
            }

            return headers;
        }
示例#16
0
        private string[] List(string folder = ".")
        {
            try
            {
                var tag     = GetTag();
                var command = tag + "LIST " + folder.QuoteString() + "*";
                _stream.SendCommand(command);
                var    response = String.Empty;
                string temp;
                while (!(temp = _stream.ReadLine()).StartsWith(tag))
                {
                    response += (!string.IsNullOrEmpty(response) ? Environment.NewLine : "") + temp;
                }

                if (!temp.Contains("OK LIST"))
                {
                    throw new Exception("Problem listing folders");
                }

                // parse folder information out of text response
                var listRegex = new Regex(@"^\*\s+LIST\s+\((?<flags>[^\)]*?)\)\s+""(?<cwd>[^\""]*)""\s+""*(?<dir>.*?)""*\s*$", RegexOptions.Multiline);
                var matches   = listRegex.Matches(response).OfType <Match>().Select(x => x.Groups[3].Value);

                return(matches.ToArray());
            }
            catch (Exception ex)
            {
                if (ex is IOException)
                {
                    _authenticated = _connected = false;
                }
                Log.Error(string.Format("There was an error listing imap folders: {0}", folder), ex);
                return(new string[0]);
            }
        }
示例#17
0
 private static void Parse3Tokens(Stream stream, out string token1, out string token2, out string token3)
 {
     var reader = new StringReader(stream.ReadLine());
     token1 = reader.ReadUntilWhitespace();
     reader.SkipWhitespace();
     token2 = reader.ReadUntilWhitespace();
     reader.SkipWhitespace();
     token3 = reader.ReadLine();
 }
示例#18
0
        private static GpgSignature ReadPgpSignature(Stream stream)
        {
            var(line, eof) = stream.ReadLine();
            if (eof)
            {
                return(null);
            }

            var output = new GpgSignature();

            if (line != " ")
            {
                if (line.StartsWith(" Version: ") || line.StartsWith(" Comment: "))
                {
                    output.Text += line + '\n';
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                output.Text += " \n";
            }

            while (true)
            {
                (line, eof) = stream.ReadLine();
                if (eof)
                {
                    return(null);
                }

                if (line == " -----END PGP SIGNATURE-----")
                {
                    break;
                }

                output.Text += line + "\n";
            }

            return(output);
        }
示例#19
0
        private static void Parse3Tokens(Stream stream, out string token1, out string token2, out string token3)
        {
            var reader = new StringReader(stream.ReadLine());

            token1 = reader.ReadUntilWhitespace();
            reader.SkipWhitespace();
            token2 = reader.ReadUntilWhitespace();
            reader.SkipWhitespace();
            token3 = reader.ReadLine();
        }
示例#20
0
 protected override void ReadFirstLine(Stream stream)
 {
     var line = stream.ReadLine();
     var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
     if (parts.Length != 3)
         throw new Exception("Invalid HttpRequest");
     Method = parts[0];
     Destination = parts[1];
     Version = parts[2];
 }
示例#21
0
        protected static IList <KeyValuePair <string, string> > ReadHeaders(Stream stream)
        {
            var headers = new List <KeyValuePair <string, string> >();
            var line    = stream.ReadLine();

            while (line.Trim() != "")
            {
                var parts = line.Split(new[] { ':' }, 2);
                if (parts.Length != 2)
                {
                    throw new Exception("Invalid HttpHeader");
                }
                var name  = parts[0].Trim();
                var value = parts[1].Trim();
                headers.Add(new KeyValuePair <string, string>(name, value));
                line = stream.ReadLine();
            }

            return(headers);
        }
示例#22
0
        private static INode ReadTag(Stream stream)
        {
            var size = stream.ReadString(0);

            if (string.IsNullOrEmpty(size))
            {
                return(null);
            }

            var output = new Tag
            {
                dataSize = size.Substring(0, size.Length - 1)
            };

            while (true)
            {
                var(line, eof) = stream.ReadLine();
                if (eof)
                {
                    break;
                }

                if (string.IsNullOrEmpty(line))
                {
                    output.Message = stream.ReadAll();
                }
                else if (line.StartsWith("object "))
                {
                    output.Object = Multibase.Base16.Decode(line.Substring(7)).AsShaToCid();
                }
                else if (line.StartsWith("tag "))
                {
                    output.Name = line.Substring(4);
                }
                else if (line.StartsWith("tagger "))
                {
                    var c = ParsePersonInfo(line);
                    if (c == null)
                    {
                        return(null);
                    }

                    output.Tagger = c;
                }
                else if (line.StartsWith("type "))
                {
                    output.Type = line.Substring(5);
                }
            }

            output.cid = HashObject(output.RawData());

            return(output);
        }
示例#23
0
        public static async Task <bool> ReadUntil(this Stream stream, string textPresent)
        {
            for (int i = 0; i < 10; i++)
            {
                if ((await stream.ReadLine()).Echo() == textPresent)
                {
                    return(true);
                }
            }

            return(false);
        }
        protected override void ReadFirstLine(Stream stream)
        {
            var line  = stream.ReadLine();
            var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length != 3)
            {
                throw new Exception("Invalid HttpRequest");
            }
            Method      = parts[0];
            Destination = parts[1];
            Version     = parts[2];
        }
示例#25
0
 protected override void ReadFirstLine(Stream stream)
 {
     var line = stream.ReadLine();
     var parts = line.Split(new[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);
     if (parts.Length < 2)
         throw new Exception("Invalid HttpRequest");
     Version = parts[0];
     var statusCode = 0;
     if (!int.TryParse(parts[1], out statusCode))
         Errors.Add("Invalid StatusCode");
     StatusCode = (HttpStatusCode) statusCode;
     if (parts.Length == 3)
         StatusDescription = parts[2];
 }
        public T LoadNonCollection <T>()
        {
            string line;
            var    input = new StringBuilder();

            while ((line = Stream.ReadLine()) != null)
            {
                input.Append(line);
            }

            Dispose();

            return((T)Converter.ConvertFromString(input.ToString()));
        }
        public T[,] LoadArray2D <T>()
        {
            // Get dimensions of data.
            string line;

            string[] values;
            var      rowCount            = 0;
            var      colCount            = 0;
            var      previousColumnCount = colCount;

            while ((line = Stream.ReadLine()) != null)
            {
                values   = line.Split(Delimiter);
                colCount = values.Length;

                // Data integrity check.
                if ((rowCount > 0) && (previousColumnCount != colCount))
                {
                    var warningMessage =
                        "Input data from [" + Source + "] is incomplete in row [" + rowCount + "].";
                    LogManager.Instance().LogWarningMessage(warningMessage);
                }

                rowCount++;
                previousColumnCount = colCount;
            }

            var t = new T[rowCount, colCount];

            // Reset stream and populate array.
            Stream.BaseStream.Seek(0, SeekOrigin.Begin);
            var row = 0;

            while ((line = Stream.ReadLine()) != null)
            {
                values = line.Split(Delimiter);
                for (var col = 0; col < values.Length; col++)
                {
                    t[row, col] = (T)Converter.ConvertFromString(values[col]);
                }

                row++;
            }

            Dispose();

            return(t);
        }
        public List <T> LoadList <T>()
        {
            var t = new List <T>();

            string line;

            while ((line = Stream.ReadLine()) != null)
            {
                var values = line.Split(Delimiter);
                t.AddRange(values.Select(value => (T)Converter.ConvertFromString(value)));
            }

            Dispose();

            return(t);
        }
示例#29
0
        public HvjEthpiaca Read()
        {
            //获取标题之后,可以获取内容
            //添加进去,继续获取类别
            //获取是否发布
            MdmetaXsawJnfzmrs.Sort((a, b) => - 1 * a.Priority.CompareTo(b.Priority));

            var hvjEthpiaca = new HvjEthpiaca();

            hvjEthpiaca.Title = GetTitle();
            foreach (var temp in MdmetaXsawJnfzmrs)
            {
                temp.HvjEthpiaca = hvjEthpiaca;
            }

            while (!Stream.EndOfStream)
            {
                string str = Stream.ReadLine();

                var nghtsBdlbthhur = new NghtsBdlbthhur(Stream, str);

                foreach (var temp in MdmetaXsawJnfzmrs.Where(temp => temp.ReadCsfLvi))
                {
                    temp.Read(nghtsBdlbthhur);
                    Text.Append(nghtsBdlbthhur.Text);
                    if (nghtsBdlbthhur.Handle)
                    {
                        break;
                    }
                }
            }
            hvjEthpiaca.Text = Text.ToString();

            DasmxxfgTqqxo.HfuvuwTwve.DmutmraDtgzwihr(hvjEthpiaca, MdmetaXsawJnfzmrs);

            foreach (var temp in MdmetaXsawJnfzmrs)
            {
                temp.HgvaHhloe();
            }

            foreach (var temp in StalirromearSikals)
            {
                temp.Read(hvjEthpiaca);
            }

            return(hvjEthpiaca);
        }
示例#30
0
 private static int GetChunkLength(Stream source, out string chunkHeader)
 {
     chunkHeader = null;
     try
     {
         chunkHeader = source.ReadLine();
         var parts      = chunkHeader.Split(new char[] { ':' }, 2, StringSplitOptions.None);
         var sizeString = parts[0].Trim();
         var chunkSize  = int.Parse(sizeString, NumberStyles.AllowHexSpecifier);
         return(chunkSize);
     }
     catch (Exception ex)
     {
         Debug.WriteLine("CopyAllToAsync error: " + ex.Message);
         return(-1);
     }
 }
示例#31
0
        internal static string GetFirstLine(Stream stream, Encoding encoding, out int readBytes)
        {
            var line = stream.ReadLine(encoding, out readBytes);

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

            // trim UTF-8 BOM
            if (line.Length >= 3 && line[0] == 0xEF && line[1] == 0xBB && line[2] == 0xBF)
            {
                line = line.Substring(3);
            }

            return(line);
        }
示例#32
0
        public override object Deserialize(Stream stream)
        {
            string typeName = stream.ReadLine(MessageEncoding);

            int length = stream.ReadInt();
            byte[] messageBuffer = stream.Read(length);
            Type type = ReflectionHelper.FindType(typeName);

            if (type != null)
            {
                MemoryStream messageStream = new MemoryStream(messageBuffer);
                return Serializer.NonGeneric.Deserialize(type, messageStream);
            }
            else
            {
                throw new Exception("Invalid message type");
            }
        }
示例#33
0
        /// <summary>
        /// Executa o parser dos cabeçalhos.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="onHeader"></param>
        private static void ParseHeaders(Stream stream, Action <string, string> onHeader)
        {
            string headerLine = null;

            while (true)
            {
                headerLine = stream.ReadLine();
                if (headerLine == String.Empty)
                {
                    break;
                }
                var    headerReader = new StringReader(headerLine);
                string key          = headerReader.ReadUntil(c => c == ':');
                headerReader.Read();
                headerReader.SkipWhitespace();
                string value = headerReader.ReadToEnd();
                onHeader(key, value);
            }
        }
示例#34
0
        public override object Deserialize(Stream stream)
        {
            string typeName = stream.ReadLine(MessageEncoding);

            int length = stream.ReadInt();

            byte[] messageBuffer = stream.Read(length);
            Type   type          = ReflectionHelper.FindType(typeName);

            if (type != null)
            {
                MemoryStream messageStream = new MemoryStream(messageBuffer);
                return(Serializer.NonGeneric.Deserialize(type, messageStream));
            }
            else
            {
                throw new Exception("Invalid message type");
            }
        }
示例#35
0
        public override IMessage Deserialize(Stream stream)
        {
            // The command should be on its own line
            string messageName = stream.ReadLine(MessageEncoding);
            //while (commandLine.Length == 0)
            //    commandLine = stream.ReadLine(MessageEncoding);

            //string[] commandTokens = commandLine.Split(" ".ToCharArray());

            IMessage message = MessageFactory.Create(messageName);
            if (message != null)
            {
                message.Deserialize(stream, MessageEncoding);
            }
            else
            {
                throw new Exception("Unknown message: " + messageName);
            }

            return message;
        }
示例#36
0
        private static void ParseHeaders(Stream stream, Action<string, string> onHeader)
        {
            string headerLine = null;

            while (true)
            {
                headerLine = stream.ReadLine();

                if (headerLine == String.Empty)
                {
                    break;
                }

                var headerReader = new StringReader(headerLine);
                string key = headerReader.ReadUntil(c => c == ':');
                headerReader.Read();
                headerReader.SkipWhitespace();
                string value = headerReader.ReadToEnd();

                onHeader(key, value);
            }
        }
示例#37
0
        protected override void ReadFirstLine(Stream stream)
        {
            var line  = stream.ReadLine();
            var parts = line.Split(new[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length < 2)
            {
                throw new Exception("Invalid HttpRequest");
            }
            Version = parts[0];
            var statusCode = 0;

            if (!int.TryParse(parts[1], out statusCode))
            {
                Errors.Add("Invalid StatusCode");
            }
            StatusCode = (HttpStatusCode)statusCode;
            if (parts.Length == 3)
            {
                StatusDescription = parts[2];
            }
        }
示例#38
0
        public override IMessage Deserialize(Stream stream)
        {
            // The command should be on its own line
            string messageName = stream.ReadLine(MessageEncoding);
            //while (commandLine.Length == 0)
            //    commandLine = stream.ReadLine(MessageEncoding);

            //string[] commandTokens = commandLine.Split(" ".ToCharArray());

            IMessage message = MessageFactory.Create(messageName);

            if (message != null)
            {
                message.Deserialize(stream, MessageEncoding);
            }
            else
            {
                throw new Exception("Unknown message: " + messageName);
            }

            return(message);
        }
示例#39
0
        private static bool ParseMultipartFile(Stream stream, FormData form, string fieldName, string fileName, byte[] boundaryBytes) {
            string contentType = null;
            string headerLine;
            while ((headerLine = stream.ReadLine(Encoding.UTF8)) != string.Empty) {
                // parse 'Content-" headers
                var match = ContentTypeFileRegex.Match(headerLine);
                if (match.Success) {
                    contentType = match.Groups[1].Value.Trim();
                }
            }
            if (contentType == null) {
                //todo: infer from file type (extension)
                contentType = "application/octet-stream";
            }

            byte[] data;
            if (!stream.ReadTo(boundaryBytes, out data)) {
                return false;
            }
            form.Files.Add(new PostedFile(fieldName, fileName, data, contentType));
            return true;
        }
示例#40
0
        private static bool ParseMultipartField(Stream stream, FormData form, string fieldName, byte[] boundaryBytes) {
            string contentType = null;
            string headerLine;
            Match match;
            while ((headerLine = stream.ReadLine(Encoding.UTF8)) != string.Empty) {
                // parse 'Content-" headers
                match = ContentTypeFormDataRegex.Match(headerLine);
                if (match.Success) {
                    // nested: Content-Type: multipart/mixed; boundary=BbC04y
                    contentType = match.Groups[1].Value.Trim();
                    if (match.Groups[2].Success) {
                        string fileBoundary = match.Groups[4].Value;
                        byte[] fileBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + fileBoundary);
                        byte[] temp;
                        if (!stream.ReadTo(fileBoundaryBytes, out temp)) {
                            return false;
                        }
                        if (stream.ReadLine(Encoding.UTF8) != string.Empty) {
                            return false;
                        }
                        bool moreFiles = true;
                        while (moreFiles) {
                            string line = stream.ReadLine(Encoding.UTF8);
                            match = ContentDispositionFileRegex.Match(line);
                            if (!match.Success) {
                                return false;
                            }
                            string filename = match.Groups[1].Value;
                            if (!ParseMultipartFile(stream, form, fieldName, filename, fileBoundaryBytes)) {
                                return false;
                            }
                            line = stream.ReadLine(Encoding.UTF8);
                            if (line == "--") {
                                moreFiles = false;
                            }
                            else if (line != string.Empty) {
                                return false;
                            }
                        }
                        // NB: CrLf already ripped here
                        var boundaryNoCrLf = new byte[boundaryBytes.Length - 2];
                        Array.Copy(boundaryBytes, 2, boundaryNoCrLf, 0, boundaryBytes.Length - 2);
                        if (!stream.ReadTo(boundaryNoCrLf, out temp)) {
                            return false;
                        }
                        if (temp.Length != 0) {
                            return false;
                        }
                        return true;
                    }
                }
            }
            if (contentType == null) {
                contentType = "text/plain";
            }

            byte[] value;
            if (!stream.ReadTo(boundaryBytes, out value)) {
                return false;
            }
            // handle charset: content-type: text/plain;charset=windows-1250
            match = CharsetRegex.Match(contentType);
            Encoding encoding = match.Success ? Encoding.GetEncoding(match.Groups[2].Value) : Encoding.UTF8;
            form[fieldName] = encoding.GetString(value);

            return true;
        }
示例#41
0
        private static string ParseMime(Stream reader, string boundary, ref int maxLength, ICollection<Attachment> attachments, Encoding encoding, char? termChar, Scope scope)
        {
            var maxLengthSpecified = maxLength > 0;
            string data = null,
                bounderInner = "--" + boundary,
                bounderOuter = bounderInner + "--";
            var n = 0;
            var body = new System.Text.StringBuilder();
            do
            {
                if (maxLengthSpecified && maxLength <= 0)
                    return body.ToString();
                if (data != null)
                {
                    body.Append(data);
                }
                data = reader.ReadLine(ref maxLength, encoding, termChar);
                n++;
            } while (data != null && !data.StartsWith(bounderInner));

            while (data != null && !data.StartsWith(bounderOuter) && !(maxLengthSpecified && maxLength == 0))
            {
                data = reader.ReadLine(ref maxLength, encoding, termChar);
                if (data == null) break;
                var a = new Attachment { Encoding = encoding };

                var part = new StringBuilder();
                // read part header
                while (!data.StartsWith(bounderInner) && data != string.Empty && !(maxLengthSpecified && maxLength == 0))
                {
                    part.AppendLine(data);
                    data = reader.ReadLine(ref maxLength, encoding, termChar);
                    if (data == null) break;
                }
                a.RawHeaders = part.ToString();
                // header body

                // check for nested part
                var nestedboundary = a.Headers.GetBoundary();
                if (!string.IsNullOrEmpty(nestedboundary))
                {
                    ParseMime(reader, nestedboundary, ref maxLength, attachments, encoding, termChar, scope);
                    while (!data.StartsWith(bounderInner))
                        data = reader.ReadLine(ref maxLength, encoding, termChar);
                }
                else
                {
                    data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
                    if (data == null) break;
                    var nestedBody = new StringBuilder();
                    while (!data.StartsWith(bounderInner) && !(maxLengthSpecified && maxLength == 0))
                    {
                        nestedBody.AppendLine(data);
                        data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
                        if (data == null)
                        {
                            throw new EndOfStreamException("Unexpected end of file");
                        }
                    }
                    if (scope > Scope.HeadersAndMime)
                    {
                        a.SetBody(nestedBody.ToString());
                    }
                    attachments.Add(a);
                }
            }
            return body.ToString();
        }
示例#42
0
        private static void ParseMime(Stream reader, string boundary, ref int maxLength, ICollection<Attachment> attachments, Encoding encoding, char? termChar)
        {
            var maxLengthSpecified = maxLength > 0;
            string data,
                bounderInner = "--" + boundary,
                bounderOuter = bounderInner + "--";

            do {
                data = reader.ReadLine(ref maxLength, encoding, termChar);
            } while (data != null && !data.StartsWith(bounderInner));

            while (data != null && !data.StartsWith(bounderOuter) && !(maxLengthSpecified && maxLength == 0)) {
                data = reader.ReadLine(ref maxLength, encoding, termChar);
                var a = new Attachment { Encoding = encoding };

                var part = new StringBuilder();
                // read part header
                while (!data.StartsWith(bounderInner) && data != string.Empty && !(maxLengthSpecified && maxLength == 0)) {
                    part.AppendLine(data);
                    data = reader.ReadLine(ref maxLength, encoding, termChar);
                }
                a.RawHeaders = part.ToString();
                // header body

                // check for nested part
                var nestedboundary = a.Headers.GetBoundary();
                if (!string.IsNullOrEmpty(nestedboundary)) {
                    ParseMime(reader, nestedboundary, ref maxLength, attachments, encoding, termChar);
                } else {
                    data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
                    var body = new StringBuilder();
                    while (!data.StartsWith(bounderInner) && !(maxLengthSpecified && maxLength == 0)) {
                        body.AppendLine(data);
                        data = reader.ReadLine(ref maxLength, a.Encoding, termChar);
                    }
                    a.SetBody(body.ToString());
                    attachments.Add(a);
                }
            }
        }
示例#43
0
        private static bool CopyHttpStream(Stream fromStream, Stream toStream, string firstLine = "", string sslTunnelDomain="")
        {
            bool keepAlive = false; 
            var encoding = Encoding.UTF8;
            string method;
            string version;
            string url;

            using (var fromStreamReader = new BinaryReader(fromStream, encoding, true))
            using (var toStreamWriter = new BinaryWriter(toStream, encoding, true))
            {
                if (String.IsNullOrEmpty(firstLine))
                    firstLine = fromStream.ReadLine();

                if (!String.IsNullOrEmpty(sslTunnelDomain))
                {
                    //modify the path in the http request to include the domain
                    ParseHttpCommand(firstLine, out method, out url, out version);
                    //modify the forward address so it has complete URL 
                    firstLine = method + ' ' + "https://" + sslTunnelDomain + url + ' ' + version;
                    firstLine += "\r\n";
                    firstLine += "X-Forward-Secure: true";
                }
                LogMessage(string.Format(firstLine));
                toStream.WriteLine(firstLine);
                toStream.Flush();

                string line;
                int contentLength = 0;
                bool chunked = false;

                //copy the headers
                while (!String.IsNullOrEmpty(line = fromStreamReader.ReadLine()))
                {
                    if (line.StartsWith("Content-Length:", true, CultureInfo.CurrentCulture))
                        contentLength = int.Parse(line.Replace("Content-Length:", ""));
                    if (line.StartsWith("Transfer-Encoding: chunked", true, CultureInfo.CurrentCulture))
                        chunked = true;
                    if (line.StartsWith("Proxy-Connection: Keep-Alive", true, CultureInfo.CurrentCulture))
                        keepAlive = true;
                    toStreamWriter.WriteLine(line);
                }
                toStreamWriter.WriteLine();
                if (contentLength > 0)
                    toStreamWriter.Write(fromStreamReader.ReadBytes(contentLength));

                if(chunked)
                {
                    while (!String.IsNullOrEmpty(line = fromStreamReader.ReadLine()))
                    {
                        contentLength = int.Parse(line, System.Globalization.NumberStyles.HexNumber);
                        toStreamWriter.Write(fromStreamReader.ReadBytes(contentLength));
                        fromStreamReader.ReadLine();
                    }
                }
                toStreamWriter.Flush();
            }
            return keepAlive;
        }
示例#44
0
        private void ParseMime(Stream reader, string boundary, int maxLength)
        {
            var maxLengthSpecified = maxLength > 0;
              string data,
            bounderInner = "--" + boundary,
            bounderOuter = bounderInner + "--";

              do {
            data = reader.ReadLine(ref maxLength, Encoding);
              } while (data != null && !data.StartsWith(bounderInner));

              while (data != null && !data.StartsWith(bounderOuter) && (maxLength > 0 || !maxLengthSpecified)) {
            data = reader.ReadLine(ref maxLength, Encoding);
            var a = new Attachment { Encoding = Encoding };

            var part = new StringBuilder();
            // read part header
            while (!data.StartsWith(bounderInner) && data != string.Empty) {
              part.AppendLine(data);
              data = reader.ReadLine(ref maxLength, Encoding);
            }
            a.RawHeaders = part.ToString();
            // header body

            data = reader.ReadLine(ref maxLength, Encoding);
            var body = new StringBuilder();
            while (data != string.Empty && !data.StartsWith(bounderInner)) {
              body.AppendLine(data);
              data = reader.ReadLine(ref maxLength, Encoding);
            }
            // check for nested part
            string nestedboundary = a.Headers.GetBoundary();
            if (!string.IsNullOrEmpty(nestedboundary)) {
              ParseMime(body.ToString(), nestedboundary);

            } else { // nested
              a.SetBody(body.ToString());
              (a.IsAttachment ? Attachments : AlternateViews).Add(a);
            }
              }

              if (maxLength > 0)
            data = reader.ReadToEnd(maxLength, Encoding);
        }
示例#45
0
		public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char? termChar = null)
		{
			_HeadersOnly = headersOnly;
			Headers = null;
			Body = null;
			if (maxLength == 0)
				return;


			var headers = new StringBuilder();
			string line;
			while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null) {
				if (line.Length == 0)
					if (headers.Length == 0)
						continue;
					else
						break;
				headers.AppendLine(line);
			}
			RawHeaders = headers.ToString();

			if (!headersOnly) {
				string boundary = Headers.GetBoundary();
				if (!string.IsNullOrEmpty(boundary)) {
					var atts = new List<Attachment>();
					var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
					if (!string.IsNullOrEmpty(body))
						SetBody(body);

					foreach (var att in atts)
						(att.IsAttachment ? Attachments : AlternateViews).Add(att);

					if (maxLength > 0)
						reader.ReadToEnd(maxLength, Encoding);
				} else {
					//	sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
					string body = String.Empty;
					if (maxLength > 0)
						body = reader.ReadToEnd(maxLength, Encoding);

					SetBody(body);
				}
			}
			else if (maxLength > 0)
				reader.ReadToEnd(maxLength, Encoding);

			if ((string.IsNullOrWhiteSpace(Body) || ContentType.StartsWith("multipart/")) && AlternateViews.Count > 0) {
				var att = AlternateViews.GetTextView() ?? AlternateViews.GetHtmlView();
				if (att != null) {
					Body = att.Body;
					ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
					ContentType = att.Headers["Content-Type"].RawValue;
				}
			}

			Date = Headers.GetDate();
			To = Headers.GetMailAddresses("To").ToList();
			Cc = Headers.GetMailAddresses("Cc").ToList();
			Bcc = Headers.GetMailAddresses("Bcc").ToList();
			Sender = Headers.GetMailAddresses("Sender").FirstOrDefault();
			ReplyTo = Headers.GetMailAddresses("Reply-To").ToList();
			From = Headers.GetMailAddresses("From").FirstOrDefault();
			MessageID = Headers["Message-ID"].RawValue;

			Importance = Headers.GetEnum<MailPriority>("Importance");
			Subject = Headers["Subject"].RawValue;
		}
示例#46
0
        public virtual void Load(Stream reader,  Scope scope, int maxLength, char? termChar = null)
        {
            Scope = scope;
            Headers = null;
            Body = null;

            var headers = new StringBuilder();
            string line;
            while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null)
            {
                if (line.Trim().Length == 0)
                    if (headers.Length == 0)
                        continue;
                    else
                        break;
                headers.AppendLine(line);
            }
            RawHeaders = headers.ToString();

            if (Scope > Scope.Headers)
            {
                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    var atts = new List<Attachment>();
                    // Read the mime structure anyways, but the body might be empty.
                    var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar, scope);
                    if (Scope > Scope.HeadersAndMime && !string.IsNullOrEmpty(body))
                    {
                        SetBody(body);
                    }

                    foreach (var att in atts)
                    {
                        Add(att);
                    }

                    if (maxLength > 0)
                        reader.ReadToEnd(maxLength, Encoding);
                }
                else if (Scope > Scope.HeadersAndMime)
                {
                    //	sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
                    string body = String.Empty;
                    if (maxLength > 0)
                        body = reader.ReadToEnd(maxLength, Encoding);

                    SetBody(body);
                }
            }

            Date = Headers.GetDate();
            To = Headers.GetMailAddresses("To").ToList();
            Cc = Headers.GetMailAddresses("Cc").ToList();
            Bcc = Headers.GetMailAddresses("Bcc").ToList();
            Sender = Headers.GetMailAddresses("Sender").FirstOrDefault();
            ReplyTo = Headers.GetMailAddresses("Reply-To").ToList();
            From = Headers.GetMailAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum<MailPriority>("Importance");
            Subject = Headers["Subject"].RawValue;
        }
示例#47
0
        private static Stream GetSslTunnelStream(Stream stream, string version = "HTTP/1.1")
        {
            SslStream sslStream = null;
            //Browser wants to create a secure tunnel
            //read and ignore headers
            while (!String.IsNullOrEmpty(stream.ReadLine())) ;
            //tell the client that a tunnel has been established              
            LogMessage(string.Format("Doing CONNECT"));
            var connectStreamWriter = new BinaryWriter(stream);
            connectStreamWriter.WriteLine(version + " 200 Connection established");
            connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
            connectStreamWriter.WriteLine("Proxy-agent: buskerproxy");
            connectStreamWriter.WriteLine();
            connectStreamWriter.Flush();

            //open a decrypting stream    
            sslStream = new SslStream(stream, false);
            try
            {
                sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
            }
            catch (Exception ex)
            {
                stream.Close();
                sslStream.Close();
                return null;
            }
            return sslStream;
        }
示例#48
0
        public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char? termChar = null)
        {
            _HeadersOnly = headersOnly;
            Headers = null;
            Body = null;

            if (headersOnly) {
                RawHeaders = reader.ReadToEnd(maxLength, _DefaultEncoding);
            } else {
                var headers = new StringBuilder();
                string line;
                while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null) {
                    if (line.Trim().Length == 0)
                        if (headers.Length == 0)
                            continue;
                        else
                            break;
                    headers.AppendLine(line);
                }
                RawHeaders = headers.ToString();

                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary)) {
                    //else this is a multipart Mime Message
                    //using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
                    var atts = new List<Attachment>();
                    ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
                    foreach (var att in atts)
                        (att.IsAttachment ? Attachments : AlternateViews).Add(att);

                    if (maxLength > 0)
                        reader.ReadToEnd(maxLength, Encoding);
                } else {
                    SetBody(reader.ReadToEnd(maxLength, Encoding).Trim());
                }
            }

            if (string.IsNullOrWhiteSpace(Body) && AlternateViews.Count > 0) {
                var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain"));
                if (att == null) {
                    att = AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));
                }

                if (att != null) {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType = att.Headers["Content-Type"].RawValue;
                }
            }

            Date = Headers.GetDate();
            To = Headers.GetAddresses("To").ToList();
            Cc = Headers.GetAddresses("Cc").ToList();
            Bcc = Headers.GetAddresses("Bcc").ToList();
            Sender = Headers.GetAddresses("Sender").FirstOrDefault();
            ReplyTo = Headers.GetAddresses("Reply-To").ToList();
            From = Headers.GetAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum<MailPriority>("Importance");
            Subject = Headers["Subject"].RawValue;
        }