Inheritance: Fiddler.HTTPHeaders, ICloneable
Beispiel #1
0
        public override bool AssignFromString(string sHeaders)
        {
            if (string.IsNullOrEmpty(sHeaders))
            {
                throw new ArgumentException("Header string must not be null or empty");
            }
            if (!sHeaders.Contains("\r\n\r\n"))
            {
                sHeaders += "\r\n\r\n";
            }
            HTTPResponseHeaders hTTPResponseHeaders = null;

            try
            {
                hTTPResponseHeaders = Parser.ParseResponse(sHeaders);
            }
            catch (Exception)
            {
            }
            if (hTTPResponseHeaders == null)
            {
                return(false);
            }
            this.SetStatus(hTTPResponseHeaders.HTTPResponseCode, hTTPResponseHeaders.HTTPResponseStatus);
            this.HTTPVersion = hTTPResponseHeaders.HTTPVersion;
            this.storage     = hTTPResponseHeaders.storage;
            return(true);
        }
Beispiel #2
0
 private bool ImportSessions(Session[] oSessions, string sAnnotation)
 {
     if (oSessions == null)
     {
         return(false);
     }
     foreach (Session session in oSessions)
     {
         if ((!session.HTTPMethodIs("CONNECT") && session.bHasResponse) && (session.oResponse != null))
         {
             string sRule        = "EXACT:" + session.fullUrl;
             string sDescription = string.Format("*{0}-{1}", session.responseCode, (sAnnotation == null) ? ("SESSION_" + session.id.ToString()) : (sAnnotation + "#" + session.oFlags["x-LoadedFrom"]));
             int    iLatencyMS   = 0;
             if (session.Timers != null)
             {
                 TimeSpan span = (TimeSpan)(session.Timers.ServerBeginResponse - session.Timers.ClientDoneRequest);
                 iLatencyMS = (int)span.TotalMilliseconds;
             }
             byte[] arrResponseBody  = (byte[])session.responseBodyBytes.Clone();
             HTTPResponseHeaders oRH = (HTTPResponseHeaders)session.oResponse.headers.Clone();
             this.AddRule(sRule, oRH, arrResponseBody, sDescription, iLatencyMS, true);
         }
     }
     this._bRuleListIsDirty = true;
     return(true);
 }
Beispiel #3
0
        internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders)
        {
            X509Certificate2 x509Certificate;

            try
            {
                x509Certificate = CertMaker.FindCert(sHostname);
            }
            catch (Exception ex)
            {
                FiddlerApplication.Log.LogFormat("fiddler.https> Failed to obtain certificate for {0} due to {1}", new object[]
                {
                    sHostname,
                    ex.Message
                });
                x509Certificate = null;
            }
            try
            {
                if (x509Certificate == null)
                {
                    FiddlerApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure");
                    oHeaders.SetStatus(502, "Fiddler unable to generate certificate");
                }
                if (CONFIG.bDebugSpew)
                {
                    FiddlerApplication.DebugSpew("SecureClientPipe for: " + this.ToString() + " sending data to client:\n" + Utilities.ByteArrayToHexView(oHeaders.ToByteArray(true, true), 32));
                }
                base.Send(oHeaders.ToByteArray(true, true));
                bool result;
                if (oHeaders.HTTPResponseCode != 200)
                {
                    FiddlerApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200");
                    result = false;
                    return(result);
                }
                this._httpsStream = new SslStream(new NetworkStream(this._baseSocket, false), false);
                this._httpsStream.AuthenticateAsServer(x509Certificate, ClientPipe._bWantClientCert, CONFIG.oAcceptedClientHTTPSProtocols, false);
                result = true;
                return(result);
            }
            catch (Exception eX)
            {
                FiddlerApplication.Log.LogFormat("SecureClientPipe ({0} failed: {1}.", new object[]
                {
                    sHostname,
                    Utilities.DescribeException(eX)
                });
                try
                {
                    base.End();
                }
                catch (Exception)
                {
                }
            }
            return(false);
        }
Beispiel #4
0
        public object Clone()
        {
            HTTPResponseHeaders hTTPResponseHeaders = (HTTPResponseHeaders)base.MemberwiseClone();

            hTTPResponseHeaders.storage = new List <HTTPHeaderItem>(this.storage.Count);
            foreach (HTTPHeaderItem current in this.storage)
            {
                hTTPResponseHeaders.storage.Add((HTTPHeaderItem)current.Clone());
            }
            return(hTTPResponseHeaders);
        }
        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);
        }
 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;
 }
 private bool ParseResponseForHeaders()
 {
     if ((this.m_responseData != null) && (this.iEntityBodyOffset >= 4))
     {
         this.m_inHeaders = new HTTPResponseHeaders(CONFIG.oHeaderEncoding);
         byte[] bytes = this.m_responseData.GetBuffer();
         string str   = CONFIG.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))
                 {
                     FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Response does not start with HTTP. Data:\n\n\t" + sHeaderLines[0]);
                     return(false);
                 }
                 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
                 {
                     flag = int.TryParse(sHeaderLines[0].Trim(), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out this.m_inHeaders.HTTPResponseCode);
                 }
                 if (!flag)
                 {
                     FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Response headers did not contain a status code. Data:\n\n\t" + sHeaderLines[0]);
                     return(false);
                 }
                 string sErrors = string.Empty;
                 if (!Parser.ParseNVPHeaders(this.m_inHeaders, sHeaderLines, 1, ref sErrors))
                 {
                     FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Incorrectly formed response headers.\n" + sErrors);
                 }
                 return(true);
             }
             FiddlerApplication.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);
 }
 public UIARRuleEditor(ResponderRule oRR)
 {
     this.InitializeComponent();
     this._oOwningRule = oRR;
     base.Icon         = FiddlerApplication.UI.Icon;
     FiddlerApplication.oInspectors.AddResponseInspectorsToTabControl(this.tabsResponseEditors);
     this.tmpRH = (HTTPResponseHeaders)this._oOwningRule._oResponseHeaders.Clone();
     this.tmpRB = (byte[])this._oOwningRule._arrResponseBodyBytes.Clone();
     this.Text  = "Fiddler - AutoResponse for " + this._oOwningRule.sMatch;
     FiddlerApplication.UI.actActivateTabByTitle("Headers", this.tabsResponseEditors);
     this.actUpdateEditor();
 }
