Ejemplo n.º 1
0
        public override void ProcessRequest(ref System.ServiceModel.Channels.RequestContext requestContext)
        {
            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
            {
                Trace.CorrelationManager.ActivityId = Guid.NewGuid();
            }

            var request = requestContext.RequestMessage;

            if (endpointFilter == null || endpointFilter(request))
            {
                try
                {
                    IPrincipal principal = ExtractCredentials(request);
                    if (principal != null)
                    {
                        InitializeSecurityContext(request, principal);
                    }
                    else
                    {
                        var reply            = Message.CreateMessage(MessageVersion.None, null);
                        var responseProperty = new HttpResponseMessageProperty()
                        {
                            StatusCode = HttpStatusCode.Unauthorized
                        };

                        if (sendChallenge)
                        {
                            var ts        = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();
                            var challenge = string.Format("ts=\"{0}\" ntp=\"{1}\"",
                                                          ts, "pool.ntp.org");

                            responseProperty.Headers.Add("WWW-Authenticate", challenge);
                        }

                        reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
                        requestContext.Reply(reply);

                        requestContext = null;
                    }
                }
                catch (SecurityException ex)
                {
                    TraceSource.TraceData(TraceEventType.Error, 0,
                                          string.Format("{0} - Security Exception {1}",
                                                        Trace.CorrelationManager.ActivityId, ex.ToString()));

                    var reply            = Message.CreateMessage(MessageVersion.None, null, (object)ex.Message);
                    var responseProperty = new HttpResponseMessageProperty()
                    {
                        StatusCode = HttpStatusCode.Unauthorized
                    };

                    reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
                    requestContext.Reply(reply);

                    requestContext = null;
                }
            }
        }
        public override void ProcessRequest(ref System.ServiceModel.Channels.RequestContext requestContext)
        {
            Message request = requestContext.RequestMessage;
            HttpRequestMessageProperty requestProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];


            if (bool.Parse(AppSettings.GetAbsolute("CheckSession")) == true)
            {
                Message reply;
                reply = Message.CreateMessage(MessageVersion.None, null);
                HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty()
                {
                    StatusCode = HttpStatusCode.Unauthorized
                };
                if (requestContext == null || requestContext.RequestMessage == null)
                {
                    return;
                }
                NameValueCollection queryParams = HttpUtility.ParseQueryString(requestProp.QueryString);
                if (request.Properties.Via.LocalPath.ToUpper() != LogInMessageAdress.ToUpper())
                {
                    if (requestProp.Headers[SessionHeader] == null)                    //case header not specified
                    {
                        responseProp.StatusDescription = ("You have not specified session header");
                        responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";
                        reply.Properties[HttpResponseMessageProperty.Name]   = responseProp;
                        requestContext.Reply(reply);
                        // set the request context to null to terminate processing of this request
                        requestContext = null;
                    }
                    else
                    {
                        string session = requestProp.Headers[SessionHeader];
                        int    userCode;
                        if (!IsSessionValid(session, out userCode))                        //if session is valid
                        {
                            responseProp.StatusCode        = HttpStatusCode.Unauthorized;
                            responseProp.StatusDescription = ("session is not exist or out of date");
                            responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";
                            reply.Properties[HttpResponseMessageProperty.Name]   = responseProp;
                            requestContext.Reply(reply);
                            // set the request context to null to terminate processing of this request
                            requestContext = null;
                        }
                        else
                        {
                            requestProp.Headers.Add("xUserCode", "userCode");
                        }
                    }
                }
            }
        }
 public override void ProcessRequest(ref RequestContext requestContext)
 {
     if (!manager.AuthenticateRequest(requestContext.RequestMessage)) {
         requestContext.Reply(manager.CreateInvalidAuthenticationRequest());
         requestContext = null;
     }
 }
Ejemplo n.º 4
0
 private RequestContext FinishReceiveRequest(RequestContext innerContext, TimeSpan timeout)
 {
     if (innerContext == null)
     {
         return(null);
     }
     try
     {
         this.ReadTransactionDataFromMessage(innerContext.RequestMessage, MessageDirection.Input);
     }
     catch (FaultException exception)
     {
         string  action  = exception.Action ?? innerContext.RequestMessage.Version.Addressing.DefaultFaultAction;
         Message message = Message.CreateMessage(innerContext.RequestMessage.Version, exception.CreateMessageFault(), action);
         try
         {
             innerContext.Reply(message, timeout);
         }
         finally
         {
             message.Close();
         }
         throw;
     }
     return(new TransactionRequestContext(this, this, innerContext, this.DefaultCloseTimeout, base.DefaultSendTimeout));
 }
 protected override void SendReply(Message reply, IReplyChannel channel, RequestContext item)
 {
     if (FaultHelper.AddressReply(item.RequestMessage, reply))
     {
         item.Reply(reply);
     }
 }
 private RequestContext CreateAndSendInvalidAuthenticationRequest(RequestContext requestContext)
 {
     using (Message responseMessage = authenticationManager.CreateInvalidAuthenticationRequest(requestContext.RequestMessage))
      {
     requestContext.Reply(responseMessage);
     requestContext = null;
     return requestContext;
      }
 }
