/// <summary>
        /// 和tcp不同。。。会先触发一次read。。再active
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="received"></param>
        public override void FireChannelRead(byte[] buffer, int offset, int received)
        {
            byte[] bytes = new byte[received];
            Array.Copy(buffer, offset, bytes, 0, bytes.Length);

            if (this.ClientID == 0)
            {
                IResponseMessage message = null;
                try
                {
                    message = MessageFactory.Parse(bytes);
                }
                catch (Exception)
                {
                }

                if (message != null && message.ContractID == (int)ContractType.HandShake)
                {
                    if (mKcp != null)
                    {
                        this.mKcp.Dispose();
                    }
                    MessageFactory.ParseConnectionInfo(message.BodyContent, this);
                    this.init_kcp((uint)this.ClientID);
                }
            }
            else
            {
                mRecvQueue.Push(bytes);
            }
        }
示例#2
0
        private GladNet.Common.SendResult TryRouteMessage(IResponseMessage message, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
        {
            //WARNING: Make sure to send encrypted parameter. There was a fault where we didn't. We cannot unit test it as it's within a MonoBehaviour
            switch (this.photonPeer.SendOperationResponse(new OperationResponse(1, new Dictionary <byte, object>()
            {
                { 1, message.SerializeWithVisitor(this.serializerStrategy) }
            }),
                                                          new SendParameters()
            {
                Unreliable = !deliveryMethod.isReliable(), ChannelId = channel, Encrypted = encrypt
            }))
            {
            case Photon.SocketServer.SendResult.Disconnected:
                return(GladNet.Common.SendResult.FailedNotConnected);

            default:
            case Photon.SocketServer.SendResult.SendBufferFull:
            case Photon.SocketServer.SendResult.MessageToBig:
            case Photon.SocketServer.SendResult.InvalidContentType:
            case Photon.SocketServer.SendResult.EncryptionNotSupported:
            case Photon.SocketServer.SendResult.InvalidChannel:
            case Photon.SocketServer.SendResult.Failed:
                return(GladNet.Common.SendResult.Invalid);

            case Photon.SocketServer.SendResult.Ok:
                return(GladNet.Common.SendResult.Queued);
            }
        }
示例#3
0
        public bool TryProcessMessage(IResponseMessage message, IMessageParameters parameters, TPeerType peer)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (peer == null)
            {
                throw new ArgumentNullException(nameof(peer));
            }

            TPayloadType payload = message.Payload.Data as TPayloadType;

            //if it's the not the payload type this handler handles then we
            //indicate non-consumption
            if (payload == null)
            {
                return(false);
            }
            else
            {
                OnIncomingHandlableMessage(message, payload, parameters, peer);
            }

            //If an exception wasn't thrown we'll be indicating that the payload has been consumed.
            return(true);
        }
示例#4
0
        public void SetResponse(IResponseMessage pResponse)
        {
            _objKeepAliveMonitor.Stop();
            _objKeepAliveMonitor.TimeOut      -= _objKeepAliveMonitor_TimeOut;
            _objKeepAliveMonitor.UnResponsive -= _objKeepAliveMonitor_UnResponsive;

            Task.Run(() => {
                var objSpan = (pResponse.EndTime - pResponse.StartTime);

                Log.Info(
                    String.Format(
                        "Response {0} received for {1} took {2}",
                        Message.Name,
                        $"{Message.ID}",
                        String.Format(
                            "{0}:{1}:{2}.{3}",
                            $"{objSpan.Hours.ToString().PadLeft(2, '0')}",
                            $"{objSpan.Minutes.ToString().PadLeft(2, '0')}",
                            $"{objSpan.Seconds.ToString().PadLeft(2, '0')}",
                            $"{objSpan.Milliseconds.ToString().PadLeft(3, '0')}"
                            )
                        )
                    );
                _objAction.DynamicInvoke(pResponse);
            });
        }
示例#5
0
        public async Task <SendResult> Send(IResponseMessage message)
        {
            if (message == null)
            {
                throw new NullReferenceException(nameof(message));
            }

            var aliyunMessage = message as AliyunMessage;

            if (aliyunMessage == null)
            {
                throw new NotSupportedException($"当前发布者提供程序:{GetType().FullName},无法发送类型为:{message.GetType().FullName}的消息。");
            }
            if (string.IsNullOrWhiteSpace(aliyunMessage.Topic))
            {
                throw new ArgumentException("消息主题(Topic)不能为空!");
            }
            if (string.IsNullOrWhiteSpace(aliyunMessage.Body))
            {
                throw new ArgumentException("消息主体(Body)不能为空!");
            }

            return(await Task.Run(() =>
            {
                using (var result = _producer.send(aliyunMessage.Message))
                {
                    return new SendResult {
                        MessageId = result.getMessageId()
                    };
                }
            }));
        }