Beispiel #9
0
 internal ResponderRule(string strMatch, HTTPResponseHeaders oResponseHeaders, byte[] arrResponseBytes, string strDescription, int iLatencyMS, bool bEnabled)
 {
     this._bEnabled             = true;
     this.sMatch                = strMatch;
     this.sAction               = strDescription;
     this.iLatency              = iLatencyMS;
     this._oResponseHeaders     = oResponseHeaders;
     this._arrResponseBodyBytes = arrResponseBytes;
     if ((this._oResponseHeaders != null) && (this._arrResponseBodyBytes == null))
     {
         this._arrResponseBodyBytes = new byte[0];
     }
     this._bEnabled = bEnabled;
 }
Beispiel #10
0
        internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders)
        {
            X509Certificate2 certificate;

            try
            {
                certificate = CertMaker.FindCert(sHostname, true);
            }
            catch (Exception exception)
            {
                FiddlerApplication.Log.LogFormat("fiddler.https> Failed to obtain certificate for {0} due to {1}", new object[] { sHostname, exception.Message });
                certificate = null;
            }
            try
            {
                if (certificate == null)
                {
                    FiddlerApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure");
                    oHeaders.HTTPResponseCode   = 0x1f6;
                    oHeaders.HTTPResponseStatus = "502 Fiddler unable to generate certificate";
                }
                if (CONFIG.bDebugSpew)
                {
                    FiddlerApplication.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)
                {
                    FiddlerApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200");
                    return(false);
                }
                base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
                base._httpsStream.AuthenticateAsServer(certificate, _bWantClientCert, CONFIG.oAcceptedClientHTTPSProtocols, false);
                return(true);
            }
            catch (Exception exception2)
            {
                FiddlerApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception2.Message, (exception2.InnerException == null) ? string.Empty : (" InnerException: " + exception2.InnerException.Message) });
                FiddlerApplication.DebugSpew("Secure client pipe failed: " + exception2.Message);
                try
                {
                    base.End();
                }
                catch (Exception)
                {
                }
            }
            return(false);
        }
Beispiel #11
0
 private void miRespondCloneRule_Click(object sender, EventArgs e)
 {
     if (this.lvRespondRules.SelectedItems.Count == 1)
     {
         ResponderRule       tag             = (ResponderRule)this.lvRespondRules.SelectedItems[0].Tag;
         byte[]              arrResponseBody = null;
         HTTPResponseHeaders oRH             = null;
         if (tag.HasImportedResponse)
         {
             oRH             = (HTTPResponseHeaders)tag._oResponseHeaders.Clone();
             arrResponseBody = (byte[])tag._arrResponseBodyBytes.Clone();
         }
         FiddlerApplication._AutoResponder.AddRule(tag.sMatch, oRH, arrResponseBody, tag.sAction, tag.iLatency, tag.IsEnabled);
     }
 }
Beispiel #12
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(CONFIG.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);
        }
 private void actUpdateFields(IResponseInspector2 oRI)
 {
     if ((oRI != null) && oRI.bDirty)
     {
         if (oRI.headers != null)
         {
             this.tmpRH = oRI.headers;
         }
         if (oRI.body != null)
         {
             this.tmpRB = oRI.body;
         }
         if (this.tmpRH.Exists("Content-Length"))
         {
             this.tmpRH["Content-Length"] = this.tmpRB.LongLength.ToString();
         }
     }
 }
 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);
 }
Beispiel #15
0
        public static HTTPResponseHeaders ParseResponse(string sResponse)
        {
            string[] array = Parser._GetHeaderLines(sResponse);
            if (array == null)
            {
                return(null);
            }
            HTTPResponseHeaders hTTPResponseHeaders = new HTTPResponseHeaders(CONFIG.oHeaderEncoding);
            int num = array[0].IndexOf(' ');

            if (num <= 0)
            {
                return(null);
            }
            hTTPResponseHeaders.HTTPVersion = array[0].Substring(0, num).ToUpperInvariant();
            array[0] = array[0].Substring(num + 1).Trim();
            if (!hTTPResponseHeaders.HTTPVersion.OICStartsWith("HTTP/"))
            {
                return(null);
            }
            hTTPResponseHeaders.HTTPResponseStatus = array[0];
            num = array[0].IndexOf(' ');
            bool flag;

            if (num > 0)
            {
                flag = int.TryParse(array[0].Substring(0, num).Trim(), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out hTTPResponseHeaders.HTTPResponseCode);
            }
            else
            {
                flag = int.TryParse(array[0].Trim(), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out hTTPResponseHeaders.HTTPResponseCode);
            }
            if (!flag)
            {
                return(null);
            }
            string empty = string.Empty;

            Parser.ParseNVPHeaders(hTTPResponseHeaders, array, 1, ref empty);
            return(hTTPResponseHeaders);
        }
        public bool AssignFromString(string sHeaders)
        {
            HTTPResponseHeaders headers = null;

            try
            {
                headers = Parser.ParseResponse(sHeaders);
            }
            catch (Exception)
            {
            }
            if (headers != null)
            {
                this.HTTPResponseCode   = headers.HTTPResponseCode;
                this.HTTPResponseStatus = headers.HTTPResponseStatus;
                base.HTTPVersion        = headers.HTTPVersion;
                base.storage            = headers.storage;
                return(true);
            }
            return(false);
        }