Ejemplo n.º 7
0
        public static void Unauthorized(ref RequestContext context, string nonauthorizedHeaderValue)
        {
            var reply = Message.CreateMessage(MessageVersion.None, null);
            var responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };

            responseProperty.Headers.Add(HttpResponseHeader.WwwAuthenticate,
                                         nonauthorizedHeaderValue);

            reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
            context.Reply(reply);
            context = null;
        }
Ejemplo n.º 8
0
 public override void Reply(Message message, TimeSpan timeout)
 {
     try {
         if (!message.IsFault && message.Headers.Action != Constants.WstIssueReplyAction)
         {
             message = SecureMessage(message);
         }
         source.Reply(message, timeout);
     } catch (Exception ex) {
         FaultConverter fc = FaultConverter.GetDefaultFaultConverter(msg.Version);
         Message        fault;
         if (fc.TryCreateFaultMessage(ex, out fault))
         {
             source.Reply(fault, timeout);
         }
         else
         {
             throw;
         }
     }
 }
Ejemplo n.º 9
0
            private Message ProcessContext(RequestContext context, TimeSpan timeout)
            {
                if (context == null)
                {
                    return(null);
                }
                bool    flag           = false;
                Message requestMessage = null;

                try
                {
                    requestMessage = context.RequestMessage;
                    requestMessage.Properties.Add(RequestContextMessageProperty.Name, new RequestContextMessageProperty(context));
                    if (this.validateHeader)
                    {
                        PacketRoutableHeader.ValidateMessage(requestMessage);
                    }
                    try
                    {
                        context.Reply(null, new TimeoutHelper(timeout).RemainingTime());
                        flag = true;
                    }
                    catch (CommunicationException exception)
                    {
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
                        }
                    }
                    catch (TimeoutException exception2)
                    {
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information);
                        }
                    }
                }
                finally
                {
                    if (!flag)
                    {
                        context.Abort();
                        if (requestMessage != null)
                        {
                            requestMessage.Close();
                            requestMessage = null;
                        }
                    }
                }
                return(requestMessage);
            }
        public override void ProcessRequest(ref RequestContext requestContext)
        {
            string[] credentials = ExtractCredentials(requestContext.RequestMessage);
            if (credentials.Length > 0 && AuthenticateUser(credentials[0], credentials[1]))
            {
                InitializeSecurityContext(requestContext.RequestMessage, credentials[0]);
            }
            else
            {
                Message reply = Message.CreateMessage(MessageVersion.None, null);
                HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };

                responseProperty.Headers.Add("WWW-Authenticate",
                    String.Format("Basic realm=\"{0}\"", Realm));

                reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
                requestContext.Reply(reply);

                requestContext = null;
            }
        }
Ejemplo n.º 11
0
        void HandleHttpGet(RequestContext context)
        {
            Message message = new HtmlMessage(
                context.RequestMessage.Version,
                context.RequestMessage.Headers.ReplyTo.ToString(),
                HelloWorldService.ServiceName,
                HelloWorldService.OperationName);

            HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty();
            responseProperty.StatusCode = HttpStatusCode.OK;
            HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)context.RequestMessage.Properties[HttpRequestMessageProperty.Name];
            responseProperty.Headers.Add(HttpResponseHeader.ContentType, requestProperty.Headers[HttpRequestHeader.ContentType]);
            
            message.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);

            context.Reply(message);
        }
Ejemplo n.º 12
0
        private void SendResponse(RequestContext context)
        {
            Assert.IsNotNull(context);

            // Validate request
            var request = context.RequestMessage;
            Assert.IsNotNull(request);
            var httpRequest = request.ToHttpRequestMessage();
            Assert.IsNotNull(httpRequest);

            // Create response
            var httpResponse = new HttpResponseMessage(HttpStatusCode.OK, BasicChannelTests.ChannelHttpReasonPhrase);
            Assert.IsNotNull(httpResponse);
            TestServiceCommon.CopyTestHeader(httpRequest, httpResponse);

            // Send response
            var response = httpResponse.ToMessage();
            Assert.IsNotNull(response);
            context.Reply(response);
        }