示例#6
0
        /// <summary>
        /// 和tcp不同。。。会先触发一次read。。再active
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="received"></param>
        public override void FireChannelRead(byte[] buffer, int offset, int received)
        {
            byte[] bytes = new byte[received];
            Array.Copy(buffer, offset, bytes, 0, bytes.Length);

            IResponseMessage message = null;

            try
            {
                message = MessageFactory.Parse(bytes);
            }
            catch (Exception)
            {
            }

            if (message == null)
            {
                return;
            }

            if (this.ClientID == 0 && message.ContractID == (int)ContractType.HandShake)
            {
                MessageFactory.ParseConnectionInfo(message.BodyContent, this);
            }
            else
            {
                this.OnRead(this, message);
            }
        }
示例#7
0
        protected override Transition HandleResponseMessage(IResponseMessage responseMessage)
        {
            if (responseMessage is KnowledgeExchangeRequestMessage knowledgeExchangeRequest)
            {
                var initiatorId = knowledgeExchangeRequest.SenderPlayerId;
                //Console.WriteLine($"Player #{initiatorId} requested communication in state {this}");
                IMessage knowledgeExchangeResponse =
                    new RejectKnowledgeExchangeMessage(PlayerStrategyInfo.PlayerId, initiatorId,
                                                       PlayerStrategyInfo.PlayerGuid);

                if (IsExchangeWantedWithPlayer(initiatorId))
                {
                    knowledgeExchangeResponse =
                        DataMessage.FromBoardData(
                            PlayerStrategyInfo.Board.ToBoardData(PlayerStrategyInfo.PlayerId, initiatorId), false,
                            PlayerStrategyInfo.PlayerGuid);
                }

                return(new LoopbackTransition(this, new List <IMessage> {
                    knowledgeExchangeResponse
                }));
            }

            if (responseMessage is DataMessage dataMessage && dataMessage.GoalFields.Length > 1)
            {
                HandleSuccessfulKnowledgeExchange();
                return(new LoopbackTransition(this, new List <IMessage>()));
            }

            return(base.HandleResponseMessage(responseMessage));
        }