Beispiel #17
0
 public ResponderRule AddRule(string sRule, HTTPResponseHeaders oRH, byte[] arrResponseBody, string sDescription, int iLatencyMS, bool bEnabled)
 {
     try
     {
         ResponderRule item = new ResponderRule(sRule, oRH, arrResponseBody, sDescription, iLatencyMS, bEnabled);
         try
         {
             this._RWLockRules.AcquireWriterLock(-1);
             this._alRules.Add(item);
         }
         finally
         {
             this._RWLockRules.ReleaseWriterLock();
         }
         this._bRuleListIsDirty = true;
         this.CreateViewItem(item);
         return(item);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Beispiel #18
0
        internal bool ConvertToFileBackedRule()
        {
            if (this._oResponseHeaders == null)
            {
                return(false);
            }
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + this._MakeSafeFilename(this._sAction);
            string str3 = Utilities.FileExtensionForMIMEType(Utilities.TrimAfter(this._oResponseHeaders["Content-Type"], ";"));

            path = path + str3;
            FileStream stream = File.Create(path);
            bool       flag   = true;

            if (this._oResponseHeaders.HTTPResponseCode == 200)
            {
                string str2 = this._oResponseHeaders["Content-Type"];
                if (str2.StartsWith("image/"))
                {
                    flag = false;
                }
            }
            if (flag)
            {
                byte[] buffer = this._oResponseHeaders.ToByteArray(true, true);
                stream.Write(buffer, 0, buffer.Length);
            }
            if (this._arrResponseBodyBytes != null)
            {
                stream.Write(this._arrResponseBodyBytes, 0, this._arrResponseBodyBytes.Length);
            }
            stream.Close();
            this._oResponseHeaders     = null;
            this._arrResponseBodyBytes = null;
            this._sAction = path;
            this.ViewItem.SubItems[1].Text = this._sAction;
            return(true);
        }
        public byte[] Decode(byte[] body, bool encoded, HTTPResponseHeaders headers)
        {
            if (encoded)
            {
                // decode body
                byte[] numArray = Utilities.Dupe(body);
                Utilities.utilDecodeHTTPBody(headers, ref numArray);
                body = numArray;
            }

            // get body as string
            string raw = Encoding.Default.GetString(body);

            // convert to json
            dynamic json = JsonConvert.DeserializeObject(raw);

            // decode and decompress the json
            DecodeInternal(json);

            // serialize json back to bytes
            body = Encoding.Default.GetBytes(JsonConvert.SerializeObject(json));

            return encoded ? Util.Compress(body) : body;
        }
Beispiel #20
0
        public static bool TakeResponse(MemoryStream strmServer, string sRequestMethod, out HTTPResponseHeaders headersResponse, out byte[] arrResponseBody)
        {
            headersResponse = null;
            arrResponseBody = Utilities.emptyByteArray;
            if (strmServer.Length - strmServer.Position < 16L)
            {
                return(false);
            }
            byte[] buffer = strmServer.GetBuffer();
            long   length = strmServer.Length;
            int    num    = (int)strmServer.Position;
            HTTPHeaderParseWarnings hTTPHeaderParseWarnings;

            if (!Parser.FindEndOfHeaders(buffer, ref num, length, out hTTPHeaderParseWarnings))
            {
                return(false);
            }
            byte[] array = new byte[(long)(1 + num) - strmServer.Position];
            strmServer.Read(array, 0, array.Length);
            string @string = CONFIG.oHeaderEncoding.GetString(array);

            headersResponse = Parser.ParseResponse(@string);
            if (headersResponse == null)
            {
                return(false);
            }
            if (sRequestMethod == "HEAD")
            {
                return(true);
            }
            int num2 = Parser._GetEntityLengthFromHeaders(headersResponse, strmServer);

            arrResponseBody = new byte[num2];
            strmServer.Read(arrResponseBody, 0, arrResponseBody.Length);
            return(true);
        }
Beispiel #21
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.Capacity = length;
         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(CONFIG.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.RequestGeneratedByFiddler))
     {
         str2 = "Fiddler - The file '" + sFilename + "' was not found.";
     }
     else
     {
         str2 = "Fiddler - The requested file was not found.";
     }
     str2 = str2.PadRight(0x200, ' ');
     this.m_session.responseBodyBytes = Encoding.UTF8.GetBytes(str2);
     this.m_inHeaders = new HTTPResponseHeaders(CONFIG.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;
 }
Beispiel #22
0
 public static void MakeFTPRequest(Session oSession, ref PipeReadBuffer buffBody, out HTTPResponseHeaders oRH)
 {
     FtpWebResponse response;
     if ((oSession.oRequest == null) || (oSession.oRequest.headers == null))
     {
         throw new ArgumentException("Session missing request objects.");
     }
     if (buffBody == null)
     {
         throw new ArgumentException("Response Stream may not be null.");
     }
     string fullUrl = oSession.fullUrl;
     FtpWebRequest request = (FtpWebRequest) WebRequest.Create(fullUrl);
     request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
     if (fullUrl.EndsWith("/"))
     {
         request.Method = "LIST";
     }
     else
     {
         request.Method = "RETR";
         if (oSession.oFlags.ContainsKey("FTP-UseASCII"))
         {
             request.UseBinary = false;
         }
         else
         {
             request.UseBinary = FiddlerApplication.Prefs.GetBoolPref("fiddler.ftp.UseBinary", true);
         }
     }
     if (!string.IsNullOrEmpty(oSession.oRequest.headers._uriUserInfo))
     {
         string sString = Utilities.UrlDecode(Utilities.TrimAfter(oSession.oRequest.headers._uriUserInfo, '@'));
         string userName = Utilities.TrimAfter(sString, ':');
         string password = sString.Contains(":") ? Utilities.TrimBefore(sString, ':') : string.Empty;
         request.Credentials = new NetworkCredential(userName, password);
     }
     else if (oSession.oRequest.headers.ExistsAndContains("Authorization", "Basic "))
     {
         string s = oSession.oRequest.headers["Authorization"].Substring(6);
         s = Encoding.UTF8.GetString(Convert.FromBase64String(s));
         string str6 = Utilities.TrimAfter(s, ':');
         string str7 = Utilities.TrimBefore(s, ':');
         request.Credentials = new NetworkCredential(str6, str7);
     }
     else if (oSession.oFlags.ContainsKey("x-AutoAuth") && oSession.oFlags["x-AutoAuth"].Contains(":"))
     {
         string str8 = Utilities.TrimAfter(oSession.oFlags["x-AutoAuth"], ':');
         string str9 = Utilities.TrimBefore(oSession.oFlags["x-AutoAuth"], ':');
         request.Credentials = new NetworkCredential(str8, str9);
     }
     else if (FiddlerApplication.Prefs.GetBoolPref("fiddler.ftp.AlwaysDemandCredentials", false))
     {
         byte[] bytes = Encoding.UTF8.GetBytes("Please provide login credentials for this FTP server".PadRight(0x200, ' '));
         buffBody.Write(bytes, 0, bytes.Length);
         oRH = new HTTPResponseHeaders();
         oRH.HTTPResponseCode = 0x191;
         oRH.HTTPResponseStatus = "401 Need Creds";
         oRH.Add("Content-Length", buffBody.Length.ToString());
         oRH.Add("WWW-Authenticate", "Basic realm=\"ftp://" + oSession.host + "\"");
         return;
     }
     request.UsePassive = FiddlerApplication.Prefs.GetBoolPref("fiddler.ftp.UsePassive", true);
     request.Proxy = null;
     try
     {
         response = (FtpWebResponse) request.GetResponse();
     }
     catch (WebException exception)
     {
         byte[] buffer2;
         FtpWebResponse response2 = (FtpWebResponse) exception.Response;
         if (response2 != null)
         {
             if (FtpStatusCode.NotLoggedIn == response2.StatusCode)
             {
                 buffer2 = Encoding.UTF8.GetBytes("This FTP server requires login credentials".PadRight(0x200, ' '));
                 buffBody.Write(buffer2, 0, buffer2.Length);
                 oRH = new HTTPResponseHeaders();
                 oRH.HTTPResponseCode = 0x191;
                 oRH.HTTPResponseStatus = "401 Need Creds";
                 oRH.Add("Content-Length", buffBody.Length.ToString());
                 oRH.Add("WWW-Authenticate", "Basic realm=\"ftp://" + oSession.host + "\"");
                 return;
             }
             buffer2 = Encoding.UTF8.GetBytes(string.Format("{0}{1}{2}", "Fiddler was unable to act as a HTTP-to-FTP gateway for this response. ", response2.StatusDescription, string.Empty.PadRight(0x200, ' ')));
             buffBody.Write(buffer2, 0, buffer2.Length);
         }
         else
         {
             buffer2 = Encoding.UTF8.GetBytes(string.Format("{0}{1}{2}", "Fiddler was unable to act as a HTTP-to-FTP gateway for this response. ", exception.Message, string.Empty.PadRight(0x200, ' ')));
             buffBody.Write(buffer2, 0, buffer2.Length);
         }
         oRH = new HTTPResponseHeaders();
         oRH.HTTPResponseCode = 0x1f8;
         oRH.HTTPResponseStatus = "504 HTTP-FTP Gateway failed";
         oRH.Add("Content-Length", buffBody.Length.ToString());
         return;
     }
     Stream responseStream = response.GetResponseStream();
     byte[] buffer3 = new byte[0x2000];
     for (int i = responseStream.Read(buffer3, 0, 0x2000); i > 0; i = responseStream.Read(buffer3, 0, 0x2000))
     {
         buffBody.Write(buffer3, 0, i);
     }
     oRH = new HTTPResponseHeaders();
     oRH.HTTPResponseCode = 200;
     oRH.HTTPResponseStatus = "200 OK";
     oRH.Add("FTP-Status", Utilities.ConvertCRAndLFToSpaces(response.StatusDescription));
     oRH.Add("Content-Length", buffBody.Length.ToString());
     response.Close();
 }
 private bool ParseResponseForHeaders()
 {
     if ((this.m_responseData != null) && (this.iEntityBodyOffset >= 4))
     {
         this.m_inHeaders = new HTTPResponseHeaders(CONFIG.oHeaderEncoding);
         byte[] bytes = this.m_responseData.GetBuffer();
         string str = CONFIG.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).ToUpperInvariant();
                 sHeaderLines[0] = sHeaderLines[0].Substring(index + 1).Trim();
                 if (!this.m_inHeaders.HTTPVersion.OICStartsWith("HTTP/"))
                 {
                     if (!this.m_inHeaders.HTTPVersion.OICStartsWith("ICY"))
                     {
                         FiddlerApplication.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)
                                 {
                                     FiddlerApplication.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)
                 {
                     FiddlerApplication.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))
                 {
                     FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "Incorrectly formed response headers.\n" + sErrors);
                 }
                 return true;
             }
             FiddlerApplication.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;
 }
        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(CONFIG.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.RequestGeneratedByFiddler))
            {
                str2 = "Fiddler - The file '" + sFilename + "' was not found.";
            }
            else
            {
                str2 = "Fiddler - The requested file was not found.";
            }
            str2 = str2.PadRight(0x200, ' ');
            this.m_session.responseBodyBytes = Encoding.UTF8.GetBytes(str2);
            this.m_inHeaders = new HTTPResponseHeaders(CONFIG.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);
        }
        /// <summary>
        /// CreateResponseHeaders returns a set of common response headers.
        /// </summary>
        /// <param name="tableUri">The table URI to include in the Location header. Null of empty if no location.</param>
        /// <returns></returns>
        private static HTTPResponseHeaders CreateResponseHeaders(string tableUri)
        {
            HTTPResponseHeaders headers = new HTTPResponseHeaders();
            headers["Transfer-Encoding"] = "chunked";
            headers["Date"] = DateTime.UtcNow.ToString("R");
            headers["Cache-Control"] = "no-cache";

            if (!string.IsNullOrEmpty(tableUri))
            {
                headers["Location"] = tableUri;
            }

            headers["Content-Type"] = "application/atom+xml;charset=utf-8";
            headers["x-ms-version"] = TableConstants.XMsVersion;
            headers["x-ms-request-id"] = Guid.Empty.ToString();

            return headers;
        }
 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 PipeReadBuffer(buffer.Length);
     this.m_responseData.Write(buffer, 0, buffer.Length);
     this.m_responseTotalDataCount = 0L;
     this.iEntityBodyOffset = this._iBodySeekProgress = 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;
                    }
                    else
                    {
                        if (CONFIG.bDebugSpew)
                        {
                            FiddlerApplication.DebugSpew(Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount));
                        }
                        this.m_responseData.Write(arrBuffer, 0, iMaxByteCount);
                        this.m_responseTotalDataCount += iMaxByteCount;
                        if ((this.m_inHeaders == null) && this.GetHeaders())
                        {
                            if ((this.m_session.state == SessionStates.Aborted) && this.m_session.isAnyFlagSet(SessionFlags.ProtocolViolationInResponse))
                            {
                                return(false);
                            }
                            FiddlerApplication.DoResponseHeadersAvailable(this.m_session);
                            if (CONFIG.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.ExecuteBasicResponseManipulationsUsingHeadersOnly();
                            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") || FiddlerApplication.Prefs.GetBoolPref("fiddler.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;
                        FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} was aborted {1}", new object[] { this.m_session.id, exception.Message });
                    }
                    else if (exception is OutOfMemoryException)
                    {
                        FiddlerApplication.ReportException(exception);
                        this.m_session.state = SessionStates.Aborted;
                        FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} Out of Memory", new object[] { this.m_session.id });
                    }
                    else
                    {
                        FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} raised exception {1}", new object[] { this.m_session.id, exception.Message });
                    }
                }
            }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)
            {
                FiddlerApplication.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(CONFIG.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);
        }
 public void Clear()
 {
     this.myControl.Clear();
     this.oHeaders = null;
     this.oEncoding = null;
 }
 private void _ReturnFileReadError(string sRemoteError, string sTrustedError)
 {
     string str;
     this.Initialize(false);
     if ((this.m_session.LocalProcessID > 0) || this.m_session.isFlagSet(SessionFlags.RequestGeneratedByFiddler))
     {
         str = sTrustedError;
     }
     else
     {
         str = sRemoteError;
     }
     str = str.PadRight(0x200, ' ');
     this.m_session.responseBodyBytes = Encoding.UTF8.GetBytes(str);
     this.m_inHeaders = new HTTPResponseHeaders(CONFIG.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");
 }
 internal ServerChatter(Session oSession, string sHeaders)
 {
     this._lngLastChunkInfoOffset = -1L;
     this.m_session   = oSession;
     this.m_inHeaders = Parser.ParseResponse(sHeaders);
 }
 internal ServerChatter(Session oSession, string sHeaders)
 {
     this._lngLastChunkInfoOffset = -1L;
     this.m_session = oSession;
     this.m_inHeaders = Parser.ParseResponse(sHeaders);
 }
 internal bool ReadResponseFromArray(byte[] arrResponse, bool bAllowBOM, string sContentTypeHint)
 {
     this.Initialize(true);
     int length = arrResponse.Length;
     int index = 0;
     bool flag = false;
     if (bAllowBOM)
     {
         flag = (((arrResponse.Length > 3) && (arrResponse[0] == 0xef)) && (arrResponse[1] == 0xbb)) && (arrResponse[2] == 0xbf);
         if (flag)
         {
             index = 3;
             length -= 3;
         }
     }
     bool flag2 = ((((arrResponse.Length > (5 + index)) && (arrResponse[index] == 0x48)) && ((arrResponse[index + 1] == 0x54) && (arrResponse[index + 2] == 0x54))) && (arrResponse[index + 3] == 80)) && (arrResponse[index + 4] == 0x2f);
     if (flag && !flag2)
     {
         length += 3;
         index = 0;
     }
     this.m_responseData.Capacity = length;
     this.m_responseData.Write(arrResponse, index, length);
     if ((flag2 && this.HeadersAvailable()) && this.ParseResponseForHeaders())
     {
         this.m_session.responseBodyBytes = this.TakeEntity();
     }
     else
     {
         this.Initialize(false);
         this.m_inHeaders = new HTTPResponseHeaders(CONFIG.oHeaderEncoding);
         this.m_inHeaders.HTTPResponseCode = 200;
         this.m_inHeaders.HTTPResponseStatus = "200 OK with automatic headers";
         this.m_inHeaders["Date"] = DateTime.Now.ToUniversalTime().ToString("r");
         this.m_inHeaders["Content-Length"] = arrResponse.LongLength.ToString();
         this.m_inHeaders["Cache-Control"] = "max-age=0, must-revalidate";
         if (sContentTypeHint != null)
         {
             this.m_inHeaders["Content-Type"] = sContentTypeHint;
         }
         this.m_session.responseBodyBytes = arrResponse;
     }
     return true;
 }
Beispiel #33
0
        public bool LoadRules(string sFilename, bool bIsDefaultRuleFile)
        {
            if (bIsDefaultRuleFile)
            {
                this.ClearRules();
            }
            try
            {
                if (!File.Exists(sFilename) || (new FileInfo(sFilename).Length < 0x8fL))
                {
                    return(false);
                }
                FileStream    input  = new FileStream(sFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                XmlTextReader reader = new XmlTextReader(input);
                while (reader.Read())
                {
                    string str6;
                    if ((reader.NodeType == XmlNodeType.Element) && ((str6 = reader.Name) != null))
                    {
                        if (!(str6 == "State"))
                        {
                            if (str6 == "ResponseRule")
                            {
                                goto Label_00B8;
                            }
                        }
                        else if (bIsDefaultRuleFile)
                        {
                            this.IsEnabled         = XmlConvert.ToBoolean(reader.GetAttribute("Enabled"));
                            this.PermitFallthrough = XmlConvert.ToBoolean(reader.GetAttribute("Fallthrough"));
                        }
                    }
                    continue;
Label_00B8:
                    try
                    {
                        string attribute  = reader.GetAttribute("Match");
                        string sAction    = reader.GetAttribute("Action");
                        int    iLatencyMS = 0;
                        string s          = reader.GetAttribute("Latency");
                        if (s != null)
                        {
                            iLatencyMS = XmlConvert.ToInt32(s);
                        }
                        bool   bIsEnabled = "false" != reader.GetAttribute("Enabled");
                        string str4       = reader.GetAttribute("Headers");
                        if (string.IsNullOrEmpty(str4))
                        {
                            this.AddRule(attribute, sAction, bIsEnabled);
                        }
                        else
                        {
                            byte[] buffer;
                            HTTPResponseHeaders oRH = new HTTPResponseHeaders();
                            str4 = Encoding.UTF8.GetString(Convert.FromBase64String(str4));
                            oRH.AssignFromString(str4);
                            string str5 = reader.GetAttribute("DeflatedBody");
                            if (!string.IsNullOrEmpty(str5))
                            {
                                buffer = Utilities.DeflaterExpand(Convert.FromBase64String(str5));
                            }
                            else
                            {
                                str5 = reader.GetAttribute("Body");
                                if (!string.IsNullOrEmpty(str5))
                                {
                                    buffer = Convert.FromBase64String(str5);
                                }
                                else
                                {
                                    buffer = new byte[0];
                                }
                            }
                            this.AddRule(attribute, oRH, buffer, sAction, iLatencyMS, bIsEnabled);
                        }
                        continue;
                    }
                    catch
                    {
                        continue;
                    }
                }
                reader.Close();
                if (bIsDefaultRuleFile && (this._alRules.Count < 1))
                {
                    this.IsEnabled = false;
                }
                if (bIsDefaultRuleFile)
                {
                    this._bRuleListIsDirty = false;
                }
                return(true);
            }
            catch (Exception exception)
            {
                FiddlerApplication.ReportException(exception, "Failed to load AutoResponder settings from " + sFilename);
                if (bIsDefaultRuleFile)
                {
                    this.IsEnabled = false;
                }
                return(false);
            }
        }
 internal void Initialize(bool bAllocatePipeReadBuffer)
 {
     if (bAllocatePipeReadBuffer)
     {
         this.m_responseData = new PipeReadBuffer(false);
     }
     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);
 }
Beispiel #35
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(CONFIG.oHeaderEncoding);
         int length = sHeaderLines[0].IndexOf(' ');
         if (length > 0)
         {
             oHeaders.HTTPVersion = sHeaderLines[0].Substring(0, length).ToUpperInvariant();
             sHeaderLines[0] = sHeaderLines[0].Substring(length + 1).Trim();
             if (!oHeaders.HTTPVersion.OICStartsWith("HTTP/"))
             {
                 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;
 }
Beispiel #36
0
 internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders)
 {
     X509Certificate2 certificate;
     try
     {
         certificate = CertMaker.FindCert(sHostname);
     }
     catch (Exception exception)
     {
         FiddlerApplication.Log.LogFormat("fiddler.https> Failed to obtain certificate for {0} due to {1}", new object[] { sHostname, exception.Message });
         certificate = null;
     }
     try
     {
         if (certificate == null)
         {
             FiddlerApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure");
             oHeaders.HTTPResponseCode = 0x1f6;
             oHeaders.HTTPResponseStatus = "502 Fiddler unable to generate certificate";
         }
         if (CONFIG.bDebugSpew)
         {
             FiddlerApplication.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)
         {
             FiddlerApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200");
             return false;
         }
         base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
         base._httpsStream.AuthenticateAsServer(certificate, _bWantClientCert, CONFIG.oAcceptedClientHTTPSProtocols, false);
         return true;
     }
     catch (Exception exception2)
     {
         FiddlerApplication.Log.LogFormat("SecureClientPipe ({0} failed: {1}.", new object[] { sHostname, Utilities.DescribeException(exception2) });
         try
         {
             base.End();
         }
         catch (Exception)
         {
         }
     }
     return false;
 }
 internal bool ReadResponse()
 {
     if (this.pipeServer == null)
     {
         if (this.m_session.isFTP && !this.m_session.isFlagSet(SessionFlags.SentToGateway))
         {
             FTPGateway.MakeFTPRequest(this.m_session, ref this.m_responseData, out this.m_inHeaders);
             return true;
         }
         return false;
     }
     int iMaxByteCount = 0;
     bool flag = false;
     bool flag2 = false;
     bool flag3 = false;
     bool flag4 = 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;
                 FiddlerApplication.DoReadResponseBuffer(this.m_session, arrBuffer, 0);
                 if (CONFIG.bDebugSpew)
                 {
                     FiddlerApplication.DebugSpew(string.Format("READ FROM {0}: returned 0 signaling end-of-stream", this.pipeServer));
                 }
             }
             else
             {
                 if (CONFIG.bDebugSpew)
                 {
                     FiddlerApplication.DebugSpew(string.Format("READ FROM {0}:\n{1}", this.pipeServer, Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount)));
                 }
                 if (!FiddlerApplication.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.FiddlerGotResponseHeaders = DateTime.Now;
                     if ((this.m_session.state == SessionStates.Aborted) && this.m_session.isAnyFlagSet(SessionFlags.ProtocolViolationInResponse))
                     {
                         return false;
                     }
                     FiddlerApplication.DoResponseHeadersAvailable(this.m_session);
                     string inStr = this.m_inHeaders["Content-Type"];
                     if (inStr.OICStartsWithAny(new string[] { "text/event-stream", "multipart/x-mixed-replace" }) && FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.AutoStreamByMIME", true))
                     {
                         this.m_session.bBufferResponse = false;
                     }
                     else if (CONFIG.bStreamAudioVideo && inStr.OICStartsWithAny(new string[] { "video/", "audio/", "application/x-mms-framed" }))
                     {
                         this.m_session.bBufferResponse = false;
                     }
                     if (!this.m_session.bBufferResponse && this.m_session.HTTPMethodIs("CONNECT"))
                     {
                         this.m_session.bBufferResponse = true;
                     }
                     if (!this.m_session.bBufferResponse && (0x65 == this.m_inHeaders.HTTPResponseCode))
                     {
                         this.m_session.bBufferResponse = true;
                     }
                     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") || FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.ForgetStreamedData", false))
                         {
                             flag3 = true;
                         }
                     }
                 }
                 if ((this.m_inHeaders != null) && this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
                 {
                     if (!flag4 && !this.LeakResponseBytes())
                     {
                         flag4 = true;
                     }
                     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 (SocketException exception)
         {
             flag2 = true;
             if (exception.ErrorCode == 0x274c)
             {
                 this.m_session["X-ServerPipeError"] = "Timed out while reading response.";
             }
             else
             {
                 FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} raised exception {1}", new object[] { this.m_session.id, Utilities.DescribeException(exception) });
             }
         }
         catch (Exception exception2)
         {
             flag2 = true;
             if (exception2 is OperationCanceledException)
             {
                 this.m_session.state = SessionStates.Aborted;
                 FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} was aborted {1}", new object[] { this.m_session.id, Utilities.DescribeException(exception2) });
             }
             else if (exception2 is OutOfMemoryException)
             {
                 FiddlerApplication.ReportException(exception2);
                 this.m_session.state = SessionStates.Aborted;
                 FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} Out of Memory", new object[] { this.m_session.id });
             }
             else
             {
                 FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} raised exception {1}", new object[] { this.m_session.id, Utilities.DescribeException(exception2) });
             }
         }
     }
     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 ((0L == this.m_responseTotalDataCount) && (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)
     {
         FiddlerApplication.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(CONFIG.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;
 }
Beispiel #38
0
        public static void MakeFTPRequest(Session oSession, ref PipeReadBuffer buffBody, out HTTPResponseHeaders oRH)
        {
            if (oSession.oRequest == null || oSession.oRequest.headers == null)
            {
                throw new ArgumentException("Session missing request objects.");
            }
            if (buffBody == null)
            {
                throw new ArgumentException("Response Stream may not be null.");
            }
            string        fullUrl       = oSession.fullUrl;
            FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(fullUrl);

            ftpWebRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            if (fullUrl.EndsWith("/"))
            {
                ftpWebRequest.Method = "LIST";
            }
            else
            {
                ftpWebRequest.Method = "RETR";
                if (oSession.oFlags.ContainsKey("FTP-UseASCII"))
                {
                    ftpWebRequest.UseBinary = false;
                }
                else
                {
                    ftpWebRequest.UseBinary = FiddlerApplication.Prefs.GetBoolPref("fiddler.ftp.UseBinary", true);
                }
            }
            if (!string.IsNullOrEmpty(oSession.oRequest.headers._uriUserInfo))
            {
                string text = Utilities.TrimAfter(oSession.oRequest.headers._uriUserInfo, '@');
                text = Utilities.UrlDecode(text);
                string userName = Utilities.TrimAfter(text, ':');
                string password = text.Contains(":") ? Utilities.TrimBefore(text, ':') : string.Empty;
                ftpWebRequest.Credentials = new NetworkCredential(userName, password);
            }
            else
            {
                if (oSession.oRequest.headers.ExistsAndContains("Authorization", "Basic "))
                {
                    string text2 = oSession.oRequest.headers["Authorization"].Substring(6);
                    text2 = Encoding.UTF8.GetString(Convert.FromBase64String(text2));
                    string userName2 = Utilities.TrimAfter(text2, ':');
                    string password2 = Utilities.TrimBefore(text2, ':');
                    ftpWebRequest.Credentials = new NetworkCredential(userName2, password2);
                }
                else
                {
                    if (oSession.oFlags.ContainsKey("x-AutoAuth") && oSession.oFlags["x-AutoAuth"].Contains(":"))
                    {
                        string userName3 = Utilities.TrimAfter(oSession.oFlags["x-AutoAuth"], ':');
                        string password3 = Utilities.TrimBefore(oSession.oFlags["x-AutoAuth"], ':');
                        ftpWebRequest.Credentials = new NetworkCredential(userName3, password3);
                    }
                    else
                    {
                        if (FiddlerApplication.Prefs.GetBoolPref("fiddler.ftp.AlwaysDemandCredentials", false))
                        {
                            byte[] bytes = Encoding.UTF8.GetBytes("Please provide login credentials for this FTP server".PadRight(512, ' '));
                            buffBody.Write(bytes, 0, bytes.Length);
                            oRH = new HTTPResponseHeaders();
                            oRH.SetStatus(401, "Need Creds");
                            oRH.Add("Content-Length", buffBody.Length.ToString());
                            oRH.Add("WWW-Authenticate", "Basic realm=\"ftp://" + oSession.host + "\"");
                            return;
                        }
                    }
                }
            }
            ftpWebRequest.UsePassive = FiddlerApplication.Prefs.GetBoolPref("fiddler.ftp.UsePassive", true);
            ftpWebRequest.Proxy      = null;
            FtpWebResponse ftpWebResponse;

            try
            {
                ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
            }
            catch (WebException ex)
            {
                FtpWebResponse ftpWebResponse2 = (FtpWebResponse)ex.Response;
                if (ftpWebResponse2 != null)
                {
                    byte[] bytes2;
                    if (FtpStatusCode.NotLoggedIn == ftpWebResponse2.StatusCode)
                    {
                        bytes2 = Encoding.UTF8.GetBytes("This FTP server requires login credentials".PadRight(512, ' '));
                        buffBody.Write(bytes2, 0, bytes2.Length);
                        oRH = new HTTPResponseHeaders();
                        oRH.SetStatus(401, "Need Creds");
                        oRH.Add("Content-Length", buffBody.Length.ToString());
                        oRH.Add("WWW-Authenticate", "Basic realm=\"ftp://" + oSession.host + "\"");
                        return;
                    }
                    bytes2 = Encoding.UTF8.GetBytes(string.Format("{0}{1}{2}", "Fiddler was unable to act as a HTTP-to-FTP gateway for this response. ", ftpWebResponse2.StatusDescription, string.Empty.PadRight(512, ' ')));
                    buffBody.Write(bytes2, 0, bytes2.Length);
                }
                else
                {
                    byte[] bytes2 = Encoding.UTF8.GetBytes(string.Format("{0}{1}{2}", "Fiddler was unable to act as a HTTP-to-FTP gateway for this response. ", ex.Message, string.Empty.PadRight(512, ' ')));
                    buffBody.Write(bytes2, 0, bytes2.Length);
                }
                oRH = new HTTPResponseHeaders();
                oRH.SetStatus(504, "HTTP-FTP Gateway failed");
                oRH.Add("Content-Length", buffBody.Length.ToString());
                return;
            }
            Stream responseStream = ftpWebResponse.GetResponseStream();

            byte[] buffer = new byte[8192];
            for (int i = responseStream.Read(buffer, 0, 8192); i > 0; i = responseStream.Read(buffer, 0, 8192))
            {
                buffBody.Write(buffer, 0, i);
            }
            oRH = new HTTPResponseHeaders();
            oRH.SetStatus(200, "OK");
            oRH.Add("FTP-Status", Utilities.ConvertCRAndLFToSpaces(ftpWebResponse.StatusDescription));
            oRH.Add("Content-Length", buffBody.Length.ToString());
            ftpWebResponse.Close();
        }