Exemplo n.º 1
0
        public object Clone()
        {
            HTTPResponseHeaders headers = (HTTPResponseHeaders)base.MemberwiseClone();

            headers.storage = new List <HTTPHeaderItem>(base.storage.Count);
            foreach (HTTPHeaderItem item in base.storage)
            {
                headers.storage.Add((HTTPHeaderItem)item.Clone());
            }
            return(headers);
        }
Exemplo n.º 2
0
 private void _deleteInformationalMessage()
 {
     this.m_inHeaders = null;
     byte[] buffer = new byte[this.m_responseData.Length - this.iEntityBodyOffset];
     this.m_responseData.Position = this.iEntityBodyOffset;
     this.m_responseData.Read(buffer, 0, buffer.Length);
     this.m_responseData.Dispose();
     this.m_responseData = new MemoryStream(buffer.Length);
     this.m_responseData.Write(buffer, 0, buffer.Length);
     this.m_responseTotalDataCount = 0L;
     this.iEntityBodyOffset        = this._iBodySeekProgress = 0;
 }
Exemplo n.º 3
0
        internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders)
        {
            X509Certificate2 certificate;

            try
            {
                certificate = CertMaker.FindCert(sHostname, true);
            }
            catch (Exception exception)
            {
                //KProxyApplication.Log.LogFormat("KProxy.https> Failed to obtain certificate for {0} due to {1}", new object[] { sHostname, exception.Message });
                certificate = null;
            }
            try
            {
                if (certificate == null)
                {
                    KProxyApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure");
                    oHeaders.HTTPResponseCode   = 0x1f6;
                    oHeaders.HTTPResponseStatus = "502 KProxy unable to generate certificate";
                }
                if (KPCONFIG.bDebugSpew)
                {
                    KProxyApplication.DebugSpew("SecureClientPipe for: " + this.ToString() + " sending data to client:\n" + Utilities.ByteArrayToHexView(oHeaders.ToByteArray(true, true), 0x20));
                }
                base.Send(oHeaders.ToByteArray(true, true));
                if (oHeaders.HTTPResponseCode != 200)
                {
                    KProxyApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200");
                    return(false);
                }
                base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
                base._httpsStream.AuthenticateAsServer(certificate, _bWantClientCert, KPCONFIG.oAcceptedClientHTTPSProtocols, false);
                return(true);
            }
            catch (Exception exception2)
            {
                //KProxyApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception2.Message, (exception2.InnerException == null) ? string.Empty : (" InnerException: " + exception2.InnerException.Message) });
                KProxyApplication.DebugSpew("Secure client pipe failed: " + exception2.Message);
                try
                {
                    base.End();
                }
                catch
                {
                }
            }
            return(false);
        }
Exemplo n.º 4
0
        public static HTTPResponseHeaders ParseResponse(string sResponse)
        {
            int index = sResponse.IndexOf("\r\n\r\n", StringComparison.Ordinal);

            if (index < 1)
            {
                index = sResponse.Length;
            }
            if (index >= 1)
            {
                string[] sHeaderLines = sResponse.Substring(0, index).Replace("\r\n", "\n").Split(new char[] { '\n' });
                if (sHeaderLines.Length < 1)
                {
                    return(null);
                }
                HTTPResponseHeaders oHeaders = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding);
                int length = sHeaderLines[0].IndexOf(' ');
                if (length > 0)
                {
                    oHeaders.HTTPVersion = sHeaderLines[0].Substring(0, length).ToUpper();
                    sHeaderLines[0]      = sHeaderLines[0].Substring(length + 1).Trim();
                    if (!oHeaders.HTTPVersion.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
                    {
                        return(null);
                    }
                    oHeaders.HTTPResponseStatus = sHeaderLines[0];
                    bool flag = false;
                    length = sHeaderLines[0].IndexOf(' ');
                    if (length > 0)
                    {
                        flag = int.TryParse(sHeaderLines[0].Substring(0, length).Trim(), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out oHeaders.HTTPResponseCode);
                    }
                    else
                    {
                        flag = int.TryParse(sHeaderLines[0].Trim(), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out oHeaders.HTTPResponseCode);
                    }
                    if (!flag)
                    {
                        return(null);
                    }
                    string sErrors = string.Empty;
                    ParseNVPHeaders(oHeaders, sHeaderLines, 1, ref sErrors);
                    return(oHeaders);
                }
            }
            return(null);
        }
