Ejemplo n.º 1
0
 private static void RemoveAllCertificates()
 {
     try
     {
         bool flag = false;
         if (CertMaker.rootCertIsMachineTrusted())
         {
             var rootCertificate = CertMaker.GetRootCertificate();
             if (rootCertificate != null)
             {
                 var subject = rootCertificate.Subject;
                 if (!String.IsNullOrEmpty(subject))
                 {
                     flag = Utilities.RunExecutableAndWait(CONFIG.GetPath("App") + "TrustCert.exe", String.Format("-u \"{0}\"", subject));
                 }
             }
         }
         if (CertMaker.removeFiddlerGeneratedCerts() || flag)
         {
             //FiddlerApplication.DoNotifyUser(this, string.Format("Fiddler-generated certificates have been removed from {0}", flag ? "both User and Machine Root storage." : "the Current User storage."), "Success", MessageBoxIcon.Asterisk);
         }
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception, "");
     }
 }
Ejemplo n.º 2
0
 public Session[] ImportSessions(string sFormat, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
 {
     if (sFormat == "HTTPArchive")
     {
         string str = null;
         if ((dictOptions != null) && dictOptions.ContainsKey("Filename"))
         {
             str = dictOptions["Filename"] as string;
         }
         if (string.IsNullOrEmpty(str))
         {
             str = Utilities.ObtainOpenFilename("Import " + sFormat, "HTTPArchive JSON (*.har)|*.har");
         }
         if (!string.IsNullOrEmpty(str))
         {
             try
             {
                 List <Session> listSessions = new List <Session>();
                 StreamReader   oSR          = new StreamReader(str, Encoding.UTF8);
                 HTTPArchiveJSONImport.LoadStream(oSR, listSessions, evtProgressNotifications);
                 oSR.Close();
                 return(listSessions.ToArray());
             }
             catch (Exception exception)
             {
                 FiddlerApplication.ReportException(exception, "Failed to import HTTPArchive");
                 return(null);
             }
         }
     }
     return(null);
 }
Ejemplo n.º 3
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "HTTPArchive v1.1" && sFormat != "HTTPArchive v1.2")
            {
                return(false);
            }
            bool   result = false;
            string text   = null;
            int    iMaxBinaryBodyLength = FiddlerApplication.get_Prefs().GetInt32Pref("fiddler.importexport.HTTPArchiveJSON.MaxBinaryBodyLength", 32768);
            int    iMaxTextBodyLength   = FiddlerApplication.get_Prefs().GetInt32Pref("fiddler.importexport.HTTPArchiveJSON.MaxTextBodyLength", 22);

            if (dictOptions != null)
            {
                if (dictOptions.ContainsKey("Filename"))
                {
                    text = (dictOptions["Filename"] as string);
                }
                if (dictOptions.ContainsKey("MaxTextBodyLength"))
                {
                    iMaxTextBodyLength = (int)dictOptions["MaxTextBodyLength"];
                }
                if (dictOptions.ContainsKey("MaxBinaryBodyLength"))
                {
                    iMaxBinaryBodyLength = (int)dictOptions["MaxBinaryBodyLength"];
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Utilities.ObtainSaveFilename("Export As " + sFormat, "HTTPArchive JSON (*.har)|*.har");
            }
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    StreamWriter streamWriter = new StreamWriter(text, false, Encoding.UTF8);
                    HTTPArchiveJSONExport.WriteStream(streamWriter, oSessions, sFormat == "HTTPArchive v1.2", evtProgressNotifications, iMaxTextBodyLength, iMaxBinaryBodyLength);
                    streamWriter.Close();
                    bool result2 = true;
                    return(result2);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to save HTTPArchive");
                    bool result2 = false;
                    return(result2);
                }
                return(result);
            }
            return(result);
        }
        public List <PluginClassReference> FindAvailablePlugins()
        {
            Assembly assembly;

            this.m_plugins = new List <PluginClassReference>();
            bool bNoisyEvents = FiddlerApplication.Prefs.GetBoolPref("fiddler.debug.extensions.verbose", false);

            if (bNoisyEvents)
            {
                FiddlerApplication.Log.LogFormat("Searching for VSWebTest Export Plugins under: {0}", new object[] { this.m_Path });
            }
            try
            {
                if (Directory.Exists(this.m_Path))
                {
                    Evidence   evidenceFiddler = Assembly.GetExecutingAssembly().Evidence;
                    FileInfo[] files           = (new DirectoryInfo(this.m_Path)).GetFiles("*.dll");
                    for (int i = 0; i < (int)files.Length; i++)
                    {
                        FileInfo assemblyInfo = files[i];
                        if (!assemblyInfo.Name.StartsWith("_", StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                assembly = (Environment.Version.Major >= 4 ? Assembly.LoadFrom(assemblyInfo.FullName) : Assembly.LoadFrom(assemblyInfo.FullName, evidenceFiddler));
                                this.FindPluginClassesInAssembly(assembly);
                            }
                            catch (Exception exception)
                            {
                                Exception eX = exception;
                                if (bNoisyEvents)
                                {
                                    FiddlerApplication.Log.LogFormat("Failed to load WebTestPlugin {0}; exception was {1}", new object[] { assemblyInfo.FullName, eX });
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception1)
            {
                FiddlerApplication.ReportException(exception1, "WebTestPlugin Enumeration Failed");
            }
            this.FindPluginClassesInAssembly(Assembly.GetCallingAssembly());
            return(this.m_plugins);
        }
Ejemplo n.º 5
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if ((sFormat != "HTTPArchive v1.1") && (sFormat != "HTTPArchive v1.2"))
            {
                return(false);
            }
            string str = null;
            int    iMaxBinaryBodyLength = FiddlerApplication.Prefs.GetInt32Pref("fiddler.importexport.HTTPArchiveJSON.MaxBinaryBodyLength", 0x8000);
            int    iMaxTextBodyLength   = FiddlerApplication.Prefs.GetInt32Pref("fiddler.importexport.HTTPArchiveJSON.MaxTextBodyLength", 0x16);

            if (dictOptions != null)
            {
                if (dictOptions.ContainsKey("Filename"))
                {
                    str = dictOptions["Filename"] as string;
                }
                if (dictOptions.ContainsKey("MaxTextBodyLength"))
                {
                    iMaxTextBodyLength = (int)dictOptions["MaxTextBodyLength"];
                }
                if (dictOptions.ContainsKey("MaxBinaryBodyLength"))
                {
                    iMaxBinaryBodyLength = (int)dictOptions["MaxBinaryBodyLength"];
                }
            }
            if (string.IsNullOrEmpty(str))
            {
                str = Utilities.ObtainSaveFilename("Export As " + sFormat, "HTTPArchive JSON (*.har)|*.har");
            }
            if (!string.IsNullOrEmpty(str))
            {
                try
                {
                    StreamWriter swOutput = new StreamWriter(str, false, Encoding.UTF8);
                    HTTPArchiveJSONExport.WriteStream(swOutput, oSessions, sFormat == "HTTPArchive v1.2", evtProgressNotifications, iMaxTextBodyLength, iMaxBinaryBodyLength);
                    swOutput.Close();
                    return(true);
                }
                catch (Exception exception)
                {
                    FiddlerApplication.ReportException(exception, "Failed to save HTTPArchive");
                    return(false);
                }
            }
            return(false);
        }
Ejemplo n.º 6
0
        public Stream GetFileStream(string sFilename)
        {
            ZipEntry oZE = _oZip[sFilename];

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

            if ((oZE.UsesEncryption) && String.IsNullOrEmpty(_sPassword))
            {
                StoreEncryptionInfo(oZE.Encryption);
                if (!PromptForPassword())
                {
                    throw new OperationCanceledException("Password required.");
                }
            }

            Stream strmResult = null;

RetryWithPassword:
            try
            {
                strmResult = oZE.OpenReader();
            }
            catch (Ionic.Zip.BadPasswordException)
            {
                if (!PromptForPassword())
                {
                    throw new OperationCanceledException("Password required.");
                }
                goto RetryWithPassword;
            }
            catch (Exception eX)
            {
                Debug.Assert(false, eX.Message);
                FiddlerApplication.ReportException(eX, "Error saving SAZ");
            }

            return(strmResult);
        }
Ejemplo n.º 7
0
        public void DeInitialize(Exception exp)
        {
            if (exp != null)
            {
                FiddlerApplication.ReportException(exp, "UnhandledException");
            }

            //do the most important thing first
            //this will revert the system proxy settings
            if (null != oSecureEndpoint)
            {
                oSecureEndpoint.Dispose();
            }
            FiddlerApplication.Shutdown();
            Thread.Sleep(500);

            lock (_sessionLock)
            {
                _sessions.Clear();
            }
        }
Ejemplo n.º 8
0
        public Session[] ImportSessions(string sFormat, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "HTTPArchive")
            {
                return(null);
            }
            string text = null;

            if (dictOptions != null && dictOptions.ContainsKey("Filename"))
            {
                text = (dictOptions["Filename"] as string);
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Utilities.ObtainOpenFilename("Import " + sFormat, "HTTPArchive JSON (*.har)|*.har");
            }
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    List <Session> list         = new List <Session>();
                    StreamReader   streamReader = new StreamReader(text, Encoding.UTF8);
                    HTTPArchiveJSONImport.LoadStream(streamReader, list, evtProgressNotifications);
                    streamReader.Close();
                    Session[] result = list.ToArray();
                    return(result);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to import HTTPArchive");
                    Session[] result = null;
                    return(result);
                }
            }
            return(null);
        }
Ejemplo n.º 9
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "Raw Files")
            {
                return(false);
            }
            string text  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            bool   flag  = true;
            bool   flag2 = true;
            bool   flag3 = true;
            bool   flag4 = false;

            if (dictOptions != null)
            {
                if (dictOptions.ContainsKey("Folder"))
                {
                    text  = (dictOptions["Folder"] as string);
                    flag4 = true;
                }
                if (dictOptions.ContainsKey("RecreateStructure"))
                {
                    flag  = string.Equals("True", dictOptions["RecreateStructure"] as string, StringComparison.OrdinalIgnoreCase);
                    flag4 = true;
                }
                if (dictOptions.ContainsKey("OpenFolder"))
                {
                    flag2 = string.Equals("True", dictOptions["OpenFolder"] as string, StringComparison.OrdinalIgnoreCase);
                    flag4 = true;
                }
                if (dictOptions.ContainsKey("SkipNon200"))
                {
                    flag3 = string.Equals("True", dictOptions["SkipNon200"] as string, StringComparison.OrdinalIgnoreCase);
                    flag4 = true;
                }
            }
            if (!flag4)
            {
                UIFileExport uIFileExport = new UIFileExport();
                uIFileExport.txtLocation.Text = text;
                uIFileExport.cbRecreateFolderStructure.Checked = FiddlerApplication.get_Prefs().GetBoolPref("fiddler.exporters.RawFiles.RecreateStructure", true);
                uIFileExport.cbOpenFolder.Checked  = FiddlerApplication.get_Prefs().GetBoolPref("fiddler.exporters.RawFiles.OpenFolder", true);
                uIFileExport.cbHTTP200Only.Checked = FiddlerApplication.get_Prefs().GetBoolPref("fiddler.exporters.RawFiles.SkipNon200", true);
                this.SetDefaultPath(uIFileExport.txtLocation, "fiddler.exporters.RawFiles.DefaultPath", text);
                DialogResult dialogResult = uIFileExport.ShowDialog();
                if (dialogResult != DialogResult.OK)
                {
                    return(false);
                }
                flag  = uIFileExport.cbRecreateFolderStructure.Checked;
                flag2 = uIFileExport.cbOpenFolder.Checked;
                flag3 = uIFileExport.cbHTTP200Only.Checked;
                text  = uIFileExport.txtLocation.Text;
                text  = Utilities.EnsurePathIsAbsolute(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), text).Trim();
                FiddlerApplication.get_Prefs().SetBoolPref("fiddler.exporters.RawFiles.RecreateStructure", flag);
                FiddlerApplication.get_Prefs().SetBoolPref("fiddler.exporters.RawFiles.OpenFolder", flag2);
                FiddlerApplication.get_Prefs().SetBoolPref("fiddler.exporters.RawFiles.SkipNon200", flag3);
                FiddlerApplication.get_Prefs().SetStringPref("fiddler.exporters.RawFiles.DefaultPath", text);
                uIFileExport.Dispose();
                text = string.Concat(new object[]
                {
                    text,
                    Path.DirectorySeparatorChar,
                    "Dump-",
                    DateTime.Now.ToString("MMdd-HH-mm-ss"),
                    Path.DirectorySeparatorChar
                });
            }
            try
            {
                Directory.CreateDirectory(text);
            }
            catch (Exception ex)
            {
                FiddlerApplication.ReportException(ex, "Export Failed");
                bool result = false;
                return(result);
            }
            int num = 0;

            for (int i = 0; i < oSessions.Length; i++)
            {
                Session session = oSessions[i];
                try
                {
                    if (!flag3 || session.get_responseCode() == 200)
                    {
                        if (session.HTTPMethodIs("CONNECT"))
                        {
                            num++;
                        }
                        else
                        {
                            if (session.responseBodyBytes != null && session.responseBodyBytes.Length > 0)
                            {
                                string text3;
                                if (flag)
                                {
                                    string text2 = Utilities.TrimAfter(session.get_url(), '?');
                                    text3 = text2.Replace('/', Path.DirectorySeparatorChar);
                                    if (text3.EndsWith(string.Empty + Path.DirectorySeparatorChar))
                                    {
                                        text3 += session.get_SuggestedFilename();
                                    }
                                    if (text3.Length > 0 && text3.Length < 260)
                                    {
                                        text3 = text + this._MakeSafeFilename(text3);
                                    }
                                    else
                                    {
                                        text3 = text + session.get_SuggestedFilename();
                                    }
                                }
                                else
                                {
                                    text3 = text + session.get_SuggestedFilename();
                                }
                                text3 = Utilities.EnsureUniqueFilename(text3);
                                byte[] array = session.responseBodyBytes;
                                if (session.oResponse.get_headers().Exists("Content-Encoding") || session.oResponse.get_headers().Exists("Transfer-Encoding"))
                                {
                                    array = (byte[])array.Clone();
                                    Utilities.utilDecodeHTTPBody(session.oResponse.get_headers(), ref array);
                                }
                                FiddlerApplication.get_Log().LogFormat("Writing #{0} to {1}", new object[]
                                {
                                    session.get_id().ToString(),
                                    text3
                                });
                                Utilities.WriteArrayToFile(text3, array);
                            }
                            num++;
                            if (evtProgressNotifications != null)
                            {
                                ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Dumped " + num.ToString() + " files to disk.");
                                evtProgressNotifications(null, progressCallbackEventArgs);
                                if (progressCallbackEventArgs.get_Cancel())
                                {
                                    bool result = false;
                                    return(result);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex2)
                {
                    FiddlerApplication.ReportException(ex2, "Failed to generate response file.");
                }
            }
            if (flag2)
            {
                try
                {
                    string fileName = string.Format("\"{0}\"", text);
                    using (Process.Start(new ProcessStartInfo(fileName)
                    {
                        Verb = "explore"
                    }))
                    {
                    }
                }
                catch (Exception ex3)
                {
                    FiddlerApplication.ReportException(ex3, "Cannot open folder");
                }
            }
            return(true);
        }
Ejemplo n.º 10
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "cURL Script")
            {
                return(false);
            }
            bool   result = false;
            string text   = null;

            if (dictOptions != null && dictOptions.ContainsKey("Filename"))
            {
                text = (dictOptions["Filename"] as string);
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Utilities.ObtainSaveFilename("Export As " + sFormat, "Batch Script (*.bat)|*.bat");
            }
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    string        stringPref    = FiddlerApplication.get_Prefs().GetStringPref("fiddler.exporters.cURL.DefaultOptions", "-k -i --raw");
                    int           num           = 0;
                    int           num2          = 0;
                    bool          result2;
                    for (int i = 0; i < oSessions.Length; i++)
                    {
                        Session session = oSessions[i];
                        string  text2   = string.Empty;
                        if (session.HTTPMethodIs("CONNECT"))
                        {
                            num++;
                        }
                        else
                        {
                            if (!session.HTTPMethodIs("GET"))
                            {
                                if (session.HTTPMethodIs("HEAD"))
                                {
                                    text2 = "-I ";
                                }
                                else
                                {
                                    text2 = string.Format("-X {0} ", session.get_RequestMethod());
                                }
                            }
                            string text3;
                            if (stringPref.Contains("-i"))
                            {
                                text3 = string.Format("{0}.dat", num2);
                            }
                            else
                            {
                                text3 = session.get_SuggestedFilename();
                            }
                            string text4 = string.Empty;
                            if (session.oRequest.get_Item("Content-Type").StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                            {
                                text4 = string.Format("-d \"{0}\" ", cURLExport._EscapeString(session.GetRequestBodyAsString()));
                            }
                            string text5 = cURLExport._EscapeString(session.get_fullUrl());
                            stringBuilder.AppendFormat("curl {0} -o {1} {2}{3}\"{4}\"", new object[]
                            {
                                stringPref,
                                text3,
                                text2,
                                text4,
                                text5
                            });
                            foreach (HTTPHeaderItem current in session.oRequest.get_headers())
                            {
                                if (!(current.Name == "Content-Length"))
                                {
                                    stringBuilder.AppendFormat(" -H \"{0}\"", cURLExport._EscapeString(current.ToString()));
                                }
                            }
                            stringBuilder.AppendLine();
                            num++;
                            num2++;
                            if (evtProgressNotifications != null)
                            {
                                ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Added " + num.ToString() + " sessions to cURL Script.");
                                evtProgressNotifications(null, progressCallbackEventArgs);
                                if (progressCallbackEventArgs.get_Cancel())
                                {
                                    result2 = false;
                                    return(result2);
                                }
                            }
                        }
                    }
                    this.PrependScriptHeader(stringBuilder);
                    this.EmitScriptFooter(stringBuilder);
                    File.WriteAllText(text, stringBuilder.ToString());
                    result2 = true;
                    return(result2);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to save cURLScript");
                    bool result2 = false;
                    return(result2);
                }
                return(result);
            }
            return(result);
        }
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool flag;

            if (sFormat != "OpPlan 4 Visual Studio WebTest")
            {
                return(false);
            }
            bool   bResult   = false;
            string sFilename = null;

            if (dictOptions != null && dictOptions.ContainsKey("Filename"))
            {
                sFilename = dictOptions["Filename"] as string;
            }
            if (string.IsNullOrEmpty(sFilename))
            {
                sFilename = Utilities.ObtainSaveFilename(string.Concat("Export As ", sFormat), "OpPlan 4 SAML parameterized token Visual Studio WebTest (*.webtest)|*.webtest");
            }
            if (string.IsNullOrEmpty(sFilename))
            {
                return(bResult);
            }
            this.EnsureVSTSAddons();
            bool bPromptForPlugins             = true;
            bool bIncludeAutoGeneratedComments = true;

            if (dictOptions != null)
            {
                if (dictOptions.ContainsKey("PluginPrompt") && ((string)dictOptions["PluginPrompt"]).ToLower() == "false")
                {
                    bPromptForPlugins = false;
                }
                if (dictOptions != null && dictOptions.ContainsKey("IncludeAutoGeneratedComments") && ((string)dictOptions["IncludeAutoGeneratedComments"]).ToLower() == "false")
                {
                    bIncludeAutoGeneratedComments = false;
                }
            }
            try
            {
                List <PluginClassReference> plugins = (new AssemblyHelper(FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.webtestexport.plugins", string.Concat(CONFIG.GetPath("Transcoders_User"), "VSWebTestPlugins")))).FindAvailablePlugins();
                FiddlerWebTest webTest = new FiddlerWebTest(oSessions);
                if (bPromptForPlugins)
                {
                    frmSelectPlugins frmPlugins = new frmSelectPlugins(plugins);
                    frmPlugins.cbAllowAutoComments.Checked = bIncludeAutoGeneratedComments;
                    if (DialogResult.OK != frmPlugins.ShowDialog())
                    {
                        frmPlugins.Dispose();
                        flag = false;
                        return(flag);
                    }
                    else
                    {
                        webTest.LoadPlugins(frmPlugins.SelectedPlugins);
                        webTest.Save(sFilename, evtProgressNotifications, frmPlugins.cbAllowAutoComments.Checked,
                                     frmPlugins);
                        frmPlugins.Dispose();
                    }
                }
                else
                {
                    webTest.LoadPlugins(plugins);
                    webTest.Save(sFilename, evtProgressNotifications, bIncludeAutoGeneratedComments, new frmSelectPlugins(new List <PluginClassReference>()));
                }
                flag = true;
            }
            catch (Exception exception)
            {
                FiddlerApplication.ReportException(exception, "Failed to save test");
                flag = false;
            }
            return(flag);
        }
Ejemplo n.º 12
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool   bResult   = false;
            string sFilename = null;

            if (dictOptions != null && dictOptions.ContainsKey("Filename"))
            {
                sFilename = (dictOptions["Filename"] as string);
            }
            if (string.IsNullOrEmpty(sFilename))
            {
                sFilename = Utilities.ObtainSaveFilename("Exportar como " + sFormat, "Postman collection (*.postman_collection.json)|*.postman_collection.json");
            }
            if (!string.IsNullOrEmpty(sFilename))
            {
                try
                {
                    Postman postman = new Postman();
                    postman.Info      = new Info();
                    postman.Info.Id   = Guid.NewGuid();
                    postman.Info.Name = Path.GetFileNameWithoutExtension(sFilename)?.Replace(".postman_collection", string.Empty);

                    postman.Auth       = new Auth();
                    postman.Auth.Type  = "basic";
                    postman.Auth.Basic = new List <BasicAuth>()
                    {
                        new BasicAuth {
                            Key = "password", Value = "totvs", Type = "string"
                        },
                        new BasicAuth {
                            Key = "username", Value = "mestre", Type = "string"
                        }
                    };

                    postman.Item = new List <Item>();

                    foreach (Session oS in oSessions)
                    {
                        if (null != oS.ViewItem)
                        {
                            Item request = new Item();
                            request.Name = oS.fullUrl;

                            request.Event = new List <Event>();

                            string responseOutput = string.Empty;
                            if (oS.ResponseBody != null)
                            {
                                oS.utilDecodeResponse(true);

                                responseOutput = System.Text.Encoding.UTF8.GetString(oS.ResponseBody);

                                if (!string.IsNullOrEmpty(responseOutput))
                                {
                                    responseOutput = responseOutput.Replace("\\n", "\\\\n");

                                    Event test = new Event();
                                    test.Listen      = "test";
                                    test.Script      = new Script();
                                    test.Script.Id   = Guid.NewGuid();
                                    test.Script.Exec = new List <string>();

                                    test.Script.Exec.Add(@"pm.test(""Resposta igual ao modelo"", function () 
                    { 
                      pm.expect(pm.response.text()).to.include(`" + responseOutput + @"`);
                    });");

                                    request.Event.Add(test);
                                }
                            }


                            request.Request        = new Request();
                            request.Request.Header = new List <KeyValuePair <string, string> >();

                            foreach (var requestItem in oS.RequestHeaders)
                            {
                                request.Request.Header.Add(new KeyValuePair <string, string>(requestItem.Name, requestItem.Value));
                            }

                            request.Request.Method = oS.RequestMethod;
                            request.Request.URL    = new URL(oS.fullUrl);

                            var requestBody = oS.GetRequestBodyAsString();

                            if (!string.IsNullOrEmpty(requestBody))
                            {
                                request.Request.Body     = new Body();
                                request.Request.Body.Raw = oS.GetRequestBodyAsString();
                            }

                            postman.Item.Add(request);
                        }
                    }

                    using (StreamWriter file = File.CreateText(sFilename))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
                        serializer.ContractResolver     = new LowercaseContractResolver();

                        serializer.Serialize(file, postman);
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Falha ao salvar a exportação");
                    return(false);
                }
            }
            return(bResult);
        }
