Example #1
0
 private Session[] GetSessionsFromPackets(ref PacketCaptureImport.PacketCounts pcCounts, Dictionary <string, TCPStream> dictTCPConns)
 {
     //FiddlerApplication.get_Log().LogFormat("PACKET COUNTER\n\n{0}\n", new object[]
     //{
     //    pcCounts
     //});
     if (pcCounts.IPv4 + pcCounts.IPv6 < 1u)
     {
         string text = "No IPv4 or IPv6 traffic was found in this capture.";
         if (this.loadedFileType == PacketCaptureImport.FileType.CAP)
         {
             text += "\n\nIf this capture was collected using Message Analyzer, please instead use its 'Link Local' capture mode instead of 'Firewall' mode.";
         }
         if (!PacketCaptureImport.bSilent)
         {
             Console.WriteLine(String.Format(text, "No traffic found"));
         }
         return(null);
     }
     if (PacketCaptureImport.evtOnProgress != null)
     {
         ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs(0.4f, "Finished processing raw packets...");
         PacketCaptureImport.evtOnProgress(null, progressCallbackEventArgs);
         if (progressCallbackEventArgs.Cancel == true)
         {
             return(null);
         }
     }
     PacketCaptureImport._PairTCPStreams(dictTCPConns);
     if (PacketCaptureImport.evtOnProgress != null)
     {
         ProgressCallbackEventArgs progressCallbackEventArgs2 = new ProgressCallbackEventArgs(0.6f, "Finished assembling streams...");
         PacketCaptureImport.evtOnProgress(null, progressCallbackEventArgs2);
         if (progressCallbackEventArgs2.Cancel == true)
         {
             return(null);
         }
     }
     return(PacketCaptureImport._DumpTCPTraffic(dictTCPConns));
 }
Example #2
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);
        }
Example #3
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);
        }
Example #4
0
        public bool ExportSessions(string sExportFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool ReportProgress(float percentage, string message)
            {
                if (evtProgressNotifications == null)
                {
                    return(true);
                }

                var eventArgs = new ProgressCallbackEventArgs(percentage, message);

                evtProgressNotifications(null, eventArgs);

                if (eventArgs.Cancel)
                {
                    return(false);
                }

                return(true);
            }

            try
            {
                string filenameKey = "Filename";
                string filename;

                if (dictOptions?.ContainsKey(filenameKey) == true)
                {
                    filename = (string)dictOptions[filenameKey];
                }
                else
                {
                    filename = Utilities.ObtainSaveFilename($"Export As {sExportFormat}", "JSON Files (*.postman_collection.json)|*.postman_collection.json");
                }

                if (string.IsNullOrEmpty(filename))
                {
                    return(false);
                }

                if (oSessions.Length > 100)
                {
                    var confirmResult = MessageBox.Show($"You're about to export {oSessions.Length} sessions. That's a lot. Are you sure you want to do that?",
                                                        "Just Checking", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (confirmResult != DialogResult.Yes)
                    {
                        return(false);
                    }
                }

                var name = Path.GetFileNameWithoutExtension(filename);
                var postmanCollection = new PostmanCollection
                {
                    Info = new PostmanInfo
                    {
                        Name = name
                    },
                    Items = new List <PostmanItem>(),
                };

                int countProcessed = 0;
                foreach (var session in oSessions)
                {
                    var postmanItem = new PostmanItem
                    {
                        Name    = session.PathAndQuery,
                        Request = new PostmanRequest
                        {
                            Method = session.RequestMethod,
                            Header = new List <PostmanListItem>(session.RequestHeaders.Count() + 1),
                            Url    = session.fullUrl,
                            Body   = new PostmanBody
                            {
                                Mode = "raw",
                                Raw  = session.GetRequestBodyAsString(),
                            },
                        },
                        Response = new PostmanResponse
                        {
                            Code   = session.responseCode,
                            Name   = session.PathAndQuery,
                            Body   = session.GetResponseBodyAsString(),
                            Status = session.ResponseHeaders.StatusDescription,
                            Header = new List <PostmanListItem>(session.ResponseHeaders.Count() + 1),
                        },
                    };

                    foreach (var requestHeader in session.RequestHeaders)
                    {
                        postmanItem.Request.Header.Add(new PostmanListItem
                        {
                            Type  = "text",
                            Key   = requestHeader.Name,
                            Value = requestHeader.Value
                        });
                    }

                    foreach (var responseHeader in session.ResponseHeaders)
                    {
                        postmanItem.Response.Header.Add(new PostmanListItem
                        {
                            Key   = responseHeader.Name,
                            Value = responseHeader.Value
                        });
                    }

                    postmanCollection.Items.Add(postmanItem);

                    countProcessed++;
                    if (!ReportProgress(countProcessed / (float)oSessions.Length * 0.70f, $"{countProcessed} of {oSessions.Length}"))
                    {
                        return(false);
                    }
                }

                if (!ReportProgress(0.80f, "Serializing JSON..."))
                {
                    return(false);
                }

                var json = JsonConvert.SerializeObject(postmanCollection, _jsonSerializerSettings);

                if (!ReportProgress(0.90f, "Writing JSON..."))
                {
                    return(false);
                }

                File.WriteAllText(filename, json);

                ReportProgress(1.00f, $"Finished Writing JSON to {filename}");

                return(true);
            }
            catch (Exception e)
            {
                MessageBox.Show($"Failed to export. Exception: {e.Message}");
                return(false);
            }
        }
Example #5
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);
        }