Exemplo n.º 5
0
 internal void Initialize(bool bAlloc)
 {
     if (bAlloc)
     {
         this.m_responseData = new MemoryStream(0x4000);
     }
     else
     {
         this.m_responseData = null;
     }
     this._lngLeakedOffset        = this._iBodySeekProgress = this.iEntityBodyOffset = 0;
     this._lngLastChunkInfoOffset = -1L;
     this.m_inHeaders             = null;
     this._bLeakedHeaders         = false;
     this.pipeServer     = null;
     this._bWasForwarded = false;
     this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, false);
 }
Exemplo n.º 6
0
        public bool AssignFromString(string sHeaders)
        {
            HTTPResponseHeaders headers = null;

            try
            {
                headers = Parser.ParseResponse(sHeaders);
            }
            catch
            {
            }
            if (headers != null)
            {
                this.HTTPResponseCode   = headers.HTTPResponseCode;
                this.HTTPResponseStatus = headers.HTTPResponseStatus;
                base.HTTPVersion        = headers.HTTPVersion;
                base.storage            = headers.storage;
                return(true);
            }
            return(false);
        }
Exemplo n.º 7
0
        internal bool ReadResponseFromFile(string sFilename)
        {
            string str2;

            if (System.IO.File.Exists(sFilename))
            {
                FileStream oStream  = System.IO.File.OpenRead(sFilename);
                byte[]     arrBytes = new byte[oStream.Length];
                Utilities.ReadEntireStream(oStream, arrBytes);
                oStream.Close();
                this.Initialize(true);
                int  length = arrBytes.Length;
                int  index  = 0;
                bool flag   = (((arrBytes.Length > 3) && (arrBytes[0] == 0xef)) && (arrBytes[1] == 0xbb)) && (arrBytes[2] == 0xbf);
                if (flag)
                {
                    index   = 3;
                    length -= 3;
                }
                bool flag2 = ((((arrBytes.Length > (5 + index)) && (arrBytes[index] == 0x48)) && ((arrBytes[index + 1] == 0x54) && (arrBytes[index + 2] == 0x54))) && (arrBytes[index + 3] == 80)) && (arrBytes[index + 4] == 0x2f);
                if (flag && !flag2)
                {
                    length += 3;
                    index   = 0;
                }
                this.m_responseData.Write(arrBytes, index, length);
                if ((flag2 && this.HeadersAvailable()) && this.ParseResponseForHeaders())
                {
                    this.m_session.responseBodyBytes = this.TakeEntity();
                }
                else
                {
                    this.Initialize(false);
                    this.m_inHeaders = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding);
                    this.m_inHeaders.HTTPResponseCode   = 200;
                    this.m_inHeaders.HTTPResponseStatus = "200 OK with automatic headers";
                    this.m_inHeaders["Content-Length"]  = arrBytes.LongLength.ToString();
                    this.m_inHeaders["Cache-Control"]   = "max-age=0, must-revalidate";
                    string str = Utilities.ContentTypeForFileExtension(Path.GetExtension(sFilename));
                    if (str != null)
                    {
                        this.m_inHeaders["Content-Type"] = str;
                    }
                    this.m_session.responseBodyBytes = arrBytes;
                }
                return(true);
            }
            this.Initialize(false);
            if ((this.m_session.LocalProcessID > 0) || this.m_session.isFlagSet(SessionFlags.RequestGeneratedByKProxy))
            {
                str2 = "KProxy - The file '" + sFilename + "' was not found.";
            }
            else
            {
                str2 = "KProxy - The requested file was not found.";
            }
            str2 = str2.PadRight(0x200, ' ');
            this.m_session.responseBodyBytes = Encoding.UTF8.GetBytes(str2);
            this.m_inHeaders = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding);
            this.m_inHeaders.HTTPResponseCode   = 0x194;
            this.m_inHeaders.HTTPResponseStatus = "404 Not Found";
            this.m_inHeaders.Add("Content-Length", this.m_session.responseBodyBytes.Length.ToString());
            this.m_inHeaders.Add("Cache-Control", "max-age=0, must-revalidate");
            return(false);
        }