Ejemplo n.º 13
0
 private void CreateErrorReply(ref RequestContext requestContext)
 {
     // The error message is padded so that IE shows the response by default
     using (var sr = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + ErrorHtml))
     {
         XElement response = XElement.Load(sr);
         using (Message reply = Message.CreateMessage(MessageVersion.None, null, response))
         {
             var responseProp = new HttpResponseMessageProperty
             {
                 StatusCode = HttpStatusCode.Forbidden,
                 StatusDescription = String.Format("Forbidden")
             };
             responseProp.Headers.Add("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", Realm));
             responseProp.Headers[System.Net.HttpResponseHeader.ContentType] = "text/html";
             reply.Properties[HttpResponseMessageProperty.Name] = responseProp;
             requestContext.Reply(reply);
             // set the request context to null to terminate processing of this request
             requestContext = null;
         }
     }
 }
		public void GenerateErrorResponse(ref RequestContext requestContext, HttpStatusCode statusCode, string errorMessage)
		{
			// The error message is padded so that IE shows the response by default
			var reply = Message.CreateMessage(MessageVersion.None, null, new Error() { Message = errorMessage });
			var responseProp = new HttpResponseMessageProperty()
			{
				StatusCode = statusCode
			};
			reply.Properties[HttpResponseMessageProperty.Name] = responseProp;
			requestContext.Reply(reply);
			requestContext = null;
		}
        private void ProcessRequest(RequestContext context, WsrmMessageInfo info)
        {
            bool flag  = true;
            bool flag2 = true;

            try
            {
                EndpointAddress address;
                bool            flag3;
                if (!base.ReliableSession.ProcessInfo(info, context))
                {
                    flag  = false;
                    flag2 = false;
                    return;
                }
                if (!base.ReliableSession.VerifySimplexProtocolElements(info, context))
                {
                    flag  = false;
                    flag2 = false;
                    return;
                }
                base.ReliableSession.OnRemoteActivity(false);
                if (info.CreateSequenceInfo == null)
                {
                    goto Label_0104;
                }
                if (WsrmUtilities.ValidateCreateSequence <IInputSessionChannel>(info, base.Listener, base.Binder.Channel, out address))
                {
                    Message response = WsrmUtilities.CreateCreateSequenceResponse(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion, false, info.CreateSequenceInfo, base.Listener.Ordered, base.ReliableSession.InputID, address);
                    using (context)
                    {
                        using (response)
                        {
                            if (base.Binder.AddressResponse(info.Message, response))
                            {
                                context.Reply(response, base.DefaultSendTimeout);
                            }
                        }
                        goto Label_00FB;
                    }
                }
                base.ReliableSession.OnLocalFault(info.FaultException, info.FaultReply, context);
Label_00FB:
                flag  = false;
                flag2 = false;
                return;

Label_0104:
                flag3 = false;
                bool      allAdded = false;
                bool      flag5    = false;
                WsrmFault fault    = null;
                Message   message2 = null;
                Exception e        = null;
                bool      flag6    = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005;
                bool      flag7    = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11;
                bool      flag8    = info.AckRequestedInfo != null;
                if (info.SequencedMessageInfo != null)
                {
                    lock (base.ThisLock)
                    {
                        if (base.Aborted || (base.State == CommunicationState.Faulted))
                        {
                            return;
                        }
                        long sequenceNumber = info.SequencedMessageInfo.SequenceNumber;
                        bool isLast         = flag6 && info.SequencedMessageInfo.LastMessage;
                        if (!base.Connection.IsValid(sequenceNumber, isLast))
                        {
                            if (flag6)
                            {
                                fault = new LastMessageNumberExceededFault(base.ReliableSession.InputID);
                            }
                            else
                            {
                                message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion);
                                if (PerformanceCounters.PerformanceCountersEnabled)
                                {
                                    PerformanceCounters.MessageDropped(base.perfCounterId);
                                }
                            }
                        }
                        else if (base.Connection.Ranges.Contains(sequenceNumber))
                        {
                            if (PerformanceCounters.PerformanceCountersEnabled)
                            {
                                PerformanceCounters.MessageDropped(base.perfCounterId);
                            }
                        }
                        else if (flag6 && (info.Action == "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage"))
                        {
                            base.Connection.Merge(sequenceNumber, isLast);
                            allAdded = base.Connection.AllAdded;
                        }
                        else if (base.State == CommunicationState.Closing)
                        {
                            if (flag6)
                            {
                                fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSessionClosedBeforeDone"), System.ServiceModel.SR.GetString("SessionClosedBeforeDone"));
                            }
                            else
                            {
                                message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion);
                                if (PerformanceCounters.PerformanceCountersEnabled)
                                {
                                    PerformanceCounters.MessageDropped(base.perfCounterId);
                                }
                            }
                        }
                        else if (base.DeliveryStrategy.CanEnqueue(sequenceNumber) && (base.Listener.Ordered || base.Connection.CanMerge(sequenceNumber)))
                        {
                            base.Connection.Merge(sequenceNumber, isLast);
                            flag3    = base.DeliveryStrategy.Enqueue(info.Message, sequenceNumber);
                            allAdded = base.Connection.AllAdded;
                            flag2    = false;
                        }
                        else if (PerformanceCounters.PerformanceCountersEnabled)
                        {
                            PerformanceCounters.MessageDropped(base.perfCounterId);
                        }
                        goto Label_05CE;
                    }
                }
                if (flag6 && (info.TerminateSequenceInfo != null))
                {
                    bool flag11;
                    lock (base.ThisLock)
                    {
                        flag11 = !base.Connection.Terminate();
                    }
                    if (!flag11)
                    {
                        return;
                    }
                    fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedEarlyTerminateSequence"), System.ServiceModel.SR.GetString("EarlyTerminateSequence"));
                }
                else if (flag7 && ((info.TerminateSequenceInfo != null) || (info.CloseSequenceInfo != null)))
                {
                    bool            flag13 = info.TerminateSequenceInfo != null;
                    WsrmRequestInfo info2  = flag13 ? ((WsrmRequestInfo)info.TerminateSequenceInfo) : ((WsrmRequestInfo)info.CloseSequenceInfo);
                    long            last   = flag13 ? info.TerminateSequenceInfo.LastMsgNumber : info.CloseSequenceInfo.LastMsgNumber;
                    if (!WsrmUtilities.ValidateWsrmRequest(base.ReliableSession, info2, base.Binder, context))
                    {
                        flag2 = false;
                        flag  = false;
                        return;
                    }
                    bool isLastLargeEnough = true;
                    bool flag15            = true;
                    lock (base.ThisLock)
                    {
                        if (!base.Connection.IsLastKnown)
                        {
                            if (flag13)
                            {
                                if (base.Connection.SetTerminateSequenceLast(last, out isLastLargeEnough))
                                {
                                    allAdded = true;
                                }
                                else if (isLastLargeEnough)
                                {
                                    e = new ProtocolException(System.ServiceModel.SR.GetString("EarlyTerminateSequence"));
                                }
                            }
                            else
                            {
                                allAdded          = base.Connection.SetCloseSequenceLast(last);
                                isLastLargeEnough = allAdded;
                            }
                            if (allAdded)
                            {
                                base.ReliableSession.SetFinalAck(base.Connection.Ranges);
                                base.DeliveryStrategy.Dispose();
                            }
                        }
                        else
                        {
                            flag15 = last == base.Connection.Last;
                            if ((flag13 && flag15) && base.Connection.IsSequenceClosed)
                            {
                                flag5 = true;
                            }
                        }
                    }
                    if (!isLastLargeEnough)
                    {
                        fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSmallLastMsgNumber"), System.ServiceModel.SR.GetString("SmallLastMsgNumberExceptionString"));
                    }
                    else if (!flag15)
                    {
                        fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedInconsistentLastMsgNumber"), System.ServiceModel.SR.GetString("InconsistentLastMsgNumberExceptionString"));
                    }
                    else
                    {
                        message2 = flag13 ? WsrmUtilities.CreateTerminateResponseMessage(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID) : WsrmUtilities.CreateCloseSequenceResponse(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID);
                        flag8    = true;
                    }
                }