Example #6
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);
        }
Example #7
0
    public bool ExportSessions(string sFormat, Session[] oSessions,
                               Dictionary <string, object> dictOptions,
                               EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
    {
        bool   bResult = false;
        string chSplit;

        // Determine if we already have a filename
        // from the dictOptions collection
        string sFilename = null;

        if (null != dictOptions && dictOptions.ContainsKey("Filename"))
        {
            sFilename = dictOptions["Filename"] as string;
        }

        // If we don't yet have a filename, prompt the user
        // with a File Save dialog, using the correct file extension
        // for the export format they selected
        if (sFormat == "Comma-Separated Values")
        {
            chSplit = ",";
            if (string.IsNullOrEmpty(sFilename))
            {
                sFilename = Fiddler.Utilities.ObtainSaveFilename(
                    "Export As " + sFormat, "CSV Files (*.csv)|*.csv");
            }
        }
        else
        {
            // Ensure caller asked for Tab-delimiting.
            if (sFormat != "TAB-Separated Values")
            {
                return(false);
            }
            chSplit = "\t";
            if (string.IsNullOrEmpty(sFilename))
            {
                sFilename = Fiddler.Utilities.ObtainSaveFilename(
                    "Export As " + sFormat, "TSV Files (*.tsv)|*.tsv");
            }
        }

        // If we didn't get a filename, user cancelled. If so, bail out.
        if (String.IsNullOrEmpty(sFilename))
        {
            return(false);
        }

        try
        {
            StreamWriter swOutput = new StreamWriter(sFilename, false, Encoding.UTF8);
            int          iCount   = 0;
            int          iMax     = oSessions.Length;

            #region WriteColHeaders
            bool bFirstCol = true;
            foreach (ColumnHeader oLVCol in FiddlerApplication.UI.lvSessions.Columns)
            {
                if (!bFirstCol)
                {
                    swOutput.Write(chSplit);
                }
                else
                {
                    bFirstCol = false;
                }

                // Remove any delimiter characters from the value
                swOutput.Write(oLVCol.Text.Replace(chSplit, ""));
            }

            swOutput.WriteLine();
            #endregion WriteColHeaders

            #region WriteEachSession
            foreach (Session oS in oSessions)
            {
                iCount++;

                // The ViewItem object is the ListViewItem in the Web Sessions list
                // Obviously, this doesn't exist in FiddlerCore-based applications
                if (null != oS.ViewItem)
                {
                    bFirstCol = true;
                    ListViewItem oLVI = (oS.ViewItem as ListViewItem);
                    if (null == oLVI)
                    {
                        continue;
                    }
                    foreach (ListViewItem.ListViewSubItem oLVC in oLVI.SubItems)
                    {
                        if (!bFirstCol)
                        {
                            swOutput.Write(chSplit);
                        }
                        else
                        {
                            bFirstCol = false;
                        }

                        // Remove any delimiter characters from the value
                        swOutput.Write(oLVC.Text.Replace(chSplit, ""));
                    }

                    swOutput.WriteLine();
                }

                // Notify the caller of our progress
                if (null != evtProgressNotifications)
                {
                    ProgressCallbackEventArgs PCEA =
                        new ProgressCallbackEventArgs((iCount / (float)iMax),
                                                      "wrote " + iCount.ToString() + " records.");
                    evtProgressNotifications(null, PCEA);

                    // If the caller tells us to cancel, abort quickly
                    if (PCEA.Cancel)
                    {
                        swOutput.Close(); return(false);
                    }
                }
            }
            #endregion WriteEachSession

            swOutput.Close();
            bResult = true;
        }
        catch (Exception eX)
        {
            // TODO: Replace alert with FiddlerApplication.Log.LogFormat(...
            MessageBox.Show(eX.Message, "Failed to export");
            bResult = false;
        }

        return(bResult);
    }
        private bool luaExport(string sFilename,
                               Session[] oSessions,
                               EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool          inGroup         = false;
            string        strCurrentGroup = "";
            StringBuilder strbHead        = new StringBuilder();
            StringBuilder strbBody        = new StringBuilder();
            StringBuilder strbFoot        = new StringBuilder();

            StreamWriter swOutput = new StreamWriter(sFilename, false, Encoding.UTF8);

            int iCount = 0;
            int iMax   = oSessions.Length;

            Fiddler.HTTPRequestHeaders headers;
            bool     fSkip           = false;
            int      iBinarySequence = 1;
            DateTime dtPrevious      = oSessions.First <Session>().Timers.ClientDoneResponse;
            Dictionary <string, List <Session> > bg = null;

            // Write Lua header
            strbHead.Append(luaHead);
            strbHead.AppendLine();

            #region WriteEachSession

            foreach (Session oS in oSessions)
            {
                iCount++;

                // We just want requests, not connections and stuff
                if (!oS.isTunnel)
                {
                    // If the response is a redirect, skip the next request
                    if (fSkip)
                    {
                        fSkip = Utilities.IsRedirectStatus(oS.responseCode);
                        continue;
                    }
                    else
                    {
                        fSkip = Utilities.IsRedirectStatus(oS.responseCode);
                    }

                    // Figure out time between last request and this request
                    // If > threshold -> insert sleep time

                    TimeSpan dtDiff = oS.Timers.ClientBeginRequest - dtPrevious;
                    dtPrevious = oS.Timers.ClientDoneResponse;

                    // Find out if we are starting a new group, finishing a group or are in a group

                    int    iCol   = getIndexOfText(oSessions[0].ViewItem.ListView.Columns, "LI Group");
                    string strVal = oS.ViewItem.SubItems[iCol].Text;

                    if ((!inGroup) && (strVal.Length > 0))
                    {
                        // NEW group from NO group, write the header

                        // Terminate batches - except first request since it will not be in a batch

                        if (bg != null)
                        {
                            terminateLuaBatches(bg, ref strbBody, ref strbHead, ref iBinarySequence, sFilename);

                            // Dispose manually

                            bg.Clear();
                            bg = null;
                        }

                        // Insert sleep _before_ if needed

                        if (dtDiff >= TimeSpan.FromSeconds(sSleepThreshold))
                        {
                            strbBody.AppendLine("\n\tclient.sleep(" + dtDiff.Seconds + ")\n");
                        }

                        strCurrentGroup = strVal;
                        strbBody.AppendLine("http.page_start(\"" + strCurrentGroup + "\")");

                        // START NEW BATCH COLLECTION

                        bg = new Dictionary <string, List <Session> >();

                        // Set flag

                        inGroup = true;
                    }
                    else if ((inGroup) && (strVal.Length > 0) && (strVal != strCurrentGroup))
                    {
                        // NEW group from OLD group
                        // write footer to end old and header for new

                        // Terminate batches

                        terminateLuaBatches(bg, ref strbBody, ref strbHead, ref iBinarySequence, sFilename);

                        // Dispose manually

                        bg.Clear();
                        bg = null;


                        strbBody.AppendLine("http.page_end(\"" + strCurrentGroup + "\")");
                        strbBody.AppendLine();

                        // Insert sleep _between_ groups
                        if (dtDiff >= TimeSpan.FromSeconds(sSleepThreshold))
                        {
                            strbBody.AppendLine("\n\tclient.sleep(" + dtDiff.Seconds + ")\n");
                        }

                        inGroup         = true;
                        strCurrentGroup = strVal;
                        strbBody.AppendLine("http.page_start(\"" + strCurrentGroup + "\")");

                        // START NEW BATCH COLLECTION

                        bg = new Dictionary <string, List <Session> >();
                    }
                    else if ((inGroup) && (strVal.Length == 0))
                    {
                        // NO group from OLD group
                        // write footer to close group

                        // Terminate batches

                        terminateLuaBatches(bg, ref strbBody, ref strbHead, ref iBinarySequence, sFilename);

                        // Dispose manually

                        bg.Clear();
                        bg = null;

                        strbBody.AppendLine("http.page_end(\"" + strCurrentGroup + "\")");
                        strbBody.AppendLine();
                        inGroup         = false;
                        strCurrentGroup = strVal;

                        // If sleep applies after last step in group

                        if (dtDiff >= TimeSpan.FromSeconds(sSleepThreshold))
                        {
                            strbBody.AppendLine("\n\tclient.sleep(" + dtDiff.Seconds + ")\n");
                        }

                        // START NEW BATCH COLLECTION

                        bg = new Dictionary <string, List <Session> >();
                    }
                    else
                    {
                        // NO group from NO group or IN GROUP STAYING IN GROUP
                        // sleep might apply

                        // Check if batch shall be terminated by timespan, same as sleep

                        if (dtDiff >= TimeSpan.FromSeconds(sSleepThreshold))
                        {
                            // Terminate batches - except first request since it will not be in a batch

                            if (bg != null)
                            {
                                terminateLuaBatches(bg, ref strbBody, ref strbHead, ref iBinarySequence, sFilename);

                                // Dispose manually

                                bg.Clear();
                                bg = null;
                            }

                            strbBody.AppendLine("\n\tclient.sleep(" + dtDiff.Seconds + ")\n");

                            // START NEW BATCH COLLECTION

                            bg = new Dictionary <string, List <Session> >();
                        }
                        else
                        {
                            if (bg == null)
                            {
                                bg = new Dictionary <string, List <Session> >();
                            }
                        }
                    }


                    // If there is no referer header, set a __NO_REFERER referer

                    headers = oS.RequestHeaders;
                    string refKey = headers.Exists("Referer") ? headers["Referer"] : "__NO_REFERER";

                    if (!bg.ContainsKey(refKey))
                    {
                        bg[refKey] = new List <Session>();
                    }



                    // Add request to batch

                    bg[refKey].Add(oS);

                    if (oS == oSessions.Last())
                    {
                        // Terminate batches - except first request since it will not be in a batch

                        terminateLuaBatches(bg, ref strbBody, ref strbHead, ref iBinarySequence, sFilename);

                        // Dispose manually

                        bg.Clear();
                        bg = null;

                        if (inGroup)
                        {
                            // IF last request GROUP completed

                            strbBody.AppendLine("http.page_end(\"" + strCurrentGroup + "\")");
                            strbBody.AppendLine();
                            inGroup = false;
                        }
                    }
                } // endif tunnel

                if (null != evtProgressNotifications)
                {
                    //evtProgressNotifications(null, new ProgressCallbackEventArgs(0, "" ));
                    ProgressCallbackEventArgs PCEA = new ProgressCallbackEventArgs((iCount / (float)iMax), "wrote " + iCount.ToString() + " records.");
                    evtProgressNotifications(null, PCEA);
                    if (PCEA.Cancel)
                    {
                        swOutput.Close();
                        return(false);
                    }
                }
            } // endfor

            #endregion WriteEachSession

            strbFoot.Append(luaFoot);
            strbFoot.AppendLine();

            swOutput.WriteLine(strbHead);
            swOutput.WriteLine(strbBody);
            swOutput.WriteLine(strbFoot);
            swOutput.Close();
            return(true);
        }
        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);
        }
