private void bw_DoWork(object sender, DoWorkEventArgs e) { IsInvoke = true; lock (tasks) { try { Queue <KCRequest> taskBlock = new Queue <KCRequest>(); for (int i = 0; i <= tasks.Count; i++) { taskBlock.Enqueue(tasks.Dequeue()); } while (taskBlock.Count > 0) { KCRequest req = taskBlock.Dequeue(); HTTPRequestHeaders header = (HTTPRequestHeaders)Session.oRequest.headers.Clone(); header.RequestPath = "/kcsapi/" + req.Path; byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(req.Body); Session sess = new Session(header, postBytes); sess.utilSetRequestBody(req.Body); FiddlerApplication.oProxy.SendRequestAndWait(sess.oRequest.headers, sess.requestBodyBytes, null, null); Thread.Sleep(req.Sleep); } } catch (Exception ex) { Debug.Print(ex.ToString()); } } }
/// <summary> /// Checks the path to see if the header details are specified on the path. If the details exist, then /// it will populate the class properties with the values. /// </summary> /// <param name="headers">The HTTP request headers</param> /// <returns>True, if header details are on the path, false otherwise.</returns> private bool CheckIfPathHasDetails(HTTPRequestHeaders headers) { //determine if it is indeed send by the SDK if (headers.RequestPath.Contains("qsp=true")) { //Find where the header details will start var headerDetailsStart = headers.RequestPath.IndexOf("&"); if (headerDetailsStart > 0 && headerDetailsStart < headers.RequestPath.Length) { String[] headersDetails = headers.RequestPath.Substring(headerDetailsStart + 1).Split('&'); foreach (var header in headersDetails) { String[] headerKeyAndValue = header.Split('='); if (headerKeyAndValue.Length == 2) { if (headerKeyAndValue[0].Equals("client-id", StringComparison.OrdinalIgnoreCase)) { this.ClientId = headerKeyAndValue[1]; } else if (headerKeyAndValue[0].Equals("content-type", StringComparison.OrdinalIgnoreCase)) { this.ContentType = Uri.UnescapeDataString(headerKeyAndValue[1]); } } } } return(true); } return(false); }
internal List <string> CompareHeaders(HTTPRequestHeaders left, HTTPRequestHeaders right) { var leftResult = string.Empty; var rightResult = string.Empty; var leftOnly = string.Empty; foreach (var head in left) { var sameInRight = right.FirstOrDefault(x => x.Name == head.Name); if (sameInRight == null) { leftOnly += head.Name + ":" + head.Value + Environment.NewLine; } else { if (head.Value != sameInRight.Value) { leftResult += head.Name + ":" + head.Value + Environment.NewLine; rightResult += sameInRight.Name + ":" + sameInRight.Value + Environment.NewLine; } right.Remove(sameInRight.Name); } } foreach (var head in right) { rightResult += head.Name + ":" + head.Value + Environment.NewLine; } return(new List <string> { leftResult + Environment.NewLine + leftOnly, rightResult }); }
private static byte[] EncodeRequestIfNeed(ref HTTPRequestHeaders header, byte[] bodyBytes) { if (header["Content-Encoding"].Equals("gzip") && !header["Transfer-Encoding"].Equals("gzip")) { // GZIP Encode bodyBytes = Utilities.GzipCompress(bodyBytes); } return(bodyBytes); }
internal string HeaderString(HTTPRequestHeaders input) { var result = string.Empty; foreach (var head in input.OrderBy(x => x.Name)) { result += head.Name + ":" + head.Value + Environment.NewLine; } return(result); }
private static byte[] GetBodyBytes(HTTPRequestHeaders header, string bodyString) { byte[] bodyBytes = new byte[0]; if (!string.IsNullOrEmpty(bodyString)) { bodyBytes = Encoding.Unicode.GetBytes(bodyString); bodyBytes = EncodeRequestIfNeed(ref header, bodyBytes); } return(bodyBytes); }
private Dictionary<String, String> GetHeaders(HTTPRequestHeaders headers) { var dictionary = new Dictionary<String, String>(headers.Count()); foreach (var header in headers) { dictionary.Add(header.Name, header.Value); } return dictionary; }
private Dictionary <String, String> GetHeaders(HTTPRequestHeaders headers) { var dictionary = new Dictionary <String, String>(headers.Count()); foreach (var header in headers) { dictionary.Add(header.Name, header.Value); } return(dictionary); }
public byte[] Decode(HTTPRequestHeaders headers) { byte[] jsonByteArray = new byte[0]; if (headers.Exists(Constants.CustomHeader)) { var contextHeader = headers[Constants.CustomHeader]; jsonByteArray = Convert.FromBase64String(contextHeader); } return(jsonByteArray); }
internal List <string> CompareHeaders(string leftstring, string rightstring) { HTTPRequestHeaders left = new HTTPRequestHeaders(); HTTPRequestHeaders right = new HTTPRequestHeaders(); foreach (var s in leftstring.Split('\n')) { if (string.IsNullOrEmpty(s) || s.Split(':').Length < 2) { continue; } left.Add(s.Split(':')[0], s.Split(':')[1]); } foreach (var s in rightstring.Split('\n')) { if (string.IsNullOrEmpty(s) || s.Split(':').Length < 2) { continue; } right.Add(s.Split(':')[0], s.Split(':')[1]); } var leftResult = string.Empty; var rightResult = string.Empty; var leftOnly = string.Empty; foreach (var head in left) { var sameInRight = right.FirstOrDefault(x => x.Name == head.Name); if (sameInRight == null) { leftOnly += head.Name + ":" + head.Value + Environment.NewLine; } else { if (head.Value != sameInRight.Value) { leftResult += head.Name + ":" + head.Value + Environment.NewLine; rightResult += sameInRight.Name + ":" + sameInRight.Value + Environment.NewLine; } } } foreach (var head in right) { rightResult += head.Name + ":" + head.Value + Environment.NewLine; } return(new List <string> { leftResult + Environment.NewLine + leftOnly, rightResult }); }
internal void ParseRequest() { _requestHeaders.Clear(); HTTPRequestHeaders headers = _session.oRequest.headers; foreach (HTTPHeaderItem item in headers) { _requestHeaders.Add(item.Name, item.Value); } string contentType = string.Empty; if (_requestHeaders.TryGetValue("content-type", out contentType) && !string.IsNullOrEmpty(contentType)) { _requestDataType = GetType(contentType); } }
private static void OverrideHost(ref HTTPRequestHeaders header, string hostname) { if (hostname != null) { int k = hostname.IndexOf(@"://", StringComparison.Ordinal); if (k != -1) { hostname = hostname.Substring(k + 3); } k = hostname.IndexOf(@"/", StringComparison.Ordinal); if (k != -1) { hostname = hostname.Substring(0, k); } header["host"] = hostname; } }
private bool isJson(HTTPRequestHeaders header) { if (header == null) { return(false); } if (header.Exists("Accept")) { var type = header["Accept"]; if (type.ToLower().Contains("json")) { return(true); } } return(false); }
private void GetBill(string touid, bool isDemo, object obj) { try { HTTPRequestHeaders header = (HTTPRequestHeaders)obj; string cookie = header["Cookie"]; string user = DataCatchRequest.GetUser(cookie); string key = string.Format("{0}&{1}", user, touid); CacthConfig config = new CacthConfig(string.Format("{0}GetBillBeginValue", analysisUrl)) { Cookies = cookie }; //if (!CacthConfig.CatchDic.TryGetValue(key, out config)) //{ // config = new CacthConfig(string.Format("{0}GetBillBeginValue", analysisUrl)) { Cookies = cookie }; // CacthConfig.CatchDic.Add(key, config); //} //config.NewCookies = cookie; DataCatchLog log = GetCatchLog(user, isDemo, config); log.SetToUser(touid); AnsyNet.AnsyDataCatch(config, (tuser, msg) => { if (!string.IsNullOrEmpty(msg.Message)) { UpdateUI(log, msg.Message); } switch (msg.Action) { case ActionType.SendRequestData: log.EmitPostDataRequestMsg((IList)msg.Data); break; } return(msg); }); } catch (Exception e) { this.Invoke(new AsynUpdateUI((sn) => { this.textBox1.Text = sn.ToString(); }), e.Message); } }
private static string gsvr(out JObject obj, string url, string bodyData, HTTPRequestHeaders RequestHeaders) { obj = null; JObject reqData = new JObject(); reqData["a"] = "a"; reqData["url"] = url; reqData["data"] = bodyData; reqData["header"] = new JObject(); foreach (var item in RequestHeaders) { //((JArray)reqData["header"]).Add(new JObject(new JProperty("k", item.Name), new JProperty("v", item.Value))); reqData["header"][item.Name] = item.Value; } string errmsg = ""; string respData = PostData(SvrApiUrl, reqData.ToString(Formatting.None), out errmsg); if (!string.IsNullOrEmpty(errmsg)) { return(errmsg); } JObject RespJo; try { RespJo = (JObject)JsonConvert.DeserializeObject(respData); } catch (Exception exx) { return(exx.Message); } if ((bool)RespJo["ok"]) { obj = RespJo; } else { return(RespJo["msg"].ToString()); } return(""); }
public PortlessWebResponse GetPortlessResponse() { HTTPRequestHeaders headers = new HTTPRequestHeaders() { HTTPMethod = Method, RequestPath = requestUri.PathAndQuery }; foreach (string key in Headers.Keys.Cast <string>()) { headers[key] = Headers[key]; } Session session = new Session(headers, requestStream.ToArray()); using (MemoryStream fullRequestStream = new MemoryStream()) { session.WriteRequestToStream(false, false, fullRequestStream); return(new PortlessWebResponse(requestUri, session, processRequestFunc(fullRequestStream.ToArray()))); } }
public static Session Send(string method, string url, string version, string headers, byte[] bodyBytes, StringDictionary oNewFlags = null, string hostname = null) { string headerString = BuildHeader(method, url, version, headers); HTTPRequestHeaders header = new HTTPRequestHeaders(); if (!header.AssignFromString(headerString)) { // error MessageBox.Show(@"Failed to AssignFromString"); return(null); } if (hostname != null) { OverrideHost(ref header, hostname); } Session oSession = Send(header, bodyBytes); return(oSession); }
public static string Inject(string url, string method, string contenttype, string headers, string body) { if (!string.IsNullOrWhiteSpace(url) && !string.IsNullOrWhiteSpace(method)) { var guid = Guid.NewGuid().ToString(); if (!HasPrtl.IsMatch(url)) { url = "http://" + url; } var uri = new Uri(url); var headerList = SplitLine.Split(headers).Where(line => !string.IsNullOrWhiteSpace(line)).ToArray(); var httpheaders = new HTTPRequestHeaders(uri.AbsoluteUri, headerList) { HTTPMethod = method }; httpheaders["Connection"] = "keep-alive"; httpheaders["Calibur-Composer"] = guid; httpheaders["Host"] = uri.Host; if (!string.IsNullOrWhiteSpace(contenttype)) { httpheaders["Content-Type"] = contenttype; } if (!string.IsNullOrWhiteSpace(body)) { httpheaders["Content-Length"] = Encoding.UTF8.GetBytes(body).Length.ToString(); } else { body = string.Empty; } var headerstr = httpheaders.ToString(true, true, false); FiddlerApplication.oProxy.InjectCustomRequest(headerstr + body); return(guid); } else { throw new ArgumentException("url or method is empty."); } }
private async void OnNodeSelected(object sender, TreeViewEventArgs e) { var entity = e.Node.Tag as MimeEntity; var multipart = entity as Multipart; var part = entity as MimePart; byte[] body = new byte[] { }; if (multipart != null) { body = Encoding.UTF8.GetBytes(multipart.Preamble); } if (part != null && part.ContentObject != null) { Stream stream = part.ContentObject.Open(); if (string.Equals(part.ContentType?.MimeType, "application/gzip", System.StringComparison.OrdinalIgnoreCase)) { stream = await GZipCompressor.DecompressAsync(stream); } body = await StreamUtilities.ReadFullyAsync(stream); } var httpHeaders = new HTTPRequestHeaders(); if (entity != null) { foreach (var header in entity.Headers) { httpHeaders.Add(header.Field, header.Value); } } _headersRequest.headers = httpHeaders; _rawRequest.body = body; _xmlRequest.body = body; }
public static string InjectRaw(string rawRequest) { var guid = Guid.NewGuid().ToString(); var hdbd = SplitHdBd.Split(rawRequest, 2); if (hdbd.Length == 2) { var httpheaders = new HTTPRequestHeaders(); httpheaders.AssignFromString(hdbd[0]); httpheaders["Calibur-Composer"] = guid; if (!string.IsNullOrWhiteSpace(hdbd[1])) { httpheaders["Content-Length"] = Encoding.UTF8.GetBytes(hdbd[1]).Length.ToString(); } var headerstr = httpheaders.ToString(true, true, false); FiddlerApplication.oProxy.InjectCustomRequest(headerstr + hdbd[1]); return(guid); } else { throw new ArgumentException("Raw request is invalid."); } }
public static Session Send(HTTPRequestHeaders header, byte[] bodyBytes, StringDictionary oNewFlags = null, string hostname = null) { if (oNewFlags == null) { oNewFlags = new StringDictionary { ["root"] = PCName }; // Generated by PowerComposer Flag if (_oView.MaxFollowRedirect > 0) { oNewFlags[RedirNowFlag] = "0"; oNewFlags[RedirMaxFlag] = _oView.MaxFollowRedirect.ToString(); } if (_oView.IsFixContentLength) { oNewFlags["x-Builder-FixContentLength"] = "PowerComposer-required"; } if (_oView.IsAutoAuth) { oNewFlags["x-AutoAuth"] = "PowerComposer-required"; } if (_oView.IsInspectSession) { oNewFlags["x-breakrequest"] = "PowerComposer-required"; } } if (hostname != null) { OverrideHost(ref header, hostname); } Session oSession = FiddlerApplication.oProxy.SendRequest(header, bodyBytes, oNewFlags, null); return(oSession); }
public HttpHeaders(HTTPRequestHeaders hdrs, Session sess) { Headers = new Dictionary <string, string>(); foreach (var hdr in hdrs) { Headers[hdr.Name.ToLowerInvariant()] = hdr.Value; } using (var buffer = new MemoryStream()) { sess.WriteRequestToStream(true, true, buffer); buffer.Flush(); HeadersInOrder = Encoding.ASCII.GetString(buffer.ToArray()); } CacheControl = hdrs["Cache-Control"]; Connection = hdrs["Connection"]?.Split(';').Select(x => x.Trim()).ToArray(); ContentEncoding = hdrs["Content-Encoding"]; ContentLength = string.IsNullOrWhiteSpace(hdrs["Content-Length"]) ? (uint?)null : uint.Parse(hdrs["Content-Length"]); Expires = hdrs["Expires"]; Host = hdrs["Host"]; Pragma = hdrs["Pragma"]; ProxyConnection = hdrs["Proxy-Connection"]?.Split(';').Select(x => x.Trim()).ToArray(); Referer = hdrs["Referer"]; TransferEncoding = hdrs["Transfer-Encoding"]?.Split(';').Select(x => x.Trim()).ToArray(); }
public Session(HTTPRequestHeaders oRequestHeaders, byte[] arrRequestBody) { EventHandler<StateChangeEventArgs> handler = null; this.bBufferResponse = FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.bufferresponses", false); this.Timers = new SessionTimers(); this._bAllowClientPipeReuse = true; this.oFlags = new StringDictionary(); if (oRequestHeaders == null) { throw new ArgumentNullException("oRequestHeaders", "oRequestHeaders must not be null when creating a new Session."); } if (arrRequestBody == null) { arrRequestBody = Utilities.emptyByteArray; } if (CONFIG.bDebugSpew) { if (handler == null) { handler = (s, ea) => FiddlerApplication.DebugSpew(string.Format("onstatechange>#{0} moving from state '{1}' to '{2}' {3}", new object[] { this.id.ToString(), ea.oldState, ea.newState, Environment.StackTrace })); } this.OnStateChanged += handler; } this.Timers.ClientConnected = this.Timers.ClientBeginRequest = this.Timers.FiddlerGotRequestHeaders = DateTime.Now; this.m_clientIP = null; this.m_clientPort = 0; this.oFlags["x-clientIP"] = this.m_clientIP; this.oFlags["x-clientport"] = this.m_clientPort.ToString(); this.oResponse = new ServerChatter(this); this.oRequest = new ClientChatter(this); this.oRequest.pipeClient = null; this.oResponse.pipeServer = null; this.oRequest.headers = oRequestHeaders; this.requestBodyBytes = arrRequestBody; this.m_state = SessionStates.AutoTamperRequestBefore; }
/// <summary> /// Gets triggered before the request has been made /// </summary> /// <param name="objSession"></param> private void FiddlerApplication_BeforeRequest(Session objSession) { try { //Declarations Utility objUtility = new Utility(); DBUtility objDBUtility = new DBUtility(); //Declarations String strContentType = String.Empty; //Uncomment this if tampering of response is required //objSession.bBufferResponse = true; //Get the content type strContentType = objSession.oRequest.headers["Accept"]; //If its an HTML request or else the configuration has been set to capture all the requests if (strContentType.Contains("text/html") || _enConfiguration == Config.CaptureAll) { //Get the request headers HTTPRequestHeaders objRequestHeaders = objSession.oRequest.headers; //Construct the network data NetworkData objNetworkData = new NetworkData { ClientIP = objSession.clientIP, HostName = objSession.hostname, URLFullPath = objSession.fullUrl, IsHTTPS = objSession.isHTTPS, RequestedAt = objSession.Timers.ClientBeginRequest.ToString(), RequestType = objRequestHeaders.HTTPMethod }; //Get the request body String strRequestBody = objSession.GetRequestBodyAsString(); //If its a POST request if (objNetworkData.RequestType == "POST") { //Get the request parameters objNetworkData.RequestParameters = objUtility.GetRequestParameters(strRequestBody); } else if (objNetworkData.RequestType == "GET") { String [] arrQueryString = objNetworkData.URLFullPath.Split(new Char[] { '?' }); if (arrQueryString.Length > 1) { objNetworkData.RequestParameters = objUtility.GetRequestParameters(arrQueryString[1]); } } //Update the capture to Mongo DB if (_enConfiguration != Config.CaptureOnlyWithRequestParameters || objNetworkData.RequestParameters.Count > 0) { objDBUtility.AddData("NetworkData", "NetworkData", objNetworkData); } } } catch (Exception ex) { Utility.DisplayException("FiddlerApplication_BeforeRequest", ex); } }
/// <summary> /// Lookup the value of the specified header. /// </summary> /// <param name="headers">The HTTP request headers</param> /// <param name="headerName">The name of the header</param> /// <returns>The header value, or an empty string if it is not found</returns> private static string GetHeaderValue(HTTPRequestHeaders headers, string headerName) { var header = headers.FirstOrDefault(h => h.Name.Equals(headerName, StringComparison.InvariantCultureIgnoreCase)); return(header != null ? header.Value : string.Empty); }
public Session SendRequestAndWait(HTTPRequestHeaders oHeaders, byte[] arrRequestBodyBytes, StringDictionary oNewFlags, EventHandler<StateChangeEventArgs> onStateChange) { ManualResetEvent oMRE = new ManualResetEvent(false); Session session = this.SendRequest(oHeaders, arrRequestBodyBytes, oNewFlags, onStateChange); session.OnStateChanged += delegate (object o, StateChangeEventArgs scea) { if (scea.newState >= SessionStates.Done) { FiddlerApplication.DebugSpew("SendRequestAndWait Session #{0} reached state {1}", new object[] { (o as Session).id, scea.newState }); oMRE.Set(); } }; oMRE.WaitOne(); return session; }
/// <summary> /// Strips the configured Cookie / URL / POST parameters from our HTTP headers and body /// </summary> /// <param name="headers">Headers to search for Cookie and URL data</param> /// <param name="body">Body to search for POST data</param> /// <returns>True if request has been modified, False if request was not modified</returns> protected bool StripSessionFromRequest(HTTPRequestHeaders headers, ref byte[] body) { bool requestModified = false; // Strip our Cookie parameters if (headers["Cookie"] != null && authTab.CookieSelector.ParameterList.Count != 0) { foreach (string cookieName in authTab.CookieSelector.ParameterList) { Match match = Regex.Match(headers["Cookie"], String.Format(@"(\s*{0}=[^;]*;\s*)", cookieName), RegexOptions.Multiline); if (match.Success) { headers["Cookie"] = headers["Cookie"].Replace(match.Groups[1].Value, String.Empty); requestModified = true; } } if (headers["Cookie"].Trim() == String.Empty) { headers.Remove("Cookie"); } } // Strip our URL parameters if (headers.RequestPath.Contains("?") && authTab.URLParameterSelector.ParameterList.Count != 0) { foreach (string urlParameterName in authTab.URLParameterSelector.ParameterList) { Match match = Regex.Match(headers.RequestPath, String.Format(@"\?*({0}=[^&\s]*&*)", urlParameterName), RegexOptions.IgnoreCase); if (match.Success) { headers.RequestPath = headers.RequestPath.Replace(match.Groups[1].Value, String.Empty); requestModified = true; } } } // Strip our POST parameters if (body != null && body.Length != 0 && authTab.POSTParameterSelector.ParameterList.Count != 0) { string postParams = System.Text.ASCIIEncoding.ASCII.GetString(body); foreach (string postParameterName in authTab.POSTParameterSelector.ParameterList) { Match match = Regex.Match(postParams, String.Format(@"({0}=[^&\s]*&*)", postParameterName), RegexOptions.Multiline); if (match.Success) { postParams = postParams.Replace(match.Groups[1].Value, String.Empty); requestModified = true; } } body = System.Text.ASCIIEncoding.ASCII.GetBytes(postParams); headers["Content-Length"] = Convert.ToString(body.Length); } return requestModified; }
private static bool SendHTTPCONNECTToGateway(Socket oGWSocket, string sHost, int iPort, HTTPRequestHeaders oRH) { string str = oRH["User-Agent"]; string stringPref = FiddlerApplication.Prefs.GetStringPref("fiddler.composer.HTTPSProxyBasicCreds", null); if (!string.IsNullOrEmpty(stringPref)) { stringPref = Convert.ToBase64String(Encoding.UTF8.GetBytes(stringPref)); } string s = string.Format("CONNECT {0}:{1} HTTP/1.1\r\n{2}{3}Connection: close\r\n\r\n", new object[] { sHost, iPort, string.IsNullOrEmpty(str) ? string.Empty : string.Format("User-Agent: {0}\r\n", str), string.IsNullOrEmpty(stringPref) ? string.Empty : string.Format("Proxy-Authorization: Basic {0}\r\n", stringPref) }); oGWSocket.Send(Encoding.ASCII.GetBytes(s)); byte[] buffer = new byte[0x2000]; int num = oGWSocket.Receive(buffer); if ((num > 12) && Utilities.isHTTP200Array(buffer)) { return true; } if ((num > 12) && Utilities.isHTTP407Array(buffer)) { FiddlerApplication.Log.LogFormat("fiddler.network.connect2> Upstream gateway demanded proxy authentication, which is not supported in this scenario. {0}", new object[] { Encoding.UTF8.GetString(buffer, 0, Math.Min(num, 0x100)) }); return false; } FiddlerApplication.Log.LogFormat("fiddler.network.connect2> Unexpected response from upstream gateway {0}", new object[] { Encoding.UTF8.GetString(buffer, 0, Math.Min(num, 0x100)) }); return false; }
public void InjectCustomRequest(HTTPRequestHeaders oHeaders, byte[] arrRequestBodyBytes, StringDictionary oNewFlags) { this.SendRequest(oHeaders, arrRequestBodyBytes, oNewFlags); }
public JRequestHeaders(JSession session) { this.InnerHeaders = session.InnerSession.RequestHeaders; }
public void Clear() { this.oBody = null; this.oHeaders = null; this.myControl.txtRaw.Clear(); this.myControl.btnSpawnTextEditor.Enabled = false; }
// Process POST data private void processPOST(Session oS, ref StringBuilder strbBody, ref StringBuilder strbHead, ref int iBinarySequence, string sFilename) { HTTPRequestHeaders headers = oS.RequestHeaders; string strContentType = ""; // find out if we have a content-type if (headers.Exists("Content-Type")) { strContentType = headers["Content-Type"]; } else { strContentType = ""; } if (oS.RequestBody.Length > 0) { // handle different types of data // Is it multipart? // Or is it binary? // /[\x00-\x08\x0E-\x1F\x80-\xFF] if (strContentType.Contains("multipart")) { strbBody.AppendLine(", \"body\" : `"); // Need to write all the multipart stuff to a variable and use it addMultipart(MimeEntity.Load(ContentType.Parse(oS.RequestHeaders["Content-Type"]), new MemoryStream(System.Text.Encoding.UTF8.GetBytes(oS.GetRequestBodyAsString()))), sFilename, ref iBinarySequence, ref strbHead, ref strbBody); strbBody.AppendLine("`"); // Make sure we escape all double quotes " since we use double quotes for strings in the script string strCT = headers["Content-Type"]; strCT = strCT.Replace("\"", "\\\""); strbBody.Append(", \"params\" : { headers: { \"Content-Type\" : \"" + strCT + "\"} }"); } else if (Regex.IsMatch(System.Text.Encoding.UTF8.GetString(oS.RequestBody), "[\x00-\x08\x0E-\x1F\x80-\xFF]") || Utilities.IsBinaryMIME(oS.RequestHeaders["Content-Type"])) { // Save as binary file and use binary content // same location as Script output since that is allowed to be written // Append open to header before function string strCat = Path.GetDirectoryName(Path.GetFullPath(sFilename)); string strData = "bin" + iBinarySequence; string strFilename = strCat + "\\" + strData + ".bin"; FileStream f = new FileStream(strFilename, FileMode.OpenOrCreate, FileAccess.Write); f.Write(oS.RequestBody, 0, oS.RequestBody.Length); f.Close(); strbHead.AppendLine(strData + " = open(\"" + strData + ".bin\");"); strbHead.AppendLine(); strbBody.Append(", \"body\" : " + strData); iBinarySequence++; if (headers.Exists("Content-Type")) { strbBody.Append(", \"params\" : { headers: { \"Content-Type\" : \"" + headers["Content-Type"] + "\"} }"); } } else if (strContentType.Contains("application/x-www-form-urlencoded")) { // url-decode and convert string into object for // - easy JS manipulation // - readability (have you tried to read URL-encoded?) // - no need to url-encode manually since k6 methods will do that automagically // Output BODY for POST string strBody = oS.GetRequestBodyAsString(); // Split into objects System.Collections.Specialized.NameValueCollection dBody = HttpUtility.ParseQueryString(strBody); // Glue objects back together string strNewBody = ""; int nKeys = dBody.Keys.Count; int iKey = 1; foreach (string key in dBody.Keys) { // Make sure we escape all double quotes " since we use double quotes for strings in the script // If it's the last of the keys, don't add , at the end (we count since order of keys is not guaranteed) if (iKey != nKeys) { strNewBody = strNewBody + "\"" + key + "\":\"" + dBody[key].Replace("\"", "\\\"") + "\","; } else { strNewBody = strNewBody + "\"" + key + "\":\"" + dBody[key].Replace("\"", "\\\"") + "\""; } iKey++; } strbBody.Append(", \"body\" : {" + strNewBody + "}"); if (headers.Exists("Content-Type")) { strbBody.Append(", \"params\" : { headers: { \"Content-Type\" : \"" + headers["Content-Type"] + "\"} }"); } } else { // Is text // Output BODY for POST string strBody = oS.GetRequestBodyAsString(); // Make sure we escape all double quotes " since we use double quotes for strings in the script strBody = strBody.Replace("\"", "\\\""); strbBody.Append(", \"body\" : \"" + strBody + "\""); if (headers.Exists("Content-Type")) { strbBody.Append(", \"params\" : { headers: { \"Content-Type\" : \"" + headers["Content-Type"] + "\"} }"); } } } }
// Process Lua POST data private void processLuaPOST(Session oS, ref StringBuilder strbBody, ref StringBuilder strbHead, ref int iBinarySequence, string sFilename) { HTTPRequestHeaders headers = oS.RequestHeaders; string strContentType = ""; // find out if we have a content-type if (headers.Exists("Content-Type")) { strContentType = headers["Content-Type"]; } else { strContentType = ""; } if (oS.RequestBody.Length > 0) { // handle different types of data // Is it multipart? // Or is it binary? // /[\x00-\x08\x0E-\x1F\x80-\xFF] if (strContentType.Contains("multipart")) { strbBody.AppendLine(", data = [["); // Need to write all the multipart stuff to a variable and use it addLuaMultipart(MimeEntity.Load(ContentType.Parse(oS.RequestHeaders["Content-Type"]), new MemoryStream(System.Text.Encoding.UTF8.GetBytes(oS.GetRequestBodyAsString()))), ref iBinarySequence, ref strbHead, ref strbBody); strbBody.AppendLine(); strbBody.AppendLine("]]"); // Make sure we escape all double quotes " since we use double quotes for strings in the script string strCT = headers["Content-Type"]; strCT = strCT.Replace("\"", "\\\""); strbBody.Append(", headers = {[\"Content-Type\"] = \"" + strCT + "\"}"); } else if (Regex.IsMatch(System.Text.Encoding.UTF8.GetString(oS.RequestBody), "[\x00-\x08\x0E-\x1F\x80-\xFF]") || Utilities.IsBinaryMIME(oS.RequestHeaders["Content-Type"])) { // Convert to base64-blob // Load in-script // Use base64-blob and convert content-type string strData = "bin" + iBinarySequence; strbHead.AppendLine(strData + " = [["); string binBase64 = Convert.ToBase64String(oS.RequestBody, Base64FormattingOptions.None); strbHead.AppendLine(binBase64); strbHead.AppendLine("]]"); strbBody.Append(", data = " + strData); iBinarySequence++; if (headers.Exists("Content-Type")) { strbBody.Append(", headers = {[\"Content-Type\"] = \"" + headers["Content-Type"] + "\", [\"Content-Encoding\"] = \"base64\"}"); } else { strbBody.Append(", headers = {[\"Content-Encoding\"] = \"base64\"}"); } } else { // Is text // Output BODY for POST string strBody = oS.GetRequestBodyAsString(); // Make sure we escape all double quotes " since we use double quotes for strings in the script strBody = strBody.Replace("\"", "\\\""); strbBody.Append(", data = \"" + strBody + "\""); if (headers.Exists("Content-Type")) { strbBody.Append(", headers = {[\"Content-Type\"] = \"" + headers["Content-Type"] + "\"}"); } } } }
public void InjectCustomRequest(HTTPRequestHeaders oHeaders, byte[] arrRequestBodyBytes, bool bRunRequestRules, bool bViewResult) { StringDictionary oNewFlags = new StringDictionary(); oNewFlags["x-From-Builder"] = "true"; if (bViewResult) { oNewFlags["x-Builder-Inspect"] = "1"; } this.InjectCustomRequest(oHeaders, arrRequestBodyBytes, oNewFlags); }
public Session SendRequest(HTTPRequestHeaders oHeaders, byte[] arrRequestBodyBytes, StringDictionary oNewFlags) { return this.SendRequest(oHeaders, arrRequestBodyBytes, oNewFlags, null); }
public Session SendRequest(HTTPRequestHeaders oHeaders, byte[] arrRequestBodyBytes, StringDictionary oNewFlags, EventHandler<StateChangeEventArgs> onStateChange) { if (oHeaders.ExistsAndContains("Fiddler-Encoding", "base64")) { oHeaders.Remove("Fiddler-Encoding"); if (!Utilities.IsNullOrEmpty(arrRequestBodyBytes)) { arrRequestBodyBytes = Convert.FromBase64String(Encoding.ASCII.GetString(arrRequestBodyBytes)); if (oNewFlags == null) { oNewFlags = new StringDictionary(); } oNewFlags["x-Builder-FixContentLength"] = "CFE-required"; } } if (oHeaders.Exists("Fiddler-Host")) { if (oNewFlags == null) { oNewFlags = new StringDictionary(); } oNewFlags["x-OverrideHost"] = oHeaders["Fiddler-Host"]; oNewFlags["X-IgnoreCertCNMismatch"] = "Overrode HOST"; oHeaders.Remove("Fiddler-Host"); } if ((oNewFlags != null) && oNewFlags.ContainsKey("x-Builder-FixContentLength")) { if ((arrRequestBodyBytes != null) && !oHeaders.ExistsAndContains("Transfer-Encoding", "chunked")) { if (!Utilities.HTTPMethodAllowsBody(oHeaders.HTTPMethod) && (arrRequestBodyBytes.Length == 0)) { oHeaders.Remove("Content-Length"); } else { oHeaders["Content-Length"] = arrRequestBodyBytes.LongLength.ToString(); } } else { oHeaders.Remove("Content-Length"); } } Session session = new Session((HTTPRequestHeaders) oHeaders.Clone(), arrRequestBodyBytes); session.SetBitFlag(SessionFlags.RequestGeneratedByFiddler, true); if (onStateChange != null) { session.OnStateChanged += onStateChange; } if ((oNewFlags != null) && (oNewFlags.Count > 0)) { foreach (DictionaryEntry entry in oNewFlags) { session.oFlags[(string) entry.Key] = oNewFlags[(string) entry.Key]; } } session.ExecuteUponAsyncRequest(); return session; }
public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary <string, object> dictOptions, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications) { if (sFormat != "WCAT Script") { return(false); } bool result = false; string text = null; if (dictOptions != null && dictOptions.ContainsKey("Filename")) { text = (dictOptions["Filename"] as string); } if (string.IsNullOrEmpty(text)) { text = Utilities.ObtainSaveFilename("Export As " + sFormat, "WCAT Script (*.wcat)|*.wcat"); } if (!string.IsNullOrEmpty(text)) { try { StringBuilder stringBuilder = new StringBuilder(); this.EmitScenarioHeader(stringBuilder); int num = 0; bool result2; for (int i = 0; i < oSessions.Length; i++) { Session session = oSessions[i]; if (session.HTTPMethodIs("GET") || session.HTTPMethodIs("POST")) { stringBuilder.AppendLine(" request"); stringBuilder.AppendLine(" {"); stringBuilder.AppendFormat(" id = \"{0}\";\r\n", session.id); stringBuilder.AppendFormat(" url = \"{0}\";\r\n", this.WCATEscape(session.PathAndQuery)); if (session.isHTTPS) { stringBuilder.AppendLine(" secure = true"); if (session.port != 443) { stringBuilder.AppendFormat(" port = {0};\r\n", session.port); } } else { if (session.port != 80) { stringBuilder.AppendFormat(" port = {0};\r\n", session.port); } } if (session.oRequest.headers.HTTPVersion == "HTTP/1.0") { stringBuilder.AppendLine(" version = HTTP10;"); } if (session.HTTPMethodIs("POST")) { stringBuilder.AppendLine(" verb = POST;"); stringBuilder.AppendFormat(" postdata = \"{0}\";\r\n", this.WCATEscape(Encoding.UTF8.GetString(session.requestBodyBytes))); } if (session.responseCode > 0 && 200 != session.responseCode) { stringBuilder.AppendFormat(" statuscode = {0};\r\n", session.responseCode); } HTTPRequestHeaders headers = session.oRequest.headers; foreach (HTTPHeaderItem current in headers) { this.EmitRequestHeaderEntry(stringBuilder, current.Name, current.Value); } stringBuilder.AppendLine(" }"); num++; if (evtProgressNotifications != null) { ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Added " + num.ToString() + " sessions to WCAT Script."); evtProgressNotifications(null, progressCallbackEventArgs); if (progressCallbackEventArgs.Cancel) { result2 = false; return(result2); } } } } stringBuilder.AppendLine(" }\r\n}"); File.WriteAllText(text, stringBuilder.ToString()); result2 = true; return(result2); } catch (Exception ex) { FiddlerApplication.ReportException(ex, "Failed to save WCAT Script"); bool result2 = false; return(result2); } return(result); } return(result); }
private void FiddlerApplication_AfterSessionComplete(Session session) { // Ignore HTTPS connect requests if (session.RequestMethod == "CONNECT") { return; } if (session == null || session.oRequest == null || session.oRequest.headers == null) { return; } var full_url = session.fullUrl; Console.WriteLine("URL: " + full_url); HTTPRequestHeaders request_headers = session.RequestHeaders; HTTPResponseHeaders response_headers = session.ResponseHeaders; int http_response_code = response_headers.HTTPResponseCode; Console.WriteLine("HTTP Response: " + http_response_code.ToString()); string referer = null; Dictionary <String, HTTPHeaderItem> request_headers_dictionary = request_headers.ToDictionary(p => p.Name); if (request_headers_dictionary.ContainsKey("Referer")) { referer = request_headers_dictionary["Referer"].Value; } //foreach (HTTPHeaderItem header_item in response_headers) //{ // Console.Error.WriteLine(header_item.Name + " " + header_item.Value); //} //foreach (HTTPHeaderItem header_item in request_headers) //{ // Console.Error.WriteLine(header_item.Name + " " + header_item.Value); //} Console.Error.WriteLine("Referer: " + referer); var timers = session.Timers; var duration = (TimeSpan)(timers.ClientDoneResponse - timers.ClientBeginRequest); Console.Error.WriteLine(String.Format("Duration: {0:F10}", duration.Milliseconds)); var dic = new Dictionary <string, object>() { { "url", full_url }, { "status", http_response_code }, { "duration", duration.Milliseconds }, { "referer", referer } }; insert(dic); // https://groups.google.com/forum/#!msg/httpfiddler/RuFf5VzKCg0/wcgq-WeUnCoJ // the following code does not work as intended: request body is always blank //string request_body = session.GetRequestBodyAsString(); //if (!string.IsNullOrEmpty(request_body)) //{ // // TODO: UrlDecode // Console.Error.WriteLine(string.Join(Environment.NewLine, request_body.Split(new char[] { '&' }))); //} }
private bool ParseRequestForHeaders() { byte[] buffer; int num; int num2; int num3; byte[] buffer2; if ((this.m_requestData != null) && (this.iEntityBodyOffset >= 4)) { string str; this.m_headers = new HTTPRequestHeaders(CONFIG.oHeaderEncoding); buffer = this.m_requestData.GetBuffer(); Parser.CrackRequestLine(buffer, out num2, out num3, out num, out str); if ((num2 < 1) || (num3 < 1)) { FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed Request-Line"); return false; } if (!string.IsNullOrEmpty(str)) { FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, str); } this.m_headers.HTTPMethod = Encoding.ASCII.GetString(buffer, 0, num2 - 1).ToUpperInvariant(); this.m_headers.HTTPVersion = Encoding.ASCII.GetString(buffer, (num2 + num3) + 1, ((num - num3) - num2) - 2).Trim().ToUpperInvariant(); int num4 = 0; if (buffer[num2] != 0x2f) { if (((num3 > 7) && (buffer[num2 + 4] == 0x3a)) && ((buffer[num2 + 5] == 0x2f) && (buffer[num2 + 6] == 0x2f))) { this.m_headers.UriScheme = Encoding.ASCII.GetString(buffer, num2, 4); num4 = num2 + 6; num2 += 7; num3 -= 7; } else if (((num3 > 8) && (buffer[num2 + 5] == 0x3a)) && ((buffer[num2 + 6] == 0x2f) && (buffer[num2 + 7] == 0x2f))) { this.m_headers.UriScheme = Encoding.ASCII.GetString(buffer, num2, 5); num4 = num2 + 7; num2 += 8; num3 -= 8; } else if (((num3 > 6) && (buffer[num2 + 3] == 0x3a)) && ((buffer[num2 + 4] == 0x2f) && (buffer[num2 + 5] == 0x2f))) { this.m_headers.UriScheme = Encoding.ASCII.GetString(buffer, num2, 3); num4 = num2 + 5; num2 += 6; num3 -= 6; } } if (num4 == 0) { if ((this.pipeClient != null) && this.pipeClient.bIsSecured) { this.m_headers.UriScheme = "https"; } else { this.m_headers.UriScheme = "http"; } } if (num4 <= 0) { goto Label_02C0; } if (num3 != 0) { while (((num3 > 0) && (buffer[num2] != 0x2f)) && (buffer[num2] != 0x3f)) { num2++; num3--; } int index = num4 + 1; int count = num2 - index; if (count > 0) { this.m_sHostFromURI = CONFIG.oHeaderEncoding.GetString(buffer, index, count); if ((this.m_headers.UriScheme == "ftp") && this.m_sHostFromURI.Contains("@")) { int length = this.m_sHostFromURI.LastIndexOf("@") + 1; this.m_headers._uriUserInfo = this.m_sHostFromURI.Substring(0, length); this.m_sHostFromURI = this.m_sHostFromURI.Substring(length); } } goto Label_02C0; } FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed Request-Line. Request-URI component was missing.\r\n\r\n" + Encoding.ASCII.GetString(buffer, 0, num)); } return false; Label_02C0: buffer2 = new byte[num3]; Buffer.BlockCopy(buffer, num2, buffer2, 0, num3); this.m_headers.RawPath = buffer2; if (string.IsNullOrEmpty(this.m_headers.RequestPath)) { FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, false, false, "Incorrectly formed Request-Line. abs_path was empty (e.g. missing /). RFC2616 Section 5.1.2"); } string str2 = CONFIG.oHeaderEncoding.GetString(buffer, num, this.iEntityBodyOffset - num).Trim(); buffer = null; if (str2.Length >= 1) { string[] sHeaderLines = str2.Replace("\r\n", "\n").Split(new char[] { '\n' }); string sErrors = string.Empty; if (!Parser.ParseNVPHeaders(this.m_headers, sHeaderLines, 0, ref sErrors)) { FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed request headers.\n" + sErrors); } } return true; }
public static Session[] GetHTTPSHandshakeFromStreams(TCPStream tcpsClient, TCPStream tcpsServer) { Session[] result; try { if (tcpsClient == null) { result = new Session[0]; } else { MemoryStream payloadStream = tcpsClient.GetPayloadStream(null, 1024); payloadStream.Position = 0L; MemoryStream memoryStream = null; if (tcpsServer != null) { memoryStream = tcpsServer.GetPayloadStream(null, 1024); memoryStream.Position = 0L; } string text = Utilities.UNSTABLE_DescribeClientHello(payloadStream); string text2 = "No server response was found"; if (memoryStream != null && memoryStream.Length > 0L) { text2 = Utilities.UNSTABLE_DescribeServerHello(memoryStream); } if (string.IsNullOrEmpty(text) && (text2 == null || text2.Length < 48)) { result = new Session[0]; } else { HTTPRequestHeaders hTTPRequestHeaders = new HTTPRequestHeaders(); hTTPRequestHeaders.HTTPMethod = "CONNECT"; hTTPRequestHeaders.RequestPath = string.Format("{0}:{1}", tcpsClient.tcpEndpoints.addrDst, tcpsClient.tcpEndpoints.iDstPort); hTTPRequestHeaders.Add("Host", hTTPRequestHeaders.RequestPath); hTTPRequestHeaders.Add("Fiddler-Import", "Packet capture contained HTTPS traffic. Parsing HTTPS Handshake to show this mock Session."); HTTPResponseHeaders hTTPResponseHeaders = new HTTPResponseHeaders(); hTTPResponseHeaders.SetStatus(200, "Emulated CONNECT Tunnel"); Session session = new Session(hTTPRequestHeaders, Encoding.UTF8.GetBytes(text)); session.oResponse.headers = hTTPResponseHeaders; session.responseBodyBytes = Encoding.UTF8.GetBytes(text2); session.oFlags["X-EgressPort"] = (session.oFlags["X-ClientPort"] = tcpsClient.tcpEndpoints.iSrcPort.ToString()); session.oFlags["X-ClientIP"] = tcpsClient.tcpEndpoints.addrSrc.ToString(); session.oFlags["X-HostIP"] = tcpsClient.tcpEndpoints.addrDst.ToString(); session.oFlags["X-HostPort"] = tcpsClient.tcpEndpoints.iDstPort.ToString(); session.Timers.ClientConnected = tcpsClient.dtConnectStart; session.Timers.ClientBeginRequest = tcpsClient.dtFirstPayload; session.Timers.FiddlerGotRequestHeaders = (session.Timers.FiddlerGotResponseHeaders = new DateTime(0L)); session.Timers.ServerConnected = tcpsServer.dtConnectStart; session.Timers.ServerBeginResponse = tcpsServer.dtFirstPayload; string sProcessInfo = tcpsClient.sProcessInfo; if (!string.IsNullOrEmpty(sProcessInfo)) { session.oFlags["X-ProcessInfo"] = sProcessInfo; } session.UNSTABLE_SetBitFlag((SessionFlags)1, true); result = new Session[] { session }; } } } catch (Exception) { result = new Session[0]; } return(result); }
public Session SendRequest(string sRequest, StringDictionary oNewFlags) { int num; int num2; HTTPHeaderParseWarnings warnings; byte[] emptyByteArray; byte[] bytes = CONFIG.oHeaderEncoding.GetBytes(sRequest); if (!Parser.FindEntityBodyOffsetFromArray(bytes, out num, out num2, out warnings)) { throw new ArgumentException("sRequest did not represent a valid HTTP request", "sRequest"); } string sHeaders = CONFIG.oHeaderEncoding.GetString(bytes, 0, num) + "\r\n\r\n"; HTTPRequestHeaders oHeaders = new HTTPRequestHeaders(); if (!oHeaders.AssignFromString(sHeaders)) { throw new ArgumentException("sRequest did not contain valid HTTP headers", "sRequest"); } if (1 > (bytes.Length - num2)) { emptyByteArray = Utilities.emptyByteArray; } else { emptyByteArray = new byte[bytes.Length - num2]; Buffer.BlockCopy(bytes, num2, emptyByteArray, 0, emptyByteArray.Length); } return this.SendRequest(oHeaders, emptyByteArray, oNewFlags); }
public static HTTPRequestHeaders ParseRequest(string sRequest) { HTTPRequestHeaders oHeaders = new HTTPRequestHeaders(CONFIG.oHeaderEncoding); string[] sHeaderLines = sRequest.Substring(0, sRequest.IndexOf("\r\n\r\n", StringComparison.Ordinal)).Replace("\r\n", "\n").Split(new char[] { '\n' }); if (sHeaderLines.Length >= 1) { int index = sHeaderLines[0].IndexOf(' '); if (index > 0) { oHeaders.HTTPMethod = sHeaderLines[0].Substring(0, index).ToUpperInvariant(); sHeaderLines[0] = sHeaderLines[0].Substring(index).Trim(); } index = sHeaderLines[0].LastIndexOf(' '); if (index > 0) { string inStr = sHeaderLines[0].Substring(0, index); oHeaders.HTTPVersion = sHeaderLines[0].Substring(index).Trim().ToUpperInvariant(); if (inStr.OICStartsWith("http://")) { oHeaders.UriScheme = "http"; index = inStr.IndexOfAny(new char[] { '/', '?' }, 7); if (index == -1) { oHeaders.RequestPath = "/"; } else { oHeaders.RequestPath = inStr.Substring(index); } } else if (inStr.OICStartsWith("https://")) { oHeaders.UriScheme = "https"; index = inStr.IndexOfAny(new char[] { '/', '?' }, 8); if (index == -1) { oHeaders.RequestPath = "/"; } else { oHeaders.RequestPath = inStr.Substring(index); } } else if (inStr.OICStartsWith("ftp://")) { oHeaders.UriScheme = "ftp"; index = inStr.IndexOf('/', 6); if (index == -1) { oHeaders.RequestPath = "/"; } else { string sString = inStr.Substring(6, index - 6); if (sString.Contains("@")) { oHeaders._uriUserInfo = Utilities.TrimTo(sString, sString.IndexOf("@") + 1); } oHeaders.RequestPath = inStr.Substring(index); } } else { oHeaders.RequestPath = inStr; } string sErrors = string.Empty; ParseNVPHeaders(oHeaders, sHeaderLines, 1, ref sErrors); return oHeaders; } } return null; }
private bool isRequestComplete() { if (this.m_headers == null) { if (!this.HeadersAvailable()) { return false; } if (!this.ParseRequestForHeaders()) { string str; if (this.m_requestData != null) { str = Utilities.ByteArrayToHexView(this.m_requestData.GetBuffer(), 0x18, (int) Math.Min(this.m_requestData.Length, 0x800L)); } else { str = "{Fiddler:no data}"; } if (this.m_headers == null) { this.m_headers = new HTTPRequestHeaders(); this.m_headers.HTTPMethod = "BAD"; this.m_headers["Host"] = "BAD-REQUEST"; this.m_headers.RequestPath = "/BAD_REQUEST"; } this.FailSession(400, "Fiddler - Bad Request", "[Fiddler] Request Header parsing failed. Request was:\n" + str); return true; } this.m_session.Timers.FiddlerGotRequestHeaders = DateTime.Now; this.m_session._AssignID(); FiddlerApplication.DoRequestHeadersAvailable(this.m_session); } if (this.m_headers.ExistsAndEquals("Transfer-encoding", "chunked")) { long num; long num2; return Utilities.IsChunkedBodyComplete(this.m_session, this.m_requestData, (long) this.iEntityBodyOffset, out num2, out num); } if (Utilities.isRPCOverHTTPSMethod(this.m_headers.HTTPMethod) && !this.m_headers.ExistsAndEquals("Content-Length", "0")) { this.m_session.SetBitFlag(SessionFlags.RequestStreamed, true); return true; } if (this.m_headers.Exists("Content-Length")) { long result = 0L; try { if (!long.TryParse(this.m_headers["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result) || (result < 0L)) { FiddlerApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, "Request content length was invalid.\nContent-Length: " + this.m_headers["Content-Length"]); this.FailSession(400, "Fiddler - Bad Request", "[Fiddler] Request Content-Length header parsing failed.\nContent-Length: " + this.m_headers["Content-Length"]); return true; } return (this.m_requestData.Length >= (this.iEntityBodyOffset + result)); } catch { this.FailSession(400, "Fiddler - Bad Request", "[Fiddler] Unknown error: Check content length header?"); return false; } } return true; }