private void RunResponseHeaderTest(string headerName, string expectedValue) { HTTPHeaders headers = new HTTPHeaders(); headers.Add(headerName, expectedValue); RunResponseHeaderTest(headers); }
public static Task <MimeMessage> ParseMessageAsync(Stream inputStream, HTTPHeaders headers, CancellationToken cancellationToken = default(CancellationToken)) { return(Task.Run(() => { return ParseMessage(inputStream, headers, cancellationToken); }, cancellationToken)); }
private static List <Cookie> GetCookies(HTTPHeaders oHeaders) { var cookies = new List <Cookie>(); if (oHeaders is HTTPRequestHeaders) { string cookiesString = oHeaders["Cookie"]; if (!string.IsNullOrEmpty(cookiesString)) { cookies.AddRange( from cookieString in cookiesString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) select cookieString.Trim() into trimmedCookieString where trimmedCookieString.Length >= 1 select new Cookie { name = Utilities.TrimAfter(trimmedCookieString, '='), value = Utilities.TrimBefore(trimmedCookieString, '=') // #TODO - fully parse cookie string //, //comment = "", //domain = "", //expires = "", //httpOnly = false, //path = "", //secure = false }); } } return(cookies); }
public static Task <MimeMessage> ParseMessageAsync(byte[] message, HTTPHeaders headers, CancellationToken cancellationToken = default(CancellationToken)) { return(Task.Run(() => { return ParseMessage(message, headers, cancellationToken); }, cancellationToken)); }
protected string GetUpdatedParameterValue(HttpRequestInfo curWorkingReqInfo, TestJob testJob) { string val = null; HttpVariables variables = null; HTTPHeaders headers = null; switch (testJob.RequestLocation) { case RequestLocation.Body: variables = curWorkingReqInfo.BodyVariables; break; case RequestLocation.Path: variables = curWorkingReqInfo.PathVariables; break; case RequestLocation.Query: variables = curWorkingReqInfo.QueryVariables; break; case RequestLocation.Cookies: variables = curWorkingReqInfo.Cookies; break; case RequestLocation.Headers: headers = curWorkingReqInfo.Headers; break; } if (variables != null && variables.ContainsKey(testJob.ParameterName)) { val = variables[testJob.ParameterName]; } else if (headers != null) { val = headers[testJob.ParameterName]; } return(val); }
public static MimeMessage ParseMessage(byte[] message, HTTPHeaders headers, CancellationToken cancellationToken) { using (var ms = new MemoryStream(message)) { return(ParseMessage(ms, headers, cancellationToken)); } }
/// <summary> /// Write headers /// </summary> /// <param name="writer"></param> /// <param name="host"></param> /// <param name="port"></param> /// <param name="headers"></param> private static void WriteHeaders(XmlWriter writer, string host, int port, HTTPHeaders headers) { //write headers foreach (HTTPHeader header in headers) { writer.WriteStartElement("header"); writer.WriteAttributeString("name", header.Name); if (String.Compare(header.Name, "host", true) == 0) { if (port == 443 || port == 80) { writer.WriteAttributeString("value", host); } else { writer.WriteAttributeString("value", String.Format("{0}:{1}", host, port)); } } else { writer.WriteAttributeString("value", header.Value); } writer.WriteEndElement(); } }
public static MimeMessage ParseMessage(Stream inputStream, HTTPHeaders headers, CancellationToken cancellationToken) { if (inputStream == null || inputStream == Stream.Null) { return(null); } var headerArray = headers.ToArray(); if (IsMimeMessage(headerArray) == false) { return(null); } string headerString = String.Join("\r\n", headerArray.Select(h => $"{h.Name}: {h.Value}")); try { using (ChainedStream streamWithHeaders = new ChainedStream()) { streamWithHeaders.Add(new MemoryStream(Encoding.UTF8.GetBytes(headerString)), false); streamWithHeaders.Add(inputStream, false); var parser = new MimeKit.MimeParser(streamWithHeaders); return(parser.ParseMessage(cancellationToken)); } } catch (FormatException) { return(null); } }
private void RunResponseHeaderTest(HTTPHeaders expectedHeaders) { HttpRequestInfo expectedRequest = new HttpRequestInfo("GET / HTTP/1.1\r\n\r\n"); HttpResponseInfo expectedResponse = new HttpResponseInfo("HTTP/1.1 200 OK\r\n" + expectedHeaders.ToString() + "\r\nbody"); HttpRequestInfo receivedReqInfo; HttpResponseInfo receivedResponseInfo; SendTestRequestToMockProxy(expectedRequest, expectedResponse, out receivedReqInfo, out receivedResponseInfo); foreach (HTTPHeader expectedHeader in expectedHeaders) { List <HTTPHeader> headers = receivedResponseInfo.Headers.GetHeaders(expectedHeader.Name); bool isMatch = false; foreach (HTTPHeader header in headers) { if (String.Compare(header.Value, expectedHeader.Value, false) == 0) { isMatch = true; } } Assert.IsTrue(isMatch, "Header {0} mismatch", expectedHeader.Name); } }
public static void ReadCallback(IAsyncResult ar) { String content = String.Empty; StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); content = state.sb.ToString(); HTTPHeaders header = new HTTPHeaders(); if (content.IndexOf((char)13) > -1) { if (state.sb.ToString().StartsWith("GET /")) { string getPath = content.ToString().Split(' ')[1].Replace('/', '\\'); string pathDest = path + getPath; FileHandleClass fH = new FileHandleClass(pathDest); if (fH.FileExists()) { byte[] fileData = fH.GetFileBytes(); byte[] headerData = System.Text.Encoding.UTF8.GetBytes(header.HeaderSuccess(fileData.Length)); byte[] allData = new byte[fileData.Length + headerData.Length + 2]; Array.Copy(headerData, allData, headerData.Length); Array.Copy(fileData, 0, allData, headerData.Length, fileData.Length); allData[allData.Length - 2] = 13; allData[allData.Length - 1] = 10; content = header.HeaderSuccess(fileData.Length); Send(handler, allData); } else { content = header.HeaderNotFound(); Send(handler, content); } } else { content = header.HeaderBadRequest(); Send(handler, content); } Console.WriteLine("Read {0} bytes. \n Data : {1}", content.Length, content); } else { content = header.HeaderBadRequest(); Send(handler, content); } } }
private async void Check() { DisplayStatusMessage = false; IsCheckRunning = true; // Measure time StartTime = DateTime.Now; stopwatch.Start(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); dispatcherTimer.Start(); EndTime = null; Headers = null; HeadersCount = 0; // Change the tab title (not nice, but it works) Window window = Application.Current.Windows.OfType <Window>().FirstOrDefault(x => x.IsActive); if (window != null) { foreach (TabablzControl tabablzControl in VisualTreeHelper.FindVisualChildren <TabablzControl>(window)) { tabablzControl.Items.OfType <DragablzTabItem>().First(x => x.ID == _tabId).Header = WebsiteUri; } } try { HTTPHeadersOptions options = new HTTPHeadersOptions() { Timeout = SettingsManager.Current.HTTPHeaders_Timeout }; WebHeaderCollection headers = await HTTPHeaders.GetHeadersAsync(new Uri(WebsiteUri), options); Headers = headers.ToString(); HeadersCount = headers.Count; } catch (Exception ex) { StatusMessage = ex.Message; DisplayStatusMessage = true; } AddWebsiteUriToHistory(WebsiteUri); // Stop timer and stopwatch stopwatch.Stop(); dispatcherTimer.Stop(); Duration = stopwatch.Elapsed; EndTime = DateTime.Now; stopwatch.Reset(); IsCheckRunning = false; }
public void Test_HttpClient_ResponseHeaders_SetCookie_multiple() { HTTPHeaders headers = new HTTPHeaders(); headers.Add("Set-Cookie", "ORASSO_AUTH_HINT=v1.0~20130715222353; path=/; ;"); headers.Add("Set-Cookie", "ORA_UCM_INFO=3~291A1AA7BA90676EE0401490BEAB1D1; path=/; ; expires=Sat, 11-Jan-2014 14:23:53 GMT"); headers.Add("Set-Cookie", "CookieName=cookie_v==alue; expires=Sat, 11-Jan-2014 14:23:53 GMT; path=/; ;"); RunResponseHeaderTest(headers); }
public static bool IsProtobufPacket(HTTPHeaders headers) { if (null == headers) { return(false); } return(null != headers && (headers.ExistsAndContains("Content-Type", "application/x-protobuf") || headers.ExistsAndContains("Content-Type", "application/x-google-protobuf"))); }
public void Test_HttpClient_ResponseHeaders_WWWAuthenticate_multiple() { HTTPHeaders headers = new HTTPHeaders(); headers.Add("WWW-Authenticate", "Negotiate"); headers.Add("WWW-Authenticate", "NTLM"); headers.Add("WWW-Authenticate", "digest"); headers.Add("WWW-Authenticate", "basic"); RunResponseHeaderTest(headers); }
private static ArrayList getHeadersAsArrayList(HTTPHeaders oHeaders) { ArrayList list = new ArrayList(); foreach (HTTPHeaderItem item in oHeaders) { Hashtable hashtable = new Hashtable(2); hashtable.Add("name", item.Name); hashtable.Add("value", item.Value); list.Add(hashtable); } return(list); }
public bool Match(HTTPHeaders matchHeaders) { if (HeadsFilter != null && HeadsFilter.Count > 0) { foreach (MyKeyValuePair <string, string> headFilter in HeadsFilter) { if (!matchHeaders.ExistsAndContains(headFilter.Key, headFilter.Value)) { return(false); } } } return(true); }
private static List <NameValuePair> GetHeaders(HTTPHeaders headers) { var list = new List <NameValuePair>(); foreach (HTTPHeaderItem item in headers) { list.Add(new NameValuePair { name = item.Name, value = item.Value }); } return(list); }
private string GetContentType(HTTPHeaders headers) { if (headers != null && headers["Content-Type"] != null) { if (headers["Content-Type"].ToLower() == "application/json") { return("JSON"); } if (headers["Content-Type"].ToLower() == "application/xml") { return("XML"); } } return(string.Empty); }
private async void Check() { DisplayStatusMessage = false; IsCheckRunning = true; // Measure time StartTime = DateTime.Now; stopwatch.Start(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); dispatcherTimer.Start(); EndTime = null; Headers = null; HeadersCount = 0; try { HTTPHeadersOptions options = new HTTPHeadersOptions() { Timeout = SettingsManager.Current.HTTPHeaders_Timeout }; WebHeaderCollection headers = await HTTPHeaders.GetHeadersAsync(new Uri(WebsiteUri), options); Headers = headers.ToString(); HeadersCount = headers.Count; } catch (Exception ex) { StatusMessage = ex.Message; DisplayStatusMessage = true; } AddWebsiteUriToHistory(WebsiteUri); // Stop timer and stopwatch stopwatch.Stop(); dispatcherTimer.Stop(); Duration = stopwatch.Elapsed; EndTime = DateTime.Now; stopwatch.Reset(); IsCheckRunning = false; }
private async void Check() { DisplayStatusMessage = false; IsCheckRunning = true; // Measure time StartTime = DateTime.Now; stopwatch.Start(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); dispatcherTimer.Start(); EndTime = null; Headers = null; HeadersCount = 0; try { WebHeaderCollection headers = await HTTPHeaders.GetHeadersAsync(new Uri(WebsiteUri)); Headers = headers.ToString(); HeadersCount = headers.Count; } catch (Exception ex) { StatusMessage = ex.Message; DisplayStatusMessage = true; } WebsiteUriHistory = new List <string>(HistoryListHelper.Modify(WebsiteUriHistory, WebsiteUri, SettingsManager.Current.Application_HistoryListEntries)); // Stop timer and stopwatch stopwatch.Stop(); dispatcherTimer.Stop(); Duration = stopwatch.Elapsed; EndTime = DateTime.Now; stopwatch.Reset(); IsCheckRunning = false; }
private static ArrayList getHeadersAsArrayList(HTTPHeaders oHeaders) { ArrayList arrayList = new ArrayList(); foreach (HTTPHeaderItem hTTPHeaderItem in oHeaders) { arrayList.Add(new Hashtable(2) { { "name", hTTPHeaderItem.Name }, { "value", hTTPHeaderItem.Value } }); } return(arrayList); }
public static Dictionary <string, string> ToDictionary(this HTTPHeaders headers) { if (headers == null) { return(null); } var result = new Dictionary <string, string>(); foreach (var item in headers.ToArray()) { if (!result.ContainsKey(item.Name)) { result.Add(item.Name, item.Value); } else { result[item.Name] += ";" + item.Value; } } return(result); }
// Use the same rule like Charles to parse message type and decriptorset url // Refer to: https://www.charlesproxy.com/documentation/using-charles/protocol-buffers/ public static bool ParseMessageTypeNameAndDescriptorSetUrl(HTTPHeaders headers, out string messageTypeName, out string descriptorSetUrl) { messageTypeName = ""; descriptorSetUrl = ""; if (null == headers || !headers.Exists("Content-Type")) { return(false); } messageTypeName = headers.GetTokenValue("Content-Type", "messageType"); if (null == messageTypeName) { messageTypeName = headers.GetTokenValue("Content-Type", "MessageType"); } descriptorSetUrl = headers.GetTokenValue("Content-Type", "Desc"); if (null == descriptorSetUrl) { descriptorSetUrl = headers.GetTokenValue("Content-Type", "desc"); } return(true); }
/// <summary> /// Parse the HTTP payload to FSSHTTP and WOPI message. /// </summary> /// <param name="responseHeaders">The HTTP response header.</param> /// <param name="bytesFromHTTP">The raw data from HTTP layer.</param> /// <param name="direction">The direction of the traffic.</param> /// <returns>The object parsed result</returns> public object ParseHTTPPayloadForFSSHTTP(HTTPHeaders responseHeaders, byte[] bytesFromHTTP, TrafficDirection direction) { object objectOut = null; byte[] emptyByte = new byte[0]; if (bytesFromHTTP == null || bytesFromHTTP.Length == 0) { return(null); } try { if (direction == TrafficDirection.Out && responseHeaders.Exists("Transfer-Encoding") && responseHeaders["Transfer-Encoding"] == "chunked") { bytesFromHTTP = Utilities.GetPaylodFromChunkedBody(bytesFromHTTP); } Stream stream = new MemoryStream(bytesFromHTTP); StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); Regex SOAPRegex = new Regex(@"\<s:Envelop.*\<\/s:Envelope\>"); // extract envelop from http payload. if (SOAPRegex.Match(text).Success) { XmlDocument doc = new XmlDocument(); string soapbody = SOAPRegex.Match(text).Value; if (direction == TrafficDirection.In) { Regex FSSHTTPRequestRegex = new Regex("xsi:type=\"\\w*\"\\s"); // remove xsi:type in xml message. this xsi:type is used for inherit in xmlSerializer. string FSSHTTPRequest = FSSHTTPRequestRegex.Replace(soapbody, string.Empty); MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(FSSHTTPRequest ?? "")); XmlSerializer serializer = new XmlSerializer(typeof(RequestEnvelope)); RequestEnvelope requestEnvelop = (RequestEnvelope)serializer.Deserialize(ms); objectOut = requestEnvelop.Body; // if SubRequestData has fsshttpb messages do parser. if (requestEnvelop.Body.RequestCollection != null) { TryParseFSSHTTPBRequestMessage(requestEnvelop.Body.RequestCollection.Request, bytesFromHTTP); } } else { MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(soapbody ?? "")); XmlSerializer serializer = new XmlSerializer(typeof(ResponseEnvelope)); ResponseEnvelope responseEnvelop = (ResponseEnvelope)serializer.Deserialize(ms); objectOut = responseEnvelop.Body; // if SubResponseData has fsshttpb messages do parser. if (responseEnvelop.Body.ResponseCollection != null) { TryParseFSSHTTPBResponseMessage(responseEnvelop.Body.ResponseCollection.Response, bytesFromHTTP); } } } return(objectOut); } catch (Exception ex) { objectOut = ex.ToString(); return(objectOut); } }
/// <summary> /// Parse the HTTP payload to WOPI message. /// </summary> /// <param name="requestHeaders">The HTTP request header.</param> /// <param name="responseHeaders">The HTTP response header.</param> /// <param name="url">url for a HTTP message.</param> /// <param name="bytesFromHTTP">The raw data from HTTP layer.</param> /// <param name="direction">The direction of the traffic.</param> /// <returns>The object parsed result</returns> public object ParseHTTPPayloadForWOPI(HTTPHeaders requestHeaders, HTTPHeaders responseHeaders, string url, byte[] bytesFromHTTP, out string binaryStructureRopName, TrafficDirection direction) { object objectOut = null; binaryStructureRopName = string.Empty; try { if (direction == TrafficDirection.Out && responseHeaders.Exists("Transfer-Encoding") && responseHeaders["Transfer-Encoding"] == "chunked") { bytesFromHTTP = Utilities.GetPaylodFromChunkedBody(bytesFromHTTP); } Stream stream = new MemoryStream(bytesFromHTTP); StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); WOPIOperations operation = GetWOPIOperationName(requestHeaders, url); if (direction == TrafficDirection.In) { switch (operation) { case WOPIOperations.PutRelativeFile: objectOut = bytesFromHTTP; binaryStructureRopName = "PutRelativeFile"; break; case WOPIOperations.PutFile: objectOut = bytesFromHTTP; binaryStructureRopName = "PutFile"; break; case WOPIOperations.ExecuteCellStorageRelativeRequest: case WOPIOperations.ExecuteCellStorageRequest: byte[] cellreq = bytesFromHTTP; MemoryStream ms; if (requestHeaders.Exists("Content-Encoding") && requestHeaders["Content-Encoding"] == "gzip") { cellreq = Fiddler.Utilities.GzipExpand(cellreq); ms = new MemoryStream(cellreq); } else { ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text ?? "")); } XmlSerializer serializer = new XmlSerializer(typeof(RequestEnvelope)); RequestEnvelope requestEnvelop = (RequestEnvelope)serializer.Deserialize(ms); objectOut = requestEnvelop.Body; if (requestEnvelop.Body.RequestCollection != null) { TryParseFSSHTTPBRequestMessage(requestEnvelop.Body.RequestCollection.Request, bytesFromHTTP); } break; case WOPIOperations.PutUserInfo: objectOut = text; break; case WOPIOperations.Discovery: case WOPIOperations.CheckFileInfo: case WOPIOperations.Lock: case WOPIOperations.RefreshLock: case WOPIOperations.RevokeRestrictedLink: case WOPIOperations.Unlock: case WOPIOperations.UnlockAndRelock: case WOPIOperations.GetLock: case WOPIOperations.DeleteFile: case WOPIOperations.ReadSecureStore: case WOPIOperations.RenameFile: case WOPIOperations.GetRestrictedLink: case WOPIOperations.CheckFolderInfo: case WOPIOperations.GetFile: case WOPIOperations.EnumerateChildren: objectOut = string.Format("{0} operation's request body is null", operation.ToString()); break; default: throw new Exception("The WOPI operations type is not right."); } } else { string status = this.session.ResponseHeaders.HTTPResponseStatus.Replace(" " + this.session.ResponseHeaders.StatusDescription, string.Empty); if (Convert.ToUInt32(status) != 200)// the status is not success { return(null); } ResponseBodyBase responseBody = new ResponseBodyBase(); switch (operation) { case WOPIOperations.Discovery: MemoryStream discoveryms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text ?? "")); XmlSerializer discoverySerializer = new XmlSerializer(typeof(wopidiscovery)); wopidiscovery discoveryres = (wopidiscovery)discoverySerializer.Deserialize(discoveryms); objectOut = discoveryres; break; case WOPIOperations.CheckFileInfo: objectOut = WOPISerilizer.JsonToObject <CheckFileInfo>(text); break; case WOPIOperations.CheckFolderInfo: objectOut = WOPISerilizer.JsonToObject <CheckFolderInfo>(text); break; case WOPIOperations.PutRelativeFile: objectOut = WOPISerilizer.JsonToObject <PutRelativeFile>(text); break; case WOPIOperations.ReadSecureStore: objectOut = WOPISerilizer.JsonToObject <ReadSecureStore>(text); break; case WOPIOperations.EnumerateChildren: objectOut = WOPISerilizer.JsonToObject <EnumerateChildren>(text); break; case WOPIOperations.RenameFile: objectOut = WOPISerilizer.JsonToObject <RenameFile>(text); break; case WOPIOperations.ExecuteCellStorageRelativeRequest: case WOPIOperations.ExecuteCellStorageRequest: { byte[] cellres = bytesFromHTTP; MemoryStream ms; string res; if (responseHeaders.Exists("Content-Encoding") && responseHeaders["Content-Encoding"] == "gzip") { cellres = Fiddler.Utilities.GzipExpand(cellres); string res_sub = System.Text.Encoding.UTF8.GetString(cellres); res = string.Format("{0}{1}{2}", @"<Body>", res_sub, "</Body>"); } else { res = string.Format("{0}{1}{2}", @"<Body>", text, "</Body>"); } ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(res ?? "")); XmlSerializer serializer = new XmlSerializer(typeof(ResponseEnvelopeBody)); ResponseEnvelopeBody body = (ResponseEnvelopeBody)serializer.Deserialize(ms); objectOut = body; // if SubResponseData has fsshttpb messages do parser. if (body.ResponseCollection != null) { TryParseFSSHTTPBResponseMessage(body.ResponseCollection.Response, bytesFromHTTP); } break; } case WOPIOperations.GetFile: objectOut = bytesFromHTTP; binaryStructureRopName = "GetFile"; break; case WOPIOperations.DeleteFile: case WOPIOperations.Lock: case WOPIOperations.GetRestrictedLink: case WOPIOperations.PutFile: case WOPIOperations.RefreshLock: case WOPIOperations.RevokeRestrictedLink: case WOPIOperations.Unlock: case WOPIOperations.UnlockAndRelock: case WOPIOperations.GetLock: case WOPIOperations.PutUserInfo: objectOut = string.Format("{0} operation's response body is null", operation.ToString()); break; default: throw new Exception("The WOPI operations type is not right."); } } return(objectOut); } catch (Exception ex) { objectOut = ex.ToString(); return(objectOut); } }
public override Tuple<int, HTTPHeaders, byte[]> transform_first_chunk(int status_code, HTTPHeaders headers, byte[] chunk, bool finishing) { if (_gzipping) { var ctype = headers.get("Content-Type", "").Split(';')[0]; _gzipping = CONTENT_TYPES.Contains(ctype) && (!finishing || chunk.Length >= MIN_LENGTH) && (finishing || !headers.ContainsKey("Content-Length")) && (!headers.ContainsKey("Content-Encoding")); } if (_gzipping) { headers["Content-Encoding"] = "gzip"; _gzip_value = new MemoryStream(); // BytesIO(); //_gzip_file = gzip.GzipFile(mode = "w", fileobj = self._gzip_value); _gzip_file = new GZipStream(_gzip_value, CompressionMode.Compress); chunk = transform_chunk(chunk, finishing); if (headers.ContainsKey("Content-Length")) headers["Content-Length"] = chunk.Length.ToString(); } return new Tuple<int, HTTPHeaders, byte[]>(status_code, headers, chunk); }
protected void SetHeaders(HTTPHeaders header) { validHeader = (header["Content-Type"] == "application/vnd.ms-sync.wbxml"); }
private static ArrayList getCookies(HTTPHeaders oHeaders) { ArrayList list = new ArrayList(); if (oHeaders is HTTPRequestHeaders) { string str = oHeaders["Cookie"]; if (!string.IsNullOrEmpty(str)) { foreach (string str2 in str.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { string sString = str2.Trim(); if (sString.Length >= 1) { Hashtable hashtable = new Hashtable(); hashtable.Add("name", Utilities.TrimAfter(sString, '=')); hashtable.Add("value", Utilities.TrimBefore(sString, '=')); list.Add(hashtable); } } } return(list); } foreach (HTTPHeaderItem item in oHeaders) { if (item.Name == "Set-Cookie") { Hashtable hashtable2 = new Hashtable(); string str4 = item.Value; string str5 = Utilities.TrimAfter(str4, ';'); hashtable2.Add("name", Utilities.TrimAfter(str5, '=')); hashtable2.Add("value", Utilities.TrimBefore(str5, '=')); string str6 = Utilities.TrimBefore(str4, ';'); if (!string.IsNullOrEmpty(str6)) { DateTime time; if (str6.IndexOf("httpOnly", StringComparison.OrdinalIgnoreCase) > -1) { hashtable2.Add("httpOnly", "true"); } if (str6.IndexOf("secure", StringComparison.OrdinalIgnoreCase) > -1) { hashtable2.Add("_secure", "true"); } Regex regex = new Regex("expires\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)"); Match match = regex.Match(str6); if ((match.Success && (match.Groups["TokenValue"] != null)) && DateTime.TryParse(match.Groups["TokenValue"].Value, out time)) { hashtable2.Add("expires", time.ToString("o")); } regex = new Regex("domain\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)"); match = regex.Match(str6); if (match.Success && (match.Groups["TokenValue"] != null)) { hashtable2.Add("domain", match.Groups["TokenValue"].Value); } match = new Regex("path\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)").Match(str6); if (match.Success && (match.Groups["TokenValue"] != null)) { hashtable2.Add("path", match.Groups["TokenValue"].Value); } } list.Add(hashtable2); } } return(list); }
public void clear() { //Resets all headers and content for this response.""" // The performance cost of tornado.httputil.HTTPHeaders is significant // (slowing down a benchmark with a trivial handler by more than 10%), // and its case-normalization is not generally necessary for // headers we generate on the server side, so use a plain dict // and list instead. _headers = new HTTPHeaders { {"Server", "TornadoServer/" + tornado.version}, {"Content-Type", "text/html; charset=UTF-8"} }; _list_headers = new TupleList<string,string>(); set_default_headers(); if (!request.supports_http_1_1()) if (request.headers.get("Connection") == "Keep-Alive") set_header("Connection", "Keep-Alive"); _write_buffer = new List<byte[]>(); _status_code = 200; }
/// <summary> /// Get the WOPI operation /// </summary> /// <param name="headers">Http headers</param> /// <param name="url">url for a session</param> /// <returns>The operation name</returns> public WOPIOperations GetWOPIOperationName(HTTPHeaders headers, string url) { if (url.EndsWith("hosting/discovery")) { return(WOPIOperations.Discovery); } if (headers.Exists("X-WOPI-Override")) { switch (headers["X-WOPI-Override"] as string) { case "PUT_RELATIVE": return(WOPIOperations.PutRelativeFile); case "UNLOCK": return(WOPIOperations.Unlock); case "REFRESH_LOCK": return(WOPIOperations.RefreshLock); case "DELETE": return(WOPIOperations.DeleteFile); case "READ_SECURE_STORE": return(WOPIOperations.ReadSecureStore); case "GET_RESTRICTED_LINK": return(WOPIOperations.GetRestrictedLink); case "REVOKE_RESTRICTED_LINK": return(WOPIOperations.RevokeRestrictedLink); case "PUT": return(WOPIOperations.PutFile); case "LOCK": if (headers.Exists("X-WOPI-OldLock")) { return(WOPIOperations.UnlockAndRelock); } else { return(WOPIOperations.Lock); } case "COBALT": if (headers.Exists("X-WOPI-RelativeTarget")) { return(WOPIOperations.ExecuteCellStorageRelativeRequest); } else { return(WOPIOperations.ExecuteCellStorageRequest); } default: return(WOPIOperations.Unknown); } } if (url.EndsWith("/contents")) { return(WOPIOperations.GetFile); } if (url.EndsWith("/children")) { return(WOPIOperations.EnumerateChildren); } if (url.Contains("/files/")) { return(WOPIOperations.CheckFileInfo); } if (url.Contains("/folders/")) { return(WOPIOperations.CheckFolderInfo); } return(WOPIOperations.Unknown); }
public virtual Tuple<int, HTTPHeaders, byte[]> transform_first_chunk(int status_code, HTTPHeaders headers, byte[] chunk, bool finishing) { return new Tuple<int,HTTPHeaders,byte[]>(status_code, headers, chunk); }
public void UpdateData() #endif { #if DEBUG || OUTPUT_PERF_LOG FiddlerApplication.Log.LogString(inspectorContext.GetName() + " UpdateData: " + reason); #else FiddlerApp.LogString(inspectorContext.GetName() + " UpdateData"); #endif if (inspectorContext.IsInvalidSession()) { #if DEBUG || OUTPUT_PERF_LOG FiddlerApp.LogString("UpdateData exits for invalidated session"); #endif ClearView(); return; } HTTPHeaders headers = inspectorContext.Headers; if (!FiddlerApp.IsProtobufPacket(headers)) { #if DEBUG || OUTPUT_PERF_LOG FiddlerApp.LogString("UpdateData exits for non-protobuf session"); #endif ClearView(); return; } ClearView(false); string messageTypeName = ""; string descriptorSetUrl = ""; if (null != headers && FiddlerApp.ParseMessageTypeNameAndDescriptorSetUrl(headers, out messageTypeName, out descriptorSetUrl)) { this.cmbMessageType.Text = messageTypeName == null ? "" : messageTypeName; this.cmbMessageType.Enabled = (messageTypeName == null || messageTypeName.Length == 0); } else { this.cmbMessageType.Enabled = true; } string protoPath = this.txtDirectory.Text; bool printEnumAsInteger = this.chkboxEnumValue.Checked; bool printPrimitiveFields = this.chkboxPrintPrimitiveFields.Checked; try { string jsonString = null; byte[] body = FiddlerApp.DecodeContent(inspectorContext.RawBody, headers); if (null != body) { string[] protoFiles = FiddlerApp.LoadProtos(protoPath); jsonString = Protobuf2Json.ConvertToJson(protoPath, protoFiles, descriptorSetUrl, messageTypeName, printEnumAsInteger, printPrimitiveFields, false, body); object jsonObject = Fiddler.WebFormats.JSON.JsonDecode(jsonString); Fiddler.WebFormats.JSON.JSONParseResult jsonResult = null; if (!(jsonObject is Fiddler.WebFormats.JSON.JSONParseResult)) { tvJson.Nodes.Clear(); return; } jsonResult = jsonObject as Fiddler.WebFormats.JSON.JSONParseResult; tvJson.Tag = jsonString; #if DEBUG || OUTPUT_PERF_LOG FiddlerApplication.Log.LogString(inspectorContext.GetName() + " beginUpdate"); #endif TreeNode rootNode = new TreeNode("Protobuf"); Queue <KeyValuePair <object, TreeNode> > queue = new Queue <KeyValuePair <object, TreeNode> >(); object jsonItem = jsonResult.JSONObject; TreeNode parentNode = rootNode; while (true) { AddNode(jsonItem, parentNode, queue); if (queue.Count == 0) { break; } KeyValuePair <object, TreeNode> kv = queue.Dequeue(); jsonItem = kv.Key; parentNode = kv.Value; } rootNode.ExpandAll(); tvJson.BeginUpdate(); try { if (tvJson.Nodes.Count > 0) { tvJson.Nodes.Clear(); } tvJson.Nodes.Add(rootNode); // tvJson.ExpandAll(); // rootNode.EnsureVisible(); } finally { tvJson.EndUpdate(); #if DEBUG || OUTPUT_PERF_LOG FiddlerApp.LogString(inspectorContext.GetName() + " EndUpdate: " + tvJson.GetNodeCount(true).ToString()); #endif } } } catch (Exception ex) { FiddlerApp.LogString(ex.Message); } }
public override Tuple<int, HTTPHeaders, byte[]> transform_first_chunk(int status_code, HTTPHeaders headers, byte[] chunk, bool finishing) { // 304 responses have no body (not even a zero-length body), and so // should not have either Content-Length or Transfer-Encoding headers. if (_chunking && status_code != 304) { // No need to chunk the output if a Content-Length is specified if (headers.ContainsKey("Content-Length") || headers.ContainsKey("Transfer-Encoding")) _chunking = false; else { headers["Transfer-Encoding"] = "chunked"; chunk = transform_chunk(chunk, finishing); } } return new Tuple<int, HTTPHeaders, byte[]>(status_code, headers, chunk); }
public HTTPRequest(string method_, string uri_, string version_="HTTP/1.0", HTTPHeaders headers_=null, byte[] body_=null, string remote_ip_=null, string protocol_=null, string host_=null, string files=null, HTTPConnection connection_=null) { method = method_; uri = uri_; version = version_; headers = headers_ ?? new HTTPHeaders(); body = body_ ?? new byte[] {}; if (connection != null && connection.xheaders) { // Squid uses X-Forwarded-For, others use X-Real-Ip remote_ip = headers.get( "X-Real-Ip", headers.get("X-Forwarded-For", remote_ip_)); if (!_valid_ip(remote_ip)) remote_ip = remote_ip_; // AWS uses X-Forwarded-Proto protocol = headers.get( "X-Scheme", headers.get("X-Forwarded-Proto", protocol_)); if (protocol != "http" && protocol != "https") protocol = "http"; } else { remote_ip = remote_ip_; if (protocol_ != null) protocol = protocol_; //todo ssl else if (connection != null && isinstance(connection.stream, iostream.SSLIOStream): // protocol = "https" else protocol = "http"; } host = host_ ?? headers.get("Host") ?? "127.0.0.1"; //todo files = files_ ?? {} connection = connection_; _start_time = DateTime.Now; _finish_time = null; var parts = uri.Split(new char[] { '?' }, 2); path = parts.Length > 0 ? parts[0] : null; query = parts.Length > 1 ? parts[1] : null; var arguments_ = System.Web.HttpUtility.ParseQueryString(query ?? "");// parse_qs_bytes(query) arguments = new Dictionary<string, string[]>(); foreach(var name in arguments_.AllKeys) { var values = arguments_.GetValues(name); if(values != null) arguments[name] = values; } }
public void flush(bool include_footers=false, Action callback=null) { /*Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. */ if (application._wsgi) throw new Exception("WSGI applications do not support flush()"); var chunk = ByteArrayExtensions.join(_write_buffer.ToArray()); _write_buffer = new List<byte[]>(); byte[] headers = null; if (!_headers_written) { _headers_written = true; foreach (var transform in _transforms) { var result = transform.transform_first_chunk(_status_code, _headers, chunk, include_footers); _status_code = result.Item1; _headers = result.Item2; chunk = result.Item3; } headers = _generate_headers(); } else { foreach (var transform in _transforms) chunk = transform.transform_chunk(chunk, include_footers); headers = new byte[]{}; } // Ignore the chunk and only write the headers for HEAD requests if (request.method == "HEAD") { if (headers != null && headers.Length > 0) request.write(headers, callback); return; } request.write(ByteArrayExtensions.join(headers, chunk), callback); }
private static ArrayList getCookies(HTTPHeaders oHeaders) { ArrayList arrayList = new ArrayList(); if (oHeaders is HTTPRequestHeaders) { string text = oHeaders.get_Item("Cookie"); if (string.IsNullOrEmpty(text)) { return(arrayList); } string[] array = text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string text2 = array2[i]; string text3 = text2.Trim(); if (text3.Length >= 1) { arrayList.Add(new Hashtable { { "name", Utilities.TrimAfter(text3, '=') }, { "value", Utilities.TrimBefore(text3, '=') } }); } } } else { foreach (HTTPHeaderItem hTTPHeaderItem in oHeaders) { if (hTTPHeaderItem.Name == "Set-Cookie") { Hashtable hashtable = new Hashtable(); string value = hTTPHeaderItem.Value; string text4 = Utilities.TrimAfter(value, ';'); hashtable.Add("name", Utilities.TrimAfter(text4, '=')); hashtable.Add("value", Utilities.TrimBefore(text4, '=')); string text5 = Utilities.TrimBefore(value, ';'); if (!string.IsNullOrEmpty(text5)) { if (text5.IndexOf("httpOnly", StringComparison.OrdinalIgnoreCase) > -1) { hashtable.Add("httpOnly", "true"); } if (text5.IndexOf("secure", StringComparison.OrdinalIgnoreCase) > -1) { hashtable.Add("_secure", "true"); } Regex regex = new Regex("expires\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)"); Match match = regex.Match(text5); DateTime dateTime; if (match.Success && match.Groups["TokenValue"] != null && DateTime.TryParse(match.Groups["TokenValue"].Value, out dateTime)) { hashtable.Add("expires", dateTime.ToString("o")); } regex = new Regex("domain\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)"); match = regex.Match(text5); if (match.Success && match.Groups["TokenValue"] != null) { hashtable.Add("domain", match.Groups["TokenValue"].Value); } regex = new Regex("path\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)"); match = regex.Match(text5); if (match.Success && match.Groups["TokenValue"] != null) { hashtable.Add("path", match.Groups["TokenValue"].Value); } } arrayList.Add(hashtable); } } } return(arrayList); }