Esempio n. 1
0
        private double IsMatch(IRequestMessage requestMessage)
        {
            if (requestMessage.Cookies == null)
            {
                return(MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch));
            }

            // Check if we want to use IgnoreCase to compare the Cookie-Name and Cookie-Value
            var cookies = !_ignoreCase ? requestMessage.Cookies : new Dictionary <string, string>(requestMessage.Cookies, StringComparer.OrdinalIgnoreCase);

            if (Funcs != null)
            {
                return(MatchScores.ToScore(Funcs.Any(f => f(cookies))));
            }

            if (Matchers == null)
            {
                return(MatchScores.Mismatch);
            }

            if (!cookies.ContainsKey(Name))
            {
                return(MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch));
            }

            string value = cookies[Name];

            return(Matchers.Max(m => m.IsMatch(value)));
        }
Esempio n. 2
0
        public override IResponseMessage OnTextRequest(IRequestMessage requestMessage)
        {
            var art1 = new ResponseMessageInnerType.Article
            {
                Title       = "ESAP第十四弹 手把手教你玩转ES微信开发",
                Description = "来自村长的ESAP系统最新技术分享。",
                PicUrl      = "http://iesap.net/wp-content/uploads/2015/12/esap3-1.jpg",
                Url         = "http://iesap.net/index.php/2015/12/28/esap14/"
            };
            var art2 = new ResponseMessageInnerType.Article
            {
                Title       = "打通信息化的“任督二脉”(二)",
                Description = "来自村长的ESAP2.0系统技术分享。",
                PicUrl      = "http://iesap.net/wp-content/uploads/2015/12/taiji.jpg",
                Url         = "http://iesap.net/index.php/2015/12/16/esap2-1/"
            };
            var art3 = new ResponseMessageInnerType.Article
            {
                Title       = "打通信息化的“任督二脉”(一)",
                Description = "来自村长的ESAP2.0系统技术分享。",
                PicUrl      = "http://iesap.net/wp-content/uploads/2015/12/rdem.jpg",
                Url         = "http://iesap.net/index.php/2015/12/11/esap2-0/"
            };

            var responseMessage = ResponseMessage.CreateFromRequestMessage(requestMessage, QY.Enums.ResponseType.News);

            responseMessage.Articles.Add(art1);
            responseMessage.Articles.Add(art2);
            responseMessage.Articles.Add(art3);
            return(responseMessage);
        }
Esempio n. 3
0
        public MessageProcessorHandle Process(IRequestMessage requestMessage)
        {
            var handle = new MessageProcessorHandle(requestMessage);

            queue.Post(handle);
            return(handle);
        }
        protected override void OnIncomingHandlableMessage(IRequestMessage message, EntityInteractionRequestPayload payload, IMessageParameters parameters, InstanceClientSession peer)
        {
            if (Logger.IsDebugEnabled)
            {
                Logger.Debug($"Recieved interaction request for {payload.NetworkGuid.EntityId}.");
            }

            if (EntityCollection.ContainsKey(payload.NetworkGuid))
            {
                IWorldInteractable interactable = EntityCollection[payload.NetworkGuid]?.WorldObject?.GetComponent <IWorldInteractable>();

                if (interactable == null)
                {
                    if (Logger.IsWarnEnabled)
                    {
                        Logger.Warn($"Recieved interaction request for entity that can't be interacted with ID: {payload.NetworkGuid.EntityId} Type: {payload.NetworkGuid.EntityType} from NetId: {peer.PeerDetails.ConnectionID}.");
                    }
                }
                else
                {
                    interactable.TryInteract(GuidLookupService.Lookup(peer.PeerDetails.ConnectionID));
                }
            }
            else
            if (Logger.IsWarnEnabled)
            {
                Logger.Warn($"Recieved interaction request for unknown entity ID: {payload.NetworkGuid.EntityId} Type: {payload.NetworkGuid.EntityType} from NetId: {peer.PeerDetails.ConnectionID}.");
            }
        }
Esempio n. 5
0
        private double IsMatch(IRequestMessage requestMessage)
        {
            if (Funcs != null)
            {
                return(MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query))));
            }

            WireMockList <string> valuesPresentInRequestMessage = ((RequestMessage)requestMessage).GetParameter(Key, IgnoreCase ?? false);

            if (valuesPresentInRequestMessage == null)
            {
                // Key is not present at all, just return Mismatch
                return(MatchScores.Mismatch);
            }

            if (Matchers != null && Matchers.Any())
            {
                // Return the score based on Matchers and valuesPresentInRequestMessage
                return(CalculateScore(valuesPresentInRequestMessage));
            }

            if (Matchers == null || !Matchers.Any())
            {
                // Matchers are null or not defined, and Key is present, just return Perfect.
                return(MatchScores.Perfect);
            }

            return(MatchScores.Mismatch);
        }
