Ejemplo n.º 1
0
 internal static void LogAddonException(Exception eX, string sTitle)
 {
     if (FiddlerApplication.Prefs.GetBoolPref("fiddler.debug.extensions.showerrors", false) || FiddlerApplication.Prefs.GetBoolPref("fiddler.debug.extensions.verbose", false))
     {
         FiddlerApplication.Log.LogFormat("!Exception from Extension: {0}", new object[]
         {
             Utilities.DescribeException(eX)
         });
         FiddlerApplication.ReportException(eX, sTitle, "Fiddler has encountered an unexpected problem with an extension.");
     }
 }
Ejemplo n.º 2
0
 internal void CollectConnectoidAndGatewayInfo()
 {
     try
     {
         this.oAllConnectoids = new WinINETConnectoids();
         this.RefreshUpstreamGatewayInformation();
     }
     catch (Exception eX)
     {
         FiddlerApplication.ReportException(eX, "System Error");
     }
 }
Ejemplo n.º 3
0
        internal ServerPipe TakePipe(string sPoolKey, int iPID, int HackiForSession)
        {
            if (!CONFIG.bReuseServerSockets)
            {
                return(null);
            }
            Dictionary <string, Stack <ServerPipe> > obj;

            Monitor.Enter(obj = this.thePool);
            Stack <ServerPipe> stack;

            try
            {
                if ((iPID == 0 || !this.thePool.TryGetValue(string.Format("PID{0}*{1}", iPID, sPoolKey), out stack) || stack.Count < 1) && (!this.thePool.TryGetValue(sPoolKey, out stack) || stack.Count < 1))
                {
                    ServerPipe result = null;
                    return(result);
                }
            }
            finally
            {
                Monitor.Exit(obj);
            }
            Stack <ServerPipe> obj2;

            Monitor.Enter(obj2 = stack);
            ServerPipe result2;

            try
            {
                if (stack.Count == 0)
                {
                    ServerPipe result = null;
                    return(result);
                }
                result2 = stack.Pop();
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX);
                ServerPipe result = null;
                return(result);
            }
            finally
            {
                Monitor.Exit(obj2);
            }
            return(result2);
        }
Ejemplo n.º 4
0
        private void _NotifyThreadExecute(object objThreadState)
        {
            PrefChangeEventArgs e = (PrefChangeEventArgs)objThreadState;
            string prefName       = e.PrefName;
            List <EventHandler <PrefChangeEventArgs> > list = null;

            try
            {
                this._RWLockWatchers.AcquireReaderLock(-1);
                try
                {
                    foreach (PrefWatcher watcher in this._listWatchers)
                    {
                        if (prefName.StartsWith(watcher.sPrefixToWatch, StringComparison.Ordinal))
                        {
                            if (list == null)
                            {
                                list = new List <EventHandler <PrefChangeEventArgs> >();
                            }
                            list.Add(watcher.fnToNotify);
                        }
                    }
                }
                finally
                {
                    this._RWLockWatchers.ReleaseReaderLock();
                }
                if (list != null)
                {
                    foreach (EventHandler <PrefChangeEventArgs> handler in list)
                    {
                        try
                        {
                            handler(this, e);
                            continue;
                        }
                        catch (Exception exception)
                        {
                            FiddlerApplication.ReportException(exception);
                            continue;
                        }
                    }
                }
            }
            catch (Exception exception2)
            {
                FiddlerApplication.ReportException(exception2);
            }
        }
Ejemplo n.º 5
0
 private void RunTunnel()
 {
     if (FiddlerApplication.oProxy == null)
     {
         return;
     }
     try
     {
         this.DoTunnel();
     }
     catch (Exception eX)
     {
         FiddlerApplication.ReportException(eX, "Uncaught Exception in Tunnel; Session #" + this._mySession.Int32_0.ToString());
     }
 }
Ejemplo n.º 6
0
        internal byte[] TakeEntity()
        {
            byte[] bytes;
            if (this.iEntityBodyOffset < 0)
            {
                throw new InvalidDataException("Request Entity Body Offset must not be negative");
            }
            long num  = this.m_requestData.Length - this.iEntityBodyOffset;
            long num2 = this._calculateExpectedEntityTransferSize();

            if (num > num2)
            {
                FiddlerApplication.Log.LogFormat("HTTP Pipelining Client detected; excess data on client socket for session #{0}.", new object[] { this.m_session.id });
                try
                {
                    bytes = new byte[num - num2];
                    this.m_requestData.Position = this.iEntityBodyOffset + num2;
                    this.m_requestData.Read(bytes, 0, bytes.Length);
                }
                catch (OutOfMemoryException exception)
                {
                    FiddlerApplication.ReportException(exception, "HTTP Request Pipeline Too Large");
                    bytes = Encoding.ASCII.GetBytes("Fiddler: Out of memory");
                    this.m_session.PoisonClientPipe();
                    return(new byte[0]);
                }
                this.pipeClient.putBackSomeBytes(bytes);
                num = num2;
            }
            if ((num != num2) && (num < num2))
            {
                FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, string.Format("Content-Length mismatch: Request Header indicated {0:N0} bytes, but client sent {1:N0} bytes.", num2, num));
            }
            try
            {
                bytes = new byte[num];
                this.m_requestData.Position = this.iEntityBodyOffset;
                this.m_requestData.Read(bytes, 0, bytes.Length);
            }
            catch (OutOfMemoryException exception2)
            {
                FiddlerApplication.ReportException(exception2, "HTTP Request Too Large");
                bytes = Encoding.ASCII.GetBytes("Fiddler: Out of memory");
                this.m_session.PoisonClientPipe();
            }
            this._freeRequestData();
            return(bytes);
        }
Ejemplo n.º 7
0
        private void _NotifyThreadExecute(object objThreadState)
        {
            PrefChangeEventArgs prefChangeEventArgs = (PrefChangeEventArgs)objThreadState;
            string prefName = prefChangeEventArgs.PrefName;
            List <EventHandler <PrefChangeEventArgs> > list = null;

            try
            {
                PreferenceBag.GetReaderLock(this._RWLockWatchers);
                try
                {
                    foreach (PreferenceBag.PrefWatcher current in this._listWatchers)
                    {
                        if (prefName.OICStartsWith(current.sPrefixToWatch))
                        {
                            if (list == null)
                            {
                                list = new List <EventHandler <PrefChangeEventArgs> >();
                            }
                            list.Add(current.fnToNotify);
                        }
                    }
                }
                finally
                {
                    PreferenceBag.FreeReaderLock(this._RWLockWatchers);
                }
                if (list != null)
                {
                    foreach (EventHandler <PrefChangeEventArgs> current2 in list)
                    {
                        try
                        {
                            current2(this, prefChangeEventArgs);
                        }
                        catch (Exception eX)
                        {
                            FiddlerApplication.ReportException(eX);
                        }
                    }
                }
            }
            catch (Exception eX2)
            {
                FiddlerApplication.ReportException(eX2);
            }
        }
Ejemplo n.º 8
0
 internal byte[] TakeEntity()
 {
     byte[] bytes;
     try
     {
         bytes = new byte[this.m_responseData.Length - this.iEntityBodyOffset];
         this.m_responseData.Position = this.iEntityBodyOffset;
         this.m_responseData.Read(bytes, 0, bytes.Length);
     }
     catch (OutOfMemoryException exception)
     {
         FiddlerApplication.ReportException(exception, "HTTP Response Too Large");
         bytes = Encoding.ASCII.GetBytes("Fiddler: Out of memory");
         this.m_session.PoisonServerPipe();
     }
     this.FreeResponseDataBuffer();
     return(bytes);
 }
Ejemplo n.º 9
0
 internal static bool exportRootToDesktop()
 {
     try
     {
         byte[] bytes = getRootCertBytes();
         if (bytes != null)
         {
             File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\FiddlerRoot.cer", bytes);
             return(true);
         }
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception);
         return(false);
     }
     return(false);
 }
Ejemplo n.º 10
0
 public FiddlerScript()
 {
     this.objVSASite                               = new ScriptEngineSite(this);
     this.scriptsFolderWatcher                     = new FileSystemWatcher();
     this.scriptsFolderWatcher.Filter              = "CustomRules.js";
     this.scriptsFolderWatcher.NotifyFilter        = NotifyFilters.LastWrite;
     this.scriptsFolderWatcher.SynchronizingObject = FiddlerApplication.UI;
     this.scriptsFolderWatcher.Deleted            += new FileSystemEventHandler(this.scriptsFolderWatcher_Notify);
     this.scriptsFolderWatcher.Created            += new FileSystemEventHandler(this.scriptsFolderWatcher_Notify);
     this.scriptsFolderWatcher.Changed            += new FileSystemEventHandler(this.scriptsFolderWatcher_Notify);
     try
     {
         this.scriptsFolderWatcher.Path = CONFIG.GetPath("Scripts");
         this.scriptsFolderWatcher.EnableRaisingEvents = true;
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception, "ScriptWatcher Failure");
     }
 }
Ejemplo n.º 11
0
 private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
 {
     try
     {
         DNSResolver.ClearCache();
         FiddlerApplication.Log.LogString("NetworkAddressChanged.");
         if (this.oAutoProxy != null)
         {
             this.oAutoProxy.iAutoProxySuccessCount = 0;
         }
         if ((CONFIG.bForwardToGateway && (this.piPrior != null)) && this.piPrior.bUseManualProxies)
         {
             this._DetermineGatewayIPEndPoints();
         }
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception);
     }
 }