Ejemplo n.º 13
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "HTML5 AppCache Manifest")
            {
                return(false);
            }
            bool   flag = false;
            string str  = null;

            if (string.IsNullOrEmpty(str))
            {
                AppCacheOptions options = new AppCacheOptions();
                List <string>   list    = new List <string>();
                options.lvItems.BeginUpdate();
                foreach (Session session in oSessions)
                {
                    if ((!session.HTTPMethodIs("CONNECT") && (session.responseCode >= 200)) && ((session.responseCode <= 0x18f) && !list.Contains(session.fullUrl)))
                    {
                        list.Add(session.fullUrl);
                        string       text = (session.oResponse.headers != null) ? Utilities.TrimAfter(session.oResponse.headers["Content-Type"], ";") : string.Empty;
                        ListViewItem item = options.lvItems.Items.Add(session.fullUrl);
                        item.SubItems.Add((session.responseBodyBytes != null) ? session.responseBodyBytes.Length.ToString() : "0");
                        item.SubItems.Add(text);
                        if (session.HTTPMethodIs("POST"))
                        {
                            item.Checked = true;
                        }
                        if (text.IndexOf("script", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            item.Group = options.lvItems.Groups["lvgScript"];
                        }
                        else if (text.IndexOf("image/", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            item.Group = options.lvItems.Groups["lvgImages"];
                        }
                        else if (text.IndexOf("html", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            item.Group = options.lvItems.Groups["lvgMarkup"];
                        }
                        else if (text.IndexOf("css", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            item.Group = options.lvItems.Groups["lvgCSS"];
                        }
                        else
                        {
                            item.Group = options.lvItems.Groups["lvgOther"];
                        }
                        item.Tag = session;
                    }
                }
                options.lvItems.EndUpdate();
                if (options.lvItems.Items.Count > 0)
                {
                    options.lvItems.FocusedItem = options.lvItems.Items[0];
                }
                if (DialogResult.OK != options.ShowDialog(FiddlerApplication.UI))
                {
                    return(flag);
                }
                str = Utilities.ObtainSaveFilename("Export As " + sFormat, "AppCache Manifest (*.appcache)|*.appcache");
                if (!string.IsNullOrEmpty(str))
                {
                    try
                    {
                        List <string> list2 = new List <string>();
                        List <string> list3 = new List <string>();
                        string        str3  = options.txtBase.Text.Trim();
                        if (str3.Length == 0)
                        {
                            str3 = null;
                        }
                        for (int i = 0; i < options.lvItems.Items.Count; i++)
                        {
                            string str4 = options.lvItems.Items[i].Text;
                            if (((str3 != null) && (str4.Length > str3.Length)) && str4.StartsWith(str3))
                            {
                                str4 = str4.Substring(str3.Length);
                            }
                            if (options.lvItems.Items[i].Checked)
                            {
                                list3.Add(str4);
                            }
                            else
                            {
                                list2.Add(str4);
                            }
                        }
                        StringBuilder builder = new StringBuilder();
                        builder.AppendFormat("CACHE MANIFEST\r\n# Generated: {0}\r\n\r\n", DateTime.Now.ToString());
                        if (str3 != null)
                        {
                            builder.AppendFormat("# Deploy so that URLs are relative to: {0}\r\n\r\n", str3);
                        }
                        if (list2.Count > 0)
                        {
                            builder.Append("CACHE:\r\n");
                            builder.Append(string.Join("\r\n", list2.ToArray()));
                            builder.Append("\r\n");
                        }
                        if (options.cbNetworkFallback.Checked || (list3.Count > 0))
                        {
                            builder.Append("\r\nNETWORK:\r\n");
                            if (options.cbNetworkFallback.Checked)
                            {
                                builder.Append("*\r\n");
                            }
                            builder.Append(string.Join("\r\n", list3.ToArray()));
                        }
                        File.WriteAllText(str, builder.ToString());
                        Process.Start("notepad.exe", str);
                        return(true);
                    }
                    catch (Exception exception)
                    {
                        FiddlerApplication.ReportException(exception, "Failed to save MeddlerScript");
                        return(false);
                    }
                }
                options.Dispose();
            }
            return(flag);
        }
Ejemplo n.º 14
0
        internal static bool WriteStream(StreamWriter swOutput, Session[] oSessions, bool bUseV1dot2Format, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications, int iMaxTextBodyLength, int iMaxBinaryBodyLength)
        {
            HTTPArchiveJSONExport._iMaxTextBodyLength   = iMaxTextBodyLength;
            HTTPArchiveJSONExport._iMaxBinaryBodyLength = iMaxBinaryBodyLength;
            Hashtable hashtable = new Hashtable();

            hashtable.Add("version", bUseV1dot2Format ? "1.2" : "1.1");
            hashtable.Add("pages", new ArrayList(0));
            if (bUseV1dot2Format)
            {
                hashtable.Add("comment", "exported @ " + DateTime.Now.ToString());
            }
            Hashtable hashtable2 = new Hashtable();

            hashtable2.Add("name", "Fiddler");
            hashtable2.Add("version", Application.ProductVersion);
            if (bUseV1dot2Format)
            {
                hashtable2.Add("comment", "http://www.fiddler2.com");
            }
            hashtable.Add("creator", hashtable2);
            ArrayList arrayList = new ArrayList();
            int       num       = 0;
            int       i         = 0;

            while (i < oSessions.Length)
            {
                Session session = oSessions[i];
                try
                {
                    if (session.get_state() < 11)
                    {
                        goto IL_24D;
                    }
                    Hashtable hashtable3 = new Hashtable();
                    hashtable3.Add("startedDateTime", session.Timers.ClientBeginRequest.ToString("o"));
                    hashtable3.Add("request", HTTPArchiveJSONExport.getRequest(session));
                    hashtable3.Add("response", HTTPArchiveJSONExport.getResponse(session, bUseV1dot2Format));
                    hashtable3.Add("cache", new Hashtable());
                    Hashtable timings = HTTPArchiveJSONExport.getTimings(session.Timers, bUseV1dot2Format);
                    hashtable3.Add("time", HTTPArchiveJSONExport.getTotalTime(timings));
                    hashtable3.Add("timings", timings);
                    if (bUseV1dot2Format)
                    {
                        string value = session.get_Item("ui-comments");
                        if (!string.IsNullOrEmpty(value))
                        {
                            hashtable3.Add("comment", session.get_Item("ui-comments"));
                        }
                        string arg_1A9_0 = session.m_hostIP;
                        if (!string.IsNullOrEmpty(value) && !session.isFlagSet(2048))
                        {
                            hashtable3.Add("serverIPAddress", session.m_hostIP);
                        }
                        hashtable3.Add("connection", session.get_clientPort().ToString());
                    }
                    arrayList.Add(hashtable3);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to Export Session");
                }
                goto IL_20B;
IL_24D:
                i++;
                continue;
IL_20B:
                num++;
                if (evtProgressNotifications == null)
                {
                    goto IL_24D;
                }
                ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Wrote " + num.ToString() + " sessions to HTTPArchive.");
                evtProgressNotifications(null, progressCallbackEventArgs);
                if (progressCallbackEventArgs.get_Cancel())
                {
                    return(false);
                }
                goto IL_24D;
            }
            hashtable.Add("entries", arrayList);
            swOutput.WriteLine(JSON.JsonEncode(new Hashtable
            {
                {
                    "log",
                    hashtable
                }
            }));
            return(true);
        }
        public Session[] ImportSessions(string sFormat, Dictionary <string, object> dictOptions, EventHandler <Fiddler.ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if ((sFormat != "NetLog JSON"))
            {
                Debug.Assert(false); return(null);
            }

            MemoryStream strmContent = null;
            string       sFilename   = null;

            if (null != dictOptions)
            {
                if (dictOptions.ContainsKey("Filename"))
                {
                    sFilename = dictOptions["Filename"] as string;
                }
                else if (dictOptions.ContainsKey("Content"))
                {
                    strmContent = new MemoryStream(Encoding.UTF8.GetBytes(dictOptions["Content"] as string));
                }
            }

            if ((null == strmContent) && string.IsNullOrEmpty(sFilename))
            {
                sFilename = Fiddler.Utilities.ObtainOpenFilename("Import " + sFormat, "NetLog JSON (*.json[.gz], *.zip)|*.json;*.json.gz;*.zip");
            }

            if ((null != strmContent) || !String.IsNullOrEmpty(sFilename))
            {
                try
                {
                    List <Session> listSessions = new List <Session>();
                    StreamReader   oSR;

                    if (null != strmContent)
                    {
                        oSR = new StreamReader(strmContent);
                    }
                    else
                    {
                        Stream oFS = File.OpenRead(sFilename);

                        // Check to see if this file data was GZIP'd or PKZIP'd.
                        bool bWasGZIP  = false;
                        bool bWasPKZIP = false;
                        int  bFirst    = oFS.ReadByte();
                        if (bFirst == 0x1f && oFS.ReadByte() == 0x8b)
                        {
                            bWasGZIP = true;
                            evtProgressNotifications?.Invoke(null, new ProgressCallbackEventArgs(0, "Import file was compressed using gzip/DEFLATE."));
                        }
                        else if (bFirst == 0x50 && oFS.ReadByte() == 0x4b)
                        {
                            bWasPKZIP = true;
                            evtProgressNotifications?.Invoke(null, new ProgressCallbackEventArgs(0, "Import file was a ZIP archive."));
                        }

                        oFS.Position = 0;
                        if (bWasGZIP)
                        {
                            oFS = GetUnzippedBytes(oFS);
                        }
                        else if (bWasPKZIP)
                        {
                            // Open the first JSON file.
                            ZipArchive oZA = new ZipArchive(oFS, ZipArchiveMode.Read, false, Encoding.UTF8);
                            foreach (ZipArchiveEntry oZE in oZA.Entries)
                            {
                                if (oZE.FullName.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
                                {
                                    oFS = oZE.Open();
                                    break;
                                }
                            }
                        }

                        oSR = new StreamReader(oFS, Encoding.UTF8);
                    }

                    using (oSR)
                    {
                        new NetlogImporter(oSR, listSessions, evtProgressNotifications);
                    }
                    return(listSessions.ToArray());
                }
                catch (Exception eX)
                {
                    FiddlerApplication.ReportException(eX, "Failed to import NetLog");
                    return(null);
                }
            }
            return(null);
        }
Ejemplo n.º 16
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "HTML5 AppCache Manifest")
            {
                return(false);
            }
            bool   result = false;
            string text   = null;

            if (string.IsNullOrEmpty(text))
            {
                AppCacheOptions appCacheOptions = new AppCacheOptions();
                List <string>   list            = new List <string>();
                appCacheOptions.lvItems.BeginUpdate();
                for (int i = 0; i < oSessions.Length; i++)
                {
                    Session session = oSessions[i];
                    if (!session.HTTPMethodIs("CONNECT") && session.get_responseCode() >= 200 && session.get_responseCode() <= 399 && !list.Contains(session.get_fullUrl()))
                    {
                        list.Add(session.get_fullUrl());
                        string       text2        = (session.oResponse.get_headers() != null) ? Utilities.TrimAfter(session.oResponse.get_headers().get_Item("Content-Type"), ";") : string.Empty;
                        ListViewItem listViewItem = appCacheOptions.lvItems.Items.Add(session.get_fullUrl());
                        listViewItem.SubItems.Add((session.responseBodyBytes != null) ? session.responseBodyBytes.Length.ToString() : "0");
                        listViewItem.SubItems.Add(text2);
                        if (session.HTTPMethodIs("POST"))
                        {
                            listViewItem.Checked = true;
                        }
                        if (text2.IndexOf("script", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            listViewItem.Group = appCacheOptions.lvItems.Groups["lvgScript"];
                        }
                        else
                        {
                            if (text2.IndexOf("image/", StringComparison.OrdinalIgnoreCase) > -1)
                            {
                                listViewItem.Group = appCacheOptions.lvItems.Groups["lvgImages"];
                            }
                            else
                            {
                                if (text2.IndexOf("html", StringComparison.OrdinalIgnoreCase) > -1)
                                {
                                    listViewItem.Group = appCacheOptions.lvItems.Groups["lvgMarkup"];
                                }
                                else
                                {
                                    if (text2.IndexOf("css", StringComparison.OrdinalIgnoreCase) > -1)
                                    {
                                        listViewItem.Group = appCacheOptions.lvItems.Groups["lvgCSS"];
                                    }
                                    else
                                    {
                                        listViewItem.Group = appCacheOptions.lvItems.Groups["lvgOther"];
                                    }
                                }
                            }
                        }
                        listViewItem.Tag = session;
                    }
                }
                appCacheOptions.lvItems.EndUpdate();
                if (appCacheOptions.lvItems.Items.Count > 0)
                {
                    appCacheOptions.lvItems.FocusedItem = appCacheOptions.lvItems.Items[0];
                }
                if (DialogResult.OK == appCacheOptions.ShowDialog(FiddlerApplication.get_UI()))
                {
                    text = Utilities.ObtainSaveFilename("Export As " + sFormat, "AppCache Manifest (*.appcache)|*.appcache");
                    if (!string.IsNullOrEmpty(text))
                    {
                        try
                        {
                            List <string> list2 = new List <string>();
                            List <string> list3 = new List <string>();
                            string        text3 = appCacheOptions.txtBase.Text.Trim();
                            if (text3.Length == 0)
                            {
                                text3 = null;
                            }
                            for (int j = 0; j < appCacheOptions.lvItems.Items.Count; j++)
                            {
                                string text4 = appCacheOptions.lvItems.Items[j].Text;
                                if (text3 != null && text4.Length > text3.Length && text4.StartsWith(text3))
                                {
                                    text4 = text4.Substring(text3.Length);
                                }
                                if (appCacheOptions.lvItems.Items[j].Checked)
                                {
                                    list3.Add(text4);
                                }
                                else
                                {
                                    list2.Add(text4);
                                }
                            }
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.AppendFormat("CACHE MANIFEST\r\n# Generated: {0}\r\n\r\n", DateTime.Now.ToString());
                            if (text3 != null)
                            {
                                stringBuilder.AppendFormat("# Deploy so that URLs are relative to: {0}\r\n\r\n", text3);
                            }
                            if (list2.Count > 0)
                            {
                                stringBuilder.Append("CACHE:\r\n");
                                stringBuilder.Append(string.Join("\r\n", list2.ToArray()));
                                stringBuilder.Append("\r\n");
                            }
                            if (appCacheOptions.cbNetworkFallback.Checked || list3.Count > 0)
                            {
                                stringBuilder.Append("\r\nNETWORK:\r\n");
                                if (appCacheOptions.cbNetworkFallback.Checked)
                                {
                                    stringBuilder.Append("*\r\n");
                                }
                                stringBuilder.Append(string.Join("\r\n", list3.ToArray()));
                            }
                            File.WriteAllText(text, stringBuilder.ToString());
                            Process.Start(CONFIG.GetPath("TextEditor"), text);
                            bool result2 = true;
                            return(result2);
                        }
                        catch (Exception ex)
                        {
                            FiddlerApplication.ReportException(ex, "Failed to save MeddlerScript");
                            bool result2 = false;
                            return(result2);
                        }
                    }
                    appCacheOptions.Dispose();
                }
            }
            return(result);
        }
Ejemplo n.º 17
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "Raw Files")
            {
                return(false);
            }
            string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            bool   bValue     = true;
            bool   flag2      = true;
            bool   flag3      = false;

            if (dictOptions != null)
            {
                if (dictOptions.ContainsKey("Folder"))
                {
                    folderPath = dictOptions["Folder"] as string;
                    flag3      = true;
                }
                if (dictOptions.ContainsKey("RecreateStructure"))
                {
                    bValue = string.Equals("True", dictOptions["RecreateStructure"] as string, StringComparison.OrdinalIgnoreCase);
                    flag3  = true;
                }
                if (dictOptions.ContainsKey("OpenFolder"))
                {
                    flag2 = string.Equals("True", dictOptions["OpenFolder"] as string, StringComparison.OrdinalIgnoreCase);
                    flag3 = true;
                }
            }
            if (!flag3)
            {
                UIFileExport export = new UIFileExport {
                    txtLocation = { Text = folderPath },
                    cbRecreateFolderStructure = { Checked = FiddlerApplication.Prefs.GetBoolPref("fiddler.exporters.RawFiles.RecreateStructure", true) },
                    cbOpenFolder = { Checked = FiddlerApplication.Prefs.GetBoolPref("fiddler.exporters.RawFiles.OpenFolder", true) }
                };
                this.SetDefaultPath(export.txtLocation, "fiddler.exporters.RawFiles.DefaultPath", folderPath);
                if (export.ShowDialog() != DialogResult.OK)
                {
                    return(false);
                }
                bValue     = export.cbRecreateFolderStructure.Checked;
                flag2      = export.cbOpenFolder.Checked;
                folderPath = export.txtLocation.Text;
                FiddlerApplication.Prefs.SetBoolPref("fiddler.exporters.RawFiles.RecreateStructure", bValue);
                FiddlerApplication.Prefs.SetBoolPref("fiddler.exporters.RawFiles.OpenFolder", flag2);
                FiddlerApplication.Prefs.SetStringPref("fiddler.exporters.RawFiles.DefaultPath", folderPath);
                export.Dispose();
                folderPath = folderPath + @"\Dump-" + DateTime.Now.ToString("MMdd-HH-mm-ss") + @"\";
            }
            try
            {
                Directory.CreateDirectory(folderPath);
            }
            catch (Exception exception)
            {
                FiddlerApplication.ReportException(exception, "Export Failed");
                return(false);
            }
            int num = 0;

            foreach (Session session in oSessions)
            {
                try
                {
                    if (session.HTTPMethodIs("CONNECT"))
                    {
                        num++;
                    }
                    else
                    {
                        if ((session.responseBodyBytes != null) && (session.responseBodyBytes.Length > 0))
                        {
                            string str2;
                            if (bValue)
                            {
                                str2 = Utilities.TrimAfter(session.url, '?').Replace('/', '\\');
                                if (str2.EndsWith(@"\"))
                                {
                                    str2 = str2 + session.SuggestedFilename;
                                }
                                if ((str2.Length > 0) && (str2.Length < 260))
                                {
                                    str2 = folderPath + this._MakeSafeFilename(str2);
                                }
                                else
                                {
                                    str2 = folderPath + session.SuggestedFilename;
                                }
                            }
                            else
                            {
                                str2 = folderPath + session.SuggestedFilename;
                            }
                            str2 = Utilities.EnsureUniqueFilename(str2);
                            byte[] responseBodyBytes = session.responseBodyBytes;
                            if (session.oResponse.headers.Exists("Content-Encoding") || session.oResponse.headers.Exists("Transfer-Encoding"))
                            {
                                responseBodyBytes = (byte[])responseBodyBytes.Clone();
                                Utilities.utilDecodeHTTPBody(session.oResponse.headers, ref responseBodyBytes);
                            }
                            Utilities.WriteArrayToFile(str2, responseBodyBytes);
                        }
                        num++;
                        if (evtProgressNotifications != null)
                        {
                            ProgressCallbackEventArgs e = new ProgressCallbackEventArgs(((float)num) / ((float)oSessions.Length), "Dumped " + num.ToString() + " files to disk.");
                            evtProgressNotifications(null, e);
                            if (e.Cancel)
                            {
                                return(false);
                            }
                        }
                    }
                }
                catch (Exception exception2)
                {
                    FiddlerApplication.ReportException(exception2, "Failed to generate response file.");
                }
            }
            if (flag2)
            {
                Process.Start("explorer.exe", folderPath);
            }
            return(true);
        }
Ejemplo n.º 18
0
        public Session[] ImportSessions(string sImportFormat, Dictionary <string, object> dictOptions,
                                        EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            try
            {
                if (sImportFormat != "WARC")
                {
                    throw new ArgumentException("Invalid import format");
                }

                string filename = null, content = null;
                // filename = @"X:\stuff\fiddler-warc\samples\logfile.csv";

                if (dictOptions != null)
                {
                    if (dictOptions.ContainsKey("Filename"))
                    {
                        filename = dictOptions["Filename"] as string;
                    }
                    else if (dictOptions.ContainsKey("Content"))
                    {
                        content = dictOptions["Content"] as string;
                    }
                }

                if (String.IsNullOrWhiteSpace(filename) && content == null)
                {
                    var filter = "WARC file (*.warc)|*.warc|Text files (*.txt)|*.txt|Log files (*.log)|.log|All files (*.*)|*.*";
                    filter   = "All files (*.*)|*.*";
                    filename = Fiddler.Utilities.ObtainOpenFilename("Import " + sImportFormat, filter);
                }

                WARCParser warc;
                if (!String.IsNullOrWhiteSpace(filename))
                {
                    warc = new WARCParser(new FileStream(filename, FileMode.Open));
                }
                else if (content != null)
                {
                    warc = new WARCParser(new MemoryStream(Encoding.UTF8.GetBytes(content)));
                }
                else
                {
                    throw new ArgumentException("Invalid options");
                }

                var sessions = new List <Session>();
                using (warc)
                {
                    WARCParser.Record prevRequest = null;
                    foreach (var record in warc.parse())
                    {
                        if (prevRequest == null)
                        {
                            if (record.Type == "request")
                            {
                                prevRequest = record;
                            }
                        }
                        else
                        {
                            WARCParser.Record request  = prevRequest;
                            WARCParser.Record response = null;
                            if (record.Type == "response")
                            {
                                response = record;
                            }

                            if (response == null)
                            {
                                var session = new Session(
                                    request.Body,
                                    null,
                                    SessionFlags.ImportedFromOtherTool);

                                session.Timers.ClientBeginRequest = request.Date;

                                sessions.Add(session);
                            }
                            else if (request.RecordID == response.ConcurrentTo)
                            {
                                if (!String.IsNullOrWhiteSpace(request.SentBy))
                                {
                                    var session = new Session(
                                        request.Body,
                                        response.Body,
                                        SessionFlags.ImportedFromOtherTool);

                                    session.Timers.ClientBeginRequest = request.Date;
                                    session.Timers.ServerDoneResponse = response.Date;

                                    sessions.Add(session);
                                }
                            }
                            else
                            {
                                if (!String.IsNullOrWhiteSpace(request.SentBy))
                                {
                                    var requestSession = new Session(
                                        request.Body,
                                        null,
                                        SessionFlags.ImportedFromOtherTool);

                                    requestSession.Timers.ClientBeginRequest = request.Date;

                                    sessions.Add(requestSession);
                                }
                                var responseSession = new Session(
                                    null,
                                    response.Body,
                                    SessionFlags.ImportedFromOtherTool);

                                responseSession.Timers.ServerDoneResponse = response.Date;

                                sessions.Add(responseSession);
                            }

                            prevRequest = null;
                        }
                    }
                }

                return(sessions.ToArray());
            }
            catch (Exception ex)
            {
                FiddlerApplication.ReportException(ex, "Failed to import NetLog");
                return(null);
            }
        }
Ejemplo n.º 19
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "MeddlerScript")
            {
                return(false);
            }
            bool   result = false;
            string text   = null;

            if (dictOptions != null && dictOptions.ContainsKey("Filename"))
            {
                text = (dictOptions["Filename"] as string);
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Utilities.ObtainSaveFilename("Export As " + sFormat, "MeddlerScript (*.ms)|*.ms");
            }
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    int           num           = 0;
                    string        text2         = null;
                    bool          result2;
                    for (int i = 0; i < oSessions.Length; i++)
                    {
                        Session session = oSessions[i];
                        if (text2 == null)
                        {
                            text2 = "http://localhost:{$PORT}" + session.get_PathAndQuery();
                        }
                        stringBuilder.AppendFormat("\r\n\t\t\tif (oSession.requestHeaders.Path == '{0}')\r\n\t\t\t{{\r\n", session.get_PathAndQuery().Replace("'", "\\'"));
                        stringBuilder.AppendFormat("\r\n\t\t\t\toHeaders.Version='{0}';", session.oResponse.get_headers().HTTPVersion.Replace("'", "\\'"));
                        stringBuilder.AppendFormat("\r\n\t\t\t\toHeaders.Status='{0}';\r\n", session.oResponse.get_headers().HTTPResponseStatus.Replace("'", "\\'"));
                        foreach (HTTPHeaderItem current in session.oResponse.get_headers())
                        {
                            stringBuilder.AppendFormat("\r\n\t\t\t\toHeaders.Add('{0}', '{1}');", current.Name.Replace("'", "\\'"), current.Value.Replace("'", "\\'"));
                        }
                        stringBuilder.AppendFormat("\r\n\t\t\t\toSession.WriteString(oHeaders);\r\n", new object[0]);
                        stringBuilder.AppendFormat("\r\n\t\t\t\toSession.WriteBytes(Convert.FromBase64String('", new object[0]);
                        stringBuilder.AppendFormat(Convert.ToBase64String(session.responseBodyBytes), new object[0]);
                        stringBuilder.AppendFormat("'));\r\n", new object[0]);
                        stringBuilder.AppendFormat("\t\t\t\toSession.CloseSocket(); return;\r\n\t\t\t}}\r\n", new object[0]);
                        num++;
                        if (evtProgressNotifications != null)
                        {
                            ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Added " + num.ToString() + " sessions to MeddlerScript.");
                            evtProgressNotifications(null, progressCallbackEventArgs);
                            if (progressCallbackEventArgs.get_Cancel())
                            {
                                result2 = false;
                                return(result2);
                            }
                        }
                    }
                    this.PrependMeddlerHeader(stringBuilder, text2 ?? "http://localhost:{$PORT}/");
                    this.EmitMeddlerFooter(stringBuilder);
                    File.WriteAllText(text, stringBuilder.ToString());
                    result2 = true;
                    return(result2);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to save MeddlerScript");
                    bool result2 = false;
                    return(result2);
                }
                return(result);
            }
            return(result);
        }