Esempio n. 6
0
        public static void GetLatestVersionOfPass(IRequestMessage request, IResponseMessage response)
        {
            Pass pass;

            using (Repository repository = new Repository())
            {
                pass = repository.GetPass(
                    request.RouteValue<string>("passTypeIdentifier"),
                    request.RouteValue<string>("serialNumber"));
            }

            if (pass != null)
            {
                if (pass.LastUpdated > request.Headers.Get<DateTime>("If-Modified-Since"))
                {
                    response.ResponseObject = pass.Data;
                }
                else
                {
                    response.SetStatus(StatusCode.NotModified);
                }
            }
            else
            {
                response.SetStatus(StatusCode.NotFound);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Makes a synchronous request
        ///
        /// Note that this block the application run
        /// It is recommended to use Request<R>(IRequestMessage, Action<R>) instead
        /// as that does not block the current thread and has a callback action instead
        /// </summary>
        /// <typeparam name="R"></typeparam>
        /// <param name="pRequest"></param>
        /// <returns></returns>
        public R Request <R>(IRequestMessage pRequest) where R : IResponseMessage
        {
            var objTask = RequestAsync <R>(pRequest);

            objTask.Wait();
            return(objTask.Result);
        }
Esempio n. 8
0
        /// <summary>
        /// Returns true if there is an Authorization HTTP header present in the request, the header has a scheme
        /// that is "hawk" and that the parameter in the header is not empty.
        /// </summary>
        internal static bool HasValidHawkScheme(this IRequestMessage request)
        {
            var header = request.Authorization;

            return(header != null && header.Scheme.ToLower() == HawkConstants.Scheme &&
                   !String.IsNullOrWhiteSpace(header.Parameter));
        }
        /// <summary>
        /// Creates the HTTP Authorization header in hawk scheme.
        /// </summary>
        internal async Task CreateClientAuthorizationInternalAsync(IRequestMessage request, DateTime utcNow)
        {
            var credential = options.CredentialsCallback();

            this.artifacts = new ArtifactsContainer()
            {
                Id        = credential.Id,
                Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(),
                Nonce     = NonceGenerator.Generate()
            };

            if (options.NormalizationCallback != null)
            {
                this.artifacts.ApplicationSpecificData = options.NormalizationCallback(request);
            }

            var normalizedRequest = new NormalizedRequest(request, this.artifacts, options.HostNameSource);

            this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential);

            // Sign the request
            bool includePayloadHash = options.RequestPayloadHashabilityCallback != null &&
                                      options.RequestPayloadHashabilityCallback(request);

            string payload = includePayloadHash ? await request.ReadBodyAsStringAsync() : null;

            crypto.Sign(payload, request.ContentType);

            request.Authorization = new AuthenticationHeaderValue(HawkConstants.Scheme,
                                                                  this.artifacts.ToAuthorizationHeaderParameter());
        }
Esempio n. 10
0
        public async Task <IResponseMessage> SendAsync(IRequestMessage requestMessage)
        {
            try
            {
                var response = await dummyResponderClient.RipostAsync(new Request()
                {
                    Message = requestMessage.Message
                }, null);

                return(new ResponseMessage()
                {
                    Message = response.Message
                });
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.InvalidArgument)
            {
                return(new ResponseMessage()
                {
                    Message = ex.Status.Detail
                });
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.Aborted)
            {
                channel.Dispose();
                channel = GrpcChannel.ForAddress("https://localhost:5001");

                dummyResponderClient = new DummyResponder.DummyResponderClient(channel);

                return(new ResponseMessage()
                {
                    Message = ex.Status.Detail
                });
            }
        }
Esempio n. 11
0
        public IDisposable SubscribeToEvent(
            IRequestMessage <SubscribeRequest> subscribeRequest,
            IObservable <IEventMessage <IEventData> > hotMessages,
            IObservable <IEventMessage <IEventData> > replayMessages)
        {
            _isUsingOldEventSubscription = false;

            var subscribeResponse = new SubscribeResponse();

            _outStream.OnNext(Response.CreateSuccess(subscribeRequest, subscribeResponse));

            var subscribeArgs = subscribeRequest.Arguments;

            if (subscribeArgs.Replay)
            {
                return(replayMessages
                       .Where(d => EventTypeMatchesFilter(d.Name, subscribeRequest.Arguments.Filter))
                       .Subscribe(
                           data => _outStream.OnNext(new Event <IEventData>(data.Name, data.Data, subscribeArgs.SubscriptionId))));
            }
            else
            {
                return(hotMessages
                       .Where(d => EventTypeMatchesFilter(d.Name, subscribeRequest.Arguments.Filter))
                       .Subscribe(
                           data => _outStream.OnNext(new Event <IEventData>(data.Name, data.Data, subscribeArgs.SubscriptionId))));
            }
        }
Esempio n. 12
0
 private void NotifyRequest(IRequestMessage request, string message)
 {
     if (!(request is InvalidRequestStrategy))
     {
         _notification.Info("Client is trying to say", message);
     }
 }
Esempio n. 13
0
        private async Task ResponseToRequest(IRequestMessage strategy, string message)
        {
            NotifyRequest(strategy, message);
            var response = await strategy.Send();

            _notification.Success("Server Replied", response.Message);
        }
Esempio n. 14
0
 public RequestLog(IRequestMessage message, int playerId, TeamColor color, PlayerType role)
 {
     Message  = message;
     PlayerId = playerId;
     Color    = color;
     Role     = role;
 }
        private double IsMatch(IRequestMessage requestMessage)
        {
            if (requestMessage.Headers == null)
            {
                return(MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch));
            }

            // Check if we want to use IgnoreCase to compare the Header-Name and Header-Value(s)
            var headers = !_ignoreCase ? requestMessage.Headers : new Dictionary <string, WireMockList <string> >(requestMessage.Headers, StringComparer.OrdinalIgnoreCase);

            if (Funcs != null)
            {
                return(MatchScores.ToScore(Funcs.Any(f => f(headers.ToDictionary(entry => entry.Key, entry => entry.Value.ToArray())))));
            }

            if (Matchers == null)
            {
                return(MatchScores.Mismatch);
            }

            if (!headers.ContainsKey(Name))
            {
                return(MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch));
            }

            WireMockList <string> list = headers[Name];

            return(Matchers.Max(m => list.Max(m.IsMatch))); // TODO : is this correct ?
        }
            public async Task ShouldStopClientAndThrowExceptionWhenProtocolErrorOccurs()
            {
                using (var harness = new SocketClientTestHarness(FakeUri, null))
                {
                    var messages = new IRequestMessage[]
                    {
                        new RunMessage("This will cause a syntax error"),
                        new PullAllMessage()
                    };

                    var messageHandler = new TestResponseHandler();

                    messageHandler.Register(new InitMessage("MyClient/1.1", new Dictionary <string, object>()));
                    messageHandler.Register(messages[0], new ResultBuilder());
                    messageHandler.Register(messages[1], new ResultBuilder());

                    harness.SetupReadStream("00 00 00 01" +
                                            "00 03 b1 70 a0 00 00");

                    harness.SetupWriteStream();

                    await harness.Client.Start();

                    messageHandler.Error = new ClientException("Neo.ClientError.Request.Invalid", "Test Message");

                    // When
                    var ex = Record.Exception(() => harness.Client.Send(messages, messageHandler));
                    ex.Should().BeOfType <ClientException>();

                    harness.MockTcpSocketClient.Verify(x => x.DisconnectAsync(), Times.Once);
                    harness.MockTcpSocketClient.Verify(x => x.Dispose(), Times.Once);
                }
            }