示例#8
0
        /// <summary>
        /// 创建实例 状态成员
        /// </summary>
        /// <typeparam name="T_IHandler">IHandler类型</typeparam>
        /// <param name="hanlderConfig">IHandlerConfig</param>
        public static void CreateInstanceStatusMember <T_IHandler>(this IHandlerConfig <T_IHandler> hanlderConfig,
                                                                   out IResponseMessage readyMessage, out IResponseMessage successResult, out IResponseMessage failResult)
            where T_IHandler : IHandler
        {
            //初始化
            readyMessage  = null;
            successResult = null;
            failResult    = null;

            //根据赋值情况进行创建
            if (hanlderConfig.ReadyMessageConfig != null)
            {
                dynamic config = hanlderConfig.ReadyMessageConfig;
                readyMessage = config.CreateInstanceFromConfig();
            }
            if (hanlderConfig.SuccessResultConfig != null)
            {
                dynamic config = hanlderConfig.SuccessResultConfig;
                readyMessage = config.CreateInstanceFromConfig();
            }
            if (hanlderConfig.FailResultConfig != null)
            {
                dynamic config = hanlderConfig.FailResultConfig;
                readyMessage = config.CreateInstanceFromConfig();
            }
        }
        /// <inheritdoc />
        protected override async Task UpdateBuild(Build build, ChangeBuildState command)
        {
            StateChangeCheckResult result = await changeChecker.Check(build, command.NewState);

            if (!result.CanChange)
            {
                throw new ValidationException(new BuildTransferRuleCheckValidationError()
                {
                    ErrorName = "StateTranslateRuleViolation",
                    From      = build.LifeCycleState,
                    To        = command.NewState,
                    Rules     = result.UnMatchRuleNames,
                });
            }

            List <string> newSuffixes = GetNewSuffixes(build.Suffixes.ToArray(), build.LifeCycleState, command.NewState).ToList();

            Logger.LogDebug($"Try change state of build {build}. NewState: {command.NewState}. NewSuffixes: {newSuffixes.JoinWith(",")}");

            IResponseMessage response =
                await buildSyncService.ChangeSuffix(build.Location, build.SourceType, newSuffixes, build.Suffixes.ToList());

            switch (response)
            {
            case ChangeSuffixesResponse {
                    IsSuccessful: true
            } :
                build.UpdateLifeCycleState(command.NewState, DateTime.Now, command.Comment, command.User.Sid);
                return;
        /// <summary>
        /// Returns true, if there is a WWW-Authenticate header containing ts and tsm but mac
        /// computed for ts does not match tsm, indicating possible tampering. Otherwise, returns false.
        /// This method also sets the compensation field so that the timestamp in the subsequent requests
        /// are adjusted to reduce the clock skew.
        /// </summary>
        private bool IsTimestampResponseTampered(ArtifactsContainer artifacts, IResponseMessage response)
        {
            var wwwHeader = response.WwwAuthenticate;

            if (wwwHeader != null)
            {
                string parameter = wwwHeader.Parameter;

                ArtifactsContainer timestampArtifacts;
                if (!String.IsNullOrWhiteSpace(parameter) &&
                    ArtifactsContainer.TryParse(parameter, out timestampArtifacts))
                {
                    var ts = new NormalizedTimestamp(timestampArtifacts.Timestamp, options.CredentialsCallback(), options.LocalTimeOffsetMillis);

                    if (!ts.IsValid(timestampArtifacts.TimestampMac))
                    {
                        return(true);
                    }

                    lock (myPrecious)
                        HawkClient.CompensatorySeconds = (int)(timestampArtifacts.Timestamp - DateTime.UtcNow.ToUnixTime());

                    Tracing.Information("HawkClient.CompensatorySeconds set to " + HawkClient.CompensatorySeconds);
                }
            }

            return(false);
        }
示例#11
0
        private async Task <SlackChatHub> GetChatHub(
            IResponseMessage responseMessage,
            ISlackConnection slackConnection)
        {
            SlackChatHub chatHub = null;

            switch (responseMessage.ResponseType)
            {
            case ResponseType.Channel:
                chatHub = new SlackChatHub {
                    Id = responseMessage.Channel
                };
                break;

            case ResponseType.DirectMessage when string.IsNullOrEmpty(responseMessage.Channel):
                chatHub = await GetUserChatHub(
                    responseMessage.UserId,
                    slackConnection);

                break;

            case ResponseType.DirectMessage:
                chatHub = new SlackChatHub {
                    Id = responseMessage.Channel
                };
                break;
            }

            return(chatHub);
        }
示例#12
0
        /// <summary>
        ///     Adds a breakpoint.
        /// </summary>
        /// <param name="breakpoint">Break point.</param>
        public async Task AddBreakpointAsync(NodeBreakpoint breakpoint)
        {
            IResponseMessage response = await _client.SendMessage("setbreakpoint", new
            {
                type      = "script",
                target    = breakpoint.Filename,
                line      = breakpoint.Line,
                column    = breakpoint.Column,
                condition = breakpoint.Condition
            }).ConfigureAwait(false);

            var setBreakpointMessage = response as SetBreakpointMessage;

            if (setBreakpointMessage == null || !setBreakpointMessage.IsSuccessful)
            {
                string message = string.Format("Invalid breakpoint response: {0}", response);
                throw new InvalidOperationException(message);
            }

            IsRunning         = response.IsRunning;
            breakpoint.Id     = setBreakpointMessage.Id;
            breakpoint.Line   = setBreakpointMessage.Line;
            breakpoint.Column = setBreakpointMessage.Column;

            if (!_wasContinued)
            {
                CheckWhetherFirstLineBreakpoint(breakpoint);
            }

            _breakpoints.Add(breakpoint.Id, breakpoint);
        }
示例#13
0
        public async Task InitializeAsync()
        {
            // Retrieve v8 version
            IResponseMessage response = await _client.SendMessage("version").ConfigureAwait(false);

            var versionMessage = response as VersionMessage;

            if (versionMessage == null || !versionMessage.IsSuccessful)
            {
                string message = string.Format("Invalid version response: {0}", response);
                throw new InvalidOperationException(message);
            }

            IsRunning        = versionMessage.IsRunning;
            _v8EngineVersion = versionMessage.Version;

            response = await _client.SendMessage("frame", new { inlineRefs = true }).ConfigureAwait(false);

            var frameMessage = response as FrameMessage;

            if (frameMessage == null || !frameMessage.IsSuccessful)
            {
                string message = string.Format("Invalid listbreakpoints response: {0}", response);
                throw new InvalidOperationException(message);
            }

            foreach (NodeScript script in frameMessage.Scripts)
            {
                AddModuleIfNotExist(script.Id, script.Filename);
            }

            _initialFrame = frameMessage;
        }
示例#14
0
 static void LogResponse(IResponseMessage response)
 {
     if (Services.IsRegistered(typeof(ILogQueue)))
     {
         Services.Create <ILogQueue>().LogQueueMessage(response);
     }
 }
示例#15
0
        public sealed override void OnReceiveResponse(IResponseMessage message, IMessageParameters parameters)
        {
            //TODO: Phase out easyexception
            Throw <ArgumentNullException> .If.IsNull(message)?.Now(nameof(message), $"Cannot have a null {nameof(IResponseMessage)} in on recieve. This should never occur internally. Indicates major fault. Should never reach this point.");

            responseHandler.TryProcessMessage(message, null, this as TInheritingType);
        }
示例#16
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);
            }
        }