Ejemplo n.º 12
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.º 13
0
 internal static bool exportRootToDesktop()
 {
     try
     {
         byte[] rootCertBytes = CertMaker.getRootCertBytes();
         if (rootCertBytes != null)
         {
             File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + Path.DirectorySeparatorChar + "FiddlerRoot.cer", rootCertBytes);
             bool result = true;
             return(result);
         }
         FiddlerApplication.DoNotifyUser("The root certificate could not be located.", "Export Failed");
     }
     catch (Exception eX)
     {
         FiddlerApplication.ReportException(eX, "Certificate Export Failed");
         bool result = false;
         return(result);
     }
     return(false);
 }
Ejemplo n.º 14
0
 private void RunTunnel()
 {
     if (FiddlerApplication.oProxy != null)
     {
         try
         {
             IPEndPoint ipepForwardHTTPS = null;
             if (this._mySession.oFlags["x-overrideGateway"] != null)
             {
                 if (string.Equals("DIRECT", this._mySession.oFlags["x-overrideGateway"], StringComparison.OrdinalIgnoreCase))
                 {
                     this._mySession.bypassGateway = true;
                 }
                 else
                 {
                     ipepForwardHTTPS = Utilities.IPEndPointFromHostPortString(this._mySession.oFlags["x-overrideGateway"]);
                 }
             }
             else if (!this._mySession.bypassGateway)
             {
                 int tickCount = Environment.TickCount;
                 ipepForwardHTTPS = FiddlerApplication.oProxy.FindGatewayForOrigin("https", this._mySession.oFlags["x-overrideHost"] ?? this._mySession.PathAndQuery);
                 this._mySession.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount;
             }
             if (ipepForwardHTTPS != null)
             {
                 this.TunnelToGateway(ipepForwardHTTPS);
             }
             else
             {
                 this.TunnelDirectly();
             }
         }
         catch (Exception exception)
         {
             FiddlerApplication.ReportException(exception, "Uncaught Exception in Tunnel; Session #" + this._mySession.id.ToString());
         }
     }
 }
Ejemplo n.º 15
0
        internal ServerPipe DequeuePipe(string sPoolKey, int iPID, int HackiForSession)
        {
            Queue <ServerPipe> queue;
            ServerPipe         pipe;
            Queue <ServerPipe> queue2;

            if (!CONFIG.bReuseServerSockets)
            {
                return(null);
            }
            lock (this.thePool)
            {
                if ((((iPID == 0) || !this.thePool.TryGetValue(string.Format("PID{0}*{1}", iPID, sPoolKey), out queue)) || (queue.Count < 1)) && (!this.thePool.TryGetValue(sPoolKey, out queue) || (queue.Count < 1)))
                {
                    return(null);
                }
            }
            Monitor.Enter(queue2 = queue);
            try
            {
                if (queue.Count == 0)
                {
                    return(null);
                }
                pipe = queue.Dequeue();
            }
            catch (Exception exception)
            {
                FiddlerApplication.ReportException(exception);
                return(null);
            }
            finally
            {
                Monitor.Exit(queue2);
            }
            return(pipe);
        }
Ejemplo n.º 16
0
        internal byte[] TakeEntity()
        {
            if (this.iEntityBodyOffset < 0)
            {
                throw new InvalidDataException("Request Entity Body Offset must not be negative");
            }
            long num  = this.m_requestData.Length - (long)this.iEntityBodyOffset;
            long num2 = this._calculateExpectedEntityTransferSize();

            byte[] array;
            if (num != num2)
            {
                if (num > num2)
                {
                    FiddlerApplication.Log.LogFormat("HTTP Pipelining Client detected; excess data on client socket for session #{0}.", new object[]
                    {
                        this.m_session.Int32_0
                    });
                    byte[] emptyByteArray;
                    try
                    {
                        array = new byte[num - num2];
                        this.m_requestData.Position = (long)this.iEntityBodyOffset + num2;
                        this.m_requestData.Read(array, 0, array.Length);
                        goto IL_CD;
                    }
                    catch (OutOfMemoryException eX)
                    {
                        FiddlerApplication.ReportException(eX, "HTTP Request Pipeline Too Large");
                        array = Encoding.ASCII.GetBytes("Fiddler: Out of memory");
                        this.m_session.PoisonClientPipe();
                        emptyByteArray = Utilities.emptyByteArray;
                    }
                    return(emptyByteArray);

IL_CD:
                    this.pipeClient.putBackSomeBytes(array);
                    num = num2;
                }
                else
                {
                    if (!this.m_session.isFlagSet(SessionFlags.RequestStreamed))
                    {
                        FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, string.Format("Content-Length mismatch: Request Header indicated {0:N0} bytes, but client sent {1:N0} bytes.", num2, num));
                    }
                }
            }
            try
            {
                array = new byte[num];
                this.m_requestData.Position = (long)this.iEntityBodyOffset;
                this.m_requestData.Read(array, 0, array.Length);
            }
            catch (OutOfMemoryException eX2)
            {
                FiddlerApplication.ReportException(eX2, "HTTP Request Too Large");
                array = Encoding.ASCII.GetBytes("Fiddler: Out of memory");
                this.m_session.PoisonClientPipe();
            }
            this._freeRequestData();
            return(array);
        }
Ejemplo n.º 17
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);
            }

            List <Session> outSessions = new List <Session>();

            try
            {
                // Sniff for ZIP file.
                using (FileStream 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.");
                        return(null);
                    }
                }

                using (Package oZip = Package.Open(sFilename, FileMode.Open))
                {
                    PackagePartCollection oAllParts = oZip.GetParts();
                    foreach (PackagePart oPPC in oAllParts)
                    {
                        string sURI = oPPC.Uri.ToString();
                        if (!sURI.EndsWith("_c.txt"))
                        {
                            continue;
                        }

                        byte[] arrRequest  = null;
                        byte[] arrResponse = null;

                        // Okay, we now have a Request. Let's read it.
                        using (Stream oData = oPPC.GetStream(FileMode.Open, FileAccess.Read))
                        {
                            arrRequest = ReadEntireStream(oData);
                        }

                        try
                        {
                            sURI = sURI.Replace("_c.txt", "_s.txt");

                            // Get the response
                            PackagePart oResponse = oZip.GetPart(new Uri(sURI, UriKind.Relative));
                            using (Stream oData = oResponse.GetStream(FileMode.Open, FileAccess.Read))
                            {
                                arrResponse = ReadEntireStream(oData);
                            }
                        }
                        catch (Exception eX)
                        {
                            FiddlerApplication.Log.LogString("Could not load Server Response: " + sURI + "\n" + eX.Message);
                            // Fatal error. Skip this session
                            continue;
                        }

                        Session oSession = new Session(arrRequest, arrResponse);
                        oSession.oFlags["x-LoadedFrom"] = sURI;

                        sURI = sURI.Replace("_s.txt", "_m.xml");

                        try
                        {
                            // Get the Metadata
                            PackagePart oMetadata = oZip.GetPart(new Uri(sURI, UriKind.Relative));
                            Stream      oData     = oMetadata.GetStream(FileMode.Open, FileAccess.Read);
                            oSession.LoadMetadata(oData);  // Note: Closes the stream automatically
                        }
                        catch
                        {
                            FiddlerApplication.Log.LogString("Could not load Metadata: " + sURI);
                            // Missing metadata is not-fatal.
                        }
                        outSessions.Add(oSession);
                    }
                }
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX, "ReadSessionArchive Error");
                return(null);
            }

            return(outSessions.ToArray());
        }