Esempio n. 17
0
        internal OwinListenerContext(ConnectionInfo listenerContext, IRequestMessage request)
        {
            _listenerContext = listenerContext;
            _environment     = new CallEnvironment
            {
                { Constants.RequestScheme, "" },//Uri.UriSchemeHttp
                { Constants.RequestMethod, "" },
                { Constants.RequestPathBase, "" },
                { Constants.RequestPath, "" },
                { Constants.RequestQueryString, "" },
                { Constants.RequestProtocol, "" },
                { Constants.RequestHeaders, new RequestHeadersDictionary(request) },
                { Constants.RequestBody, new ListenerStreamWrapper(request.InputStream) },

                { Constants.ResponseStatusCode, (int)HttpStatusCode.OK },
                { Constants.ResponseBody, new ListenerStreamWrapper(new MemoryStream()) },
                { Constants.ResponseHeaders, new ResponseHeadersDictionary() },

                { Constants.OwinVersion, "" },
                { Constants.CallCancelled, GetCallCancelled() },

                { Constants.CommonKeys.RemoteIpAddress, "" },
                { Constants.CommonKeys.RemotePort, "" },
                { Constants.CommonKeys.LocalIpAddress, "" },
                { Constants.CommonKeys.LocalPort, "" },
                { Constants.CommonKeys.IsLocal, "" }
            };

            var user     = new ClaimsPrincipal();
            var Identity = new ClaimsIdentity("session");

            Identity.AddClaim(new Claim(ClaimTypes.Sid, _listenerContext.SessionId));
            user.AddIdentity(Identity);
            _environment.Add(Constants.Security.User, user);
        }
Esempio n. 18
0
 public MessageContext(MessageType messageType, IRequestMessage request, string body, MessageEventType?eventType = null)
 {
     MessageType = messageType;
     Request     = request;
     Body        = body;
     EventType   = eventType;
 }
Esempio n. 19
0
        /// <summary>
        /// Returns true, if a query string parameter with a name of 'bewit' exists and that there
        /// is no HTTP Authorization header present in the request. Also, returns the value of the
        /// bewit parameter from the query string.
        /// </summary>
        internal static bool TryGetBewit(IRequestMessage request, out string bewit)
        {
            bewit = HttpUtility.ParseQueryString(request.Uri.Query)[HawkConstants.Bewit];

            return(!String.IsNullOrWhiteSpace(bewit) &&
                   (request.Authorization == null));
        }
        internal RequestHeadersDictionary(IRequestMessage request)
            : base()
        {
            _request = request;

            Headers = _request.Headers;
        }
        private double CalculateMatchScore(IRequestMessage requestMessage, IMatcher matcher)
        {
            // Check if the matcher is a IObjectMatcher
            if (matcher is IObjectMatcher objectMatcher)
            {
                // If the body is a JSON object, try to match.
                if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
                {
                    return(objectMatcher.IsMatch(requestMessage.BodyData.BodyAsJson));
                }

                // If the body is a byte array, try to match.
                if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Bytes)
                {
                    return(objectMatcher.IsMatch(requestMessage.BodyData.BodyAsBytes));
                }
            }

            // Check if the matcher is a IStringMatcher
            if (matcher is IStringMatcher stringMatcher)
            {
                // If the body is a Json or a String, use the BodyAsString to match on.
                if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json || requestMessage?.BodyData?.DetectedBodyType == BodyType.String)
                {
                    return(stringMatcher.IsMatch(requestMessage.BodyData.BodyAsString));
                }
            }

            return(MatchScores.Mismatch);
        }
 /// <summary>
 /// Returns true, if a query string parameter with a name of 'bewit' exists and that there
 /// is no HTTP Authorization header present in the request. Also, returns the value of the
 /// bewit parameter from the query string.
 /// </summary>
 internal static bool TryGetBewit(IRequestMessage request, out string bewit)
 {
     bewit = HttpUtility.ParseQueryString(request.Uri.Query)[HawkConstants.Bewit];
     
     return !String.IsNullOrWhiteSpace(bewit) &&
                 (request.Authorization == null);
 }
Esempio n. 23
0
            public async Task ShouldStopClientAndThrowExceptionWhenProtocolErrorOccurs()
            {
                using (var harness = new SocketClientTestHarness(FakeUri))
                {
                    var messages = new IRequestMessage[]
                    {
                        new RunMessage("Any message"),
                    };

                    var messageHandler = new TestResponseHandler();

                    messageHandler.EnqueueMessage(messages[0]);
                    harness.SetupReadStream("00 00 00 01" +
                                            "00 02 b0 7e 00 00"); // read whatever message but not success

                    harness.SetupWriteStream();

                    await harness.Client.Start();

                    // force to recive an error
                    messageHandler.Error = new ClientException("Neo.ClientError.Request.Invalid", "Test Message");

                    // When
                    harness.Client.Send(messages);
                    var ex = Record.Exception(() => harness.Client.Receive(messageHandler));
                    ex.Should().BeOfType <ClientException>();

                    harness.MockTcpSocketClient.Verify(x => x.DisconnectAsync(), Times.Once);
                    harness.MockTcpSocketClient.Verify(x => x.Dispose(), Times.Once);
                }
            }
Esempio n. 24
0
 public override void WriteAndFlushAsync(IRequestMessage message)
 {
     if (OnRead != null)
     {
         this.OnRead(this, MessageFactory.Fake(message));
     }
 }
Esempio n. 25
0
 static void LogRequest(IRequestMessage request)
 {
     if (Services.IsRegistered(typeof(ILogQueue)))
     {
         Services.Create <ILogQueue>().LogQueueMessage(request);
     }
 }
Esempio n. 26
0
            public async Task ShouldCreateExceptionWhenErrorReceivedFromDatabase()
            {
                using (var harness = new SocketClientTestHarness(FakeUri, null))
                {
                    var messages       = new IRequestMessage[] { new RunMessage("This will cause a syntax error") };
                    var messageHandler = new MessageResponseHandler();
                    messageHandler.EnqueueMessage(new InitMessage("MyClient/1.1", new Dictionary <string, object>()));
                    messageHandler.EnqueueMessage(messages[0], new ResultBuilder());

                    harness.SetupReadStream("00 00 00 01" +
                                            "00 03 b1 70 a0 00 00" +
                                            "00a0b17fa284636f6465d0274e656f2e436c69656e744572726f722e53746174656d656e742e496e76616c696453796e746178876d657373616765d065496e76616c696420696e707574202754273a206578706563746564203c696e69743e20286c696e6520312c20636f6c756d6e203120286f66667365743a203029290a22546869732077696c6c20636175736520612073796e746178206572726f72220a205e0000");

                    harness.SetupWriteStream();

                    await harness.Client.Start();

                    harness.ResetCalls();

                    // When
                    harness.Client.Send(messages);
                    Record.Exception(() => harness.Client.Receive(messageHandler));

                    // Then
                    harness.VerifyWriteStreamUsages(2 /*write + flush*/);

                    messageHandler.HasError.Should().BeTrue();
                    messageHandler.Error.Code.Should().Be("Neo.ClientError.Statement.InvalidSyntax");
                    messageHandler.Error.Message.Should().Be(
                        "Invalid input 'T': expected <init> (line 1, column 1 (offset: 0))\n\"This will cause a syntax error\"\n ^");
                }
            }