Exemplo n.º 8
0
        internal bool ReadResponse()
        {
            int  iMaxByteCount = 0;
            bool flag          = false;
            bool flag2         = false;
            bool flag3         = false;

            byte[] arrBuffer = new byte[_cbServerReadBuffer];
            do
            {
                try
                {
                    iMaxByteCount = this.pipeServer.Receive(arrBuffer);
                    if (0L == this.m_session.Timers.ServerBeginResponse.Ticks)
                    {
                        this.m_session.Timers.ServerBeginResponse = DateTime.Now;
                    }
                    if (iMaxByteCount <= 0)
                    {
                        flag = true;
                        KProxyApplication.DoReadResponseBuffer(this.m_session, arrBuffer, 0);
                    }
                    else
                    {
                        if (KPCONFIG.bDebugSpew)
                        {
                            KProxyApplication.DebugSpew(Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount));
                        }
                        if (!KProxyApplication.DoReadResponseBuffer(this.m_session, arrBuffer, iMaxByteCount))
                        {
                            flag2 = true;
                        }
                        this.m_responseData.Write(arrBuffer, 0, iMaxByteCount);
                        this.m_responseTotalDataCount += iMaxByteCount;
                        if ((this.m_inHeaders == null) && this.GetHeaders())
                        {
                            this.m_session.Timers.KProxyGotResponseHeaders = DateTime.Now;
                            if ((this.m_session.state == SessionStates.Aborted) && this.m_session.isAnyFlagSet(SessionFlags.ProtocolViolationInResponse))
                            {
                                return(false);
                            }
                            KProxyApplication.DoResponseHeadersAvailable(this.m_session);
                            if (KPCONFIG.bStreamAudioVideo)
                            {
                                string str = this.m_inHeaders["Content-Type"];
                                if ((str.StartsWith("video/", StringComparison.OrdinalIgnoreCase) || str.StartsWith("audio/", StringComparison.OrdinalIgnoreCase)) || str.StartsWith("application/x-mms-framed", StringComparison.OrdinalIgnoreCase))
                                {
                                    this.m_session.bBufferResponse = false;
                                }
                            }
                            if (!this.m_session.bBufferResponse)
                            {
                                this.m_session.bBufferResponse = this.m_session.HTTPMethodIs("CONNECT");
                            }
                            if (!this.m_session.bBufferResponse && (this.m_session.oRequest.pipeClient == null))
                            {
                                this.m_session.bBufferResponse = true;
                            }
                            if ((!this.m_session.bBufferResponse && ((0x191 == this.m_inHeaders.HTTPResponseCode) || (0x197 == this.m_inHeaders.HTTPResponseCode))) && this.m_session.oFlags.ContainsKey("x-AutoAuth"))
                            {
                                this.m_session.bBufferResponse = true;
                            }
                            this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, !this.m_session.bBufferResponse);
                            if (!this.m_session.bBufferResponse)
                            {
                                if (this.m_session.oFlags.ContainsKey("response-trickle-delay"))
                                {
                                    int num2 = int.Parse(this.m_session.oFlags["response-trickle-delay"]);
                                    this.m_session.oRequest.pipeClient.TransmitDelay = num2;
                                }
                                if (this.m_session.oFlags.ContainsKey("log-drop-response-body") || KProxyApplication.Prefs.GetBoolPref("KProxy.network.streaming.ForgetStreamedData", false))
                                {
                                    flag3 = true;
                                }
                            }
                        }
                        if ((this.m_inHeaders != null) && this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
                        {
                            this.LeakResponseBytes();
                            if (flag3)
                            {
                                this.m_session.SetBitFlag(SessionFlags.ResponseBodyDropped, true);
                                if (this._lngLastChunkInfoOffset > -1L)
                                {
                                    this.ReleaseStreamedChunkedData();
                                }
                                else if (this.m_inHeaders.ExistsAndContains("Transfer-Encoding", "chunked"))
                                {
                                    this.ReleaseStreamedChunkedData();
                                }
                                else
                                {
                                    this.ReleaseStreamedData();
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    flag2 = true;
                    if (exception is OperationCanceledException)
                    {
                        this.m_session.state = SessionStates.Aborted;
                    }
                    else if (exception is OutOfMemoryException)
                    {
                        KProxyApplication.ReportException(exception);
                        this.m_session.state = SessionStates.Aborted;
                    }
                    else
                    {
                    }
                }
            }while ((!flag && !flag2) && ((this.m_inHeaders == null) || !this.isResponseBodyComplete()));
            this.m_session.Timers.ServerDoneResponse = DateTime.Now;
            if (this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
            {
                this.m_session.Timers.ClientDoneResponse = this.m_session.Timers.ServerDoneResponse;
            }
            if ((this.m_responseTotalDataCount == 0L) && (this.m_inHeaders == null))
            {
                flag2 = true;
            }
            arrBuffer = null;
            if (flag2)
            {
                this.m_responseData.Dispose();
                this.m_responseData = null;
                return(false);
            }
            if (this.m_inHeaders == null)
            {
                KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "The Server did not return properly formatted HTTP Headers. Maybe missing altogether (e.g. HTTP/0.9), maybe only \\r\\r instead of \\r\\n\\r\\n?\n");
                this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, false);
                this.m_inHeaders                    = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding);
                this.m_inHeaders.HTTPVersion        = "HTTP/1.0";
                this.m_inHeaders.HTTPResponseCode   = 200;
                this.m_inHeaders.HTTPResponseStatus = "200 This buggy server did not return headers";
                this.iEntityBodyOffset              = 0;
                return(true);
            }
            return(true);
        }
Exemplo n.º 9
0
 private bool ParseResponseForHeaders()
 {
     if ((this.m_responseData != null) && (this.iEntityBodyOffset >= 4))
     {
         this.m_inHeaders = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding);
         byte[] bytes = this.m_responseData.GetBuffer();
         string str   = KPCONFIG.oHeaderEncoding.GetString(bytes, 0, this.iEntityBodyOffset).Trim();
         if ((str == null) || (str.Length < 1))
         {
             this.m_inHeaders = null;
             return(false);
         }
         string[] sHeaderLines = str.Replace("\r\n", "\n").Split(new char[] { '\n' });
         if (sHeaderLines.Length >= 1)
         {
             int index = sHeaderLines[0].IndexOf(' ');
             if (index > 0)
             {
                 this.m_inHeaders.HTTPVersion = sHeaderLines[0].Substring(0, index).ToUpper();
                 sHeaderLines[0] = sHeaderLines[0].Substring(index + 1).Trim();
                 if (!this.m_inHeaders.HTTPVersion.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
                 {
                     if (!this.m_inHeaders.HTTPVersion.StartsWith("ICY", StringComparison.OrdinalIgnoreCase))
                     {
                         KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Response does not start with HTTP. Data:\n\n\t" + sHeaderLines[0]);
                         return(false);
                     }
                     this.m_session.bBufferResponse = false;
                     this.m_session.oFlags["log-drop-response-body"] = "ICY";
                 }
                 this.m_inHeaders.HTTPResponseStatus = sHeaderLines[0];
                 bool flag = false;
                 index = sHeaderLines[0].IndexOf(' ');
                 if (index > 0)
                 {
                     flag = int.TryParse(sHeaderLines[0].Substring(0, index).Trim(), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out this.m_inHeaders.HTTPResponseCode);
                 }
                 else
                 {
                     string s = sHeaderLines[0].Trim();
                     flag = int.TryParse(s, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out this.m_inHeaders.HTTPResponseCode);
                     if (!flag)
                     {
                         for (int i = 0; i < s.Length; i++)
                         {
                             if (!char.IsDigit(s[i]))
                             {
                                 flag = int.TryParse(s.Substring(0, i), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out this.m_inHeaders.HTTPResponseCode);
                                 if (flag)
                                 {
                                     KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, false, "The response's status line was missing a space between ResponseCode and ResponseStatus. Data:\n\n\t" + s);
                                 }
                                 break;
                             }
                         }
                     }
                 }
                 if (!flag)
                 {
                     KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "The response's status line did not contain a ResponseCode. Data:\n\n\t" + sHeaderLines[0]);
                     return(false);
                 }
                 string sErrors = string.Empty;
                 if (!Parser.ParseNVPHeaders(this.m_inHeaders, sHeaderLines, 1, ref sErrors))
                 {
                     KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Incorrectly formed response headers.\n" + sErrors);
                 }
                 return(true);
             }
             KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Cannot parse HTTP response; Status line contains no spaces. Data:\n\n\t" + sHeaderLines[0]);
         }
     }
     return(false);
 }
Exemplo n.º 10
0
 internal ServerChatter(Session oSession, string sHeaders)
 {
     this._lngLastChunkInfoOffset = -1L;
     this.m_session   = oSession;
     this.m_inHeaders = Parser.ParseResponse(sHeaders);
 }