示例#17
0
        //-----------Static------------

        #region 创建实例

        private static DefaultDealingHandler InternalCreateInstance(IResponseMessage DealingMessage)
        {
            DefaultDealingHandler result = new DefaultDealingHandler
            {
                DealingMessage = DealingMessage,
            };

            return(result);
        }
示例#18
0
        public sealed override void OnReceiveResponse(IResponseMessage message, IMessageParameters parameters)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            ResponseMessageHandler.TryProcessMessage(message, null, this as TInheritingType);
        }
        protected override Transition HandleResponseMessage(IResponseMessage responseMessage)
        {
            if (responseMessage is DataMessage)
            {
                return(new LoopbackTransition(this, new List <IMessage>()));
            }

            return(base.HandleResponseMessage(responseMessage));
        }
示例#20
0
        public void SetResponse(IResponseMessage response)
        {
            //if (this.MessageType == MessageType.Event)
            //{
            //    throw new WeixinException("事件无需设置Response");
            //}

            this.Response = response;
        }
        /// <summary>
        /// Returns the name of the response header (WWW-Authenticate or Server-Authorization) and the corresponding
        /// value, respectively for an unauthorized and a successful request.
        /// </summary>
        public async Task <Tuple <string, string> > CreateServerAuthorizationAsync(IResponseMessage response)
        {
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                string challenge   = String.Format(" {0}", request.ChallengeParameter ?? String.Empty);
                string headerValue = HawkConstants.Scheme + challenge.TrimEnd(' ');

                return(new Tuple <string, string>(HawkConstants.WwwAuthenticateHeaderName, headerValue));
            }
            else
            {
                // No Server-Authorization header for the following:
                // (1) There is no result or failed authentication.
                // (2) The credential is a bewit.
                // (3) The server is configured to not send the header.
                bool createHeader = this.result != null &&
                                    this.result.IsAuthentic &&
                                    (!this.IsBewitRequest) &&
                                    options.EnableServerAuthorization;

                if (createHeader)
                {
                    if (options.NormalizationCallback != null)
                    {
                        this.result.Artifacts.ApplicationSpecificData = options.NormalizationCallback(response);
                    }

                    // Sign the response
                    Tuple <string, string> hostAndPort = options.DetermineHostDetailsCallback(request);
                    var normalizedRequest = new NormalizedRequest(request, this.result.Artifacts, hostAndPort.Item1, hostAndPort.Item2)
                    {
                        IsServerAuthorization = true
                    };
                    var crypto = new Cryptographer(normalizedRequest, this.result.Artifacts, this.result.Credential);

                    // Response body is needed only if payload hash must be included in the response MAC.
                    string body = null;
                    if (options.ResponsePayloadHashabilityCallback != null &&
                        options.ResponsePayloadHashabilityCallback(this.request))
                    {
                        body = await response.ReadBodyAsStringAsync();
                    }

                    crypto.Sign(body, response.ContentType);

                    string authorization = this.result.Artifacts.ToServerAuthorizationHeaderParameter();

                    if (!String.IsNullOrWhiteSpace(authorization))
                    {
                        return(new Tuple <string, string>(HawkConstants.ServerAuthorizationHeaderName,
                                                          String.Format("{0} {1}", HawkConstants.Scheme, authorization)));
                    }
                }
            }

            return(null);
        }