Esempio n. 27
0
        private double CalculateMatchScore(IRequestMessage requestMessage)
        {
            if (Matchers != null && Matchers.Any())
            {
                return(Matchers.Max(matcher => CalculateMatchScore(requestMessage, matcher)));
            }

            if (Func != null)
            {
                return(MatchScores.ToScore(Func(requestMessage?.BodyData?.BodyAsString)));
            }

            if (JsonFunc != null)
            {
                return(MatchScores.ToScore(JsonFunc(requestMessage?.BodyData?.BodyAsJson)));
            }

            if (DataFunc != null)
            {
                return(MatchScores.ToScore(DataFunc(requestMessage?.BodyData?.BodyAsBytes)));
            }

            if (BodyDataFunc != null)
            {
                return(MatchScores.ToScore(BodyDataFunc(requestMessage?.BodyData)));
            }

            return(MatchScores.Mismatch);
        }
Esempio n. 28
0
        /// <summary>
        /// Handles incoming message in lidgren format.
        /// </summary>
        /// <param name="message">Message to handle.</param>
        public virtual void HandleIncomingMessage(NetIncomingMessage message)
        {
            IMessage imessage;

            try
            {
                CryptoProviderResolver.Resolve(message.SenderEndPoint)?.Decrypt(message);
                imessage = DeserializeMessage(message.ReadBytes(message.LengthBytes));
            }
            catch (Exception)
            {
                // If a message can't be deserialized / decrypted, it's fair to assume
                // it's either malicious or accidental, and so it should be ignored. We especially
                // don't want any malicious messages to raise exceptions that would crash the
                // message loop.
                return;
            }
            IRequestMessage request = imessage as IRequestMessage;

            if (request != null && InterfaceResolver.SenderEndPointIsExpectedByInterface(request))
            {
                // Modified such that interface method names that end in _ will provide the Client's IP
                object[] args2 = new object[request.Args?.Length + 1 ?? 1];
                request.Args?.CopyTo(args2, 0);
                args2[args2.Length - 1] = message.SenderEndPoint;
                request.Args            = args2;
            }
            OnReceive(imessage);
        }
Esempio n. 29
0
        public async Task <IInventoryServiceCompletedMessage> PerformOperation(IRequestMessage request, Task <OperationResult <IRealTimeInventory> > response, IRealTimeInventory originalInventory)
        {
            var perf = new TestPerformanceService();

            perf.Init();
            return((await response).ProcessAndSendResult(request, CompletedMessageFactory.GetResponseCompletedMessage(request), originalInventory, null, perf).InventoryServiceCompletedMessage);
        }
            internal static Tuple <string, string> DetermineHostDetails(IRequestMessage request)
            {
                string host = request.Headers.FirstOrDefault("X-Forwarded-Host");

                HawkEventSource.Log.Debug("X-Forwarded-Host=" + (host ?? String.Empty));

                if (String.IsNullOrWhiteSpace(host))
                {
                    host = request.Host;
                }

                HawkEventSource.Log.Debug("Host=" + (host ?? String.Empty));

                if (String.IsNullOrWhiteSpace(host))
                {
                    host = request.Uri.Host;
                }

                string hostName = String.Empty;
                string port     = String.Empty;

                string pattern = @"^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$";
                var    match   = Regex.Match(host, pattern);

                if (match.Success && match.Groups.Count == 3)
                {
                    hostName = match.Groups[1].Value;

                    if (!String.IsNullOrWhiteSpace(hostName))
                    {
                        port = match.Groups[2].Value;
                    }
                }

                if (String.IsNullOrWhiteSpace(port))
                {
                    port = request.Headers.FirstOrDefault("X-Forwarded-Port");

                    HawkEventSource.Log.Debug("X-Forwarded-Port=" + (port ?? String.Empty));
                }

                if (String.IsNullOrWhiteSpace(port))
                {
                    string scheme = request.Headers.FirstOrDefault("X-Forwarded-Proto");

                    HawkEventSource.Log.Debug("X-Forwarded-Proto=" + (scheme ?? String.Empty));

                    if (String.IsNullOrWhiteSpace(scheme))
                    {
                        scheme = request.Scheme;
                    }

                    port = "https".Equals(scheme, StringComparison.OrdinalIgnoreCase) ? "443" : "80";

                    HawkEventSource.Log.Debug("Port chosen based on HTTP scheme: " + port);
                }

                return(new Tuple <string, string>(hostName, port));
            }
