Exemple #1
0
        /// <summary>
        /// Sends a request message to the client over the open network stream and stores the request to the list of unfinished requests.
        /// </summary>
        /// <param name="Message">Message to send.</param>
        /// <param name="Context">Caller's defined context to store information required for later response processing.</param>
        /// <returns>true if the connection to the client should remain open, false otherwise.</returns>
        public async Task <bool> SendMessageAndSaveUnfinishedRequestAsync(Message Message, object Context)
        {
            log.Trace("()");
            bool res = false;

            UnfinishedRequest unfinishedRequest = new UnfinishedRequest(Message, Context);

            if (AddUnfinishedRequest(unfinishedRequest))
            {
                res = await SendMessageInternalAsync(Message);

                if (res)
                {
                    // If the message was sent successfully to the target, we close the connection only in case it was a protocol violation error response.
                    if (Message.MessageTypeCase == Message.MessageTypeOneofCase.Response)
                    {
                        res = Message.Response.Status != Status.ErrorProtocolViolation;
                    }
                }
                else
                {
                    RemoveUnfinishedRequest(unfinishedRequest.RequestMessage.Id);
                }
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemple #2
0
        /// <summary>
        /// Adds unfinished request to the list of unfinished requests.
        /// </summary>
        /// <param name="Request">Request to add to the list.</param>
        /// <returns>true if the function succeeds, false if the number of unfinished requests is over the limit.</returns>
        public bool AddUnfinishedRequest(UnfinishedRequest Request)
        {
            log.Trace("(Request.RequestMessage.Id:{0})", Request.RequestMessage.Id);

            bool res = false;

            lock (unfinishedRequestsLock)
            {
                unfinishedRequests.Add(Request.RequestMessage.Id, Request);
                res = true;
            }

            log.Trace("(-):{0},unfinishedRequests.Count={1}", res, unfinishedRequests.Count);
            return(res);
        }
Exemple #3
0
        /// <summary>
        /// Finds an unfinished request message by its ID and removes it from the list.
        /// </summary>
        /// <param name="Id">Identifier of the message to find.</param>
        /// <returns>Unfinished request with the given ID, or null if no such request is in the list.</returns>
        public UnfinishedRequest GetAndRemoveUnfinishedRequest(uint Id)
        {
            log.Trace("(Id:{0})", Id);

            UnfinishedRequest res = null;

            lock (unfinishedRequestsLock)
            {
                if (unfinishedRequests.TryGetValue(Id, out res))
                {
                    unfinishedRequests.Remove(Id);
                }
            }

            log.Trace("(-):{0},unfinishedRequests.Count={1}", res != null ? "UnfinishedRequest" : "null", unfinishedRequests.Count);
            return(res);
        }
Exemple #4
0
        /// <summary>
        /// Processes FinishNeighborhoodInitializationResponse message from client.
        /// </summary>
        /// <param name="Client">Client that sent the response.</param>
        /// <param name="ResponseMessage">Full response message.</param>
        /// <param name="Request">Unfinished request message that corresponds to the response message.</param>
        /// <returns>true if the connection to the client that sent the response should remain open, false if the client should be disconnected.</returns>
        public bool ProcessMessageFinishNeighborhoodInitializationResponse(IncomingClient Client, Message ResponseMessage, UnfinishedRequest Request)
        {
            log.Trace("()");

            bool res = true;

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemple #5
0
        /// <summary>
        /// Processes NeighborhoodSharedProfileUpdateResponse message from client.
        /// </summary>
        /// <param name="Client">Client that sent the response.</param>
        /// <param name="ResponseMessage">Full response message.</param>
        /// <param name="Request">Unfinished request message that corresponds to the response message.</param>
        /// <returns>true if the connection to the client that sent the response should remain open, false if the client should be disconnected.</returns>
        public bool ProcessMessageNeighborhoodSharedProfileUpdateResponse(IncomingClient Client, Message ResponseMessage, UnfinishedRequest Request)
        {
            log.Trace("()");

            bool res = true;

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemple #6
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(IncomingClient Client, Message IncomingMessage)
        {
            MessageBuilder messageBuilder = Client.MessageBuilder;

            bool res = false;

            log.Debug("()");

            try
            {
                log.Trace("Received message type is {0}, message ID is {1}.", IncomingMessage.MessageTypeCase, IncomingMessage.Id);
                switch (IncomingMessage.MessageTypeCase)
                {
                case Message.MessageTypeOneofCase.Request:
                {
                    Message 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}'.", Crypto.ToHex(conversationRequest.Signature.ToByteArray()));
                        }
                        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;

                        case ConversationRequest.RequestTypeOneofCase.StartNeighborhoodInitialization:
                            responseMessage = ProcessMessageStartNeighborhoodInitializationRequest(Client, IncomingMessage);
                            break;

                        case ConversationRequest.RequestTypeOneofCase.FinishNeighborhoodInitialization:
                            responseMessage = ProcessMessageFinishNeighborhoodInitializationRequest(Client, IncomingMessage);
                            break;

                        case ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate:
                            responseMessage = ProcessMessageNeighborhoodSharedProfileUpdateRequest(Client, IncomingMessage);
                            break;

                        case ConversationRequest.RequestTypeOneofCase.StopNeighborhoodUpdates:
                            responseMessage = ProcessMessageStopNeighborhoodUpdatesRequest(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);
                    }
                    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))
                    {
                        Message requestMessage = 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)
                                {
                                case ConversationRequest.RequestTypeOneofCase.NeighborhoodSharedProfileUpdate:
                                    res = ProcessMessageNeighborhoodSharedProfileUpdateResponse(Client, IncomingMessage, unfinishedRequest);
                                    break;

                                case ConversationRequest.RequestTypeOneofCase.FinishNeighborhoodInitialization:
                                    res = ProcessMessageFinishNeighborhoodInitializationResponse(Client, IncomingMessage, unfinishedRequest);
                                    break;

                                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);
                            // 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;
            }

            profileServer.AddMessage(IncomingMessage, Client.ServerRole, res ? Client : null);

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