Ejemplo n.º 20
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "WCAT Script")
            {
                return(false);
            }
            bool   result = false;
            string text   = null;

            if (dictOptions != null && dictOptions.ContainsKey("Filename"))
            {
                text = (dictOptions["Filename"] as string);
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Utilities.ObtainSaveFilename("Export As " + sFormat, "WCAT Script (*.wcat)|*.wcat");
            }
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    this.EmitScenarioHeader(stringBuilder);
                    int  num = 0;
                    bool result2;
                    for (int i = 0; i < oSessions.Length; i++)
                    {
                        Session session = oSessions[i];
                        if (session.HTTPMethodIs("GET") || session.HTTPMethodIs("POST"))
                        {
                            stringBuilder.AppendLine("    request");
                            stringBuilder.AppendLine("    {");
                            stringBuilder.AppendFormat("      id = \"{0}\";\r\n", session.id);
                            stringBuilder.AppendFormat("      url     = \"{0}\";\r\n", this.WCATEscape(session.PathAndQuery));
                            if (session.isHTTPS)
                            {
                                stringBuilder.AppendLine("      secure = true");
                                if (session.port != 443)
                                {
                                    stringBuilder.AppendFormat("      port = {0};\r\n", session.port);
                                }
                            }
                            else
                            {
                                if (session.port != 80)
                                {
                                    stringBuilder.AppendFormat("      port = {0};\r\n", session.port);
                                }
                            }
                            if (session.oRequest.headers.HTTPVersion == "HTTP/1.0")
                            {
                                stringBuilder.AppendLine("      version = HTTP10;");
                            }
                            if (session.HTTPMethodIs("POST"))
                            {
                                stringBuilder.AppendLine("      verb = POST;");
                                stringBuilder.AppendFormat("      postdata = \"{0}\";\r\n", this.WCATEscape(Encoding.UTF8.GetString(session.requestBodyBytes)));
                            }
                            if (session.responseCode > 0 && 200 != session.responseCode)
                            {
                                stringBuilder.AppendFormat("      statuscode = {0};\r\n", session.responseCode);
                            }
                            HTTPRequestHeaders headers = session.oRequest.headers;
                            foreach (HTTPHeaderItem current in headers)
                            {
                                this.EmitRequestHeaderEntry(stringBuilder, current.Name, current.Value);
                            }
                            stringBuilder.AppendLine("    }");
                            num++;
                            if (evtProgressNotifications != null)
                            {
                                ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Added " + num.ToString() + " sessions to WCAT Script.");
                                evtProgressNotifications(null, progressCallbackEventArgs);
                                if (progressCallbackEventArgs.Cancel)
                                {
                                    result2 = false;
                                    return(result2);
                                }
                            }
                        }
                    }
                    stringBuilder.AppendLine("  }\r\n}");
                    File.WriteAllText(text, stringBuilder.ToString());
                    result2 = true;
                    return(result2);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to save WCAT Script");
                    bool result2 = false;
                    return(result2);
                }
                return(result);
            }
            return(result);
        }