Esempio n. 31
0
        public MessageHandle(IRequestMessage request)
        {
            this.Request = request;

            isComplete      = false;
            completionLock  = new object();
            completionEvent = new TaskCompletionSource <IResponseMessage>();
        }
 public void EnqueueMessage(IRequestMessage requestMessage, IMessageResponseCollector responseCollector = null)
 {
     lock (_syncLock)
     {
         _unhandledMessages.Enqueue(requestMessage);
         _resultBuilders.Enqueue(responseCollector);
     }
 }
        internal NormalizedRequest(IRequestMessage request, ArtifactsContainer artifacts, string hostName = null, string port = null)
        {
            this.artifacts = artifacts;

            this.hostName = (hostName ?? request.Uri.Host).ToLower();
            this.port = port ?? request.Uri.Port.ToString();
            this.method = request.Method.Method.ToUpper();
            this.path = WebUtility.UrlDecode(request.Uri.AbsolutePath) + request.Uri.Query;
        }
        /// <summary>
        /// Creates the HTTP Authorization header in hawk scheme.
        /// The counterpart of the CreateServerAuthorization method in HawkServer.
        /// </summary>
        /// <param name="request">Request object</param>
        /// <returns></returns>
        public async Task CreateClientAuthorizationAsync(IRequestMessage request)
        {
            HawkEventSource.Log.Debug(
                String.Format("HawkClient.CreateClientAuthorizationAsync for {0} {1}",
                                request.Method.ToString(),
                                request.Uri.ToString()));

            await CreateClientAuthorizationInternalAsync(request, DateTime.UtcNow);
        }
 /// <summary>
 /// Represents the query parameter bewit used by Hawk for granting temporary access.
 /// </summary>
 /// <param name="request">Request object</param>
 /// <param name="credential">Hawk credential to use for creating and validating bewit.</param>
 /// <param name="utcNow">Current date and time in UTC.</param>
 /// <param name="lifeSeconds">Bewit life time (time to live in seconds).</param>
 /// <param name="applicationSpecificData">Application specific data to be sent in the bewit</param>
 /// <param name="localOffset">Local offset in milliseconds.</param>
 internal Bewit(IRequestMessage request, Credential credential,
                     DateTime utcNow, int lifeSeconds, string applicationSpecificData, int localOffset = 0)
 {
     this.credential = credential;
     this.request = request;
     this.utcNow = utcNow;
     this.lifeSeconds = lifeSeconds;
     this.applicationSpecificData = applicationSpecificData;
     this.localOffset = localOffset;
 }
        private static bool OnVerificationCallback(IRequestMessage request, string ext)
        {
            if (string.IsNullOrEmpty(ext))
            {
                return true;
            }

            const string name = "X-Request-Header-To-Protect";
            return ext.Equals(name + ":" + request.Headers[name].First());
        }
        /// <summary>
        /// Authenticates the incoming request based on the Authorize request header or bewit query string parameter
        /// </summary>
        /// <param name="request">The request object to be authenticated</param>
        /// <param name="options">Hawk authentication options</param>
        public HawkServer(IRequestMessage request, Options options)
        {
            now = DateTime.UtcNow.ToUnixTimeMillis(); // Record time before doing anything else

            if (options == null || options.CredentialsCallback == null)
                throw new ArgumentNullException("Invalid Hawk authentication options. Credentials callback cannot be null.");

            this.request = request;
            this.options = options;
        }
        /// <summary>
        /// Returns an AuthenticationResult object corresponding to the result of authentication done
        /// using the client supplied artifacts in the HTTP authorization header in hawk scheme.
        /// </summary>
        /// <param name="now">Current UNIX time in milliseconds.</param>
        /// <param name="request">Request object.</param>
        /// <param name="options">Hawk authentication options</param>
        /// <returns></returns>
        internal static async Task<AuthenticationResult> AuthenticateAsync(ulong now, IRequestMessage request, Options options)
        {
            ArtifactsContainer artifacts = null;
            Credential credential = null;

            if (request.HasValidHawkScheme())
            {
                if (ArtifactsContainer.TryParse(request.Authorization.Parameter, out artifacts))
                {
                    if (artifacts != null && artifacts.AreClientArtifactsValid)
                    {
                        credential = options.CredentialsCallback(artifacts.Id);
                        if (credential != null && credential.IsValid)
                        {
                            var normalizedRequest = new NormalizedRequest(request, artifacts);
                            var crypto = new Cryptographer(normalizedRequest, artifacts, credential);

                            // Request body is needed only when payload hash is present in the request
                            string body = null;
                            if (artifacts.PayloadHash != null && artifacts.PayloadHash.Length > 0)
                            {
                                body = await request.ReadBodyAsStringAsync();
                            }

                            if (crypto.IsSignatureValid(body, request.ContentType)) // MAC and hash checks
                            {
                                if (IsTimestampFresh(now, artifacts, options))
                                {
                                    // If you get this far, you are authentic. Welcome and thanks for flying Hawk!
                                    return new AuthenticationResult()
                                    {
                                        IsAuthentic = true,
                                        Artifacts = artifacts,
                                        Credential = credential,
                                        ApplicationSpecificData = artifacts.ApplicationSpecificData
                                    };
                                }
                                else
                                {
                                    // Authentic but for the timestamp freshness.
                                    // Give a chance to the client to correct the clocks skew.
                                    var timestamp = new NormalizedTimestamp(DateTime.UtcNow, credential, options.LocalTimeOffsetMillis);
                                    request.ChallengeParameter = timestamp.ToWwwAuthenticateHeaderParameter();
                                }
                            }
                        }
                    }
                }
            }

            return new AuthenticationResult() { IsAuthentic = false };
        }