Ejemplo n.º 18
0
        internal bool Start(int iPort, bool bAllowRemote)
        {
            if (CONFIG.bIsViewOnly && DialogResult.No == MessageBox.Show("This instance is running in Fiddler's Viewer Mode. Do you want to start the listener anyway?", "Warning: Viewer Mode", MessageBoxButtons.YesNo))
            {
                return(false);
            }
            bool flag = false;
            bool result;

            try
            {
                flag = (bAllowRemote && CONFIG.bEnableIPv6 && Socket.OSSupportsIPv6);
            }
            catch (Exception ex)
            {
                if (ex is ConfigurationErrorsException)
                {
                    FiddlerApplication.DoNotifyUser(string.Concat(new object[]
                    {
                        "A Microsoft .NET configuration file (listed below) is corrupt and contains invalid data. You can often correct this error by installing updates from WindowsUpdate and/or reinstalling the .NET Framework.\n\n",
                        ex.Message,
                        "\nSource: ",
                        ex.Source,
                        "\n",
                        ex.StackTrace,
                        "\n\n",
                        ex.InnerException,
                        "\nFiddler v",
                        Application.ProductVersion,
                        (8 == IntPtr.Size) ? " (x64) " : " (x86) ",
                        " [.NET ",
                        Environment.Version,
                        " on ",
                        Environment.OSVersion.VersionString,
                        "] "
                    }), ".NET Configuration Error", MessageBoxIcon.Hand);
                    this.oAcceptor = null;
                    result         = false;
                    return(result);
                }
            }
            try
            {
                if (flag)
                {
                    this.oAcceptor = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    if (Environment.OSVersion.Version.Major > 5)
                    {
                        this.oAcceptor.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
                    }
                }
                else
                {
                    this.oAcceptor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
                if (CONFIG.ForceExclusivePort)
                {
                    this.oAcceptor.ExclusiveAddressUse = true;
                }
                if (bAllowRemote)
                {
                    if (flag)
                    {
                        this.oAcceptor.Bind(new IPEndPoint(IPAddress.IPv6Any, iPort));
                    }
                    else
                    {
                        this.oAcceptor.Bind(new IPEndPoint(IPAddress.Any, iPort));
                    }
                }
                else
                {
                    this.oAcceptor.Bind(new IPEndPoint(IPAddress.Loopback, iPort));
                }
                this.oAcceptor.Listen(50);
            }
            catch (SocketException ex2)
            {
                string text      = string.Empty;
                string sTitle    = "Fiddler Cannot Listen";
                int    errorCode = ex2.ErrorCode;
                if (errorCode != 10013)
                {
                    switch (errorCode)
                    {
                    case 10047:
                    case 10049:
                        if (flag)
                        {
                            text = "\nThis often means that you've enabled IPv6 support inside Tools > Fiddler Options, but your computer has IPv6 disabled.";
                            goto IL_248;
                        }
                        goto IL_248;

                    case 10048:
                        break;

                    default:
                        goto IL_248;
                    }
                }
                text   = string.Format("\nThis is usually due to another service running on this port. Use NETSTAT -AB at a command prompt to identify it.\n{0}", (iPort == CONFIG.ListenPort) ? "If you don't want to stop using the other program, simply change the port used by Fiddler.\nClick Tools > Fiddler Options > Connections, select a new port, and restart Fiddler." : string.Empty);
                sTitle = "Port in Use";
IL_248:
                this.oAcceptor = null;
                FiddlerApplication.DoNotifyUser(string.Format("Unable to bind to port [{0}]. ErrorCode: {1}.\n{2}\n\n{3}\n\n{4}", new object[]
                {
                    iPort,
                    ex2.ErrorCode,
                    text,
                    ex2.ToString(),
                    string.Concat(new object[]
                    {
                        "Fiddler v",
                        Application.ProductVersion,
                        " [.NET ",
                        Environment.Version,
                        " on ",
                        Environment.OSVersion.VersionString,
                        "]"
                    })
                }), sTitle, MessageBoxIcon.Hand);
                result = false;
                return(result);
            }
            catch (UnauthorizedAccessException eX)
            {
                this.oAcceptor = null;
                FiddlerApplication.ReportException(eX, "Cannot Create Listener", "Fiddler could not start its Listener socket. This problem will occur if you attempt to\nrun Fiddler2 using the limited 'Guest' account. (Fiddler v4 does not have this limitation.)");
                result = false;
                return(result);
            }
            catch (Exception eX2)
            {
                this.oAcceptor = null;
                FiddlerApplication.ReportException(eX2);
                result = false;
                return(result);
            }
            try
            {
                this.oAcceptor.BeginAccept(new AsyncCallback(this.AcceptConnection), null);
                return(true);
            }
            catch (Exception ex3)
            {
                this.oAcceptor = null;
                FiddlerApplication.Log.LogFormat("Fiddler BeginAccept() Exception: {0}", new object[]
                {
                    ex3.Message
                });
                result = false;
            }
            return(result);
        }
Ejemplo n.º 19
0
 private static void _DoShow()
 {
     if (tstripMain == null)
     {
         object obj2;
         Monitor.Enter(obj2 = oShowHideLock);
         try
         {
             tstripMain = new ToolStrip();
             if (CONFIG.flFontSize >= 10f)
             {
                 tstripMain.Font = new Font(tstripMain.Font.FontFamily, 10f);
             }
             tstripMain.SuspendLayout();
             tstripMain.ImageList        = FiddlerApplication.UI.imglToolbar;
             tstripMain.GripStyle        = ToolStripGripStyle.Hidden;
             tstripMain.RenderMode       = ToolStripRenderMode.System;
             tstripMain.Renderer         = new TSRenderWithoutBorder();
             tstripMain.AllowItemReorder = true;
             tstripMain.ShowItemToolTips = true;
             if (CONFIG.bIsViewOnly)
             {
                 tstripMain.RenderMode = ToolStripRenderMode.Professional;
                 tsbWindowName         = new ToolStripButton("FiddlerViewer");
                 tsbWindowName.Font    = new Font(tsbWindowName.Font, FontStyle.Bold);
                 tsbWindowName.Padding = new Padding(5, 0, 15, 0);
                 tsbWindowName.Click  += delegate(object sender, EventArgs e) {
                     tsbWindowName.Text = frmPrompt.GetUserString("FiddlerViewer Name", "Enter a new title for this viewer:", tsbWindowName.Text);
                 };
                 tstripMain.Items.Add(tsbWindowName);
             }
             ToolStripButton button = new ToolStripButton("")
             {
                 ToolTipText = "Add a comment to the selected sessions.",
                 ImageKey    = "comment"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actCommentSelectedSessions();
             };
             tstripMain.Items.Add(button);
             button = new ToolStripButton("Reissue")
             {
                 ToolTipText = "Reissue the selected requests.\nHold CTRL to reissue unconditionally.\nHold SHIFT to reissue multiple times.",
                 ImageKey    = "refresh"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 if (Utilities.GetAsyncKeyState(0x11) < 0)
                 {
                     FiddlerApplication.UI.actUnconditionallyReissueSelected();
                 }
                 else
                 {
                     FiddlerApplication.UI.actReissueSelected();
                 }
             };
             tstripMain.Items.Add(button);
             ToolStripDropDownButton button2 = new ToolStripDropDownButton("")
             {
                 ToolTipText = "Remove sessions from the session list.",
                 ImageKey    = "remove"
             };
             ((ToolStripDropDownMenu)button2.DropDown).ShowCheckMargin = false;
             ((ToolStripDropDownMenu)button2.DropDown).ShowImageMargin = true;
             ((ToolStripDropDownMenu)button2.DropDown).ImageList       = FiddlerApplication.UI.imglToolbar;
             ToolStripMenuItem item = new ToolStripMenuItem("Remove all")
             {
                 DisplayStyle = ToolStripItemDisplayStyle.ImageAndText,
                 ImageKey     = "redbang"
             };
             item.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actRemoveAllSessions();
             };
             button2.DropDownItems.Add(item);
             item = new ToolStripMenuItem("Images")
             {
                 ImageKey     = "image",
                 DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
             };
             item.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actSelectSessionsWithResponseHeaderValue("Content-Type", "image/");
                 FiddlerApplication.UI.actRemoveSelectedSessions();
                 FiddlerApplication.UI.sbpInfo.Text = "Removed all images.";
             };
             button2.DropDownItems.Add(item);
             item = new ToolStripMenuItem("CONNECTs")
             {
                 ImageKey     = "lock",
                 DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
             };
             item.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actSelectSessionsMatchingCriteria(oSess => oSess.HTTPMethodIs("CONNECT"));
                 FiddlerApplication.UI.actRemoveSelectedSessions();
                 FiddlerApplication.UI.sbpInfo.Text = "Removed CONNECT tunnels";
             };
             button2.DropDownItems.Add(item);
             item = new ToolStripMenuItem("Non-200s")
             {
                 ImageKey     = "info",
                 DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
             };
             item.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actSelectSessionsMatchingCriteria(oSess => (oSess.state >= SessionStates.Done) && (200 != oSess.responseCode));
                 FiddlerApplication.UI.actRemoveSelectedSessions();
                 FiddlerApplication.UI.sbpInfo.Text = "Removed all but HTTP/200 responses.";
             };
             button2.DropDownItems.Add(item);
             item = new ToolStripMenuItem("Non-Browser")
             {
                 ImageKey     = "builder",
                 DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
             };
             item.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actSelectSessionsMatchingCriteria(delegate(Session oSess) {
                     string str = oSess.oFlags["x-ProcessInfo"];
                     if (!string.IsNullOrEmpty(str))
                     {
                         bool flag = ((str.StartsWith("ie", StringComparison.OrdinalIgnoreCase) || str.StartsWith("firefox", StringComparison.OrdinalIgnoreCase)) || (str.StartsWith("chrome", StringComparison.OrdinalIgnoreCase) || str.StartsWith("opera", StringComparison.OrdinalIgnoreCase))) || str.StartsWith("safari", StringComparison.OrdinalIgnoreCase);
                         return(!flag);
                     }
                     return(true);
                 });
                 FiddlerApplication.UI.actRemoveSelectedSessions();
                 FiddlerApplication.UI.sbpInfo.Text = "Removed all but browser traffic.";
             };
             button2.DropDownItems.Add(item);
             item = new ToolStripMenuItem("Un-Marked")
             {
                 ImageKey     = "mark",
                 DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
             };
             item.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.TrimSessionList(0);
                 FiddlerApplication.UI.sbpInfo.Text = "Removed all unmarked sessions.";
             };
             button2.DropDownItems.Add(item);
             tstripMain.Items.Add(button2);
             button = new ToolStripButton("Resume All")
             {
                 ToolTipText = "Resume all sessions that are currently stopped at breakpoints.",
                 ImageKey    = "resume"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actResumeAllSessions();
             };
             tstripMain.Items.Add(button);
             ToolStripSeparator separator = new ToolStripSeparator();
             tstripMain.Items.Add(separator);
             tsbStreaming              = new ToolStripButton("Streaming");
             tsbStreaming.ToolTipText  = "When Streaming Mode is enabled, all breakpoints are skipped and all HTTP responses are streamed.";
             tsbStreaming.ImageKey     = "streaming";
             tsbStreaming.Checked      = !FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.bufferresponses", true);
             tsbStreaming.CheckOnClick = true;
             tsbStreaming.Click       += delegate(object sender, EventArgs e) {
                 FiddlerApplication.Prefs.SetBoolPref("fiddler.ui.rules.bufferresponses", !(sender as ToolStripButton).Checked);
             };
             tstripMain.Items.Add(tsbStreaming);
             tsbRemoveEncodings              = new ToolStripButton("AutoDecode");
             tsbRemoveEncodings.ToolTipText  = "When enabled all traffic is decompressed for easy viewing.";
             tsbRemoveEncodings.ImageKey     = "decoder";
             tsbRemoveEncodings.CheckOnClick = true;
             tsbRemoveEncodings.Checked      = FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.removeencoding", false);
             tsbRemoveEncodings.Click       += delegate(object sender, EventArgs e) {
                 FiddlerApplication.Prefs.SetBoolPref("fiddler.ui.rules.removeencoding", tsbRemoveEncodings.Checked);
             };
             tstripMain.Items.Add(tsbRemoveEncodings);
             separator = new ToolStripSeparator();
             tstripMain.Items.Add(separator);
             if (CONFIG.bMapSocketToProcess && !CONFIG.bIsViewOnly)
             {
                 tslProcessFilter            = new ToolStripLabel("Process Filter");
                 tslProcessFilter.Font       = new Font(tslProcessFilter.Font.FontFamily, tstripMain.Font.SizeInPoints, FontStyle.Italic);
                 tslProcessFilter.BackColor  = Color.Transparent;
                 tslProcessFilter.MouseDown += delegate(object sender, MouseEventArgs e) {
                     if (e.Button == MouseButtons.Right)
                     {
                         _bCapturing       = false;
                         tstripMain.Cursor = Cursors.Default;
                         ClearProcessFilter();
                     }
                     else
                     {
                         tstripMain.Capture = true;
                         _bCapturing        = true;
                         FiddlerApplication._iShowOnlyPID = _iFilterPID = 0;
                         tstripMain.Cursor     = Cursors.Cross;
                         _hInvertedWindow      = IntPtr.Zero;
                         tslProcessFilter.Font = new Font(tslProcessFilter.Font, FontStyle.Italic);
                         tslProcessFilter.Text = "pick target...";
                     }
                 };
                 tstripMain.MouseMove += delegate(object sender, MouseEventArgs e) {
                     if (_bCapturing)
                     {
                         ShowHoveredApplication();
                     }
                 };
                 tslProcessFilter.MouseUp += delegate(object sender, MouseEventArgs e) {
                     EndMouseCapture();
                 };
                 tstripMain.MouseUp += delegate(object sender, MouseEventArgs e) {
                     EndMouseCapture();
                 };
                 tslProcessFilter.ImageKey    = "crosshair";
                 tslProcessFilter.ToolTipText = "Drag this icon to a window to show traffic from only that process.\nRight-click to cancel the filter.";
                 tstripMain.Items.Add(tslProcessFilter);
             }
             button = new ToolStripButton("Find")
             {
                 ToolTipText = "Find sessions containing specified content.",
                 ImageKey    = "find"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actDoFind();
             };
             tstripMain.Items.Add(button);
             button = new ToolStripButton("Save")
             {
                 ToolTipText = "Save all sessions in a .SAZ file.",
                 ImageKey    = "save"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actSaveAllSessions();
             };
             tstripMain.Items.Add(button);
             separator = new ToolStripSeparator();
             tstripMain.Items.Add(separator);
             button = new ToolStripButton {
                 ToolTipText = "Add a screenshot to the capture\nHold SHIFT to delay 5 seconds.",
                 ImageKey    = "camera"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actCaptureScreenshot((Utilities.GetAsyncKeyState(0x10) < 0) || (Utilities.GetAsyncKeyState(0x11) < 0));
             };
             tstripMain.Items.Add(button);
             ToolStripButton button3 = new ToolStripButton("Launch IE")
             {
                 ToolTipText = "Launch IE to the selected URL, or about:blank."
             };
             button3.Click   += new EventHandler(FiddlerToolbar.tsbLaunchIE_Click);
             button3.ImageKey = "ie";
             tstripMain.Items.Add(button3);
             if (!CONFIG.bIsViewOnly)
             {
                 button = new ToolStripButton("Clear Cache")
                 {
                     ToolTipText = "Clear the WinINET cache. Hold CTRL to also delete persistent cookies.",
                     ImageKey    = "clearcache"
                 };
                 button.Click += delegate(object sender, EventArgs e) {
                     FiddlerApplication.UI.actClearWinINETCache();
                     if ((Utilities.GetAsyncKeyState(0x10) < 0) || (Utilities.GetAsyncKeyState(0x11) < 0))
                     {
                         FiddlerApplication.UI.actClearWinINETCookies();
                     }
                 };
                 tstripMain.Items.Add(button);
             }
             button = new ToolStripButton("Encoder")
             {
                 ToolTipText = "Create a new instance of the text encoder/decoder.",
                 ImageKey    = "tools"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actShowEncodingTools();
             };
             tstripMain.Items.Add(button);
             separator = new ToolStripSeparator();
             tstripMain.Items.Add(separator);
             button = new ToolStripButton("Tearoff")
             {
                 ToolTipText = "Open Details View in a floating window.",
                 ImageKey    = "tearoff"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 FiddlerApplication.UI.actTearoffInspectors();
             };
             tstripMain.Items.Add(button);
             separator = new ToolStripSeparator();
             tstripMain.Items.Add(separator);
             ToolStripTextBox tstbMSDN = new ToolStripTextBox("MSDNSearch");
             Utilities.SetCueText(tstbMSDN.Control, "MSDN Search...");
             tstbMSDN.AcceptsReturn = true;
             tstbMSDN.KeyUp        += delegate(object sender, KeyEventArgs e) {
                 if (e.KeyCode == Keys.Return)
                 {
                     e.SuppressKeyPress = true;
                     e.Handled          = true;
                     Utilities.LaunchHyperlink("http://social.msdn.microsoft.com/Search/en-US/?Refinement=59&Query=" + HttpUtility.UrlEncode(tstbMSDN.Text, Encoding.UTF8));
                 }
             };
             tstbMSDN.KeyDown += delegate(object sender, KeyEventArgs e) {
                 if (e.KeyCode == Keys.Return)
                 {
                     e.SuppressKeyPress = true;
                 }
                 else if ((e.KeyCode == Keys.A) && e.Control)
                 {
                     tstbMSDN.SelectAll();
                     e.SuppressKeyPress = true;
                     e.Handled          = true;
                 }
             };
             tstripMain.Items.Add(tstbMSDN);
             button = new ToolStripButton("Help")
             {
                 ToolTipText = "Show Fiddler's online help.",
                 ImageKey    = "help"
             };
             button.Click += delegate(object sender, EventArgs e) {
                 Utilities.LaunchHyperlink(CONFIG.GetUrl("HelpContents") + Application.ProductVersion);
             };
             tstripMain.Items.Add(button);
             button = new ToolStripButton("")
             {
                 ToolTipText = "Close this toolbar. Click View / Show Toolbar to get it back.",
                 ImageKey    = "close",
                 Alignment   = ToolStripItemAlignment.Right
             };
             button.Click += delegate(object sender, EventArgs e) {
                 Hide();
             };
             tstripMain.Items.Add(button);
             tslNetStat             = new ToolStripLabel("Detecting");
             tslNetStat.Alignment   = ToolStripItemAlignment.Right;
             tslNetStat.BackColor   = Color.Transparent;
             tslNetStat.ImageKey    = "notconnected";
             tslNetStat.ToolTipText = "Detecting network status...";
             tslNetStat.MouseDown  += delegate(object sender, MouseEventArgs e) {
                 if (e.Clicks > 1)
                 {
                     Utilities.RunExecutable("control.exe", "netconnections");
                 }
             };
             tstripMain.Items.Add(tslNetStat);
             UpdateNetworkStatus(NetworkInterface.GetIsNetworkAvailable());
             tstripMain.ResumeLayout();
             FiddlerApplication.UI.Controls.Add(tstripMain);
         }
         catch (Exception exception)
         {
             FiddlerApplication.ReportException(exception, "Toolbar failed");
         }
         finally
         {
             Monitor.Exit(obj2);
         }
     }
 }