Label_05CE:
                if (fault != null)
                {
                    base.ReliableSession.OnLocalFault(fault.CreateException(), fault, context);
                    flag2 = false;
                    flag  = false;
                }
                else
                {
                    if ((message2 != null) && flag8)
                    {
                        base.AddAcknowledgementHeader(message2);
                    }
                    else if (message2 == null)
                    {
                        message2 = base.CreateAcknowledgmentMessage();
                    }
                    using (message2)
                    {
                        context.Reply(message2);
                    }
                    if (flag5)
                    {
                        lock (base.ThisLock)
                        {
                            base.Connection.Terminate();
                        }
                    }
                    if (e != null)
                    {
                        base.ReliableSession.OnRemoteFault(e);
                    }
                    else
                    {
                        if (flag3)
                        {
                            base.Dispatch();
                        }
                        if (allAdded)
                        {
                            ActionItem.Schedule(new Action <object>(this.ShutdownCallback), null);
                        }
                    }
                }
            }
            finally
            {
                if (flag2)
                {
                    info.Message.Close();
                }
                if (flag)
                {
                    context.Close();
                }
            }
        }
        private void CreateSuccessReply(ref RequestContext p_RequestContext, string p_PasswordHash)
        {
            var l_Message = new CustomResponse();
            l_Message.Message = "Login Successful";
            l_Message.Data = p_PasswordHash;

            using (Message reply = Message.CreateMessage(MessageVersion.None, "", l_Message, new DataContractJsonSerializer(typeof(CustomResponse))))
            {
                var responseProp = new HttpResponseMessageProperty
                {
                    StatusCode = HttpStatusCode.Accepted,
                    StatusDescription = String.Format("Accepted")
                };

                responseProp.Headers.Add("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", Realm));
                responseProp.Headers[HttpResponseHeader.ContentType] = "application/json; charset=utf-8";
                reply.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
                reply.Properties[HttpResponseMessageProperty.Name] = responseProp;

                p_RequestContext.Reply(reply);

            }
        }