Esempio n. 39
0
        public static void RegisterDeviceForPushNotifications(IRequestMessage<Registration> request, IResponseMessage response)
        {
            if (!string.IsNullOrEmpty(request.RequestObject.PushToken))
            {
                using (Repository repository = new Repository())
                {
                    using (IDbTransaction transaction = repository.Connection.BeginTransaction())
                    {
                        try
                        {
                            Pass pass = repository.GetPass(
                                request.RouteValue<string>("passTypeIdentifier"),
                                request.RouteValue<string>("serialNumber"),
                                transaction);

                            if (pass != null)
                            {
                                Registration registration = new Registration()
                                {
                                    Created = DateTime.UtcNow,
                                    DeviceLibraryIdentifier = request.RouteValue<string>("deviceLibraryIdentifier"),
                                    LastUpdated = DateTime.UtcNow,
                                    PassId = pass.Id,
                                    PushToken = request.RequestObject.PushToken
                                };

                                if (repository.CreateRegistration(registration, transaction))
                                {
                                    response.SetStatus(StatusCode.Created);
                                }
                            }
                            else
                            {
                                response.SetStatus(StatusCode.NotFound);
                            }

                            transaction.Commit();
                        }
                        catch
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }
            else
            {
                response.SetStatus(StatusCode.BadRequest);
            }
        }
        internal NormalizedRequest(IRequestMessage request,
                                        ArtifactsContainer artifacts,
                                            HostNameSource? hostNameSource = null)
        {
            this.artifacts = artifacts;

            // Case 1: For bewit, host and port are always from the request URI.
            if (IsBewit)
            {
                this.hostName = request.Uri.Host;
                this.port = request.Uri.Port.ToString();
            }
            else
            {
                if (hostNameSource.HasValue) // Case 2: NOT bewit and user has specified the host name source
                {
                    switch (hostNameSource.Value)
                    {
                        case HostNameSource.XForwardedForHeader:
                            this.hostName = this.GetHostName(request.ForwardedFor, out this.port); break;
                        case HostNameSource.HostHeader:
                            this.hostName = this.GetHostName(request.Host, out this.port); break;
                        case HostNameSource.RequestUri:
                                this.hostName = request.Uri.Host; break;
                    }
                }

                if (String.IsNullOrWhiteSpace(this.hostName))
                {
                    // Case 3: NOT bewit and user has specified the host name source but unable to determine host name.
                    // Case 4: NOT bewit and user has NOT specified the host name source.
                    // For both cases, try X-Forwarded-For header first, then Host header, and finally request URI.

                    this.hostName = this.GetHostName(request.ForwardedFor, out this.port) ??
                                        this.GetHostName(request.Host, out this.port) ??
                                            request.Uri.Host;
                }
            }

            if (String.IsNullOrWhiteSpace(this.port))
                this.port = request.Uri.Port.ToString();

            this.method = request.Method.Method.ToUpper();
            this.path = request.Uri.PathAndQuery;
        }
        internal NormalizedRequest(IRequestMessage request, ArtifactsContainer artifacts)
        {
            this.artifacts = artifacts;

            // Determine host and port - take the host name from X-Forwarded-For header, if present, or from
            // the Host header, if present, or from the HttpRequestMessage object. For bewit, it is always from URI.
            string firstPreference = IsBewit? null : request.ForwardedFor;
            string secondPreference = IsBewit ? null : request.Host;

            this.hostName = this.GetHostName(firstPreference, out this.port) ??
                                this.GetHostName(secondPreference, out this.port) ??
                                    request.Uri.Host;

            if (String.IsNullOrWhiteSpace(this.port))
                this.port = request.Uri.Port.ToString();

            this.method = request.Method.Method.ToUpper();
            this.path = request.Uri.PathAndQuery;
        }
Esempio n. 42
0
        public static void GetSerialNumbersForDevice(IRequestMessage request, IResponseMessage response)
        {
            DeviceSerialNumbers serialNumbers;

            using (Repository repository = new Repository())
            {
                serialNumbers = repository.GetDeviceSerialNumbers(
                    request.RouteValue<string>("deviceLibraryIdentifier"),
                    request.RouteValue<string>("passTypeIdentifier"),
                    request.QueryValue<DateTime?>("passesUpdatedSince"));
            }

            if (serialNumbers != null)
            {
                response.ResponseObject = serialNumbers;
            }
            else
            {
                response.SetStatus(StatusCode.NoContent);
            }
        }
Esempio n. 43
0
        /// <summary>
        /// Used for sending a message that gets a reply such as a query.
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        /// <exception cref="IOException">A reconnect will be issued but it is up to the caller to handle the error.</exception>
        public ReplyMessage SendTwoWayMessage(IRequestMessage msg)
        {
            if (this.State != ConnectionState.Opened)
            {
                throw new MongoException("Operation cannot be performed on a closed connection.");
            }
            try
            {
                ReplyMessage reply = new ReplyMessage();
                lock (_connection)
                {

                    msg.Write(_connection.GetStream(), Console.Out);
                    reply.Read(_connection.GetStream());
                }
                return reply;
            }
            catch (IOException)
            {
                ReplaceInvalidConnection();
                throw;
            }

        }
Esempio n. 44
0
 public void SendRequestAsync(IRequestMessage request, Action<IResponseMessage> responseHandler)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Adds the bewit to the query string of the specified HttpRequestMessage object and 
        /// returns the bewit string.
        /// </summary>
        internal string CreateBewitInternal(IRequestMessage request, DateTime utcNow, int lifeSeconds)
        {
            string appData = null;
            if (options.NormalizationCallback != null)
                appData = options.NormalizationCallback(request);

            var bewit = new Bewit(request, options.CredentialsCallback(),
                                    utcNow, lifeSeconds, appData, options.LocalTimeOffsetMillis);
            string bewitString = bewit.ToBewitString();

            string parameter = String.Format("{0}={1}", HawkConstants.Bewit, bewitString);

            string queryString = request.Uri.Query;
            queryString = String.IsNullOrWhiteSpace(queryString) ? parameter : queryString.Substring(1) + "&" + parameter;
            request.QueryString = queryString;

            return bewitString;
        }
Esempio n. 46
0
 public RequestTimeoutMessage(IRequestMessage request)
 {
     this.request = request;
 }
Esempio n. 47
0
        public IResponseMessage SendRequest(IRequestMessage request)
        {
            var serializer = new BinaryFormatter();

            byte[] rawRequest;

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, request);
                rawRequest = stream.ToArray();
            }

            var rawResponse = DispatchServiceProxy.SendMessage(rawRequest);
            IResponseMessage response = null;

            using (var stream = new MemoryStream(rawResponse))
            {
                response = (IResponseMessage)serializer.Deserialize(stream);
            }
            return response;
        }
        /// <summary>
        /// Interface method overload for receiving a <see cref="IRequestMessage"/>.
        /// </summary>
        /// <param name="message">The request recieved from the remote peer.</param>
        /// <param name="parameters">The message parameters the message was sent with.</param>
        public void OnNetworkMessageReceive(IRequestMessage message, IMessageParameters parameters)
        {
            Throw<ArgumentNullException>.If.IsNull(message)?.Now(nameof(message));

            RequestPublisher?.Invoke(message, parameters);
        }
Esempio n. 49
0
        public virtual MethodResult Invoke(IRequestMessage request, IResponseMessage response)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", "request cannot be null.");
            }

            if (response == null)
            {
                throw new ArgumentNullException("response", "response cannot be null.");
            }

            MethodResult result = new MethodResult();

            if (this.action != null)
            {
                try
                {
                    this.action();
                    result.Success = true;
                }
                catch (Exception ex)
                {
                    result.Exception = ex;
                }
            }
            else if (this.requestAction != null)
            {
                try
                {
                    this.requestAction(request);
                    result.Success = true;
                }
                catch (Exception ex)
                {
                    result.Exception = ex;
                }
            }
            else if (this.requestResponseAction != null)
            {
                try
                {
                    this.requestResponseAction(request, response);
                    result.Success = true;
                }
                catch (Exception ex)
                {
                    result.Exception = ex;
                }
            }
            else
            {
                throw new InvalidOperationException("No action was found to invoke.");
            }

            return result;
        }