Ejemplo n.º 20
0
 public bool GetFromWinINET(string sConnectionName)
 {
     this.Clear();
     try
     {
         INTERNET_PER_CONN_OPTION_LIST structure = new INTERNET_PER_CONN_OPTION_LIST();
         INTERNET_PER_CONN_OPTION[]    internet_per_conn_optionArray = new INTERNET_PER_CONN_OPTION[5];
         if (sConnectionName == "DefaultLAN")
         {
             sConnectionName = null;
         }
         structure.Connection                      = sConnectionName;
         structure.OptionCount                     = internet_per_conn_optionArray.Length;
         structure.OptionError                     = 0;
         internet_per_conn_optionArray[0]          = new INTERNET_PER_CONN_OPTION();
         internet_per_conn_optionArray[0].dwOption = 1;
         internet_per_conn_optionArray[1]          = new INTERNET_PER_CONN_OPTION();
         internet_per_conn_optionArray[1].dwOption = 2;
         internet_per_conn_optionArray[2]          = new INTERNET_PER_CONN_OPTION();
         internet_per_conn_optionArray[2].dwOption = 3;
         internet_per_conn_optionArray[3]          = new INTERNET_PER_CONN_OPTION();
         internet_per_conn_optionArray[3].dwOption = 4;
         internet_per_conn_optionArray[4]          = new INTERNET_PER_CONN_OPTION();
         internet_per_conn_optionArray[4].dwOption = 10;
         int cb = 0;
         for (int i = 0; i < internet_per_conn_optionArray.Length; i++)
         {
             cb += Marshal.SizeOf(internet_per_conn_optionArray[i]);
         }
         IntPtr ptr  = Marshal.AllocCoTaskMem(cb);
         IntPtr ptr2 = ptr;
         for (int j = 0; j < internet_per_conn_optionArray.Length; j++)
         {
             Marshal.StructureToPtr(internet_per_conn_optionArray[j], ptr2, false);
             ptr2 = (IntPtr)(((long)ptr2) + Marshal.SizeOf(internet_per_conn_optionArray[j]));
         }
         structure.pOptions = ptr;
         structure.Size     = Marshal.SizeOf(structure);
         int  size = structure.Size;
         bool flag = InternetQueryOptionList(IntPtr.Zero, 0x4b, ref structure, ref size);
         int  num5 = Marshal.GetLastWin32Error();
         if (!flag && (0x57 == num5))
         {
             internet_per_conn_optionArray[4].dwOption = 5;
             ptr2 = ptr;
             for (int k = 0; k < internet_per_conn_optionArray.Length; k++)
             {
                 Marshal.StructureToPtr(internet_per_conn_optionArray[k], ptr2, false);
                 ptr2 = (IntPtr)(((long)ptr2) + Marshal.SizeOf(internet_per_conn_optionArray[k]));
             }
             structure.pOptions = ptr;
             structure.Size     = Marshal.SizeOf(structure);
             size = structure.Size;
             flag = InternetQueryOptionList(IntPtr.Zero, 0x4b, ref structure, ref size);
             num5 = Marshal.GetLastWin32Error();
         }
         if (flag)
         {
             ptr2 = ptr;
             for (int m = 0; m < internet_per_conn_optionArray.Length; m++)
             {
                 Marshal.PtrToStructure(ptr2, internet_per_conn_optionArray[m]);
                 ptr2 = (IntPtr)(((long)ptr2) + Marshal.SizeOf(internet_per_conn_optionArray[m]));
             }
             this._bDirect           = 1 == (internet_per_conn_optionArray[0].Value.dwValue & 1);
             this._bUseConfigScript  = 4 == (internet_per_conn_optionArray[0].Value.dwValue & 4);
             this._bAutoDetect       = 8 == (internet_per_conn_optionArray[0].Value.dwValue & 8);
             this._bProxiesSpecified = 2 == (internet_per_conn_optionArray[0].Value.dwValue & 2);
             if (internet_per_conn_optionArray[4].dwOption == 10)
             {
                 this._bAutoDetectWasUserSet = 8 == (internet_per_conn_optionArray[4].Value.dwValue & 8);
             }
             else
             {
                 this._bAutoDetectWasUserSet = this._bAutoDetect && (1 == (internet_per_conn_optionArray[4].Value.dwValue & 1));
             }
             this._sScriptURL = Marshal.PtrToStringAnsi(internet_per_conn_optionArray[3].Value.pszValue);
             Utilities.GlobalFree(internet_per_conn_optionArray[3].Value.pszValue);
             if (internet_per_conn_optionArray[1].Value.pszValue != IntPtr.Zero)
             {
                 string sProxyString = Marshal.PtrToStringAnsi(internet_per_conn_optionArray[1].Value.pszValue);
                 Utilities.GlobalFree(internet_per_conn_optionArray[1].Value.pszValue);
                 this.InitializeFromProxyString(sProxyString);
             }
             if (internet_per_conn_optionArray[2].Value.pszValue != IntPtr.Zero)
             {
                 this._sHostsThatBypass = Marshal.PtrToStringAnsi(internet_per_conn_optionArray[2].Value.pszValue);
                 Utilities.GlobalFree(internet_per_conn_optionArray[2].Value.pszValue);
                 this._bBypassIntranetHosts = this._sHostsThatBypass.Contains("<local>");
             }
         }
         Marshal.FreeCoTaskMem(ptr);
         return(flag);
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception, "Unable to get proxy information for " + (sConnectionName ?? "DefaultLAN"));
         return(false);
     }
 }