Ejemplo n.º 17
0
    public override void ProcessRequest(ref RequestContext requestContext)
    {
      if (requestContext == null || requestContext.RequestMessage == null)
      {
        return;
      }

      Message request = requestContext.RequestMessage;

      var requestProperty = (HttpRequestMessageProperty) request.Properties[HttpRequestMessageProperty.Name];

      IOAuthContext context = new OAuthContextBuilder().FromUri(requestProperty.Method, request.Headers.To);

      try
      {
        _provider.AccessProtectedResourceRequest(context);

        AccessToken accessToken = _repository.GetToken(context.Token);

        TokenPrincipal principal = CreatePrincipalFromToken(accessToken);

        InitializeSecurityContext(request, principal);
      }
      catch (OAuthException authEx)
      {
        XElement response = GetHtmlFormattedErrorReport(authEx);
        Message reply = Message.CreateMessage(MessageVersion.None, null, response);
        var responseProperty = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.Forbidden, StatusDescription = authEx.Report.ToString()};
        responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";
        reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
        requestContext.Reply(reply);

        requestContext = null;
      }
    }
 private void ProcessRequest(RequestContext context, WsrmMessageInfo info)
 {
     bool flag = true;
     bool flag2 = true;
     try
     {
         EndpointAddress address;
         bool flag3;
         if (!base.ReliableSession.ProcessInfo(info, context))
         {
             flag = false;
             flag2 = false;
             return;
         }
         if (!base.ReliableSession.VerifySimplexProtocolElements(info, context))
         {
             flag = false;
             flag2 = false;
             return;
         }
         base.ReliableSession.OnRemoteActivity(false);
         if (info.CreateSequenceInfo == null)
         {
             goto Label_0104;
         }
         if (WsrmUtilities.ValidateCreateSequence<IInputSessionChannel>(info, base.Listener, base.Binder.Channel, out address))
         {
             Message response = WsrmUtilities.CreateCreateSequenceResponse(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion, false, info.CreateSequenceInfo, base.Listener.Ordered, base.ReliableSession.InputID, address);
             using (context)
             {
                 using (response)
                 {
                     if (base.Binder.AddressResponse(info.Message, response))
                     {
                         context.Reply(response, base.DefaultSendTimeout);
                     }
                 }
                 goto Label_00FB;
             }
         }
         base.ReliableSession.OnLocalFault(info.FaultException, info.FaultReply, context);
     Label_00FB:
         flag = false;
         flag2 = false;
         return;
     Label_0104:
         flag3 = false;
         bool allAdded = false;
         bool flag5 = false;
         WsrmFault fault = null;
         Message message2 = null;
         Exception e = null;
         bool flag6 = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005;
         bool flag7 = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11;
         bool flag8 = info.AckRequestedInfo != null;
         if (info.SequencedMessageInfo != null)
         {
             lock (base.ThisLock)
             {
                 if (base.Aborted || (base.State == CommunicationState.Faulted))
                 {
                     return;
                 }
                 long sequenceNumber = info.SequencedMessageInfo.SequenceNumber;
                 bool isLast = flag6 && info.SequencedMessageInfo.LastMessage;
                 if (!base.Connection.IsValid(sequenceNumber, isLast))
                 {
                     if (flag6)
                     {
                         fault = new LastMessageNumberExceededFault(base.ReliableSession.InputID);
                     }
                     else
                     {
                         message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion);
                         if (PerformanceCounters.PerformanceCountersEnabled)
                         {
                             PerformanceCounters.MessageDropped(base.perfCounterId);
                         }
                     }
                 }
                 else if (base.Connection.Ranges.Contains(sequenceNumber))
                 {
                     if (PerformanceCounters.PerformanceCountersEnabled)
                     {
                         PerformanceCounters.MessageDropped(base.perfCounterId);
                     }
                 }
                 else if (flag6 && (info.Action == "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage"))
                 {
                     base.Connection.Merge(sequenceNumber, isLast);
                     allAdded = base.Connection.AllAdded;
                 }
                 else if (base.State == CommunicationState.Closing)
                 {
                     if (flag6)
                     {
                         fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSessionClosedBeforeDone"), System.ServiceModel.SR.GetString("SessionClosedBeforeDone"));
                     }
                     else
                     {
                         message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion);
                         if (PerformanceCounters.PerformanceCountersEnabled)
                         {
                             PerformanceCounters.MessageDropped(base.perfCounterId);
                         }
                     }
                 }
                 else if (base.DeliveryStrategy.CanEnqueue(sequenceNumber) && (base.Listener.Ordered || base.Connection.CanMerge(sequenceNumber)))
                 {
                     base.Connection.Merge(sequenceNumber, isLast);
                     flag3 = base.DeliveryStrategy.Enqueue(info.Message, sequenceNumber);
                     allAdded = base.Connection.AllAdded;
                     flag2 = false;
                 }
                 else if (PerformanceCounters.PerformanceCountersEnabled)
                 {
                     PerformanceCounters.MessageDropped(base.perfCounterId);
                 }
                 goto Label_05CE;
             }
         }
         if (flag6 && (info.TerminateSequenceInfo != null))
         {
             bool flag11;
             lock (base.ThisLock)
             {
                 flag11 = !base.Connection.Terminate();
             }
             if (!flag11)
             {
                 return;
             }
             fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedEarlyTerminateSequence"), System.ServiceModel.SR.GetString("EarlyTerminateSequence"));
         }
         else if (flag7 && ((info.TerminateSequenceInfo != null) || (info.CloseSequenceInfo != null)))
         {
             bool flag13 = info.TerminateSequenceInfo != null;
             WsrmRequestInfo info2 = flag13 ? ((WsrmRequestInfo) info.TerminateSequenceInfo) : ((WsrmRequestInfo) info.CloseSequenceInfo);
             long last = flag13 ? info.TerminateSequenceInfo.LastMsgNumber : info.CloseSequenceInfo.LastMsgNumber;
             if (!WsrmUtilities.ValidateWsrmRequest(base.ReliableSession, info2, base.Binder, context))
             {
                 flag2 = false;
                 flag = false;
                 return;
             }
             bool isLastLargeEnough = true;
             bool flag15 = true;
             lock (base.ThisLock)
             {
                 if (!base.Connection.IsLastKnown)
                 {
                     if (flag13)
                     {
                         if (base.Connection.SetTerminateSequenceLast(last, out isLastLargeEnough))
                         {
                             allAdded = true;
                         }
                         else if (isLastLargeEnough)
                         {
                             e = new ProtocolException(System.ServiceModel.SR.GetString("EarlyTerminateSequence"));
                         }
                     }
                     else
                     {
                         allAdded = base.Connection.SetCloseSequenceLast(last);
                         isLastLargeEnough = allAdded;
                     }
                     if (allAdded)
                     {
                         base.ReliableSession.SetFinalAck(base.Connection.Ranges);
                         base.DeliveryStrategy.Dispose();
                     }
                 }
                 else
                 {
                     flag15 = last == base.Connection.Last;
                     if ((flag13 && flag15) && base.Connection.IsSequenceClosed)
                     {
                         flag5 = true;
                     }
                 }
             }
             if (!isLastLargeEnough)
             {
                 fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSmallLastMsgNumber"), System.ServiceModel.SR.GetString("SmallLastMsgNumberExceptionString"));
             }
             else if (!flag15)
             {
                 fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedInconsistentLastMsgNumber"), System.ServiceModel.SR.GetString("InconsistentLastMsgNumberExceptionString"));
             }
             else
             {
                 message2 = flag13 ? WsrmUtilities.CreateTerminateResponseMessage(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID) : WsrmUtilities.CreateCloseSequenceResponse(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID);
                 flag8 = true;
             }
         }
     Label_05CE:
         if (fault != null)
         {
             base.ReliableSession.OnLocalFault(fault.CreateException(), fault, context);
             flag2 = false;
             flag = false;
         }
         else
         {
             if ((message2 != null) && flag8)
             {
                 base.AddAcknowledgementHeader(message2);
             }
             else if (message2 == null)
             {
                 message2 = base.CreateAcknowledgmentMessage();
             }
             using (message2)
             {
                 context.Reply(message2);
             }
             if (flag5)
             {
                 lock (base.ThisLock)
                 {
                     base.Connection.Terminate();
                 }
             }
             if (e != null)
             {
                 base.ReliableSession.OnRemoteFault(e);
             }
             else
             {
                 if (flag3)
                 {
                     base.Dispatch();
                 }
                 if (allAdded)
                 {
                     ActionItem.Schedule(new Action<object>(this.ShutdownCallback), null);
                 }
             }
         }
     }
     finally
     {
         if (flag2)
         {
             info.Message.Close();
         }
         if (flag)
         {
             context.Close();
         }
     }
 }
        private void CreateErrorReply(ref RequestContext p_RequestContext)
        {
            var l_Message = new CustomResponse();
            l_Message.Message = "Login Failed";

             using (Message reply = Message.CreateMessage(MessageVersion.None, "", l_Message, new DataContractJsonSerializer(typeof(CustomResponse))))
             {
                 var responseProp = new HttpResponseMessageProperty
                 {
                     StatusCode = HttpStatusCode.Forbidden,
                     StatusDescription = String.Format("Forbidden")
                 };

                 responseProp.Headers.Add("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", Realm));
                 responseProp.Headers[HttpResponseHeader.ContentType] = "application/json; charset=utf-8";
                 reply.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
                 reply.Properties[HttpResponseMessageProperty.Name] = responseProp;

                 p_RequestContext.Reply(reply);
                 // set the request context to null to terminate processing of this request
                 p_RequestContext = null;

             }
        }