Ejemplo n.º 21
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "WCAT Script")
            {
                return(false);
            }
            string str = null;

            if ((dictOptions != null) && dictOptions.ContainsKey("Filename"))
            {
                str = dictOptions["Filename"] as string;
            }
            if (string.IsNullOrEmpty(str))
            {
                str = Utilities.ObtainSaveFilename("Export As " + sFormat, "WCAT Script (*.wcat)|*.wcat");
            }
            if (!string.IsNullOrEmpty(str))
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    this.EmitScenarioHeader(sb);
                    int num = 0;
                    foreach (Session session in oSessions)
                    {
                        if (session.HTTPMethodIs("GET") || session.HTTPMethodIs("POST"))
                        {
                            sb.AppendLine("    request");
                            sb.AppendLine("    {");
                            if (session.HTTPMethodIs("POST"))
                            {
                                sb.AppendLine("      verb = POST;");
                                sb.AppendFormat("      postdata = \"{0}\";", Encoding.UTF8.GetString(session.requestBodyBytes).Replace("\"", "\\\""));
                            }
                            sb.AppendFormat("      url     = \"{0}\";", session.PathAndQuery.Replace("\"", "\\\""));
                            foreach (HTTPHeaderItem item in session.oRequest.headers)
                            {
                                this.EmitRequestHeaderEntry(sb, item.Name, item.Value);
                            }
                            sb.AppendLine("    }");
                            num++;
                            if (evtProgressNotifications != null)
                            {
                                ProgressCallbackEventArgs e = new ProgressCallbackEventArgs(((float)num) / ((float)oSessions.Length), "Added " + num.ToString() + " sessions to WCAT Script.");
                                evtProgressNotifications(null, e);
                                if (e.Cancel)
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                    sb.AppendLine("  }\r\n}");
                    File.WriteAllText(str, sb.ToString());
                    return(true);
                }
                catch (Exception exception)
                {
                    FiddlerApplication.ReportException(exception, "Failed to save WCAT Script");
                    return(false);
                }
            }
            return(false);
        }