Esempio n. 50
0
 /// <summary>
 /// Used for sending a message that gets no reply such as insert or update.
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 /// <exception cref="IOException">A reconnect will be issued but it is up to the caller to handle the error.</exception>        
 public void SendMessage(IRequestMessage msg)
 {
     if (this.State != ConnectionState.Opened) {
         throw new MongoCommException ("Operation cannot be performed on a closed connection.", this);
     }
     try {
         lock (_connection) {
             msg.Write (_connection.GetStream ());
         }
     } catch (IOException) {
         //Sending doesn't seem to always trigger the detection of a closed socket.
         ReplaceInvalidConnection ();
         throw;
     }
 }
        /// <summary>
        /// Returns an AuthenticationResult object corresponding to the result of authentication done
        /// using the client supplied artifacts in the HTTP authorization header in hawk scheme.
        /// </summary>
        /// <param name="now">Current UNIX time in milliseconds.</param>
        /// <param name="request">Request object.</param>
        /// <param name="options">Hawk authentication options</param>
        /// <returns></returns>
        internal static async Task<AuthenticationResult> AuthenticateAsync(ulong now, IRequestMessage request, Options options)
        {
            ArtifactsContainer artifacts = null;
            Credential credential = null;

            if (request.HasValidHawkScheme())
            {
                if (ArtifactsContainer.TryParse(request.Authorization.Parameter, out artifacts))
                {
                    if (artifacts != null && artifacts.AreClientArtifactsValid)
                    {
                        string lastUsedBy = options.DetermineNonceReplayCallback(artifacts.Nonce);

                        if (String.IsNullOrEmpty(lastUsedBy)) // Not an old nonce, and hence not a replay.
                        {
                            credential = options.CredentialsCallback(artifacts.Id);
                            if (credential != null && credential.IsValid)
                            {
                                HawkEventSource.Log.Debug(
                                    String.Format("Algorithm={0} Key={1} ID={2}",
                                                        credential.Algorithm.ToString(),
                                                        Convert.ToBase64String(credential.Key),
                                                        credential.Id));

                                Tuple<string, string> hostAndPort = options.DetermineHostDetailsCallback(request);
                                var normalizedRequest = new NormalizedRequest(request, artifacts, hostAndPort.Item1, hostAndPort.Item2);
                                var crypto = new Cryptographer(normalizedRequest, artifacts, credential);

                                // Request body is needed only when payload hash is present in the request
                                string body = null;
                                if (artifacts.PayloadHash != null && artifacts.PayloadHash.Length > 0)
                                {
                                    body = await request.ReadBodyAsStringAsync();
                                }

                                if (crypto.IsSignatureValid(body, request.ContentType)) // MAC and hash checks
                                {
                                    if (IsTimestampFresh(now, artifacts, options))
                                    {
                                        // If you get this far, you are authentic. Welcome and thanks for flying Hawk!

                                        // Before returning the result, store nonce to detect replays.
                                        options.StoreNonceCallback(artifacts.Nonce, credential.Id, options.ClockSkewSeconds);

                                        return new AuthenticationResult()
                                        {
                                            IsAuthentic = true,
                                            Artifacts = artifacts,
                                            Credential = credential,
                                            ApplicationSpecificData = artifacts.ApplicationSpecificData
                                        };
                                    }
                                    else
                                    {
                                        // Authentic but for the timestamp freshness.
                                        // Give a chance to the client to correct the clocks skew.
                                        var timestamp = new NormalizedTimestamp(DateTime.UtcNow, credential, options.LocalTimeOffsetMillis);
                                        request.ChallengeParameter = timestamp.ToWwwAuthenticateHeaderParameter();
                                    }
                                }
                            }
                        }
                        else
                        {
                            HawkEventSource.Log.NonceReplay(artifacts.Nonce, lastUsedBy);
                        }
                    }
                }
            }

            return new AuthenticationResult() { IsAuthentic = false };
        }
        /// <summary>
        /// Adds the bewit to the query string of the specified HttpRequestMessage object and
        /// returns the bewit string.
        /// </summary>
        public string CreateBewit(IRequestMessage request, int lifeSeconds)
        {
            HawkEventSource.Log.Debug(
                String.Format("HawkClient.CreateBewit for {0} {1}",
                                request.Method.ToString(),
                                request.Uri.ToString()));

            return CreateBewitInternal(request, DateTime.UtcNow, lifeSeconds);
        }
        /// <summary>
        /// Removes the bewit parameter from the URI of the specified IRequestMessage object.
        /// </summary>
        private static void RemoveBewitFromUri(IRequestMessage request)
        {
            string query = request.Uri.Query;
            string bewit = HttpUtility.ParseQueryString(request.Uri.Query)[HawkConstants.Bewit];

            query = query.Replace(HawkConstants.Bewit + "=" + bewit, String.Empty)
                            .Replace("&&", "&")
                            .Replace("?&", "?")
                            .Trim('&').Trim('?');

            request.QueryString = query;
        }
        /// <summary>
        /// Creates the HTTP Authorization header in hawk scheme.
        /// </summary>
        internal async Task CreateClientAuthorizationInternalAsync(IRequestMessage request, DateTime utcNow)
        {
            var credential = options.CredentialsCallback();
            this.artifacts = new ArtifactsContainer()
            {
                Id = credential.Id,
                Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(),
                Nonce = NonceGenerator.Generate()
            };

            if (options.NormalizationCallback != null)
                this.artifacts.ApplicationSpecificData = options.NormalizationCallback(request);

            var normalizedRequest = new NormalizedRequest(request, this.artifacts);
            this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential);

            // Sign the request
            bool includePayloadHash = options.RequestPayloadHashabilityCallback != null &&
                                            options.RequestPayloadHashabilityCallback(request);

            string payload = includePayloadHash ? await request.ReadBodyAsStringAsync() : null;
            crypto.Sign(payload, request.ContentType);

            request.Authorization = new AuthenticationHeaderValue(HawkConstants.Scheme,
                                                this.artifacts.ToAuthorizationHeaderParameter());
        }
 /// <summary>
 /// Creates the HTTP Authorization header in hawk scheme.
 /// The counterpart of the CreateServerAuthorization method in HawkServer.
 /// </summary>
 /// <param name="request">Request object</param>
 /// <returns></returns>
 public async Task CreateClientAuthorizationAsync(IRequestMessage request)
 {
     await CreateClientAuthorizationInternalAsync(request, DateTime.UtcNow);
 }
 /// <summary>
 /// Adds the bewit to the query string of the specified HttpRequestMessage object and
 /// returns the bewit string.
 /// </summary>
 public string CreateBewit(IRequestMessage request, int lifeSeconds)
 {
     return CreateBewitInternal(request, DateTime.UtcNow, lifeSeconds);
 }
