public TableStorageResponse(HttpStatusCode statusCode, string response, WebHeaderCollection headers) { StatusCode = statusCode; Body = String.IsNullOrEmpty(response) ? null : new TableStorageResponseBody(response); var values = headers.GetValues(StorageHttpConstants.HeaderNames.PrefixForTableContinuation + StorageHttpConstants.HeaderNames.NextRowKey); NextRowKey = values != null ? values.FirstOrDefault() : null; values = headers.GetValues(StorageHttpConstants.HeaderNames.PrefixForTableContinuation + StorageHttpConstants.HeaderNames.NextPartitionKey); NextPartitionKey = values != null ? values.FirstOrDefault() : null; }
private string GetRemoteNzbFilename(WebHeaderCollection whc) { try { foreach (string key in whc.Keys) { string value = whc.GetValues(key)[0]; if (key == "X-DNZB-Name") { return value; } if (key == "Content-Disposition") { int start = value.IndexOf("filename=") + 9; int end = value.IndexOf(".nzb"); int length = end - start; return value.Substring(start, length).TrimStart('\"', ' ').TrimEnd('\"', ' '); } } } catch (Exception) { return "unknown"; } return "unknown"; }
public Dictionary<string, string> MapHeaders(WebHeaderCollection headerCollection) { var headers = new Dictionary<string, string>(); for (var i = 0; i < headerCollection.Count; i++) { headers.Add(headerCollection.GetKey(i), string.Join(",", headerCollection.GetValues(i))); } return headers; }
public void AddHeaders(WebHeaderCollection headers) { if (headers != null) { Headers = new List<Header>(); for (int i = 0; i < headers.Count; ++i) { string header = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { Headers.Add(new Header(header, value)); } } } }
private static string FormatHeaders(WebHeaderCollection headers) { var sb = new StringBuilder(); for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); string[] values = headers.GetValues(i); for (int j = 0; j < values.Length; j++) { sb.Append(key).Append(": ").Append(values[j]).Append("\r\n"); } } return(sb.Append("\r\n").ToString()); }
public static void Test_WebHeader_01() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("xxx", "yyy"); headers.Add("xxx", "yyy222"); headers.Add("zzz", "fff"); headers.Add("xxx", "ttt"); for (int i = 0; i < headers.Count; ++i) { string key = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { Trace.WriteLine("{0}: {1}", key, value); } } }
/// <summary> /// Add x-ms- prefixed headers in a fixed order. /// </summary> /// <param name="headers">The headers.</param> /// <param name="canonicalizedString">The canonicalized string.</param> internal static void AddCanonicalizedHeaders(WebHeaderCollection headers, CanonicalizedString canonicalizedString) { CultureInfo sortingCulture = new CultureInfo("en-US"); StringComparer sortingComparer = StringComparer.Create(sortingCulture, false); // Look for header names that start with x-ms-, then sort them in case-insensitive manner. List<string> httpStorageHeaderNameArray = new List<string>(); foreach (string key in headers.Keys) { if (key.StartsWith(Constants.HeaderConstants.PrefixForStorageHeader, StringComparison.OrdinalIgnoreCase)) { httpStorageHeaderNameArray.Add(key.ToLowerInvariant()); } } httpStorageHeaderNameArray.Sort(sortingComparer); // Now go through each header's values in the sorted order and append them to the canonicalized string. foreach (string key in httpStorageHeaderNameArray) { StringBuilder canonicalizedElement = new StringBuilder(key); string delimiter = ":"; // Go through values, unfold them, and then append them to the canonicalized element string. string[] values = headers.GetValues(key); if (values.Length == 0 || string.IsNullOrEmpty(values[0])) { continue; } foreach (string value in values) { // Unfolding is simply removal of CRLF. string unfoldedValue = value.TrimStart().Replace("\r\n", string.Empty); // Append it to the canonicalized element string. canonicalizedElement.Append(delimiter); canonicalizedElement.Append(unfoldedValue); delimiter = ","; } // Now, add this canonicalized element to the canonicalized header string. canonicalizedString.AppendCanonicalizedElement(canonicalizedElement.ToString()); } }
private string GetRemoteNzbCategory(WebHeaderCollection whc) { try { foreach (string key in whc.Keys) { string value = whc.GetValues(key)[0]; if (key == "X-DNZB-Category") { return value; } } } catch (Exception) { return String.Empty; } return String.Empty; }
private static string CanonicalizedUCloudHeaders(WebHeaderCollection header) { string canoncializedUCloudHeaders = string.Empty; SortedDictionary<string, string> headerMap = new SortedDictionary<string, string> (); for (int i = 0; i < header.Count; ++i) { string headerKey = header.GetKey (i); if (headerKey.ToLower().StartsWith ("x-ucloud-")) { foreach (string value in header.GetValues(i)) { if (headerMap.ContainsKey (headerKey)) { headerMap [headerKey] += value; headerMap [headerKey] += @","; } else { headerMap.Add (headerKey, value); } } } } foreach (KeyValuePair<string, string> item in headerMap) { canoncializedUCloudHeaders += (item.Key + @":" + item.Value + @"\n"); } return canoncializedUCloudHeaders; }
static string FormatHeaders(WebHeaderCollection headers) { var sb = new StringBuilder(); for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); if (WebHeaderCollection.AllowMultiValues(key)) { foreach (string v in headers.GetValues(i)) { sb.Append(key).Append(": ").Append(v).Append("\r\n"); } } else { sb.Append(key).Append(": ").Append(headers.Get(i)).Append("\r\n"); } } return(sb.Append("\r\n").ToString()); }
private bool GetConnectionResponse(WebHeaderCollection whc) { try { foreach (string key in whc.Keys) { string value = whc.GetValues(key)[0]; if (key == "Connection") { if (value.Contains("close")) //Look if the connection was closed (NZB was not returned) - NZBMatrix returns close for Valid Requests return false; //Will this always work?? return true; //Return true } } } catch (Exception) { return false; } return false; }
public void GetValues () { WebHeaderCollection w = new WebHeaderCollection (); w.Add ("Hello", "H1"); w.Add ("Hello", "H2"); w.Add ("Hello", "H3,H4"); string [] sa = w.GetValues ("Hello"); Assert.AreEqual (3, sa.Length, "#1"); Assert.AreEqual ("H1,H2,H3,H4", w.Get ("Hello"), "#2"); w = new WebHeaderCollection (); w.Add ("Accept", "H1"); w.Add ("Accept", "H2"); w.Add ("Accept", "H3, H4 "); Assert.AreEqual (3, w.GetValues (0).Length, "#3a"); Assert.AreEqual (4, w.GetValues ("Accept").Length, "#3b"); Assert.AreEqual ("H4", w.GetValues ("Accept")[3], "#3c"); Assert.AreEqual ("H1,H2,H3, H4", w.Get ("Accept"), "#4"); w = new WebHeaderCollection (); w.Add ("Allow", "H1"); w.Add ("Allow", "H2"); w.Add ("Allow", "H3,H4"); sa = w.GetValues ("Allow"); Assert.AreEqual (4, sa.Length, "#5"); Assert.AreEqual ("H1,H2,H3,H4", w.Get ("Allow"), "#6"); w = new WebHeaderCollection (); w.Add ("AUTHorization", "H1, H2, H3"); sa = w.GetValues ("authorization"); Assert.AreEqual (3, sa.Length, "#9"); w = new WebHeaderCollection (); w.Add ("proxy-authenticate", "H1, H2, H3"); sa = w.GetValues ("Proxy-Authenticate"); Assert.AreEqual (3, sa.Length, "#9"); w = new WebHeaderCollection (); w.Add ("expect", "H1,\tH2, H3 "); sa = w.GetValues ("EXPECT"); Assert.AreEqual (3, sa.Length, "#10"); Assert.AreEqual ("H2", sa [1], "#11"); Assert.AreEqual ("H3", sa [2], "#12"); try { w.GetValues (null); Assert.Fail ("#13"); } catch (ArgumentNullException) { } Assert.AreEqual (null, w.GetValues (""), "#14"); Assert.AreEqual (null, w.GetValues ("NotExistent"), "#15"); w = new WebHeaderCollection (); w.Add ("Accept", null); Assert.AreEqual (1, w.GetValues ("Accept").Length, "#16"); w = new WebHeaderCollection (); w.Add ("Accept", ",,,"); Assert.AreEqual (3, w.GetValues ("Accept").Length, "#17"); }
public static string ParseMachineName(WebHeaderCollection responseHeaders) { string machineName = "?"; for (int i = 0; i < responseHeaders.Count; i++) { if (responseHeaders.Keys[i] == "X-ServerName") { string[] values = responseHeaders.GetValues(i); if (values != null && values.Length > 0) machineName = values[0]; break; } } return machineName; }
public void GetValuesForMultipleHeaderManyLines () { WebHeaderCollection w = new WebHeaderCollection (); w.Add ("Pragma", "H1, H2"); w.Add ("Pragma", "H3"); Assert.AreEqual (3, w.GetValues ("Pragma").Length, "#1"); }
public void GetValues_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("Accept", "text/plain, text/html"); string[] values = w.GetValues("Accept"); Assert.Equal(2, values.Length); Assert.Equal("text/plain", values[0]); Assert.Equal("text/html", values[1]); }
/// <summary> /// Loads the file metadata from the given HTTP headers. /// </summary> /// <param name="p_whcFileHeader">The HTTP header collection containing the file's metadata.</param> private void Initialize(WebHeaderCollection p_whcFileHeader) { foreach (string strKey in p_whcFileHeader.Keys) { switch (strKey) { case "Content-Disposition": Regex rgxFilename = new Regex("filename=([^;]+)"); Match mchFilename = rgxFilename.Match(p_whcFileHeader.GetValues(strKey)[0]); if (mchFilename.Success) SuggestedFileName = mchFilename.Groups[1].Value.Trim("\"".ToCharArray()); break; case "Content-Length": if (Length == 0) Length = UInt64.Parse(p_whcFileHeader.GetValues(strKey)[0]); break; case "Content-Type": IsHtml = p_whcFileHeader.GetValues(strKey)[0].Equals("text/html", StringComparison.OrdinalIgnoreCase); break; case "Accept-Ranges": case "Content-Range": string strValue = p_whcFileHeader.GetValues(strKey)[0]; SupportsResume |= strValue.Contains("bytes"); if (strKey.Equals("Content-Range") && !String.IsNullOrEmpty(strValue)) { string[] strRange = strValue.Split(' ', '-', '/'); if (strRange[0].Equals("bytes")) Length = UInt64.Parse(strRange[3]); } break; case "ETag": ETag = p_whcFileHeader.GetValues(strKey)[0]; break; case "NexusError": NexusError = p_whcFileHeader.GetValues(strKey)[0]; break; case "NexusErrorInfo": NexusErrorInfo = p_whcFileHeader.GetValues(strKey)[0]; break; default: Other[strKey] = p_whcFileHeader.GetValues(strKey); break; } } }
public static void Test_WebHeader_02() { string file = @"http\header_01.json"; string file2 = @"http\header_02.json"; file = zPath.Combine(_directory, file); file2 = zPath.Combine(_directory, file2); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("xxx", "yyy"); headers.Add("xxx", "yyy222"); headers.Add("zzz", "fff"); headers.Add("yyy", "ttt"); for (int i = 0; i < headers.Count; ++i) { string key = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { Trace.WriteLine("{0}: {1}", key, value); } } //headers.zSave(file); BsonDocument doc = headers.ToBsonDocument(); doc.zSave(file); }
private static string GetCookieString(WebHeaderCollection webHeaderCollection) { try { string CokString = ""; for (int i = 0; i < webHeaderCollection.Count; i++) { String header__ = webHeaderCollection.GetKey(i); if (header__ != "Set-Cookie") continue; String[] values = webHeaderCollection.GetValues(header__); if (values.Length < 1) continue; foreach (string v in values) if (v != "") CokString += MrHTTP.StripCokNameANdVal(v)+";"; } if (CokString.Length > 0) return CokString.Substring(0, CokString.Length - 1); return CokString; } catch { return ""; } }
public IEnumerable<ShippingProviderMethod> GetAllShippingMethods(int id) { var methods = new List<ShippingProviderMethod>(); var provider = ShippingProviderHelper.GetShippingProvider(id); var helper = new ShippingConfigHelper(provider); var request = new ShippingRequest(); var orderInfo = OrderHelper.GetOrderInfo(); var postalCodeFrom = helper.Settings["zipPostalCodeFrom"]; var customerPostalCode = OrderHelper.CustomerInformationValue(orderInfo, "customerPostalCode"); if (string.IsNullOrEmpty(customerPostalCode)) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: customerPostalCode IsNullOrEmpty: CUSTOMER SHOULD ENTER A POSTALCODE FIRST!"); return methods; } var orderWeight = orderInfo.OrderLines.Sum(x => x.OrderLineWeight)/1000; if (orderWeight < 0.1) { orderWeight = 0.1; } if (orderWeight > 20) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: Weight > 20: Weight should be in grams"); return methods; } var orderWeightCulture = decimal.Parse(orderWeight.ToString(), NumberStyles.Currency, CultureInfo.GetCultureInfo("en-AU")); var orderWidth = orderInfo.OrderLines.Sum(x => x.ProductInfo.Weight); if (orderWidth < 5) { orderWidth = 5; } if (orderWidth > 105) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: Wide > 105: width should be in cm"); return methods; } var orderWidthCulture = decimal.Parse(orderWidth.ToString(), NumberStyles.Currency, CultureInfo.GetCultureInfo("en-AU")); var orderHeight = orderInfo.OrderLines.Sum(x => x.ProductInfo.Height); if (orderHeight < 5) { orderHeight = 5; } if (orderHeight > 105) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: Hight > 105: height should be in cm"); return methods; } var orderHeightCulture = decimal.Parse(orderHeight.ToString(), NumberStyles.Currency, CultureInfo.GetCultureInfo("en-AU")); var orderLength = orderInfo.OrderLines.Sum(x => x.ProductInfo.Length); if (orderLength < 5) { orderLength = 5; } if (orderLength > 105) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: Length > 105: length should be in cm"); return methods; } var widthOrLength = orderWidth; if (orderLength > orderWidth) { widthOrLength = orderLength; } var girth = 2*(Math.Round(widthOrLength, MidpointRounding.AwayFromZero) + Math.Round(orderHeight, MidpointRounding.AwayFromZero)); if (girth < 16) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: Girth < 16 (sizes should be in cm)"); return methods; } if (girth > 140) { Log.Instance.LogDebug("AUSPOST GetAllShippingMethods: Girth > 140 (sizes should be in cm)"); return methods; } var orderLengthCulture = decimal.Parse(orderLength.ToString(), NumberStyles.Currency, CultureInfo.GetCultureInfo("en-AU")); if (orderInfo.CustomerInfo.CountryCode.ToUpper() == "AU") { request.ShippingUrlBase = helper.Settings["ServiceUrlDomestic"]; request.Parameters.Add("from_postcode", postalCodeFrom); request.Parameters.Add("to_postcode", customerPostalCode); request.Parameters.Add("length", Math.Round(orderLengthCulture, 2).ToString()); request.Parameters.Add("width", Math.Round(orderWidthCulture, 2).ToString()); request.Parameters.Add("height", Math.Round(orderHeightCulture, 2).ToString()); } else { request.ShippingUrlBase = helper.Settings["ServiceUrlInternational"]; request.Parameters.Add("country_code", orderInfo.CustomerInfo.CountryCode); } request.Parameters.Add("weight", Math.Round(orderWeightCulture, 2).ToString()); var requestHeader = new WebHeaderCollection {{"AUTH-KEY", helper.Settings["authKey"]}}; Log.Instance.LogDebug("AUSPOST API URL: " + request.ShippingUrlBase); Log.Instance.LogDebug("AUSPOST API ParametersAsString: " + request.ParametersAsString); Log.Instance.LogDebug("AUSPOST API requestHeader AUTH-KEY: " + requestHeader.GetValues("AUTH-KEY")); var issuerRequest = _requestSender.GetRequest(request.ShippingUrlBase, request.ParametersAsString, requestHeader); XNamespace ns = string.Empty; var issuerXml = XDocument.Parse(issuerRequest); foreach (var service in issuerXml.Descendants(ns + "service")) { var issuerId = service.Descendants(ns + "code").First().Value; var issuerName = service.Descendants(ns + "name").First().Value; var issuerPriceValue = service.Descendants(ns + "price").First().Value; decimal issuerPrice; decimal.TryParse(issuerPriceValue, out issuerPrice); var priceInCents = issuerPrice*100; var paymentImageId = 0; var logoDictionaryItem = library.GetDictionaryItem(issuerId + "LogoId"); if (string.IsNullOrEmpty(logoDictionaryItem)) { int.TryParse(library.GetDictionaryItem(issuerId + "LogoId"), out paymentImageId); } methods.Add(new ShippingProviderMethod {Id = issuerId, Description = issuerName, Title = issuerName, Name = issuerName, ProviderName = GetName(), ImageId = paymentImageId, PriceInCents = (int) priceInCents, Vat = 21}); } return methods; }
private string MessageHeadersToString(WebHeaderCollection headers) { string[] keys = headers.AllKeys; StringBuilder result = new StringBuilder(); foreach (string key in keys) { result.AppendLine(string.Format( "{0,-30}: {1}", key, General.ArrayToString<string>(headers.GetValues(key), ","))); } return result.ToString(); }
private SetCookieParser(WebHeaderCollection headers) { parse( headers.GetValues("Set-Cookie")); }
private static void CopyHeadersFrom(this HttpResponseMessage message, WebHeaderCollection headers) { if (headers != null) { foreach (string headerName in headers) { string[] headerValues = headers.GetValues(headerName); if (!message.Headers.TryAddWithoutValidation(headerName, headerValues)) { message.Content.Headers.TryAddWithoutValidation(headerName, headerValues); } } } }
public static string HTTPFetch(string url, string method, WebHeaderCollection headers, byte[] streamBytes, int contentLength, out string[] responseFields, string contentType = "application/x-www-form-urlencoded", string requestAccept = null, string host = null) { _active = true; try { var uri = new Uri(url); if (EndpointCallback != null) EndpointCallback(uri.AbsolutePath); if (string.IsNullOrEmpty(host)) host = uri.Host; string reqStr = String.Format("{0} {1} HTTP/1.1\r\n", method, url) + String.Format("Host: {0}\r\n", host) + String.Format("Connection: Close\r\n"); if (!IsNullOrWhiteSpace(requestAccept)) reqStr += String.Format("Accept: {0}\r\n", requestAccept); if (contentType != null) reqStr += String.Format("Content-Type: {0}\r\n", contentType); if (headers != null) { for (int i = 0; i < headers.Count; ++i) { string header = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { reqStr += String.Format("{0}: {1}\r\n", header, value); } } } reqStr += String.Format("Content-Length: {0}\r\n", contentLength); reqStr += "\r\n"; byte[] headerBytes = ToByteArray(reqStr); byte[] finalBytes = headerBytes; if (contentLength > 0) { var requestBytes = new byte[headerBytes.Length + contentLength]; Buffer.BlockCopy(headerBytes, 0, requestBytes, 0, headerBytes.Length); Buffer.BlockCopy(streamBytes, 0, requestBytes, headerBytes.Length, contentLength); finalBytes = requestBytes; } string responseFromServer = ""; responseFields = new string[] { }; var tcpClient = new TcpClient(); string responseStr = ""; int responseLength = 0; if (url.ToLower().StartsWith("https")) { //HTTPS tcpClient.Connect(uri.Host, 443); ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => true); //This has a bug on mono: Message "The authentication or decryption has failed." //Therefore unfortunately we have to ignore certificates. using (var s = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => true))) { s.AuthenticateAsClient(uri.Host, null, SslProtocols.Tls, false); if (UpstreamCallback != null && UpstreamCallbackRate > 0) { int i = 0; while (i < finalBytes.Length) { if (!_active) throw new Exception("Halt"); if (i + _upstreamCallbackRate > finalBytes.Length) { s.Write(finalBytes, i, finalBytes.Length - i); UpstreamCallback(contentLength, contentLength); break; } s.Write(finalBytes, i, (int)_upstreamCallbackRate); i += (int)_upstreamCallbackRate; UpstreamCallback(Math.Min(i, contentLength), contentLength); } } else s.Write(finalBytes, 0, finalBytes.Length); s.Flush(); while (true) { var responseBytes = new byte[8192]; int i = s.Read(responseBytes, 0, responseBytes.Length); if (i == 0) break; responseStr += Encoding.UTF8.GetString(responseBytes, 0, i); responseLength += i; } } } else { //HTTP tcpClient.Connect(uri.Host, 80); if (UpstreamCallback != null && UpstreamCallbackRate > 0) { var s = tcpClient.GetStream(); int i = 0; while (i < finalBytes.Length) { if (!_active) throw new Exception("Halt"); if (i + _upstreamCallbackRate > finalBytes.Length) { s.Write(finalBytes, i, finalBytes.Length - i); UpstreamCallback(contentLength, contentLength); break; } s.Write(finalBytes, i, (int)_upstreamCallbackRate); i += (int)_upstreamCallbackRate; UpstreamCallback(Math.Min(i, contentLength), contentLength); } } else tcpClient.Client.Send(finalBytes); while (true) { var responseBytes = new byte[8192]; int i = tcpClient.Client.Receive(responseBytes); if (i == 0) break; responseStr += Encoding.UTF8.GetString(responseBytes, 0, i); responseLength += i; } } tcpClient.Close(); var bodyPos = responseStr.IndexOf("\r\n\r\n"); if (bodyPos >= 0) { responseFields = responseStr.Substring(0, bodyPos).Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); bodyPos += 4; responseFromServer = responseStr.Substring(bodyPos, responseStr.Length - bodyPos); } Debug.WriteLine(String.Format("Response from URL {0}:", url), "HTTPFetch"); Debug.WriteLine(responseFromServer, "HTTPFetch"); if (VerboseCallback != null) { VerboseCallback(String.Format("Response from URL {0}:", url)); VerboseCallback(responseFromServer); } return responseFromServer; } catch (Exception e) { _active = false; throw e; } }
public override string GetHeader(WebHeaderCollection headers, string name, Func<string, bool> valuePredicate) { var values = headers.GetValues(name); return values == null ? null : values.FirstOrDefault(valuePredicate); }
private static List<string> GetHeaderValues(WebHeaderCollection headers, string headerName) { var list = new List<string>(); var values = headers.GetValues(headerName); if (values != null) { foreach (string value in values) { list.Add(value.TrimStart(new char[0])); } } return list; }
private static IEnumerable<KeyValuePair<string, IEnumerable<string>>> ConvertHeaders( WebHeaderCollection webHeaders) { for (var i = 0; i < webHeaders.Count; i++) { var key = webHeaders.GetKey(i); yield return new KeyValuePair<string, IEnumerable<string>>(key, webHeaders.GetValues(i)); } }
public HttpAuthenticationHeader(WebHeaderCollection headers) { authenticationSchemes = headers.GetValues("WWW-Authenticate"); }
bool CreateTunnel(HttpWebRequest request, Uri connectUri, Stream stream, out byte[] buffer) { StringBuilder sb = new StringBuilder(); sb.Append("CONNECT "); sb.Append(request.Address.Host); sb.Append(':'); sb.Append(request.Address.Port); sb.Append(" HTTP/"); if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11) { sb.Append("1.1"); } else { sb.Append("1.0"); } sb.Append("\r\nHost: "); sb.Append(request.Address.Authority); bool ntlm = false; var challenge = Data.Challenge; Data.Challenge = null; var auth_header = request.Headers ["Proxy-Authorization"]; bool have_auth = auth_header != null; if (have_auth) { sb.Append("\r\nProxy-Authorization: "); sb.Append(auth_header); ntlm = auth_header.ToUpper().Contains("NTLM"); } else if (challenge != null && Data.StatusCode == 407) { ICredentials creds = request.Proxy.Credentials; have_auth = true; if (connect_request == null) { // create a CONNECT request to use with Authenticate connect_request = (HttpWebRequest)WebRequest.Create( connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/"); connect_request.Method = "CONNECT"; connect_request.Credentials = creds; } if (creds != null) { for (int i = 0; i < challenge.Length; i++) { var auth = AuthenticationManager.Authenticate(challenge [i], connect_request, creds); if (auth == null) { continue; } ntlm = (auth.ModuleAuthenticationType == "NTLM"); sb.Append("\r\nProxy-Authorization: "); sb.Append(auth.Message); break; } } } if (ntlm) { sb.Append("\r\nProxy-Connection: keep-alive"); connect_ntlm_auth_state++; } sb.Append("\r\n\r\n"); Data.StatusCode = 0; byte [] connectBytes = Encoding.Default.GetBytes(sb.ToString()); stream.Write(connectBytes, 0, connectBytes.Length); int status; WebHeaderCollection result = ReadHeaders(stream, out buffer, out status); if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) && result != null && status == 407) // Needs proxy auth { var connectionHeader = result ["Connection"]; if (socket != null && !string.IsNullOrEmpty(connectionHeader) && connectionHeader.ToLower() == "close") { // The server is requesting that this connection be closed socket.Close(); socket = null; } Data.StatusCode = status; Data.Challenge = result.GetValues("Proxy-Authenticate"); Data.Headers = result; return(false); } if (status != 200) { Data.StatusCode = status; Data.Headers = result; return(false); } return(result != null); }
static Uri FindXrdDocumentLocationInHeaders(WebHeaderCollection headers) { Uri xrdUrl = null; string[] links = headers.GetValues("link"); if (links != null && links.Length > 0) { for (int i = 0; i < links.Length; i++) { string link = links[i]; if (link.Contains("rel=\"describedby\"")) { if (Uri.TryCreate(Regex.Replace(link, @"^.*<(.*?)>.*$", "$1"), UriKind.Absolute, out xrdUrl)) break; } } } return xrdUrl; }
static string FormatHeaders (WebHeaderCollection headers) { var sb = new StringBuilder(); for (int i = 0; i < headers.Count ; i++) { string key = headers.GetKey (i); if (WebHeaderCollection.AllowMultiValues (key)) { foreach (string v in headers.GetValues (i)) { sb.Append (key).Append (": ").Append (v).Append ("\r\n"); } } else { sb.Append (key).Append (": ").Append (headers.Get (i)).Append ("\r\n"); } } return sb.Append("\r\n").ToString(); }