Example #10
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);
        }
Example #11
0
        public bool ExportSessions(string sExportFormat,
                                   Session[] oSessions,
                                   Dictionary <string, object> dictOptions,
                                   EventHandler <ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool result = false;

            string filename = null;

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

            if (sExportFormat == "Postman-Collection")
            {
                if (string.IsNullOrEmpty(filename))
                {
                    filename = Fiddler.Utilities.ObtainSaveFilename(string.Format("Export as {0}", sExportFormat), "Postman Collection (*.postman_collection.json)|*.postman_collection.json");
                }
            }

            if (string.IsNullOrEmpty(filename))
            {
                return(false);
            }

            try
            {
                using (StreamWriter sw = new StreamWriter(filename, false, Encoding.UTF8))
                {
                    Request                   request             = new Request();
                    Response                  response            = new Response();
                    List <string>             order               = new List <string>();
                    List <Request>            requests            = new List <Request>();
                    List <Response>           responses           = new List <Response>();
                    List <ResponseHeaderInfo> responseHeaderInfos = new List <ResponseHeaderInfo>();
                    int addedSessions = 0;
                    int numSessions   = oSessions.Length;

                    PostmanCollection postmanCollection = new PostmanCollection();
                    postmanCollection.id        = Guid.NewGuid().ToString();
                    postmanCollection.name      = string.Format("Collection_{0}", DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss"));
                    postmanCollection.timestamp = DateTime.UtcNow.Ticks;
                    postmanCollection.owner     = 0;
                    postmanCollection.__public  = false;

                    foreach (Session session in oSessions)
                    {
                        addedSessions++;
                        if (session != null)
                        {
                            request.id            = Guid.NewGuid().ToString();
                            request.collectionId  = postmanCollection.id;
                            request.method        = session.RequestMethod;
                            request.url           = session.fullUrl;
                            request.name          = session.fullUrl;
                            request.currentHelper = "normal";
                            request.dataMode      = "raw";
                            request.rawModeData   = Encoding.Default.GetString(session.RequestBody);
                            request.time          = DateTime.UtcNow.Ticks;
                            request.headers       = "";

                            List <RequestHeaderInfo> requestHeaderInfoList = new List <RequestHeaderInfo>();

                            foreach (HTTPHeaderItem httphi in session.RequestHeaders)
                            {
                                request.headers += string.Format("{0}: {1}\\n", httphi.Name, httphi.Value);

                                requestHeaderInfoList.Add(new RequestHeaderInfo()
                                {
                                    key = httphi.Name, value = httphi.Value, enabled = true
                                });
                            }

                            response.responseCode = new ResponseCodeInfo()
                            {
                                code = session.responseCode
                            };
                            response.text                   = Encoding.Default.GetString(session.ResponseBody);
                            response.language               = "json";
                            response.rawDataType            = "text";
                            response.previewType            = "text";
                            response.searchResultScrolledTo = -1;
                            response.forceNoPretty          = false;
                            response.write                  = true;
                            response.empty                  = false;
                            response.failed                 = false;
                            response.state                  = new ResponseState()
                            {
                                size = "normal"
                            };
                            response.id      = Guid.NewGuid().ToString();
                            response.name    = "response";
                            response.request = new RequestInfo()
                            {
                                url      = session.fullUrl,
                                headers  = requestHeaderInfoList.ToArray(),
                                data     = "",
                                method   = session.RequestMethod,
                                dataMode = "raw"
                            };

                            foreach (HTTPHeaderItem httphi in session.ResponseHeaders)
                            {
                                responseHeaderInfos.Add(new ResponseHeaderInfo()
                                {
                                    name = httphi.Name, key = httphi.Name, value = httphi.Value, description = httphi.Name
                                });
                            }

                            responses.Add(response);
                            request.responses = responses.ToArray();
                            response          = new Response();
                            responses         = new List <Response>();

                            requests.Add(request);
                            order.Add(request.id);
                            request = new Request();
                        }
                        if (evtProgressNotifications != null)
                        {
                            ProgressCallbackEventArgs pcea = new ProgressCallbackEventArgs((addedSessions / (float)numSessions), string.Format("{0} records added", addedSessions));
                            evtProgressNotifications(null, pcea);
                            if (pcea.Cancel)
                            {
                                sw.Close();
                                return(false);
                            }
                        }
                    }

                    postmanCollection.requests = requests.ToArray();
                    postmanCollection.order    = order.ToArray();

                    sw.Write(Utilities.ToJSONString(postmanCollection).Replace("__", ""));
                    sw.Close();
                }

                result = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Failed to export");
                result = false;
            }

            return(result);
        }
Example #12
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);
        }
Example #13
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);
        }
Example #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);
        }