Esempio n. 57
0
        private static InvokeActionsResult InvokeActions(IEnumerable<FilterAction> actions, IRequestMessage request, IResponseMessage response, IEnumerable<Exception> exceptions)
        {
            List<FilterActionResult> results = new List<FilterActionResult>();
            bool success = true, cont = true;

            foreach (FilterAction action in actions)
            {
                FilterActionResult result = action.Invoke(request, response, exceptions);
                results.Add(result);
                success = success && result.Success;
                cont = cont && result.Continue;

                if (!cont)
                {
                    break;
                }
            }

            return new InvokeActionsResult(success, cont, results);
        }
        /// <summary>
        /// Returns an AuthenticationResult object corresponding to the result of authentication done
        /// using the client supplied artifacts in the bewit query string parameter.
        /// </summary>
        /// <param name="bewit">Value of the query string parameter with the name of 'bewit'.</param>
        /// <param name="now">Date and time in UTC to be used as the base for computing bewit life.</param>
        /// <param name="request">Request object.</param>
        /// <param name="options">Hawk authentication options</param>
        internal static AuthenticationResult Authenticate(string bewit, ulong now, IRequestMessage request, Options options)
        {
            if (!String.IsNullOrWhiteSpace(bewit))
            {
                if (request.Method == HttpMethod.Get)
                {
                    if (options != null && options.CredentialsCallback != null)
                    {
                        var parts = bewit.ToUtf8StringFromBase64Url().Split('\\');

                        if (parts.Length == 4)
                        {
                            ulong timestamp = 0;
                            if (UInt64.TryParse(parts[1], out timestamp) && timestamp * 1000 > now)
                            {
                                string id = parts[0];
                                string mac = parts[2];
                                string ext = parts[3];

                                if (!String.IsNullOrWhiteSpace(id) && !String.IsNullOrWhiteSpace(mac))
                                {
                                    RemoveBewitFromUri(request);

                                    Credential credential = options.CredentialsCallback(id);
                                    if (credential != null && credential.IsValid)
                                    {
                                        var artifacts = new ArtifactsContainer()
                                        {
                                            Id = id,
                                            Nonce = String.Empty,
                                            Timestamp = timestamp,
                                            Mac = mac.ToBytesFromBase64(),
                                            ApplicationSpecificData = ext ?? String.Empty
                                        };

                                        var normalizedRequest = new NormalizedRequest(request, artifacts) { IsBewit = true };
                                        var crypto = new Cryptographer(normalizedRequest, artifacts, credential);

                                        if (crypto.IsSignatureValid()) // Bewit is for GET and GET must have no request body
                                        {
                                            return new AuthenticationResult()
                                            {
                                                IsAuthentic = true,
                                                Credential = credential,
                                                Artifacts = artifacts,
                                                ApplicationSpecificData = ext
                                            };
                                        }   
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return new AuthenticationResult() { IsAuthentic = false };
        }
Esempio n. 59
0
 public static void UnregisterDevice(IRequestMessage request, IResponseMessage response)
 {
     using (Repository repository = new Repository())
     {
         repository.DeleteRegistration(
             request.RouteValue<string>("deviceLibraryIdentifier"),
             request.RouteValue<string>("passTypeIdentifier"),
             request.RouteValue<string>("serialNumber"));
     }
 }
Esempio n. 60
0
        public ReadRequestResult ReadRequest(IRequestMessage request, int contentLength, string contentEncoding, string contentType, Stream inputStream)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", "request cannot be null.");
            }

            ReadRequestResult result = new ReadRequestResult() { Success = true };

            if ((this.Method.MethodType == MethodType.Post
                || this.Method.MethodType == MethodType.Put)
                && this.RequestType != null)
            {
                if (contentLength > 0)
                {
                    EncodingLookupResult encodingResult = null;
                    FormatLookupResult formatResult = null;

                    if (!string.IsNullOrEmpty(contentEncoding))
                    {
                        try
                        {
                            encodingResult = this.GetRequestDecoder(contentEncoding);

                            if (encodingResult == null)
                            {
                                result.StatusCode = StatusCode.UnsupportedMediaType;
                                result.Success = false;
                            }
                        }
                        catch (FormatException ex)
                        {
                            result.Exception = ex;
                            result.StatusCode = StatusCode.BadRequest;
                            result.Success = false;
                        }
                    }
                    else
                    {
                        encodingResult = ResolvedService.DefaultEncodingLookupResult;
                    }

                    if (result.Success)
                    {
                        if (!string.IsNullOrEmpty(contentType))
                        {
                            try
                            {
                                formatResult = this.GetRequestDeserializer(contentType);

                                if (formatResult == null)
                                {
                                    result.StatusCode = StatusCode.UnsupportedMediaType;
                                    result.Success = false;
                                }
                            }
                            catch (FormatException ex)
                            {
                                result.Exception = ex;
                                result.StatusCode = StatusCode.BadRequest;
                                result.Success = false;
                            }
                        }
                        else
                        {
                            formatResult = ResolvedService.DefaultFormatLookupResult;
                        }
                    }

                    if (result.Success && inputStream != null)
                    {
                        object obj = null;

                        try
                        {
                            request.SetEncodingFilter(encodingResult.EncodingType, encodingResult.Encoding);
                            obj = formatResult.Format.Deserialize(formatResult.MediaType, this.RequestType, inputStream);
                            result.RequestObject = obj;
                            obj = null;
                        }
                        catch (Exception ex)
                        {
                            result.Exception = ex;
                            result.RequestObject = null;
                            result.StatusCode = StatusCode.BadRequest;
                            result.Success = false;
                            obj.DisposeIfPossible();
                            obj = null;
                        }
                    }
                }
                else
                {
                    result.StatusCode = StatusCode.LengthRequired;
                    result.Success = false;
                }
            }

            return result;
        }