Ejemplo n.º 22
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if (sFormat != "MeddlerScript")
            {
                return(false);
            }
            string str = null;

            if ((dictOptions != null) && dictOptions.ContainsKey("Filename"))
            {
                str = dictOptions["Filename"] as string;
            }
            if (string.IsNullOrEmpty(str))
            {
                str = Utilities.ObtainSaveFilename("Export As " + sFormat, "MeddlerScript (*.ms)|*.ms");
            }
            if (!string.IsNullOrEmpty(str))
            {
                try
                {
                    StringBuilder sb   = new StringBuilder();
                    int           num  = 0;
                    string        str2 = null;
                    foreach (Session session in oSessions)
                    {
                        if (str2 == null)
                        {
                            str2 = "http://*****:*****@"\'"));
                        sb.AppendFormat("\r\n\t\t\t\toHeaders.Version='{0}';", session.oResponse.headers.HTTPVersion.Replace("'", @"\'"));
                        sb.AppendFormat("\r\n\t\t\t\toHeaders.Status='{0}';\r\n", session.oResponse.headers.HTTPResponseStatus.Replace("'", @"\'"));
                        foreach (HTTPHeaderItem item in session.oResponse.headers)
                        {
                            sb.AppendFormat("\r\n\t\t\t\toHeaders.Add('{0}', '{1}');", item.Name.Replace("'", @"\'"), item.Value.Replace("'", @"\'"));
                        }
                        sb.AppendFormat("\r\n\t\t\t\toSession.WriteString(oHeaders);\r\n", new object[0]);
                        sb.AppendFormat("\r\n\t\t\t\toSession.WriteBytes(Convert.FromBase64String('", new object[0]);
                        sb.AppendFormat(Convert.ToBase64String(session.responseBodyBytes), new object[0]);
                        sb.AppendFormat("'));\r\n", new object[0]);
                        sb.AppendFormat("\t\t\t\toSession.CloseSocket(); return;\r\n\t\t\t}}\r\n", new object[0]);
                        num++;
                        if (evtProgressNotifications != null)
                        {
                            ProgressCallbackEventArgs e = new ProgressCallbackEventArgs(((float)num) / ((float)oSessions.Length), "Added " + num.ToString() + " sessions to MeddlerScript.");
                            evtProgressNotifications(null, e);
                            if (e.Cancel)
                            {
                                return(false);
                            }
                        }
                    }
                    this.PrependMeddlerHeader(sb, str2 ?? "http://localhost:{$PORT}/");
                    this.EmitMeddlerFooter(sb);
                    File.WriteAllText(str, sb.ToString());
                    return(true);
                }
                catch (Exception exception)
                {
                    FiddlerApplication.ReportException(exception, "Failed to save MeddlerScript");
                    return(false);
                }
            }
            return(false);
        }
        public Session[] ImportSessions(string sFormat, Dictionary <string, object> dictOptions, EventHandler <Fiddler.ProgressCallbackEventArgs> evtProgressNotifications)
        {
            if ((sFormat != "WPRCapture JSON"))
            {
                Debug.Assert(false); return(null);
            }

            MemoryStream strmContent = null;
            string       sFilename   = null;

            if (null != dictOptions)
            {
                if (dictOptions.ContainsKey("Filename"))
                {
                    sFilename = dictOptions["Filename"] as string;
                }
                else if (dictOptions.ContainsKey("Content"))
                {
                    strmContent = new MemoryStream(Encoding.UTF8.GetBytes(dictOptions["Content"] as string));
                }
            }

            if ((null == strmContent) && string.IsNullOrEmpty(sFilename))
            {
                sFilename = Fiddler.Utilities.ObtainOpenFilename("Import " + sFormat, "WPRGo JSON (*.wprgo)|*.wprgo");
            }

            if ((null != strmContent) || !String.IsNullOrEmpty(sFilename))
            {
                try
                {
                    List <Session> listSessions = new List <Session>();
                    StreamReader   oSR;

                    if (null != strmContent)
                    {
                        oSR = new StreamReader(strmContent);
                    }
                    else
                    {
                        Stream oFS = File.OpenRead(sFilename);

                        // Check to see if this file data was GZIP'd. It SHOULD be.
                        bool bWasGZIP = false;
                        int  bFirst   = oFS.ReadByte();
                        if (bFirst == 0x1f && oFS.ReadByte() == 0x8b)
                        {
                            bWasGZIP = true;
                            evtProgressNotifications?.Invoke(null, new ProgressCallbackEventArgs(0, "Import file was compressed using gzip/DEFLATE."));
                        }

                        oFS.Position = 0;
                        if (bWasGZIP)
                        {
                            oFS = GetUnzippedBytes(oFS);
                        }

                        oSR = new StreamReader(oFS, Encoding.UTF8);
                    }

                    using (oSR)
                    {
                        new WPRImporter(oSR, listSessions, evtProgressNotifications);
                    }
                    return(listSessions.ToArray());
                }
                catch (Exception eX)
                {
                    FiddlerApplication.ReportException(eX, "Failed to import NetLog");
                    return(null);
                }
            }
            return(null);
        }