Ejemplo n.º 21
0
        internal bool ReadRequest()
        {
            if (this.m_requestData != null)
            {
                FiddlerApplication.ReportException(new InvalidOperationException("ReadRequest called after requestData was null'd."));
                return(false);
            }
            if (this.pipeClient == null)
            {
                FiddlerApplication.ReportException(new InvalidOperationException("ReadRequest called after pipeClient was null'd."));
                return(false);
            }
            this.m_requestData = new MemoryStream(0x1000);
            this.pipeClient.IncrementUse(0);
            this.m_session.SetBitFlag(SessionFlags.ClientPipeReused, this.pipeClient.iUseCount > 1);
            this.pipeClient.setReceiveTimeout();
            int  iMaxByteCount = 0;
            bool flag          = false;
            bool flag2         = false;

            byte[] arrBuffer = new byte[_cbClientReadBuffer];
            do
            {
                try
                {
                    iMaxByteCount = this.pipeClient.Receive(arrBuffer);
                }
                catch (Exception exception)
                {
                    FiddlerApplication.DebugSpew("ReadRequest Failure: " + exception.Message);
                    flag = true;
                }
                if (iMaxByteCount <= 0)
                {
                    flag2 = true;
                    FiddlerApplication.DebugSpew("ReadRequest read 0 bytes!!!!!");
                }
                else
                {
                    if (CONFIG.bDebugSpew)
                    {
                        FiddlerApplication.DebugSpew("READ FROM: " + this.pipeClient.ToString() + ":\n" + Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount));
                    }
                    if (this.m_requestData.Length == 0L)
                    {
                        this.m_session.Timers.ClientBeginRequest = DateTime.Now;
                        int index = 0;
                        while ((index < iMaxByteCount) && ((arrBuffer[index] == 13) || (arrBuffer[index] == 10)))
                        {
                            index++;
                        }
                        this.m_requestData.Write(arrBuffer, index, iMaxByteCount - index);
                    }
                    else
                    {
                        this.m_requestData.Write(arrBuffer, 0, iMaxByteCount);
                    }
                }
            }while ((!flag2 && !flag) && !this.isRequestComplete());
            arrBuffer = null;
            if (flag || (this.m_requestData.Length == 0L))
            {
                if ((this.pipeClient.iUseCount < 2) || (this.pipeClient.bIsSecured && (this.pipeClient.iUseCount < 3)))
                {
                    FiddlerApplication.Log.LogFormat("[Fiddler] Failed to read {0} request from ({1}) new client socket, port {2}.", new object[] { this.pipeClient.bIsSecured ? "HTTPS" : "HTTP", this.m_session.oFlags["X-ProcessInfo"], this.m_session.oFlags["X-CLIENTPORT"] });
                }
                this._freeRequestData();
                return(false);
            }
            if ((this.m_headers == null) || (this.m_session.state >= SessionStates.Done))
            {
                this._freeRequestData();
                return(false);
            }
            if ("CONNECT" == this.m_headers.HTTPMethod)
            {
                this.m_session.isTunnel = true;
                this.m_sHostFromURI     = this.m_session.PathAndQuery;
            }
            if (this.m_sHostFromURI != null)
            {
                if (this.m_headers.Exists("Host") && !Utilities.areOriginsEquivalent(this.m_sHostFromURI, this.m_headers["Host"], (this.m_session.isTunnel || this.m_session.isHTTPS) ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80)))
                {
                    this.m_session.oFlags["X-Original-Host"] = this.m_headers["Host"];
                    this.m_headers["Host"] = this.m_sHostFromURI;
                }
                else if (!this.m_headers.Exists("Host"))
                {
                    if (this.m_headers.HTTPVersion.Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase))
                    {
                        this.m_session.oFlags["X-Original-Host"] = string.Empty;
                    }
                    this.m_headers["Host"] = this.m_sHostFromURI;
                }
                this.m_sHostFromURI = null;
            }
            if (!this.m_headers.Exists("Host"))
            {
                this._freeRequestData();
                return(false);
            }
            return(true);
        }
