/// <summary>
        /// Validates incoming SharedActivityUpdateItem update item.
        /// </summary>
        /// <param name="UpdateItem">Update item to validate.</param>
        /// <param name="Index">Item index in the update message.</param>
        /// <param name="SharedActivitiesCount">Number of activities the neighbor already shares with the activity server.</param>
        /// <param name="UsedFullActivityIdsInBatch">List of activity full IDs of already validated items of this batch.</param>
        /// <param name="MessageBuilder">Client's network message builder.</param>
        /// <param name="RequestMessage">Full request message received by the client.</param>
        /// <param name="ErrorResponse">If the validation fails, this is filled with response message to be sent to the neighbor.</param>
        /// <returns>true if the validation is successful, false otherwise.</returns>
        public static bool ValidateSharedActivityUpdateItem(SharedActivityUpdateItem UpdateItem, int Index, int SharedActivitiesCount, HashSet <string> UsedFullActivityIdsInBatch, ProxMessageBuilder MessageBuilder, ProxProtocolMessage RequestMessage, out ProxProtocolMessage ErrorResponse)
        {
            log.Trace("(Index:{0},SharedActivitiesCount:{1})", Index, SharedActivitiesCount);

            bool res = false;

            ErrorResponse = null;

            switch (UpdateItem.ActionTypeCase)
            {
            case SharedActivityUpdateItem.ActionTypeOneofCase.Add:
                res = ValidateSharedActivityAddItem(UpdateItem.Add, Index, SharedActivitiesCount, UsedFullActivityIdsInBatch, MessageBuilder, RequestMessage, out ErrorResponse);
                break;

            case SharedActivityUpdateItem.ActionTypeOneofCase.Change:
                res = ValidateSharedActivityChangeItem(UpdateItem.Change, Index, UsedFullActivityIdsInBatch, MessageBuilder, RequestMessage, out ErrorResponse);
                break;

            case SharedActivityUpdateItem.ActionTypeOneofCase.Delete:
                res = ValidateSharedActivityDeleteItem(UpdateItem.Delete, Index, UsedFullActivityIdsInBatch, MessageBuilder, RequestMessage, out ErrorResponse);
                break;

            case SharedActivityUpdateItem.ActionTypeOneofCase.Refresh:
                res = true;
                break;

            default:
                ErrorResponse = MessageBuilder.CreateErrorProtocolViolationResponse(RequestMessage);
                res           = false;
                break;
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemple #2
0
        /// <summary>
        /// Sends ERROR_PROTOCOL_VIOLATION to client with message ID set to 0x0BADC0DE.
        /// </summary>
        /// <param name="Client">Client to send the error to.</param>
        public async Task SendProtocolViolation(ClientBase Client)
        {
            ProxMessageBuilder mb = new ProxMessageBuilder(0, new List <SemVer>()
            {
                SemVer.V100
            }, null);
            ProxProtocolMessage response = mb.CreateErrorProtocolViolationResponse(new ProxProtocolMessage(new Message()
            {
                Id = 0x0BADC0DE
            }));

            await Client.SendMessageAsync(response);
        }
Exemple #3
0
        /// <summary>
        /// Processing of a message received from a client.
        /// </summary>
        /// <param name="Client">TCP client who send the message.</param>
        /// <param name="IncomingMessage">Full ProtoBuf message to be processed.</param>
        /// <returns>true if the conversation with the client should continue, false if a protocol violation error occurred and the client should be disconnected.</returns>
        public async Task <bool> ProcessMessageAsync(ClientBase Client, IProtocolMessage IncomingMessage)
        {
            IncomingClient      client          = (IncomingClient)Client;
            ProxProtocolMessage incomingMessage = (ProxProtocolMessage)IncomingMessage;
            ProxMessageBuilder  messageBuilder  = client.MessageBuilder;

            bool res = false;

            log.Debug("()");
            try
            {
                // Update time until this client's connection is considered inactive.
                client.NextKeepAliveTime = DateTime.UtcNow.AddMilliseconds(client.KeepAliveIntervalMs);
                log.Trace("Client ID {0} NextKeepAliveTime updated to {1}.", client.Id.ToHex(), client.NextKeepAliveTime.ToString("yyyy-MM-dd HH:mm:ss"));

                log.Trace("Received message type is {0}, message ID is {1}.", incomingMessage.MessageTypeCase, incomingMessage.Id);
                switch (incomingMessage.MessageTypeCase)
                {
                case Message.MessageTypeOneofCase.Request:
                {
                    ProxProtocolMessage responseMessage = messageBuilder.CreateErrorProtocolViolationResponse(incomingMessage);
                    Request             request         = incomingMessage.Request;
                    log.Trace("Request conversation type is {0}.", request.ConversationTypeCase);
                    switch (request.ConversationTypeCase)
                    {
                    case Request.ConversationTypeOneofCase.SingleRequest:
                    {
                        SingleRequest singleRequest = request.SingleRequest;
                        SemVer        version       = new SemVer(singleRequest.Version);
                        log.Trace("Single request type is {0}, version is {1}.", singleRequest.RequestTypeCase, version);

                        if (!version.IsValid())
                        {
                            responseMessage.Response.Details = "version";
                            break;
                        }

                        switch (singleRequest.RequestTypeCase)
                        {
                        case SingleRequest.RequestTypeOneofCase.Ping:
                            responseMessage = ProcessMessagePingRequest(client, incomingMessage);
                            break;

                        case SingleRequest.RequestTypeOneofCase.ListRoles:
                            responseMessage = ProcessMessageListRolesRequest(client, incomingMessage);
                            break;

                        default:
                            log.Warn("Invalid request type '{0}'.", singleRequest.RequestTypeCase);
                            break;
                        }

                        break;
                    }

                    case Request.ConversationTypeOneofCase.ConversationRequest:
                    {
                        ConversationRequest conversationRequest = request.ConversationRequest;
                        log.Trace("Conversation request type is {0}.", conversationRequest.RequestTypeCase);
                        if (conversationRequest.Signature.Length > 0)
                        {
                            log.Trace("Conversation signature is '{0}'.", conversationRequest.Signature.ToByteArray().ToHex());
                        }
                        else
                        {
                            log.Trace("No signature provided.");
                        }

                        switch (conversationRequest.RequestTypeCase)
                        {
                        case ConversationRequest.RequestTypeOneofCase.Start:
                            responseMessage = ProcessMessageStartConversationRequest(client, incomingMessage);
                            break;

                        case ConversationRequest.RequestTypeOneofCase.VerifyIdentity:
                            responseMessage = ProcessMessageVerifyIdentityRequest(client, incomingMessage);
                            break;

                        default:
                            log.Warn("Invalid request type '{0}'.", conversationRequest.RequestTypeCase);
                            // Connection will be closed in ReceiveMessageLoop.
                            break;
                        }

                        break;
                    }

                    default:
                        log.Error("Unknown conversation type '{0}'.", request.ConversationTypeCase);
                        // Connection will be closed in ReceiveMessageLoop.
                        break;
                    }

                    if (responseMessage != null)
                    {
                        // Send response to client.
                        res = await client.SendMessageAsync(responseMessage);

                        if (res)
                        {
                            // If the message was sent successfully to the target, we close the connection in case it was a protocol violation error response.
                            if (responseMessage.MessageTypeCase == Message.MessageTypeOneofCase.Response)
                            {
                                res = responseMessage.Response.Status != Status.ErrorProtocolViolation;
                            }
                        }
                    }
                    else
                    {
                        // If there is no response to send immediately to the client,
                        // we want to keep the connection open.
                        res = true;
                    }
                    break;
                }

                case Message.MessageTypeOneofCase.Response:
                {
                    Response response = incomingMessage.Response;
                    log.Trace("Response status is {0}, details are '{1}', conversation type is {2}.", response.Status, response.Details, response.ConversationTypeCase);

                    // Find associated request. If it does not exist, disconnect the client as it
                    // send a response without receiving a request. This is protocol violation,
                    // but as this is a reponse, we have no how to inform the client about it,
                    // so we just disconnect it.
                    UnfinishedRequest unfinishedRequest = client.GetAndRemoveUnfinishedRequest(incomingMessage.Id);
                    if ((unfinishedRequest != null) && (unfinishedRequest.RequestMessage != null))
                    {
                        ProxProtocolMessage requestMessage = (ProxProtocolMessage)unfinishedRequest.RequestMessage;
                        Request             request        = requestMessage.Request;
                        // We now check whether the response message type corresponds with the request type.
                        // This is only valid if the status is Ok. If the message types do not match, we disconnect
                        // for the protocol violation again.
                        bool typeMatch       = false;
                        bool isErrorResponse = response.Status != Status.Ok;
                        if (!isErrorResponse)
                        {
                            if (response.ConversationTypeCase == Response.ConversationTypeOneofCase.SingleResponse)
                            {
                                typeMatch = (request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                                            ((int)response.SingleResponse.ResponseTypeCase == (int)request.SingleRequest.RequestTypeCase);
                            }
                            else
                            {
                                typeMatch = (request.ConversationTypeCase == Request.ConversationTypeOneofCase.ConversationRequest) &&
                                            ((int)response.ConversationResponse.ResponseTypeCase == (int)request.ConversationRequest.RequestTypeCase);
                            }
                        }
                        else
                        {
                            typeMatch = true;
                        }

                        if (typeMatch)
                        {
                            // Now we know the types match, so we can rely on request type even if response is just an error.
                            switch (request.ConversationTypeCase)
                            {
                            case Request.ConversationTypeOneofCase.SingleRequest:
                            {
                                SingleRequest singleRequest = request.SingleRequest;
                                switch (singleRequest.RequestTypeCase)
                                {
                                default:
                                    log.Warn("Invalid conversation type '{0}' of the corresponding request.", request.ConversationTypeCase);
                                    // Connection will be closed in ReceiveMessageLoop.
                                    break;
                                }

                                break;
                            }

                            case Request.ConversationTypeOneofCase.ConversationRequest:
                            {
                                ConversationRequest conversationRequest = request.ConversationRequest;
                                switch (conversationRequest.RequestTypeCase)
                                {
                                default:
                                    log.Warn("Invalid type '{0}' of the corresponding request.", conversationRequest.RequestTypeCase);
                                    // Connection will be closed in ReceiveMessageLoop.
                                    break;
                                }
                                break;
                            }

                            default:
                                log.Error("Unknown conversation type '{0}' of the corresponding request.", request.ConversationTypeCase);
                                // Connection will be closed in ReceiveMessageLoop.
                                break;
                            }
                        }
                        else
                        {
                            log.Warn("Message type of the response ID {0} does not match the message type of the request ID {1}, the connection will be closed.", incomingMessage.Id, unfinishedRequest.RequestMessage.Id);
                            // Connection will be closed in ReceiveMessageLoop.
                        }
                    }
                    else
                    {
                        log.Warn("No unfinished request found for incoming response ID {0}, the connection will be closed.", incomingMessage.Id);
                        // Connection will be closed in ReceiveMessageLoop.
                    }

                    break;
                }

                default:
                    log.Error("Unknown message type '{0}', connection to the client will be closed.", incomingMessage.MessageTypeCase);
                    await SendProtocolViolation(client);

                    // Connection will be closed in ReceiveMessageLoop.
                    break;
                }
            }
            catch (Exception e)
            {
                log.Error("Exception occurred, connection to the client will be closed: {0}", e.ToString());
                await SendProtocolViolation(client);

                // Connection will be closed in ReceiveMessageLoop.
            }

            if (res && client.ForceDisconnect)
            {
                log.Debug("Connection to the client will be forcefully closed.");
                res = false;
            }

            log.Debug("(-):{0}", res);
            return(res);
        }