示例#22
0
文件: Room.cs 项目: djmuted/Redfox
 public void SendMessage(IResponseMessage message, User skipUser = null)
 {
     foreach (User user in users)
     {
         if (user != skipUser)
         {
             user.SendMessage(message);
         }
     }
 }
 /// <summary>
 /// Конвертирует <see cref="IResponseMessage"/> в <see cref="ActionResult"/> с помощью указанной лямбда-функции, либо возвращает BadRequest.
 /// </summary>
 /// <typeparam name="TResposeType">Тип ответа, передаваемый в лямбда функцию.</typeparam>
 /// <typeparam name="TResult">Желаемый тип для <see cref="ActionResult"/>.</typeparam>
 /// <param name="response">Пришедший ответ.</param>
 /// <param name="continueWith">Лямбла-функция.</param>
 /// <returns>Ответ веб сервера.</returns>
 public static ActionResult <TResult> ToActionResult <TResposeType, TResult>(this IResponseMessage response, Func <TResposeType, ActionResult <TResult> > continueWith)
 {
     return(response switch
     {
         ErrorResponseMessage e => new ObjectResult(e.Message)
         {
             StatusCode = (int)HttpStatusCode.BadRequest
         },
         _ => continueWith((TResposeType)response)
     });
示例#24
0
        public ResponseMessagesBuilder AddMessage(IResponseMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException($"{message} is null");
            }

            responseMessages.Add(message);
            return(this);
        }
        protected override void OnIncomingHandlableMessage(IResponseMessage message, PlayerSpawnResponsePayload payload, IMessageParameters parameters, InstanceClientPeer peer)
        {
            //TODO: Implement spawning
            logger.Info($"Recieved player spawn response. {payload.ResponseCode} {payload.Position} {payload.Rotation}");

            gameobjectFactory.CreateBuilder()
            .With(Service <INetPeer> .As(peer))
            .With(Service <NetworkEntityGuid> .As(payload.EntityGuid))
            .Create(playerPrefab, payload.Position.ToVector3(), payload.Rotation.ToQuaternion());
        }
示例#26
0
        private bool TryInformCorrespondingChildAwaiter(IResponseMessage response)
        {
            if (_tokenBuffer.TryRemove(response.Target, out var cts))
            {
                cts?.Cancel();
                cts?.Dispose();
                return(true);
            }

            return(false);
        }
示例#27
0
 protected override void OnIncomingHandlableMessage(IResponseMessage message, AuthenticationResponse payload, IMessageParameters parameters, AuthenticationWebClient peer)
 {
     if (payload.AuthenticationSuccessful)
     {
         OnSuccess?.Invoke();
     }
     else
     {
         OnFailure?.Invoke(payload.OptionalError ?? ResponseErrorCode.Error, payload.OptionalErrorMessage);
     }
 }
        public IResponseMessage RunCommand <T>(IRequest request)
        {
            IProcess process = processFactory.GetProcess(request);

            IResponseMessage validationResponseMessage = process.Validate(request);

            if (validationResponseMessage.StatusCode != Status.FAILURE)
            {
                return(process.Process(request));
            }
            return(validationResponseMessage);
        }
示例#29
0
        public override void FireChannelRead(byte[] buffer, int offset, int received)
        {
            InputStream.Seek(0, SeekOrigin.End);
            InputStream.Write(buffer, offset, received);
            InputStream.Seek(0, SeekOrigin.Begin);

            //如果消息流有消息头的长度
            while (RemainingBytes(InputStream) > 2)
            {
                //消息长度
                short messageLen = reader.ReadInt16();
                //如果消息流中有足够的消息body数据
                if (RemainingBytes(InputStream) >= messageLen)
                {
                    var bytes = reader.ReadBytes(messageLen);
                    IResponseMessage message = null;
                    try
                    {
                        message = MessageFactory.Parse(bytes);
                    }
                    catch (Exception)
                    {
                    }

                    if (message == null)
                    {
                        return;
                    }

                    if (this.ClientID == 0 && message.ContractID == (int)ContractType.HandShake)
                    {
                        MessageFactory.ParseConnectionInfo(message.BodyContent, this);
                        if (OnHandShake != null)
                        {
                            this.OnHandShake(this);
                        }
                    }
                    else
                    {
                        this.OnRead(this, message);
                    }
                }
                else
                {  //如果没有足够的数据,则将指针移到消息头长度前
                    InputStream.Position = InputStream.Position - 2;
                    break;
                }
            }
            //剩下的字节
            byte[] leftover = reader.ReadBytes((int)RemainingBytes(InputStream));
            InputStream.SetLength(0);
            InputStream.Write(leftover, 0, leftover.Length);
        }