Ejemplo n.º 24
0
        internal MemoryStream GetPayloadStream(StringBuilder sbDebugInfo, int iMaxSize)
        {
            MemoryStream memoryStream = new MemoryStream();

            this.listPayloadPacketTimes = new List <TCPStream.PayloadPacketTime>();
            try
            {
                if (sbDebugInfo != null)
                {
                    foreach (TCPFrame current in this.listFrames)
                    {
                        sbDebugInfo.AppendFormat("Packet #{0}:\tSeq #{1}\tPayloadLength: {2}\n", current._uiFrameID, current.uiSeqNum, current.PayloadLength);
                    }
                }
                ulong num = 0uL;
                foreach (TCPFrame current2 in this.listFrames)
                {
                    if (current2.PayloadLength >= 1u)
                    {
                        if (current2.uiEndsAtSeqNum < num)
                        {
                            if (PacketCaptureImport.bVerboseDebug)
                            {
                                //FiddlerApplication.get_Log().LogFormat(string.Concat(new string[]
                                //{
                                //    "Skipping Packet\n\nNext\t",
                                //    num.ToString("N0"),
                                //    "\n\nStart\t",
                                //    current2.uiSeqNum.ToString("N0"),
                                //    "\nStop\t",
                                //    current2.uiEndsAtSeqNum.ToString("N0")
                                //}), new object[0]);
                            }
                        }
                        else
                        {
                            if (memoryStream.Length == 0L)
                            {
                                this.dtFirstPayload = current2.dtWhen;
                            }
                            this.listPayloadPacketTimes.Add(new TCPStream.PayloadPacketTime
                            {
                                dtTime  = current2.dtWhen,
                                iOffset = (int)memoryStream.Length
                            });
                            uint num2 = 0u;
                            if (num > 0uL)
                            {
                                if (num < current2.uiSeqNum)
                                {
                                    uint num3 = (uint)(current2.uiSeqNum - num);
                                    if (PacketCaptureImport.bVerboseDebug)
                                    {
                                        //FiddlerApplication.get_Log().LogFormat("! Missing {0} bytes of data between {1:N0} and {2:N0} in Stream\n{3}", new object[]
                                        //{
                                        //    num3,
                                        //    num,
                                        //    current2.uiSeqNum,
                                        //    this.ToString()
                                        //});
                                    }
                                    memoryStream.Seek((long)((ulong)num3), SeekOrigin.Current);
                                    num = current2.uiSeqNum;
                                }
                                try
                                {
                                    num2 = checked ((uint)(num - current2.uiSeqNum));
                                }
                                catch (ArithmeticException)
                                {
                                    //FiddlerApplication.get_Log().LogFormat(string.Concat(new string[]
                                    //{
                                    //    "Threw on Frame #",
                                    //    current2._uiFrameID.ToString("N0"),
                                    //    "\n\nNext\t",
                                    //    num.ToString("N0"),
                                    //    "\n\nStart\t",
                                    //    current2.uiSeqNum.ToString("N0"),
                                    //    "\nStop\t",
                                    //    current2.uiEndsAtSeqNum.ToString("N0")
                                    //}), new object[0]);
                                }
                            }
                            if (sbDebugInfo != null)
                            {
                                sbDebugInfo.AppendFormat("{5}Packet #{0,-5} has {1,-5} of {2,-5} usable bytes\tFilling {3:N0}-{4:N0}\n", new object[]
                                {
                                    current2._uiFrameID,
                                    current2.PayloadLength - num2,
                                    current2.PayloadLength,
                                    memoryStream.Length,
                                    (ulong)(memoryStream.Length + (long)((ulong)(current2.PayloadLength - num2))),
                                    (num2 == 0u) ? string.Empty : "!! PARTIAL\n"
                                });
                            }
                            current2.WritePayloadToMemoryStream(memoryStream, num2);
                            num = current2.uiEndsAtSeqNum + 1uL;
                            if (iMaxSize > 0 && memoryStream.Length > (long)iMaxSize)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FiddlerApplication.ReportException(ex, "GetPayloadStream() Error", "Failure when constructing payload stream for " + this.ToString());
            }
            return(memoryStream);
        }
Ejemplo n.º 25
0
        internal static bool WriteStream(StreamWriter swOutput, Session[] oSessions, bool bUseV1dot2Format, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications, int iMaxTextBodyLength, int iMaxBinaryBodyLength)
        {
            _iMaxTextBodyLength   = iMaxTextBodyLength;
            _iMaxBinaryBodyLength = iMaxBinaryBodyLength;
            Hashtable hashtable = new Hashtable();

            hashtable.Add("version", bUseV1dot2Format ? "1.2" : "1.1");
            hashtable.Add("pages", new ArrayList(0));
            if (bUseV1dot2Format)
            {
                hashtable.Add("comment", "exported @ " + DateTime.Now.ToString());
            }
            Hashtable hashtable2 = new Hashtable();

            hashtable2.Add("name", "Fiddler");
            hashtable2.Add("version", Application.ProductVersion);
            if (bUseV1dot2Format)
            {
                hashtable2.Add("comment", "http://www.fiddler2.com");
            }
            hashtable.Add("creator", hashtable2);
            ArrayList list = new ArrayList();
            int       num  = 0;

            foreach (Session session in oSessions)
            {
                try
                {
                    if (session.state < SessionStates.Done)
                    {
                        continue;
                    }
                    Hashtable hashtable3 = new Hashtable();
                    hashtable3.Add("startedDateTime", session.Timers.ClientBeginRequest.ToString("o"));
                    hashtable3.Add("request", getRequest(session));
                    hashtable3.Add("response", getResponse(session, bUseV1dot2Format));
                    hashtable3.Add("cache", new Hashtable());
                    Hashtable htTimers = getTimings(session.Timers, bUseV1dot2Format);
                    hashtable3.Add("time", getTotalTime(htTimers));
                    hashtable3.Add("timings", htTimers);
                    if (bUseV1dot2Format)
                    {
                        string str = session["ui-comments"];
                        if (!string.IsNullOrEmpty(str))
                        {
                            hashtable3.Add("comment", session["ui-comments"]);
                        }
                        string hostIP = session.m_hostIP;
                        if (!string.IsNullOrEmpty(str) && !session.isFlagSet(SessionFlags.SentToGateway))
                        {
                            hashtable3.Add("serverIPAddress", session.m_hostIP);
                        }
                        hashtable3.Add("connection", session.clientPort.ToString());
                    }
                    list.Add(hashtable3);
                }
                catch (Exception exception)
                {
                    FiddlerApplication.ReportException(exception, "Failed to Export Session");
                }
                num++;
                if (evtProgressNotifications != null)
                {
                    ProgressCallbackEventArgs e = new ProgressCallbackEventArgs(((float)num) / ((float)oSessions.Length), "Wrote " + num.ToString() + " sessions to HTTPArchive.");
                    evtProgressNotifications(null, e);
                    if (e.Cancel)
                    {
                        return(false);
                    }
                }
            }
            hashtable.Add("entries", list);
            Hashtable json = new Hashtable();

            json.Add("log", hashtable);
            swOutput.WriteLine(JSON.JsonEncode(json));
            return(true);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Reads a session archive zip file into an array of Session objects
        /// </summary>
        /// <param name="sFilename">Filename to load</param>
        /// <param name="bVerboseDialogs"></param>
        /// <returns>Loaded array of sessions or null, in case of failure</returns>
        private static Session[] ReadSessionArchive(string sFilename, bool bVerboseDialogs)
        {
            /*  Okay, given the zip, we gotta:
             *		Unzip
             *		Find all matching pairs of request, response
             *		Create new Session object for each pair
             */
            if (!File.Exists(sFilename))
            {
                FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. File " + sFilename + " does not exist.");
                return(null);
            }

            ZipFile oZip;
            var     sPassword   = String.Empty;
            var     outSessions = new List <Session>();

            try
            {
                // Sniff for ZIP file.
                var oSniff = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                if (oSniff.Length < 64 || oSniff.ReadByte() != 0x50 || oSniff.ReadByte() != 0x4B)
                {  // Sniff for 'PK'
                    FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. " + sFilename + " is not a Fiddler-generated .SAZ archive of HTTP Sessions.");
                    oSniff.Close();
                    return(null);
                }

                oSniff.Close();
                oZip = new ZipFile(sFilename);

                if (!oZip.EntryFileNames.Contains("raw/"))
                {
                    FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. The selected ZIP is not a Fiddler-generated .SAZ archive of HTTP Sessions.");
                    return(null);
                }

                foreach (var oZE in oZip.Where(oZE => oZE.FileName.EndsWith("_c.txt") && oZE.FileName.StartsWith("raw/")))
                {
GetPassword:
                    if (oZE.Encryption != EncryptionAlgorithm.None && (String.Empty == sPassword))
                    {
                        Console.Write("Password-Protected Session Archive.\nEnter the password to decrypt, or enter nothing to abort opening.\n>");
                        sPassword = Console.ReadLine();
                        if (sPassword != String.Empty)
                        {
                            oZip.Password = sPassword;
                        }
                        else
                        {
                            return(null);
                        }
                    }

                    try
                    {
                        var    arrRequest = new byte[oZE.UncompressedSize];
                        Stream oFs;
                        try
                        {
                            oFs = oZE.OpenReader();
                        }
                        catch (BadPasswordException)
                        {
                            Console.WriteLine("Incorrect password.");
                            sPassword = String.Empty;
                            goto GetPassword;
                        }

                        var iRead = Utilities.ReadEntireStream(oFs, arrRequest);
                        oFs.Close();
                        Debug.Assert(iRead == arrRequest.Length, "Failed to read entire request.");

                        var oZEResponse = oZip[oZE.FileName.Replace("_c.txt", "_s.txt")];

                        if (null == oZEResponse)
                        {
                            FiddlerApplication.Log.LogString("Could not find a server response for: " + oZE.FileName);
                            continue;
                        }

                        var arrResponse = new byte[oZEResponse.UncompressedSize];
                        oFs   = oZEResponse.OpenReader();
                        iRead = Utilities.ReadEntireStream(oFs, arrResponse);
                        oFs.Close();
                        Debug.Assert(iRead == arrResponse.Length, "Failed to read entire response.");

                        var oSession = new Session(arrRequest, arrResponse);

                        var oZEMetadata = oZip[oZE.FileName.Replace("_c.txt", "_m.xml")];

                        if (null != oZEMetadata)
                        {
                            oSession.LoadMetadata(oZEMetadata.OpenReader());
                        }

                        oSession.oFlags["x-LoadedFrom"] = oZE.FileName.Replace("_c.txt", "_s.txt");
                        outSessions.Add(oSession);
                    }
                    catch (Exception eX)
                    {
                        FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive incomplete. Invalid data was present in session: " + oZE.FileName + ".\n\n\n" + eX.Message + "\n" + eX.StackTrace);
                    }
                }
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX, "ReadSessionArchive Error");
                return(null);
            }

            oZip.Dispose();

            return(outSessions.ToArray());
        }
 public bool LoadRules(string sFilename, bool bIsDefaultRuleFile)
 {
     this._orules.Clear();
     this._orules2.Clear();
     this.lstDuplicate.Clear();
     if (bIsDefaultRuleFile)
     {
         FiddlerApplication.oAutoResponder.ClearRules();
     }
     try
     {
         if (!File.Exists(sFilename) || (new FileInfo(sFilename).Length < 0x8fL))
         {
             return(false);
         }
         FileStream input = new FileStream(sFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         Dictionary <string, string> dictionary = new Dictionary <string, string>();
         XmlTextReader reader = new XmlTextReader(input);
         while (reader.Read())
         {
             string str;
             if (((reader.NodeType == XmlNodeType.Element) && ((str = reader.Name) != null)) && ((str != "State") && (str == "ResponseRule")))
             {
                 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 str5       = reader.GetAttribute("Headers");
                     if (string.IsNullOrEmpty(str5))
                     {
                         FiddlerApplication.oAutoResponder.IsRuleListDirty = false;
                         ResponderRule item = FiddlerApplication.oAutoResponder.AddRule(attribute, sAction, bIsEnabled);
                         this._orules.Add(item);
                         ResponderRuleExt ext = new ResponderRuleExt();
                         ext.arrResponseBytes = null;
                         ext.strMatch         = attribute;
                         ext.strDescription   = sAction;
                         ext.bEnabled         = bIsEnabled;
                         ext.iLatencyMS       = iLatencyMS;
                         ext.oResponseHeaders = null;
                         this._orules2.Add(ext);
                     }
                     else
                     {
                         byte[] buffer;
                         HTTPResponseHeaders oRH = new HTTPResponseHeaders();
                         str5 = Encoding.UTF8.GetString(Convert.FromBase64String(str5));
                         oRH.AssignFromString(str5);
                         string str6 = reader.GetAttribute("DeflatedBody");
                         if (!string.IsNullOrEmpty(str6))
                         {
                             buffer = Utilities.DeflaterExpand(Convert.FromBase64String(str6));
                         }
                         else
                         {
                             str6 = reader.GetAttribute("Body");
                             if (!string.IsNullOrEmpty(str6))
                             {
                                 buffer = Convert.FromBase64String(str6);
                             }
                             else
                             {
                                 buffer = new byte[0];
                             }
                         }
                         FiddlerApplication.oAutoResponder.IsRuleListDirty = false;
                         ResponderRule rule2 = FiddlerApplication.oAutoResponder.AddRule(attribute, oRH, buffer, sAction, iLatencyMS, bIsEnabled);
                         this._orules.Add(rule2);
                         ResponderRuleExt ext2 = new ResponderRuleExt();
                         ext2.arrResponseBytes = buffer;
                         ext2.strMatch         = attribute;
                         ext2.strDescription   = sAction;
                         ext2.bEnabled         = bIsEnabled;
                         ext2.iLatencyMS       = iLatencyMS;
                         ext2.oResponseHeaders = oRH;
                         this._orules2.Add(ext2);
                         try
                         {
                             dictionary.Add(attribute, Guid.NewGuid().ToString());
                         }
                         catch (Exception)
                         {
                             this.lstDuplicate.Add(attribute);
                         }
                     }
                     continue;
                 }
                 catch
                 {
                     continue;
                 }
             }
         }
         reader.Close();
         return(true);
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception, "Failed to load AutoResponder settings from " + sFilename);
         return(false);
     }
 }