Ejemplo n.º 1
0
        public void PostMultipart()
        {
            var  httpHandler       = new TestWebRequestHandler();
            bool callbackTriggered = false;

            httpHandler.Callback = req => {
                Match m = Regex.Match(req.ContentType, "multipart/form-data; boundary=(.+)");
                Assert.IsTrue(m.Success, "Content-Type HTTP header not set correctly.");
                string boundary = m.Groups[1].Value;
                boundary = boundary.Substring(0, boundary.IndexOf(';'));                 // trim off charset
                string expectedEntity = "--{0}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n--{0}--\r\n";
                expectedEntity = string.Format(expectedEntity, boundary);
                string actualEntity = httpHandler.RequestEntityAsString;
                Assert.AreEqual(expectedEntity, actualEntity);
                callbackTriggered = true;
                Assert.AreEqual(req.ContentLength, actualEntity.Length);
                IncomingWebResponse resp = new CachedDirectWebResponse();
                return(resp);
            };
            var request = (HttpWebRequest)WebRequest.Create("http://someserver");
            var parts   = new[] {
                MultipartPostPart.CreateFormPart("a", "b"),
            };

            request.PostMultipart(httpHandler, parts);
            Assert.IsTrue(callbackTriggered);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Determines whether a given HTTP response constitutes an XRDS document.
        /// </summary>
        /// <param name="response">The response to test.</param>
        /// <returns>
        ///     <c>true</c> if the response constains an XRDS document; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsXrdsDocument(CachedDirectWebResponse response)
        {
            if (response.ContentType == null)
            {
                return(false);
            }

            if (response.ContentType.MediaType == ContentTypes.Xrds)
            {
                return(true);
            }

            if (response.ContentType.MediaType == ContentTypes.Xml)
            {
                // This COULD be an XRDS document with an imprecise content-type.
                response.ResponseStream.Seek(0, SeekOrigin.Begin);
                XmlReader reader = XmlReader.Create(response.ResponseStream);
                while (reader.Read() && reader.NodeType != XmlNodeType.Element)
                {
                    // intentionally blank
                }
                if (reader.NamespaceURI == XrdsNode.XrdsNamespace && reader.Name == "XRDS")
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Reverts to the HTML response after the XRDS response didn't work out.
 /// </summary>
 internal void TryRevertToHtmlResponse()
 {
     if (this.htmlFallback != null)
     {
         this.ApplyHtmlResponse(this.htmlFallback);
         this.htmlFallback = null;
     }
 }
Ejemplo n.º 4
0
        internal void RegisterMockRedirect(Uri origin, Uri redirectLocation)
        {
            var redirectionHeaders = new WebHeaderCollection {
                { HttpResponseHeader.Location, redirectLocation.AbsoluteUri },
            };
            IncomingWebResponse response = new CachedDirectWebResponse(origin, origin, redirectionHeaders, HttpStatusCode.Redirect, null, null, new MemoryStream());

            this.RegisterMockResponse(response);
        }
Ejemplo n.º 5
0
        public void DirectResponsesReceivedAsKeyValueForm()
        {
            var fields = new Dictionary <string, string> {
                { "var1", "value1" },
                { "var2", "value2" },
            };
            var response = new CachedDirectWebResponse {
                CachedResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)),
            };

            Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.channel.ReadFromResponseCoreTestHook(response)));
        }
Ejemplo n.º 6
0
        internal void RegisterMockNotFound(Uri requestUri)
        {
            CachedDirectWebResponse errorResponse = new CachedDirectWebResponse(
                requestUri,
                requestUri,
                new WebHeaderCollection(),
                HttpStatusCode.NotFound,
                "text/plain",
                Encoding.UTF8.WebName,
                new MemoryStream(Encoding.UTF8.GetBytes("Not found.")));

            this.RegisterMockResponse(errorResponse);
        }