示例#30
0
 public void HandleResponse(IResponseMessage <IResponseData> response)
 {
     foreach (var pendingRequest in _pendingRequests.Value)
     {
         if (pendingRequest.Id == response.Id)
         {
             var request = pendingRequest;
             _pendingRequests.Update(l => l.Remove(request));
             request.SetResult(response);
         }
     }
 }
示例#31
0
 /// <summary>
 /// Runs the Request asynchronously in a Task
 ///
 /// Note that this uses an extra thread
 /// it is recommended to use Request<R>(IRequestMessage, Action<R>) instead
 /// as that uses much less resources
 /// </summary>
 /// <typeparam name="R"></typeparam>
 /// <param name="pRequest"></param>
 /// <returns></returns>
 public async Task<R> RequestAsync<R>(IRequestMessage pRequest) where R : IResponseMessage {
     return await Task.Run<R>(() => {
         ManualResetEvent objBlock = new ManualResetEvent(false);
         IResponseMessage objResponse = null;
         Request<R>(pRequest, r => {
             objResponse = r;
             objBlock.Set();
         });
         objBlock.WaitOne();
         return (R)objResponse;
     });
 }
        /// <summary>
        /// Returns true, if the HMAC computed for the response payload matches the HMAC in the
        /// Server-Authorization response header. This method also sets the compensation field so 
        /// that the timestamp in the subsequent requests are adjusted to reduce the clock skew.
        /// </summary>
        public async Task<bool> AuthenticateAsync(IResponseMessage response)
        {
            if (response.StatusCode != HttpStatusCode.Unauthorized &&
                    this.options.EnableResponseValidation &&
                        await this.IsResponseTamperedAsync(artifacts, crypto, response))
                return false;

            if (this.options.EnableAutoCompensationForClockSkew &&
                    this.IsTimestampResponseTampered(artifacts, response))
                return false;

            return true;
        }
示例#33
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);
            }
        }
示例#34
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);
            }
        }
示例#35
0
        public async Task<SendResult> Send(IResponseMessage message)
        {
            if (message == null)
                throw new NullReferenceException(nameof(message));

            var aliyunMessage = message as AliyunMessage;

            if (aliyunMessage == null)
                throw new NotSupportedException($"当前发布者提供程序:{GetType().FullName},无法发送类型为:{message.GetType().FullName}的消息。");
            if (string.IsNullOrWhiteSpace(aliyunMessage.Topic))
                throw new ArgumentException("消息主题(Topic)不能为空!");
            if (string.IsNullOrWhiteSpace(aliyunMessage.Body))
                throw new ArgumentException("消息主体(Body)不能为空!");

            return await Task.Run(() =>
            {
                using (var result = _producer.send(aliyunMessage.Message))
                {
                    return new SendResult { MessageId = result.getMessageId() };
                }
            });
        }