Ejemplo n.º 22
0
        internal bool ReadResponse()
        {
            int  iMaxByteCount = 0;
            bool flag          = false;
            bool flag2         = false;
            bool flag3         = false;

            byte[] arrBuffer = new byte[_cbServerReadBuffer];
            do
            {
                try
                {
                    iMaxByteCount = this.pipeServer.Receive(arrBuffer);
                    if (0L == this.m_session.Timers.ServerBeginResponse.Ticks)
                    {
                        this.m_session.Timers.ServerBeginResponse = DateTime.Now;
                    }
                    if (iMaxByteCount <= 0)
                    {
                        flag = true;
                    }
                    else
                    {
                        if (CONFIG.bDebugSpew)
                        {
                            FiddlerApplication.DebugSpew(Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount));
                        }
                        this.m_responseData.Write(arrBuffer, 0, iMaxByteCount);
                        this.m_responseTotalDataCount += iMaxByteCount;
                        if ((this.m_inHeaders == null) && this.GetHeaders())
                        {
                            if ((this.m_session.state == SessionStates.Aborted) && this.m_session.isAnyFlagSet(SessionFlags.ProtocolViolationInResponse))
                            {
                                return(false);
                            }
                            FiddlerApplication.DoResponseHeadersAvailable(this.m_session);
                            if (CONFIG.bStreamAudioVideo)
                            {
                                string str = this.m_inHeaders["Content-Type"];
                                if ((str.StartsWith("video/", StringComparison.OrdinalIgnoreCase) || str.StartsWith("audio/", StringComparison.OrdinalIgnoreCase)) || str.StartsWith("application/x-mms-framed", StringComparison.OrdinalIgnoreCase))
                                {
                                    this.m_session.bBufferResponse = false;
                                }
                            }
                            if (!this.m_session.bBufferResponse)
                            {
                                this.m_session.bBufferResponse = this.m_session.HTTPMethodIs("CONNECT");
                            }
                            if (!this.m_session.bBufferResponse && (this.m_session.oRequest.pipeClient == null))
                            {
                                this.m_session.bBufferResponse = true;
                            }
                            if ((!this.m_session.bBufferResponse && ((0x191 == this.m_inHeaders.HTTPResponseCode) || (0x197 == this.m_inHeaders.HTTPResponseCode))) && this.m_session.oFlags.ContainsKey("x-AutoAuth"))
                            {
                                this.m_session.bBufferResponse = true;
                            }
                            this.m_session.ExecuteBasicResponseManipulationsUsingHeadersOnly();
                            this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, !this.m_session.bBufferResponse);
                            if (!this.m_session.bBufferResponse)
                            {
                                if (this.m_session.oFlags.ContainsKey("response-trickle-delay"))
                                {
                                    int num2 = int.Parse(this.m_session.oFlags["response-trickle-delay"]);
                                    this.m_session.oRequest.pipeClient.TransmitDelay = num2;
                                }
                                if (this.m_session.oFlags.ContainsKey("log-drop-response-body") || FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.ForgetStreamedData", false))
                                {
                                    flag3 = true;
                                }
                            }
                        }
                        if ((this.m_inHeaders != null) && this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
                        {
                            this.LeakResponseBytes();
                            if (flag3)
                            {
                                this.m_session.SetBitFlag(SessionFlags.ResponseBodyDropped, true);
                                if (this._lngLastChunkInfoOffset > -1L)
                                {
                                    this.ReleaseStreamedChunkedData();
                                }
                                else if (this.m_inHeaders.ExistsAndContains("Transfer-Encoding", "chunked"))
                                {
                                    this.ReleaseStreamedChunkedData();
                                }
                                else
                                {
                                    this.ReleaseStreamedData();
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    flag2 = true;
                    if (exception is OperationCanceledException)
                    {
                        this.m_session.state = SessionStates.Aborted;
                        FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} was aborted {1}", new object[] { this.m_session.id, exception.Message });
                    }
                    else if (exception is OutOfMemoryException)
                    {
                        FiddlerApplication.ReportException(exception);
                        this.m_session.state = SessionStates.Aborted;
                        FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} Out of Memory", new object[] { this.m_session.id });
                    }
                    else
                    {
                        FiddlerApplication.Log.LogFormat("fiddler.network.readresponse.failure> Session #{0} raised exception {1}", new object[] { this.m_session.id, exception.Message });
                    }
                }
            }while ((!flag && !flag2) && ((this.m_inHeaders == null) || !this.isResponseBodyComplete()));
            this.m_session.Timers.ServerDoneResponse = DateTime.Now;
            if (this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
            {
                this.m_session.Timers.ClientDoneResponse = this.m_session.Timers.ServerDoneResponse;
            }
            if ((this.m_responseTotalDataCount == 0L) && (this.m_inHeaders == null))
            {
                flag2 = true;
            }
            arrBuffer = null;
            if (flag2)
            {
                this.m_responseData.Dispose();
                this.m_responseData = null;
                return(false);
            }
            if (this.m_inHeaders == null)
            {
                FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "The Server did not return properly formatted HTTP Headers. Maybe missing altogether (e.g. HTTP/0.9), maybe only \\r\\r instead of \\r\\n\\r\\n?\n");
                this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, false);
                this.m_inHeaders                    = new HTTPResponseHeaders(CONFIG.oHeaderEncoding);
                this.m_inHeaders.HTTPVersion        = "HTTP/1.0";
                this.m_inHeaders.HTTPResponseCode   = 200;
                this.m_inHeaders.HTTPResponseStatus = "200 This buggy server did not return headers";
                this.iEntityBodyOffset              = 0;
                return(true);
            }
            return(true);
        }
Ejemplo n.º 23
0
        public bool GetFromWinINET(string sConnectionName)
        {
            this.Clear();
            bool result;

            try
            {
                WinINETProxyInfo.INTERNET_PER_CONN_OPTION_LIST iNTERNET_PER_CONN_OPTION_LIST = default(WinINETProxyInfo.INTERNET_PER_CONN_OPTION_LIST);
                WinINETProxyInfo.INTERNET_PER_CONN_OPTION[]    array = new WinINETProxyInfo.INTERNET_PER_CONN_OPTION[5];
                if (sConnectionName == "DefaultLAN")
                {
                    sConnectionName = null;
                }
                iNTERNET_PER_CONN_OPTION_LIST.Connection  = sConnectionName;
                iNTERNET_PER_CONN_OPTION_LIST.OptionCount = array.Length;
                iNTERNET_PER_CONN_OPTION_LIST.OptionError = 0;
                array[0]          = new WinINETProxyInfo.INTERNET_PER_CONN_OPTION();
                array[0].dwOption = 1;
                array[1]          = new WinINETProxyInfo.INTERNET_PER_CONN_OPTION();
                array[1].dwOption = 2;
                array[2]          = new WinINETProxyInfo.INTERNET_PER_CONN_OPTION();
                array[2].dwOption = 3;
                array[3]          = new WinINETProxyInfo.INTERNET_PER_CONN_OPTION();
                array[3].dwOption = 4;
                array[4]          = new WinINETProxyInfo.INTERNET_PER_CONN_OPTION();
                array[4].dwOption = 10;
                int num = 0;
                for (int i = 0; i < array.Length; i++)
                {
                    num += Marshal.SizeOf(array[i]);
                }
                IntPtr intPtr  = Marshal.AllocCoTaskMem(num);
                IntPtr intPtr2 = intPtr;
                for (int j = 0; j < array.Length; j++)
                {
                    Marshal.StructureToPtr(array[j], intPtr2, false);
                    intPtr2 = (IntPtr)((long)intPtr2 + (long)Marshal.SizeOf(array[j]));
                }
                iNTERNET_PER_CONN_OPTION_LIST.pOptions = intPtr;
                iNTERNET_PER_CONN_OPTION_LIST.Size     = Marshal.SizeOf(iNTERNET_PER_CONN_OPTION_LIST);
                int  size           = iNTERNET_PER_CONN_OPTION_LIST.Size;
                bool flag           = WinINETProxyInfo.InternetQueryOption(IntPtr.Zero, 75, ref iNTERNET_PER_CONN_OPTION_LIST, ref size);
                int  lastWin32Error = Marshal.GetLastWin32Error();
                if (!flag)
                {
                    if (87 == lastWin32Error)
                    {
                        array[4].dwOption = 5;
                        intPtr2           = intPtr;
                        for (int k = 0; k < array.Length; k++)
                        {
                            Marshal.StructureToPtr(array[k], intPtr2, false);
                            intPtr2 = (IntPtr)((long)intPtr2 + (long)Marshal.SizeOf(array[k]));
                        }
                        iNTERNET_PER_CONN_OPTION_LIST.pOptions = intPtr;
                        iNTERNET_PER_CONN_OPTION_LIST.Size     = Marshal.SizeOf(iNTERNET_PER_CONN_OPTION_LIST);
                        size           = iNTERNET_PER_CONN_OPTION_LIST.Size;
                        flag           = WinINETProxyInfo.InternetQueryOption(IntPtr.Zero, 75, ref iNTERNET_PER_CONN_OPTION_LIST, ref size);
                        lastWin32Error = Marshal.GetLastWin32Error();
                    }
                    if (!flag)
                    {
                        FiddlerApplication.Log.LogFormat("Fiddler was unable to get information about the proxy for '{0}' [0x{1}].\n", new object[]
                        {
                            sConnectionName ?? "DefaultLAN",
                            lastWin32Error.ToString("x")
                        });
                    }
                }
                if (flag)
                {
                    intPtr2 = intPtr;
                    for (int l = 0; l < array.Length; l++)
                    {
                        Marshal.PtrToStructure(intPtr2, array[l]);
                        intPtr2 = (IntPtr)((long)intPtr2 + (long)Marshal.SizeOf(array[l]));
                    }
                    this._bDirect           = (1 == (array[0].Value.dwValue & 1));
                    this._bUseConfigScript  = (4 == (array[0].Value.dwValue & 4));
                    this._bAutoDetect       = (8 == (array[0].Value.dwValue & 8));
                    this._bProxiesSpecified = (2 == (array[0].Value.dwValue & 2));
                    if (array[4].dwOption == 10)
                    {
                        this._bAutoDetectWasUserSet = (8 == (array[4].Value.dwValue & 8));
                    }
                    else
                    {
                        this._bAutoDetectWasUserSet = (this._bAutoDetect && 1 == (array[4].Value.dwValue & 1));
                    }
                    this._sScriptURL = Marshal.PtrToStringAnsi(array[3].Value.pszValue);
                    Utilities.GlobalFree(array[3].Value.pszValue);
                    if (array[1].Value.pszValue != IntPtr.Zero)
                    {
                        string manualProxies = Marshal.PtrToStringAnsi(array[1].Value.pszValue);
                        Utilities.GlobalFree(array[1].Value.pszValue);
                        this.SetManualProxies(manualProxies);
                    }
                    if (array[2].Value.pszValue != IntPtr.Zero)
                    {
                        this._sHostsThatBypass = Marshal.PtrToStringAnsi(array[2].Value.pszValue);
                        Utilities.GlobalFree(array[2].Value.pszValue);
                    }
                }
                Marshal.FreeCoTaskMem(intPtr);
                result = flag;
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX, "Unable to get proxy information for " + (sConnectionName ?? "DefaultLAN"));
                result = false;
            }
            return(result);
        }