Ejemplo n.º 7
0
        private void ParameterizedRequestTest(HttpDeliveryMethods scheme)
        {
            TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct)
            {
                Age         = 15,
                Name        = "Andrew",
                Location    = new Uri("http://hostb/pathB"),
                Recipient   = new Uri("http://localtest"),
                Timestamp   = DateTime.UtcNow,
                HttpMethods = scheme,
            };

            CachedDirectWebResponse rawResponse = null;

            this.webRequestHandler.Callback = (req) => {
                Assert.IsNotNull(req);
                HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream);
                Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod);
                var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage;
                Assert.IsNotNull(incomingMessage);
                Assert.AreEqual(request.Age, incomingMessage.Age);
                Assert.AreEqual(request.Name, incomingMessage.Name);
                Assert.AreEqual(request.Location, incomingMessage.Location);
                Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp);

                var responseFields = new Dictionary <string, string> {
                    { "age", request.Age.ToString() },
                    { "Name", request.Name },
                    { "Location", request.Location.AbsoluteUri },
                    { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) },
                };
                rawResponse = new CachedDirectWebResponse();
                rawResponse.SetResponse(MessagingUtilities.CreateQueryString(responseFields));
                return(rawResponse);
            };

            IProtocolMessage response = this.channel.Request(request);

            Assert.IsNotNull(response);
            Assert.IsInstanceOf <TestMessage>(response);
            TestMessage responseMessage = (TestMessage)response;

            Assert.AreEqual(request.Age, responseMessage.Age);
            Assert.AreEqual(request.Name, responseMessage.Name);
            Assert.AreEqual(request.Location, responseMessage.Location);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DiscoveryResult"/> class.
 /// </summary>
 /// <param name="requestUri">The user-supplied identifier.</param>
 /// <param name="initialResponse">The initial response.</param>
 /// <param name="finalResponse">The final response.</param>
 public DiscoveryResult(Uri requestUri, CachedDirectWebResponse initialResponse, CachedDirectWebResponse finalResponse)
 {
     this.RequestUri    = requestUri;
     this.NormalizedUri = initialResponse.FinalUri;
     if (finalResponse == null)
     {
         this.ContentType  = initialResponse.ContentType;
         this.ResponseText = initialResponse.Body;
         this.IsXrds       = ContentType.MediaType == ContentTypes.Xrds;
     }
     else
     {
         this.ContentType  = finalResponse.ContentType;
         this.ResponseText = finalResponse.Body;
         this.IsXrds       = true;
         if (initialResponse != finalResponse)
         {
             this.YadisLocation = finalResponse.RequestUri;
         }
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DiscoveryResult"/> class.
        /// </summary>
        /// <param name="requestUri">The user-supplied identifier.</param>
        /// <param name="initialResponse">The initial response.</param>
        /// <param name="finalResponse">The final response.</param>
        public DiscoveryResult(Uri requestUri, CachedDirectWebResponse initialResponse, CachedDirectWebResponse finalResponse)
        {
            this.RequestUri    = requestUri;
            this.NormalizedUri = initialResponse.FinalUri;
            if (finalResponse == null || finalResponse.Status != System.Net.HttpStatusCode.OK)
            {
                this.ApplyHtmlResponse(initialResponse);
            }
            else
            {
                this.ContentType  = finalResponse.ContentType;
                this.ResponseText = finalResponse.GetResponseString();
                this.IsXrds       = true;
                if (initialResponse != finalResponse)
                {
                    this.YadisLocation = finalResponse.RequestUri;
                }

                // Back up the initial HTML response in case the XRDS is not useful.
                this.htmlFallback = initialResponse;
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Performs YADIS discovery on some identifier.
        /// </summary>
        /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param>
        /// <param name="uri">The URI to perform discovery on.</param>
        /// <param name="requireSsl">Whether discovery should fail if any step of it is not encrypted.</param>
        /// <returns>
        /// The result of discovery on the given URL.
        /// Null may be returned if an error occurs,
        /// or if <paramref name="requireSsl"/> is true but part of discovery
        /// is not protected by SSL.
        /// </returns>
        public static DiscoveryResult Discover(IDirectWebRequestHandler requestHandler, UriIdentifier uri, bool requireSsl)
        {
            CachedDirectWebResponse response;

            try {
                if (requireSsl && !string.Equals(uri.Uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                {
                    Logger.WarnFormat("Discovery on insecure identifier '{0}' aborted.", uri);
                    return(null);
                }
                response = Request(requestHandler, uri, requireSsl, ContentTypes.Html, ContentTypes.XHtml, ContentTypes.Xrds).GetSnapshot(MaximumResultToScan);
                if (response.Status != System.Net.HttpStatusCode.OK)
                {
                    Logger.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response.Status, response.Status, uri);
                    return(null);
                }
            } catch (ArgumentException ex) {
                // Unsafe URLs generate this
                Logger.WarnFormat("Unsafe OpenId URL detected ({0}).  Request aborted.  {1}", uri, ex);
                return(null);
            }
            CachedDirectWebResponse response2 = null;

            if (IsXrdsDocument(response))
            {
                Logger.Debug("An XRDS response was received from GET at user-supplied identifier.");
                response2 = response;
            }
            else
            {
                string uriString = response.Headers.Get(HeaderName);
                Uri    url       = null;
                if (uriString != null)
                {
                    if (Uri.TryCreate(uriString, UriKind.Absolute, out url))
                    {
                        Logger.DebugFormat("{0} found in HTTP header.  Preparing to pull XRDS from {1}", HeaderName, url);
                    }
                }
                if (url == null && response.ContentType.MediaType == ContentTypes.Html)
                {
                    url = FindYadisDocumentLocationInHtmlMetaTags(response.Body);
                    if (url != null)
                    {
                        Logger.DebugFormat("{0} found in HTML Http-Equiv tag.  Preparing to pull XRDS from {1}", HeaderName, url);
                    }
                }
                if (url != null)
                {
                    if (!requireSsl || string.Equals(url.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                    {
                        response2 = Request(requestHandler, url, requireSsl, ContentTypes.Xrds).GetSnapshot(MaximumResultToScan);
                        if (response2.Status != HttpStatusCode.OK)
                        {
                            Logger.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response2.Status, response2.Status, uri);
                            return(null);
                        }
                    }
                    else
                    {
                        Logger.WarnFormat("XRDS document at insecure location '{0}'.  Aborting YADIS discovery.", url);
                    }
                }
            }
            return(new DiscoveryResult(uri, response, response2));
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Applies the HTML response to the object.
 /// </summary>
 /// <param name="initialResponse">The initial response.</param>
 private void ApplyHtmlResponse(CachedDirectWebResponse initialResponse)
 {
     this.ContentType  = initialResponse.ContentType;
     this.ResponseText = initialResponse.GetResponseString();
     this.IsXrds       = this.ContentType != null && this.ContentType.MediaType == ContentTypes.Xrds;
 }