示例#36
0
 public InvokeActionsResult InvokeBeforeActions(IRequestMessage request, IResponseMessage response)
 {
     return ResolvedService.InvokeActions(this.BeforeActions, request, response, null);
 }
        /// <summary>
        /// Returns true, if there is a WWW-Authenticate header containing ts and tsm but mac
        /// computed for ts does not match tsm, indicating possible tampering. Otherwise, returns false.
        /// This method also sets the compensation field so that the timestamp in the subsequent requests
        /// are adjusted to reduce the clock skew.
        /// </summary>
        private bool IsTimestampResponseTampered(ArtifactsContainer artifacts, IResponseMessage response)
        {
            var wwwHeader = response.WwwAuthenticate;

            if (wwwHeader != null)
            {
                string parameter = wwwHeader.Parameter;

                ArtifactsContainer timestampArtifacts;
                if (!String.IsNullOrWhiteSpace(parameter) &&
                                ArtifactsContainer.TryParse(parameter, out timestampArtifacts))
                {
                    var ts = new NormalizedTimestamp(timestampArtifacts.Timestamp, options.CredentialsCallback(), options.LocalTimeOffsetMillis);

                    if (!ts.IsValid(timestampArtifacts.TimestampMac))
                        return true;

                    lock (myPrecious)
                        HawkClient.CompensatorySeconds = (int)(timestampArtifacts.Timestamp - DateTime.UtcNow.ToUnixTime());

                    Tracing.Information("HawkClient.CompensatorySeconds set to " + HawkClient.CompensatorySeconds);
                }
            }

            return false;
        }
        /// <summary>
        /// Returns true if the server response HMAC cannot be validated, indicating possible tampering.
        /// </summary>
        private async Task<bool> IsResponseTamperedAsync(ArtifactsContainer artifacts, Cryptographer crypto,
                                                        IResponseMessage response)
        {
            if (response.Headers.ContainsKey(HawkConstants.ServerAuthorizationHeaderName))
            {
                string header = response.Headers[HawkConstants.ServerAuthorizationHeaderName].FirstOrDefault();

                if (!String.IsNullOrWhiteSpace(header) &&
                                    header.Substring(0, HawkConstants.Scheme.Length).ToLower() == HawkConstants.Scheme)
                {
                    ArtifactsContainer serverAuthorizationArtifacts;
                    if (ArtifactsContainer.TryParse(header.Substring(HawkConstants.Scheme.Length + " ".Length),
                                                                                    out serverAuthorizationArtifacts))
                    {
                        // To validate response, ext, hash, and mac in the request artifacts must be
                        // replaced with the ones from the server.
                        artifacts.ApplicationSpecificData = serverAuthorizationArtifacts.ApplicationSpecificData;
                        artifacts.PayloadHash = serverAuthorizationArtifacts.PayloadHash;
                        artifacts.Mac = serverAuthorizationArtifacts.Mac;

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

                        bool isValid = crypto.IsSignatureValid(body, response.ContentType);

                        if (isValid)
                        {
                            string appSpecificData = serverAuthorizationArtifacts.ApplicationSpecificData;

                            isValid = options.VerificationCallback == null ||
                                                    options.VerificationCallback(response, appSpecificData);
                        }

                        return !isValid;
                    }
                }
            }

            return true; // Missing header means possible tampered response (to err on the side of caution).
        }
示例#39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resultMessage"></param>
        /// <param name="returnType"></param>
        /// <param name="formatter"></param>
        /// <returns></returns>
        protected virtual object GetResult(IResponseMessage resultMessage, Type returnType, IFormatter formatter)
        {
            if (resultMessage.IsSuccess)
            {
                if (resultMessage.Result == null || returnType == null)
                    return null;

                var objType = returnType;

                try
                {
                    var resultObj = formatter.Deserialize(resultMessage.Result, objType);
                    return resultObj;
                }
                catch (Exception ex)
                {
                    throw new ServiceException("parse data received error", ex);
                }
                finally
                {
                    resultMessage.Dispose();
                }
            }

            if (resultMessage.Headers.Count == 0)
                throw new ServiceException("service url is not a service address");

            var exceptionAssembly = resultMessage.Headers[HeaderName.ExceptionAssembly];
            var exceptionTypeName = resultMessage.Headers[HeaderName.ExceptionType];

            if (string.IsNullOrWhiteSpace(exceptionAssembly) || string.IsNullOrWhiteSpace(exceptionTypeName))
            {
                throw new ClientException("exception occored, but no ExceptionAssembly and ExceptionType returned");
            }

            Type exceptionType;
            try
            {
            #if NETCORE
                var asm = Assembly.Load(new AssemblyName(exceptionAssembly));
            #else
                var asm = Assembly.Load(exceptionAssembly);
            #endif
                exceptionType = asm.GetType(exceptionTypeName);
            }
            catch (Exception ex)
            {
                LogHelper.Error("can't find exception type " + exceptionTypeName, ex);
                exceptionType = typeof(Exception);
            }

            object exObj;
            try
            {
                //var buf = new byte[8192];
                //var readLength = resultMessage.Result.Read(buf, 0, buf.Length);
                //var json = Encoding.UTF8.GetString(buf);

                exObj = formatter.SupportException
                    ? formatter.Deserialize(resultMessage.Result, exceptionType)
                    : Activator.CreateInstance(exceptionType);
            }
            catch (Exception ex)
            {
                throw new ClientException("Deserialize Response failed", ex);
            }

            if (exObj != null)
                throw (Exception)exObj;

            //return default(TResult);
            throw new ServiceException("exception occored but no exception data transported");
        }
示例#40
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;
        }