Ejemplo n.º 24
0
        internal bool Start(int iPort, bool bAllowRemote)
        {
            if (CONFIG.bIsViewOnly)
            {
                return(false);
            }
            bool flag = false;

            try
            {
                flag = (bAllowRemote && CONFIG.bEnableIPv6) && Socket.OSSupportsIPv6;
            }
            catch (Exception exception)
            {
                if (exception is ConfigurationErrorsException)
                {
                    FiddlerApplication.DoNotifyUser(string.Concat(new object[] { "A Microsoft .NET configuration file (listed below) is corrupt and contains invalid data. You can often correct this error by installing updates from WindowsUpdate and/or reinstalling the .NET Framework.\n\n", exception.Message, "\nSource: ", exception.Source, "\n", exception.StackTrace, "\n\n", exception.InnerException, "\nFiddler v", Application.ProductVersion, (8 == IntPtr.Size) ? " (x64) " : " (x86) ", " [.NET ", Environment.Version, " on ", Environment.OSVersion.VersionString, "] " }), ".NET Configuration Error", MessageBoxIcon.Hand);
                    this.oAcceptor = null;
                    return(false);
                }
            }
            try
            {
                if (flag)
                {
                    this.oAcceptor = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    if (Environment.OSVersion.Version.Major > 5)
                    {
                        this.oAcceptor.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation | SocketOptionName.KeepAlive, 0);
                    }
                }
                else
                {
                    this.oAcceptor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
                if (CONFIG.ForceExclusivePort)
                {
                    this.oAcceptor.ExclusiveAddressUse = true;
                }
                if (bAllowRemote)
                {
                    if (flag)
                    {
                        this.oAcceptor.Bind(new IPEndPoint(IPAddress.IPv6Any, iPort));
                    }
                    else
                    {
                        this.oAcceptor.Bind(new IPEndPoint(IPAddress.Any, iPort));
                    }
                }
                else
                {
                    this.oAcceptor.Bind(new IPEndPoint(IPAddress.Loopback, iPort));
                }
                this.oAcceptor.Listen(50);
            }
            catch (SocketException exception2)
            {
                this.oAcceptor = null;
                FiddlerApplication.DoNotifyUser(string.Format("Unable to bind to port [Localhost:{0}]. ErrorCode: {1}.\n{2}\n\n{3}\n\n{4}", new object[] { CONFIG.ListenPort, exception2.ErrorCode, ((exception2.ErrorCode == 0x2740) || (exception2.ErrorCode == 0x271d)) ? "\nThis is usually due to another service running on this port. Run NETSTAT -A at a command prompt.\nIf you don't want to stop using the other program, simply change the port used by Fiddler.\nClick Tools > Fiddler Options > Connections, select a new port, and restart Fiddler." : string.Empty, exception2.ToString(), string.Concat(new object[] { "Fiddler v", Application.ProductVersion, " [.NET ", Environment.Version, " on ", Environment.OSVersion.VersionString, "]" }) }), ((exception2.ErrorCode == 0x2740) || (exception2.ErrorCode == 0x271d)) ? "Fiddler Port in Use" : "Fiddler Cannot Listen", MessageBoxIcon.Hand);
                return(false);
            }
            catch (Exception exception3)
            {
                this.oAcceptor = null;
                FiddlerApplication.ReportException(exception3);
                return(false);
            }
            try
            {
                this.oAcceptor.BeginAccept(new AsyncCallback(this.AcceptConnection), null);
            }
            catch (Exception exception4)
            {
                this.oAcceptor = null;
                FiddlerApplication.Log.LogFormat("Fiddler BeginAccept() Exception: {0}", new object[] { exception4.Message });
                return(false);
            }
            return(true);
        }
Ejemplo n.º 25
0
        internal bool ReadRequest()
        {
            if (this.m_requestData != null)
            {
                FiddlerApplication.ReportException(new InvalidOperationException("ReadRequest called when requestData buffer already existed."));
                return(false);
            }
            if (this.pipeClient == null)
            {
                FiddlerApplication.ReportException(new InvalidOperationException("ReadRequest called after pipeClient was null'd."));
                return(false);
            }
            this.m_requestData = new PipeReadBuffer(true);
            this.m_session.SetBitFlag(SessionFlags.ClientPipeReused, this.pipeClient.iUseCount > 0u);
            this.pipeClient.IncrementUse(0);
            this.pipeClient.setReceiveTimeout();
            int  num   = 0;
            bool flag  = false;
            bool flag2 = false;

            byte[] array = new byte[ClientChatter._cbClientReadBuffer];
            while (true)
            {
                try
                {
                    num = this.pipeClient.Receive(array);
                    goto IL_1F1;
                }
                catch (Exception ex)
                {
                    if (CONFIG.bDebugSpew)
                    {
                        FiddlerApplication.DebugSpew(string.Format("ReadRequest {0} threw {1}", (this.pipeClient == null) ? "Null pipeClient" : this.pipeClient.ToString(), ex.Message));
                    }
                    flag = true;
                    goto IL_1F1;
                }
                goto IL_D2;
IL_1DE:
                if (flag2 || flag)
                {
                    goto IL_22F;
                }
                if (this.isRequestComplete())
                {
                    goto Block_17;
                }
                continue;
IL_D2:
                flag2 = true;
                FiddlerApplication.DoReadRequestBuffer(this.m_session, array, 0);
                if (CONFIG.bDebugSpew)
                {
                    FiddlerApplication.DebugSpew(string.Format("ReadRequest {0} returned {1}", (this.pipeClient == null) ? "Null pipeClient" : this.pipeClient.ToString(), num));
                    goto IL_1DE;
                }
                goto IL_1DE;
IL_1F1:
                if (num <= 0)
                {
                    goto IL_D2;
                }
                if (CONFIG.bDebugSpew)
                {
                    FiddlerApplication.DebugSpew(string.Format("READ FROM {0}:\n{1}", this.pipeClient, Utilities.ByteArrayToHexView(array, 32, num)));
                }
                if (!FiddlerApplication.DoReadRequestBuffer(this.m_session, array, num))
                {
                    flag = true;
                }
                if (0L == this.m_requestData.Length)
                {
                    this.m_session.Timers.ClientBeginRequest = DateTime.Now;
                    if (1u == this.pipeClient.iUseCount && num > 2)
                    {
                        if (array[0] == 5)
                        {
                            break;
                        }
                        if (array[0] == 5)
                        {
                            break;
                        }
                    }
                    int i;
                    for (i = 0; i < num; i++)
                    {
                        if (13 != array[i] && 10 != array[i])
                        {
                            break;
                        }
                    }
                    this.m_requestData.Write(array, i, num - i);
                    goto IL_1DE;
                }
                this.m_requestData.Write(array, 0, num);
                goto IL_1DE;
            }
            goto IL_1FD;
Block_17:
            goto IL_22F;
IL_1FD:
            FiddlerApplication.Log.LogFormat("It looks like someone is trying to send SOCKS traffic to us.\r\n{0}", new object[]
            {
                Utilities.ByteArrayToHexView(array, 16, Math.Min(num, 256))
            });
            return(false);

IL_22F:
            array = null;
            if (!flag)
            {
                if (this.m_requestData.Length != 0L)
                {
                    if (this.m_headers == null || this.m_session.state >= SessionStates.Done)
                    {
                        this._freeRequestData();
                        return(false);
                    }
                    if ("CONNECT" == this.m_headers.HTTPMethod)
                    {
                        this.m_session.isTunnel = true;
                        this.m_sHostFromURI     = this.m_session.PathAndQuery;
                    }
                    if (this.m_sHostFromURI != null)
                    {
                        if (this.m_headers.Exists("Host"))
                        {
                            if (!Utilities.areOriginsEquivalent(this.m_sHostFromURI, this.m_headers["Host"], this.m_session.isHTTPS ? 443 : (this.m_session.isFTP ? 21 : 80)) && (!this.m_session.isTunnel || !Utilities.areOriginsEquivalent(this.m_sHostFromURI, this.m_headers["Host"], 443)))
                            {
                                this.m_session.oFlags["X-Original-Host"] = this.m_headers["Host"];
                                this.m_session.oFlags["X-URI-Host"]      = this.m_sHostFromURI;
                                if (FiddlerApplication.Prefs.GetBoolPref("fiddler.network.SetHostHeaderFromURL", true))
                                {
                                    this.m_headers["Host"] = this.m_sHostFromURI;
                                }
                            }
                        }
                        else
                        {
                            if ("HTTP/1.1".OICEquals(this.m_headers.HTTPVersion))
                            {
                                this.m_session.oFlags["X-Original-Host"] = string.Empty;
                            }
                            this.m_headers["Host"] = this.m_sHostFromURI;
                        }
                        this.m_sHostFromURI = null;
                    }
                    if (!this.m_headers.Exists("Host"))
                    {
                        this._freeRequestData();
                        return(false);
                    }
                    return(true);
                }
            }
            this._freeRequestData();
            if (this.pipeClient == null)
            {
                return(false);
            }
            if (this.pipeClient.iUseCount < 2u || (this.pipeClient.bIsSecured && this.pipeClient.iUseCount < 3u))
            {
                FiddlerApplication.Log.LogFormat("[Fiddler] No {0} request was received from ({1}) new client socket, port {2}.", new object[]
                {
                    this.pipeClient.bIsSecured ? "HTTPS" : "HTTP",
                    this.m_session.oFlags["X-ProcessInfo"],
                    this.m_session.oFlags["X-CLIENTPORT"]
                });
            }
            return(false);
        }