Ejemplo n.º 20
0
        void ProvideFaultAndReplyFailure(RequestContext request, Exception exception, ref ErrorHandlerFaultInfo faultInfo, out bool replied, out bool replySentAsync)
        {
            replied = false;
            replySentAsync = false;
            bool requestMessageIsFault = false;
            try
            {
                requestMessageIsFault = request.RequestMessage.IsFault;
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                // ---- it
            }

            bool enableFaults = false;
            if (this.listener != null)
            {
                enableFaults = this.listener.ChannelDispatcher.EnableFaults;
            }
            else if (this.channel != null && this.channel.IsClient)
            {
                enableFaults = this.channel.ClientRuntime.EnableFaults;
            }

            if ((!requestMessageIsFault) && enableFaults)
            {
                this.ProvideFault(exception, ref faultInfo);
                if (faultInfo.Fault != null)
                {
                    Message reply = faultInfo.Fault;
                    try
                    {
                        try
                        {
                            if (this.PrepareReply(request, reply))
                            {
                                if (this.sendAsynchronously)
                                {
                                    var state = new ContinuationState { ChannelHandler = this, Channel = channel, Exception = exception, FaultInfo = faultInfo, Request = request, Reply = reply };
                                    var result = request.BeginReply(reply, ChannelHandler.onAsyncReplyComplete, state);
                                    if (result.CompletedSynchronously)
                                    {
                                        ChannelHandler.AsyncReplyComplete(result, state);
                                        replied = true;
                                    }
                                    else
                                    {
                                        replySentAsync = true;
                                    }
                                }
                                else
                                {
                                    request.Reply(reply);
                                    replied = true;
                                }
                            }
                        }
                        finally
                        {
                            if (!replySentAsync)
                            {
                                reply.Close();
                            }
                        }
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        this.HandleError(e);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public void HandleRequest(RequestContext context)
        {
            Debug.Assert(context != null);

            if (context.RequestMessage.Headers.Action == requestAction)
            {
                XmlDictionaryReader reader = context.RequestMessage.GetReaderAtBodyContents();
                DataContractSerializer serializer = new DataContractSerializer(typeof(string));
                reader.ReadStartElement(); // read wrapper begin
                string value = (string)serializer.ReadObject(reader, false);
                reader.ReadEndElement(); // read wrapper end

                reader.Close();

                string result = serviceInstance.Hello(value);
                ResponseBodyWriter responseBodyWriter = new ResponseBodyWriter(
                    HelloWorldService.OperationName,
                    HelloWorldService.Namespace);
                responseBodyWriter.Result = result;

                MessageVersion requestVersion = context.RequestMessage.Version;
                UniqueId requestId = context.RequestMessage.Headers.MessageId;

                Message reply = Message.CreateMessage(requestVersion,
                                                      responseAction,
                                                      responseBodyWriter);

                PrepareReply(reply, requestId);
                if (context.RequestMessage.Headers.ReplyTo != null)
                {
                    reply.Headers.To = context.RequestMessage.Headers.ReplyTo.Uri;
                }

                context.Reply(reply);
            }
            else
            {                
                object property = null;
                if (context.RequestMessage.Properties.TryGetValue(HttpRequestMessageProperty.Name,
                    out property))
                {
                    if (string.Compare(((HttpRequestMessageProperty)property).Method, "GET", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        HandleHttpGet(context);
                        return;
                    }
                }

                SendMismatchFault(context);
            }
        }
Ejemplo n.º 22
0
        public void ProcessRequest(RequestContext context)
        {
            MessageHeaders headers = context.RequestMessage.Headers;

            //create new request channel if needed
            IRequestChannel requestChannel = null;
            if (!_Clients.TryGetValue(headers.To, out requestChannel))
            {
                WSHttpBinding binding = CreateBinding();
                IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
                factory.Open();

                requestChannel = factory.CreateChannel(new EndpointAddress(headers.To));
                requestChannel.Open();
                _Clients.Add(headers.To, requestChannel);
            }

            //forward request and send back response
            MessageContainer container = new MessageContainer();
            Message incoming = CopyMessage(context.RequestMessage, container, MessageDirection.Incoming);
            if ((DateTime.Now - _LastReceived).TotalMilliseconds > 1750)
            {
                _Group += 1;
            }
            container.Group = _Group;
            _LastReceived = DateTime.Now;

            //add request to gui
            Action<int, MessageContainer> msg = new Action<int, MessageContainer>(Messages.Insert);
            this.Dispatcher.Invoke(msg, new object[] { 0, container });

            //get response
            Message responseMessage = requestChannel.Request(incoming);
            Message outgoing = CopyMessage(responseMessage, container, MessageDirection.Outgoing);
            context.Reply(outgoing);
        }
 private bool Reply(RequestContext request, Message reply)
 {
     if (this.replied != request)
     {
         this.replied = request;
         bool flag = true;
         Message objA = null;
         try
         {
             objA = request.RequestMessage;
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
         }
         if (!object.ReferenceEquals(objA, null))
         {
             UniqueId messageId = null;
             try
             {
                 messageId = objA.Headers.MessageId;
             }
             catch (MessageHeaderException)
             {
             }
             if (!object.ReferenceEquals(messageId, null) && !this.isManualAddressing)
             {
                 RequestReplyCorrelator.PrepareReply(reply, messageId);
             }
             if (!this.hasSession && !this.isManualAddressing)
             {
                 try
                 {
                     flag = RequestReplyCorrelator.AddressReply(reply, objA);
                 }
                 catch (MessageHeaderException)
                 {
                 }
             }
         }
         if (this.IsOpen && flag)
         {
             request.Reply(reply);
             return true;
         }
     }
     return false;
 }
        private void ReplyWithMetaData(RequestContext context)
        {
            var action = context.RequestMessage.Headers.Action;

            var contractInfo = ContractInfo.FromAction(action);

            var contractType = TypeFinder.FindServiceContract(contractInfo.ServiceContractName);

            var paramTypes = TypeFinder.GetContractParamTypes(contractType, contractInfo.OperationContractName, contractInfo.Action);

            var modelProvider = ObjectBuilder.GetModelProvider();

            var typeMetaDatas = new Dictionary<string, string>();
            var serializer = ObjectBuilder.GetSerializer();

            foreach (var paramType in paramTypes)
            {
                if (typeMetaDatas.ContainsKey(paramType.Name))
                    continue;

                var modelInfo = modelProvider.CreateModelInfo(paramType.Type);

                var metaData = modelInfo.MetaData;

                var result = serializer.Serialize(metaData);

                var val = BinaryConverter.ToString(result.Data);

                typeMetaDatas.Add(paramType.Name, val);
            }

            var replyMessage = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, context.RequestMessage.Headers.Action);

            foreach (var typeMetaData in typeMetaDatas)
            {
                replyMessage.Headers.Add(MessageHeader.CreateHeader(Constants.MetaDataHeaderKeySuffix + typeMetaData.Key, 
                    Constants.DefaultCustomHeaderNamespace, typeMetaData.Value));
            }

            context.Reply(replyMessage);

            context.Close();
        }
Ejemplo n.º 25
0
 void SendMismatchFault(RequestContext context)
 {
     Message message = Message.CreateMessage(context.RequestMessage.Version, MessageFault.CreateFault(new FaultCode("NotSupported"), "The request is not supported"), responseAction);
     context.Reply(message);
 }