示例#41
0
        public WriteResponseResult WriteResponse(IResponseMessage response, string acceptEncoding, string accept)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response", "response cannot be null.");
            }

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

            if (response.ResponseObject != null)
            {
                EncodingLookupResult encodingResult = this.GetResponseEncoder(acceptEncoding);

                if (encodingResult != null)
                {
                    FormatLookupResult formatResult = this.GetResponseSerializer(accept);

                    if (formatResult != null)
                    {
                        try
                        {
                            try
                            {
                                response.SetEncodingFilter(encodingResult.EncodingType, encodingResult.Encoding);
                            }
                            catch (PlatformNotSupportedException)
                            {
                                // Custom Content-Encoding values are only supported in
                                // Integrated Pipeline Mode.
                            }

                            response.WriteOutputContent(formatResult.MediaType, formatResult.Format);
                        }
                        catch (Exception ex)
                        {
                            result.Exception = ex;
                            result.StatusCode = StatusCode.InternalServerError;
                            result.Success = false;
                        }
                    }
                    else
                    {
                        result.StatusCode = StatusCode.NotAcceptable;
                        result.Success = false;
                    }
                }
                else
                {
                    result.StatusCode = StatusCode.NotAcceptable;
                    result.Success = false;
                }
            }
            else
            {
                response.WriteOutputContent(ResolvedService.DefaultFormatLookupResult.MediaType, ResolvedService.DefaultFormatLookupResult.Format);
            }

            return result;
        }
示例#42
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);
        }
示例#43
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"));
     }
 }
示例#44
0
 /// <summary>
 /// 根据相应消息得到xml内容。
 /// </summary>
 /// <param name="responseMessage">响应消息实例。</param>
 /// <returns>xml内容。</returns>
 public string GetXmlByReponseMessage(IResponseMessage responseMessage)
 {
     return _messageFormatterFactory.GetFormatter(responseMessage.MessageType).Serialize(responseMessage);
 }
        /// <summary>
        /// Returns the name of the response header (WWW-Authenticate or Server-Authorization) and the corresponding
        /// value, respectively for an unauthorized and a successful request.
        /// </summary>
        public async Task<Tuple<string, string>> CreateServerAuthorizationAsync(IResponseMessage response)
        {
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                string challenge = String.Format(" {0}", request.ChallengeParameter ?? String.Empty);
                string headerValue = HawkConstants.Scheme + challenge.TrimEnd(' ');

                return new Tuple<string, string>(HawkConstants.WwwAuthenticateHeaderName, headerValue);
            }
            else
            {
                // No Server-Authorization header for the following:
                // (1) There is no result or failed authentication.
                // (2) The credential is a bewit.
                // (3) The server is configured to not send the header.
                bool createHeader = this.result != null
                                        && this.result.IsAuthentic
                                            && (!this.isBewitRequest)
                                                && options.EnableServerAuthorization;

                if (createHeader)
                {
                    if (options.NormalizationCallback != null)
                        this.result.Artifacts.ApplicationSpecificData = options.NormalizationCallback(response);

                    // Sign the response
                    var normalizedRequest = new NormalizedRequest(request, this.result.Artifacts);
                    var crypto = new Cryptographer(normalizedRequest, this.result.Artifacts, this.result.Credential);

                    // Response body is needed only if payload hash must be included in the response MAC.
                    string body = null;
                    if (options.ResponsePayloadHashabilityCallback != null && 
                            options.ResponsePayloadHashabilityCallback(this.request))
                    {
                        body = await response.ReadBodyAsStringAsync();
                    }

                    crypto.Sign(body, response.ContentType);

                    string authorization = this.result.Artifacts.ToServerAuthorizationHeaderParameter();

                    if (!String.IsNullOrWhiteSpace(authorization))
                    {
                        return new Tuple<string, string>(HawkConstants.ServerAuthorizationHeaderName,
                            String.Format("{0} {1}", HawkConstants.Scheme, authorization));
                    }
                }
            }

            return null;
        }
示例#46
0
 public InvokeActionsResult InvokeErrorActions(IRequestMessage request, IResponseMessage response, IEnumerable<Exception> exceptions)
 {
     return ResolvedService.InvokeActions(this.ErrorActions, request, response, exceptions);
 }
        /// <summary>
        /// Interface method overload for receiving a <see cref="IResponseMessage"/>.
        /// </summary>
        /// <param name="message">The response recieved from the remote peer.</param>
        /// <param name="parameters">The message parameters the message was sent with.</param>
        public void OnNetworkMessageReceive(IResponseMessage message, IMessageParameters parameters)
        {
            Throw<ArgumentNullException>.If.IsNull(message)?.Now(nameof(message));

            ResponsePublisher?.Invoke(message, parameters);
        }