Ejemplo n.º 26
0
 internal static void ReportException(Exception eX)
 {
     FiddlerApplication.ReportException(eX, "Sorry, you may have found a bug...", null);
 }
        /// <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);
            }

            ZipArchive     oZip        = null;
            List <Session> outSessions = new List <Session>();

            try
            {
                // Sniff for ZIP file.
                FileStream 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 ZipArchive(new DiskFile(sFilename));
                oZip.BeginUpdate();

                AbstractFolder oRaw = oZip.GetFolder("raw");
                if (!oRaw.Exists)
                {
                    FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. The selected ZIP is not a Fiddler-generated .SAZ archive of HTTP Sessions.");
                    oZip.EndUpdate();
                    return(null);
                }

                foreach (AbstractFile oRequestFile in oRaw.GetFiles(true, @"*_c.txt"))
                {
                    try
                    {
                        byte[] arrRequest = new byte[oRequestFile.Size];
                        Stream oFS;

RetryWithPassword:
                        try
                        {
                            oFS = oRequestFile.OpenRead(FileShare.Read);
                        }
                        catch (Xceed.Zip.InvalidDecryptionPasswordException)
                        {
                            Console.Write("Password-Protected Session Archive.\nEnter the password to decrypt, or enter nothing to abort opening.\n>");
                            string sPassword = Console.ReadLine();
                            if (sPassword != String.Empty)
                            {
                                oZip.DefaultDecryptionPassword = sPassword;
                                goto RetryWithPassword;
                            }

                            return(null);
                        }
                        int iRead = Utilities.ReadEntireStream(oFS, arrRequest);
                        oFS.Close();
                        Debug.Assert(iRead == arrRequest.Length, "Failed to read entire request.");

                        AbstractFile oResponseFile = oRaw.GetFile(oRequestFile.Name.Replace("_c.txt", "_s.txt"));
                        if (!oResponseFile.Exists)
                        {
                            FiddlerApplication.Log.LogString("Could not find a server response for: " + oResponseFile.FullName);
                            continue;
                        }

                        byte[] arrResponse = new byte[oResponseFile.Size];
                        oFS   = oResponseFile.OpenRead();
                        iRead = Utilities.ReadEntireStream(oFS, arrResponse);
                        oFS.Close();
                        Debug.Assert(iRead == arrResponse.Length, "Failed to read entire response.");

                        oResponseFile = oRaw.GetFile(oRequestFile.Name.Replace("_c.txt", "_m.xml"));

                        Session oSession = new Session(arrRequest, arrResponse);

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

            if (null != oZip)
            {
                oZip.EndUpdate();
                oZip = null;
            }

            return(outSessions.ToArray());
        }
Ejemplo n.º 28
0
 public static void ReportException(Exception eX, string sTitle)
 {
     FiddlerApplication.ReportException(eX, sTitle, null);
 }
Ejemplo n.º 29
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>
        public 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        = null;
            string         sPassword   = String.Empty;
            List <Session> outSessions = new List <Session>();

            try
            {
                // Sniff for ZIP file.
                FileStream 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 (ZipEntry oZE in oZip)
                {
                    // Not a request. Skip it.
                    if (!oZE.FileName.EndsWith("_c.txt") || !oZE.FileName.StartsWith("raw/"))
                    {
                        continue;
                    }

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
                    {
                        byte[] arrRequest = new byte[oZE.UncompressedSize];
                        Stream oFS;
                        try
                        {
                            oFS = oZE.OpenReader();
                        }
                        catch (Ionic.Zip.BadPasswordException)
                        {
                            Console.WriteLine("Incorrect password.");
                            sPassword = String.Empty;
                            goto GetPassword;
                        }
                        int iRead = Utilities.ReadEntireStream(oFS, arrRequest);
                        oFS.Close();
                        Debug.Assert(iRead == arrRequest.Length, "Failed to read entire request.");

                        ZipEntry 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;
                        }

                        byte[] 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.");

                        Session oSession = new Session(arrRequest, arrResponse);

                        ZipEntry 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);
                    }
                }

                /*    RetryWithPassword:
                 *  try
                 *  {
                 *      oFS = oRequestFile.OpenRead(FileShare.Read);
                 *  }
                 *  catch (Xceed.Zip.InvalidDecryptionPasswordException)
                 *  {
                 *    Console.WriteLine("Password-Protected Session Archive.\nEnter the password to decrypt, or enter nothing to abort opening.\n>");
                 *    string sPassword = Console.ReadLine();
                 *    if (sPassword != String.Empty)
                 *    {
                 *        oZip.DefaultDecryptionPassword = sPassword;
                 *        goto RetryWithPassword;
                 *    }
                 *
                 *    return null;
                 *  }
                 */
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX, "ReadSessionArchive Error");
                return(null);
            }

            if (null != oZip)
            {
                oZip.Dispose();
                oZip = null;
            }

            return(outSessions.ToArray());
        }
Ejemplo n.º 30
0
 public bool SaveRules(string sFilename)
 {
     try
     {
         Utilities.EnsureOverwritable(sFilename);
         XmlTextWriter writer = new XmlTextWriter(sFilename, Encoding.UTF8)
         {
             Formatting = Formatting.Indented
         };
         writer.WriteStartDocument();
         writer.WriteStartElement("AutoResponder");
         writer.WriteAttributeString("LastSave", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));
         writer.WriteAttributeString("FiddlerVersion", Application.ProductVersion);
         writer.WriteStartElement("State");
         writer.WriteAttributeString("Enabled", XmlConvert.ToString(this._bEnabled));
         writer.WriteAttributeString("Fallthrough", XmlConvert.ToString(this._bPermitFallthrough));
         try
         {
             this._RWLockRules.AcquireReaderLock(-1);
             foreach (ResponderRule rule in this._alRules)
             {
                 writer.WriteStartElement("ResponseRule");
                 writer.WriteAttributeString("Match", rule.sMatch);
                 writer.WriteAttributeString("Action", rule.sAction);
                 if (rule.iLatency > 0)
                 {
                     writer.WriteAttributeString("Latency", rule.iLatency.ToString());
                 }
                 writer.WriteAttributeString("Enabled", XmlConvert.ToString(rule.IsEnabled));
                 if (rule.HasImportedResponse)
                 {
                     byte[] buffer = rule._oResponseHeaders.ToByteArray(true, true);
                     writer.WriteStartAttribute("Headers");
                     writer.WriteBase64(buffer, 0, buffer.Length);
                     writer.WriteEndAttribute();
                     byte[] writeData = rule._arrResponseBodyBytes;
                     if ((writeData != null) && (writeData.Length > 0))
                     {
                         if (writeData.Length > 0x800)
                         {
                             byte[] buffer3 = Utilities.DeflaterCompress(writeData);
                             if (buffer3.Length < (0.9 * writeData.Length))
                             {
                                 writer.WriteStartAttribute("DeflatedBody");
                                 writer.WriteBase64(buffer3, 0, buffer3.Length);
                                 writer.WriteEndAttribute();
                                 writeData = null;
                             }
                         }
                         if (writeData != null)
                         {
                             writer.WriteStartAttribute("Body");
                             writer.WriteBase64(writeData, 0, writeData.Length);
                             writer.WriteEndAttribute();
                         }
                     }
                 }
                 writer.WriteEndElement();
             }
         }
         finally
         {
             this._RWLockRules.ReleaseReaderLock();
         }
         writer.WriteEndElement();
         writer.WriteEndElement();
         writer.WriteEndDocument();
         writer.Close();
         return(true);
     }
     catch (Exception exception)
     {
         FiddlerApplication.ReportException(exception, "Failed to save AutoResponder Rules");
         return(false);
     }
 }