/// <summary>
        /// Finds a checked-in client by its identity ID.
        /// </summary>
        /// <param name="IdentityId">Identifier of the identity to search for.</param>
        /// <returns>Client object of the requested online identity, or null if the identity is not online.</returns>
        public IncomingClient GetCheckedInClient(byte[] IdentityId)
        {
            log.Trace("(IdentityId:'{0}')", IdentityId.ToHex());

            IncomingClient res = null;
            PeerListItem   peer;

            lock (lockObject)
            {
                if (clientsByIdentityId.TryGetValue(IdentityId, out peer))
                {
                    res = peer.Client;
                }
            }

            if (res != null)
            {
                log.Trace("(-):{0}", res.Id.ToHex());
            }
            else
            {
                log.Trace("(-):null");
            }
            return(res);
        }
Example #2
0
        /// <summary>
        /// Creates a new relay connection from a caller to a callee using a specific application service.
        /// </summary>
        /// <param name="Caller">Network client of the caller.</param>
        /// <param name="Callee">Network client of the callee.</param>
        /// <param name="ServiceName">Name of the application service of the callee that is being used for the call.</param>
        /// <param name="RequestMessage">CallIdentityApplicationServiceRequest message that the caller send in order to initiate the call.</param>
        public RelayConnection(IncomingClient Caller, IncomingClient Callee, string ServiceName, PsProtocolMessage RequestMessage)
        {
            lockObject = new SemaphoreSlim(1);
            id         = Guid.NewGuid();
            string logPrefix = string.Format("[{0}:{1}] ", id, ServiceName);
            string logName   = "ProfileServer.Network.ClientList";

            log = new Logger(logName, logPrefix);

            log.Trace("(Caller.Id:{0},Callee.Id:{1},ServiceName:'{2}')", Caller.Id.ToHex(), Callee.Id.ToHex(), ServiceName);
            serviceName    = ServiceName;
            caller         = Caller;
            callee         = Callee;
            pendingMessage = RequestMessage;

            callerToken = Guid.NewGuid();
            calleeToken = Guid.NewGuid();
            log.Trace("Caller token is '{0}'.", callerToken);
            log.Trace("Callee token is '{0}'.", calleeToken);

            status = RelayConnectionStatus.WaitingForCalleeResponse;

            // Relay is created by caller's request, it will expire if the callee does not reply within reasonable time.
            timeoutTimer = new Timer(TimeoutCallback, status, CalleeResponseCallNotificationDelayMaxSeconds * 1000, Timeout.Infinite);

            log.Trace("(-)");
        }
Example #3
0
        /// <summary>
        /// Thread procedure that consumes clients from clientQueue.
        /// When a new client is detected in the queue, it is removed from the queue
        /// and enters asynchronous read and processing loop.
        /// </summary>
        private void ClientQueueHandlerThread()
        {
            log.Info("()");

            clientQueueHandlerThreadFinished.Reset();

            while (!ShutdownSignaling.IsShutdown)
            {
                WaitHandle[] handles = new WaitHandle[] { clientQueueEvent, ShutdownSignaling.ShutdownEvent };
                int          index   = WaitHandle.WaitAny(handles);
                if (handles[index] == ShutdownSignaling.ShutdownEvent)
                {
                    log.Info("Shutdown detected.");
                    break;
                }

                log.Debug("New client in the queue detected, queue count is {0}.", clientQueue.Count);
                bool queueEmpty = false;
                while (!queueEmpty && !ShutdownSignaling.IsShutdown)
                {
                    TcpClient tcpClient = null;
                    lock (clientQueueLock)
                    {
                        if (clientQueue.Count > 0)
                        {
                            tcpClient = clientQueue.Peek();
                        }
                    }

                    if (tcpClient != null)
                    {
                        int keepAliveInterval = IsServingClientsOnly ? ClientKeepAliveIntervalSeconds : ServerKeepAliveIntervalSeconds;

                        IncomingClient client = new IncomingClient(this, tcpClient, clientList.GetNewClientId(), UseTls, keepAliveInterval);
                        ClientHandlerAsync(client);

                        lock (clientQueueLock)
                        {
                            clientQueue.Dequeue();
                            queueEmpty = clientQueue.Count == 0;
                        }
                    }
                    else
                    {
                        queueEmpty = true;
                    }
                }
            }

            clientQueueHandlerThreadFinished.Set();

            log.Info("(-)");
        }
        /// <summary>
        /// Adds a checked-in client to the clientsByIdentityList.
        /// </summary>
        /// <param name="Client">Checked-in profile server's client to add.</param>
        /// <returns>true if the function succeeds, false otherwise. The function may fail only
        /// if there is an asynchrony in internal peer lists, which should never happen.</returns>
        public async Task <bool> AddCheckedInClient(IncomingClient Client)
        {
            log.Trace("(Client.Id:{0})", Client.Id.ToHex());

            bool res = false;

            PeerListItem peer             = null;
            PeerListItem clientToCheckOut = null;

            byte[] identityId = Client.IdentityId;

            lock (lockObject)
            {
                // First we find the peer in the list of all peers.
                if (peersByInternalId.ContainsKey(Client.Id))
                {
                    peer = peersByInternalId[Client.Id];

                    // Then we either have this identity checked-in using different network client,
                    // in which case we want to disconnect that old identity's connection and replace it with the new one.
                    clientsByIdentityId.TryGetValue(identityId, out clientToCheckOut);
                    clientsByIdentityId[identityId] = peer;

                    if (clientToCheckOut != null)
                    {
                        clientToCheckOut.Client.IsOurCheckedInClient = false;
                    }

                    Client.IsOurCheckedInClient = true;

                    res = true;
                }
            }

            if (res && (clientToCheckOut != null))
            {
                log.Info("Identity ID '{0}' has been checked-in already via network peer internal ID {1} and will now be disconnected.", identityId.ToHex(), clientToCheckOut.Client.Id.ToHex());
                await clientToCheckOut.Client.CloseConnectionAsync();
            }

            if (!res)
            {
                log.Error("peersByInternalId does not contain peer with internal ID {0}.", Client.Id.ToHex());
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Assigns ID to a new network client and safely adds it to the peersByInternalId list.
        /// </summary>
        /// <param name="Client">Network client to add.</param>
        public void AddNetworkPeer(IncomingClient Client)
        {
            log.Trace("()");

            PeerListItem peer = new PeerListItem();

            peer.Client = Client;

            lock (lockObject)
            {
                peersByInternalId.Add(Client.Id, peer);
            }
            log.Trace("Client.Id is {0}.", Client.Id.ToHex());

            log.Trace("(-)");
        }
        /// <summary>
        /// Adds a network client with identity to the peersByIdentityList.
        /// </summary>
        /// <param name="Client">Network client to add.</param>
        /// <returns>true if the function succeeds, false otherwise. The function may fail only
        /// if there is an asynchrony in internal peer lists, which should never happen.</returns>
        public bool AddNetworkPeerWithIdentity(IncomingClient Client)
        {
            log.Trace("(Client.Id:{0})", Client.Id.ToHex());

            bool res = false;

            PeerListItem peer = null;

            byte[] identityId = Client.IdentityId;

            lock (lockObject)
            {
                // First we find the peer in the list of all peers.
                if (peersByInternalId.TryGetValue(Client.Id, out peer))
                {
                    // Then we either have this identity in peersByIdentityId list,
                    // in which case we add another "instance" to the list,
                    // or we create a new list for this peer.
                    List <PeerListItem> list = null;
                    bool listExists          = peersByIdentityId.TryGetValue(identityId, out list);

                    if (!listExists)
                    {
                        list = new List <PeerListItem>();
                    }

                    list.Add(peer);

                    if (!listExists)
                    {
                        peersByIdentityId.Add(identityId, list);
                    }
                    res = true;
                }
            }

            if (!res)
            {
                log.Error("peersByInternalId does not contain peer with internal ID {0}.", Client.Id.ToHex());
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #7
0
        /// <summary>
        /// Handler for each client that connects to the TCP server.
        /// </summary>
        /// <param name="Client">Client that is connected to TCP server.</param>
        /// <remarks>The client is being handled in the processing loop until the connection to it is terminated by either side.</remarks>
        private async void ClientHandlerAsync(IncomingClient Client)
        {
            LogDiagnosticContext.Start();

            log.Info("(Client.RemoteEndPoint:{0})", Client.RemoteEndPoint);

            clientList.AddNetworkPeer(Client);
            log.Debug("Client ID set to {0}.", Client.Id.ToHex());

            await Client.ReceiveMessageLoop();

            // Free resources used by the client.
            clientList.RemoveNetworkPeer(Client);
            await Client.HandleDisconnect();

            Client.Dispose();

            log.Info("(-)");

            LogDiagnosticContext.Stop();
        }
Example #8
0
        /// <summary>
        /// Creates a new network relay between a caller identity and one of the profile server's customer identities that is online.
        /// </summary>
        /// <param name="Caller">Initiator of the call.</param>
        /// <param name="Callee">Profile server's customer client to be called.</param>
        /// <param name="ServiceName">Name of the application service to use.</param>
        /// <param name="RequestMessage">CallIdentityApplicationServiceRequest message that the caller send in order to initiate the call.</param>
        /// <returns>New relay connection object if the function succeeds, or null otherwise.</returns>
        public RelayConnection CreateNetworkRelay(IncomingClient Caller, IncomingClient Callee, string ServiceName, PsProtocolMessage RequestMessage)
        {
            log.Trace("(Caller.Id:{0},Callee.Id:{1},ServiceName:'{2}')", Caller.Id.ToHex(), Callee.Id.ToHex(), ServiceName);

            RelayConnection res = null;

            RelayConnection relay = new RelayConnection(Caller, Callee, ServiceName, RequestMessage);

            lock (lockObject)
            {
                relaysByGuid.Add(relay.GetId(), relay);
                relaysByGuid.Add(relay.GetCallerToken(), relay);
                relaysByGuid.Add(relay.GetCalleeToken(), relay);
            }

            log.Debug("Relay ID '{0}' added to the relay list.", relay.GetId());
            log.Debug("Caller token '{0}' added to the relay list.", relay.GetCallerToken());
            log.Debug("Callee token '{0}' added to the relay list.", relay.GetCalleeToken());

            res = relay;

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #9
0
        /// <summary>
        /// Handles situation when a client connected to a relay disconnected.
        /// However, the closed connection might be either connection to clCustomer/clNonCustomer port,
        /// or it might be connection to clAppService port.
        /// </summary>
        /// <param name="Client">Client that disconnected.</param>
        /// <param name="IsRelayConnection">true if the closed connection was to clAppService port, false otherwise.</param>
        public async Task HandleDisconnectedClient(IncomingClient Client, bool IsRelayConnection)
        {
            log.Trace("(Client.Id:{0},IsRelayConnection:{1})", Client.Id.ToHex(), IsRelayConnection);

            IncomingClient           clientToSendMessages = null;
            List <PsProtocolMessage> messagesToSend       = new List <PsProtocolMessage>();
            IncomingClient           clientToClose        = null;

            await lockObject.WaitAsync();

            bool isCallee = Client == callee;

            if (IsRelayConnection)
            {
                log.Trace("Client ({0}) ID {1} disconnected, relay '{2}' status {3}.", isCallee ? "callee" : "caller", Client.Id.ToHex(), id, status);
            }
            else
            {
                log.Trace("Client (customer) ID {0} disconnected, relay '{1}' status {2}.", Client.Id.ToHex(), id, status);
            }

            bool destroyRelay = false;

            switch (status)
            {
            case RelayConnectionStatus.WaitingForCalleeResponse:
            {
                if (isCallee)
                {
                    // The client is callee in a relay that is being initialized. The caller is waiting for callee's response and the callee has just disconnected
                    // from the profile server. This is situation 1) from the comment in ProcessMessageCallIdentityApplicationServiceRequestAsync.
                    // We have to send ERROR_NOT_AVAILABLE to the caller and destroy the relay.
                    log.Trace("Callee disconnected from clCustomer port of relay '{0}', message will be sent to the caller and relay destroyed.", id);
                    clientToSendMessages = caller;
                    messagesToSend.Add(caller.MessageBuilder.CreateErrorNotAvailableResponse(pendingMessage));
                    destroyRelay = true;
                }
                else
                {
                    // The client is caller in a relay that is being initialized. The caller was waiting for callee's response, but the caller disconnected before
                    // the callee replied. The callee is now expected to reply and either accept or reject the call. If the call is rejected, everything is OK,
                    // and we do not need to take any action. If the call is accepted, the callee will establish a new connection to clAppService port and will
                    // send us initial ApplicationServiceSendMessageRequest message. We will now destroy the relay so that the callee is disconnected
                    // as its token used in the initial message will not be found.
                    log.Trace("Caller disconnected from clCustomer port or clNonCustomer port of relay '{0}', relay will be destroyed.", id);
                    destroyRelay = true;
                }
                break;
            }

            case RelayConnectionStatus.WaitingForFirstInitMessage:
            {
                // In this relay status we do not care about connection to other than clAppService port.
                if (IsRelayConnection)
                {
                    // This should never happen because client's Relay is initialized only after
                    // its initialization message is received and that would upgrade the relay to WaitingForSecondInitMessage.
                }

                break;
            }

            case RelayConnectionStatus.WaitingForSecondInitMessage:
            {
                // In this relay status we do not care about connection to other than clAppService port.
                if (IsRelayConnection)
                {
                    // One of the clients has sent its initialization message to clAppService port
                    // and is waiting for the other client to do the same.
                    bool isWaitingClient = (callee == Client) || (caller == Client);

                    if (isWaitingClient)
                    {
                        // The client that disconnected was the waiting client. We destroy the relay.
                        // The other client is not connected yet or did not sent its initialization message yet.
                        log.Trace("First client on clAppService port of relay '{0}' closed its connection, destroying the relay.", id);
                        destroyRelay = true;
                    }
                    else
                    {
                        // The client that disconnected was the client that the first client is waiting for.
                        // We do not need to destroy the relay as the client may still connect again
                        // and send its initialization message on time.
                        log.Trace("Second client (that did not sent init message yet) on clAppService port of relay '{0}' closed its connection, no action taken.", id);
                    }
                }

                break;
            }

            case RelayConnectionStatus.Open:
            {
                // In this relay status we do not care about connection to other than clAppService port.
                if (IsRelayConnection)
                {
                    // Both clients were connected. We disconnect the other client and destroy the relay.
                    // However, there might be some unfinished ApplicationServiceSendMessageRequest requests
                    // that we have to send responses to.

                    IncomingClient otherClient = isCallee ? caller : callee;
                    log.Trace("{0} disconnected from relay '{1}', closing connection of {2}.", isCallee ? "Callee" : "Caller", id, isCallee ? "caller" : "callee");
                    clientToSendMessages = otherClient;
                    clientToClose        = otherClient;

                    // Find all unfinished requests from this relay.
                    // When a client sends ApplicationServiceSendMessageRequest, the profile server creates ApplicationServiceReceiveMessageNotificationRequest
                    // and adds it as an unfinished request with context set to RelayMessageContext, which contains the sender's ApplicationServiceSendMessageRequest.
                    // This unfinished message is in the list of unfinished message of the recipient.
                    List <UnfinishedRequest> unfinishedRelayRequests = Client.GetAndRemoveUnfinishedRequests();
                    foreach (UnfinishedRequest unfinishedRequest in unfinishedRelayRequests)
                    {
                        Message unfinishedRequestMessage = (Message)unfinishedRequest.RequestMessage.Message;
                        // Find ApplicationServiceReceiveMessageNotificationRequest request messages sent to the client who closed the connection.
                        if ((unfinishedRequestMessage.MessageTypeCase == Message.MessageTypeOneofCase.Request) &&
                            (unfinishedRequestMessage.Request.ConversationTypeCase == Request.ConversationTypeOneofCase.SingleRequest) &&
                            (unfinishedRequestMessage.Request.SingleRequest.RequestTypeCase == SingleRequest.RequestTypeOneofCase.ApplicationServiceReceiveMessageNotification))
                        {
                            // This unfinished request's context holds ApplicationServiceSendMessageRequest message of the client that is still connected.
                            RelayMessageContext ctx           = (RelayMessageContext)unfinishedRequest.Context;
                            PsProtocolMessage   responseError = clientToSendMessages.MessageBuilder.CreateErrorNotFoundResponse(ctx.SenderRequest);
                            messagesToSend.Add(responseError);
                        }
                    }

                    destroyRelay = true;
                }

                break;
            }

            case RelayConnectionStatus.Destroyed:
                // Nothing to be done.
                break;
            }

            lockObject.Release();


            if (messagesToSend.Count > 0)
            {
                foreach (PsProtocolMessage messageToSend in messagesToSend)
                {
                    if (!await clientToSendMessages.SendMessageAsync(messageToSend))
                    {
                        log.Warn("Unable to send message to the client ID {0}, relay '{1}', maybe it is not connected anymore.", clientToSendMessages.Id.ToHex(), id);
                        break;
                    }
                }
            }


            if (clientToClose != null)
            {
                await clientToClose.CloseConnectionAsync();
            }


            if (destroyRelay)
            {
                Server serverComponent = (Server)Base.ComponentDictionary[Server.ComponentName];
                await serverComponent.RelayList.DestroyNetworkRelay(this);
            }

            log.Trace("(-)");
        }
Example #10
0
        /// <summary>
        /// Processes incoming confirmation from the message recipient over the relay.
        /// </summary>
        /// <param name="Client">Client that sent the response.</param>
        /// <param name="ResponseMessage">Full response message.</param>
        /// <param name="SenderRequest">Sender request message that the recipient confirmed.</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 async Task <bool> RecipientConfirmedMessage(IncomingClient Client, PsProtocolMessage ResponseMessage, PsProtocolMessage SenderRequest)
        {
            log.Trace("()");

            bool res          = false;
            bool destroyRelay = false;

            await lockObject.WaitAsync();

            if (status == RelayConnectionStatus.Open)
            {
                bool isCaller = Client == caller;

                IncomingClient otherClient = isCaller ? callee : caller;
                log.Trace("Over relay '{0}', received confirmation (status code {1}) from client ID {2} of a message sent by client ID {3}.",
                          id, ResponseMessage.Response.Status, Client.Id.ToHex(), otherClient.Id.ToHex());

                if (ResponseMessage.Response.Status == Status.Ok)
                {
                    // We have received a confirmation from the recipient, so we just complete the sender's request to inform it that the message was delivered.
                    PsProtocolMessage otherClientResponse = otherClient.MessageBuilder.CreateApplicationServiceSendMessageResponse(SenderRequest);
                    if (await otherClient.SendMessageAsync(otherClientResponse))
                    {
                        res = true;
                    }
                    else
                    {
                        log.Warn("Unable to send message to other client ID '0x{0:X16}' on relay '{1}', closing connection to client and destroying the relay.", id, otherClient.Id);
                        destroyRelay = true;
                    }
                }
                else
                {
                    // We have received error from the recipient, so we forward it to the sender and destroy the relay.
                    PsProtocolMessage errorResponse = otherClient.MessageBuilder.CreateErrorNotFoundResponse(SenderRequest);

                    if (!await otherClient.SendMessageAsync(errorResponse))
                    {
                        log.Warn("In relay '{0}', unable to send error response to the sender client ID {1}, maybe it is disconnected already, destroying the relay.", id, otherClient.Id.ToHex());
                    }

                    destroyRelay = true;
                }
            }
            else
            {
                // This should never happen unless the relay is destroyed already.
                log.Debug("Relay '{0}' status is {1} instead of Open, destroying relay if it is still active.", id, status);
                destroyRelay = status != RelayConnectionStatus.Destroyed;
            }

            lockObject.Release();

            if (destroyRelay)
            {
                Server serverComponent = (Server)Base.ComponentDictionary[Server.ComponentName];
                await serverComponent.RelayList.DestroyNetworkRelay(this);
            }

            log.Trace("(-)");
            return(res);
        }
Example #11
0
        /// <summary>
        /// Processes ApplicationServiceSendMessageRequest message from a client.
        /// <para>
        /// Relay received message from one client and sends it to the other one. If this is the first request
        /// a client sends after it connects to clAppService port, the request's message is ignored and the reply is sent
        /// to the client as the other client is confirmed to join the relay.</para>
        /// </summary>
        /// <param name="Client">Client that sent the message.</param>
        /// <param name="RequestMessage">Full request message.</param>
        /// <param name="Token">Sender's relay token.</param>
        /// <returns>Response message to be sent to the client.</returns>
        public async Task <PsProtocolMessage> ProcessIncomingMessage(IncomingClient Client, PsProtocolMessage RequestMessage, Guid Token)
        {
            log.Trace("()");

            PsProtocolMessage res = null;
            bool destroyRelay     = false;

            await lockObject.WaitAsync();

            bool isCaller = callerToken.Equals(Token);

            IncomingClient otherClient = isCaller ? callee : caller;

            log.Trace("Received message over relay '{0}' in status {1} with client ID {2} being {3} and the other client ID {4} is {5}.",
                      id, status, Client.Id.ToHex(), isCaller ? "caller" : "callee", otherClient != null ? otherClient.Id.ToHex() : "N/A", isCaller ? "callee" : "caller");

            switch (status)
            {
            case RelayConnectionStatus.WaitingForCalleeResponse:
            {
                if (!isCaller)
                {
                    // We have received a message from callee, but we did not receive its IncomingCallNotificationResponse.
                    // This may be OK if this message has been sent by callee and it just not has been processed before
                    // the callee connected to clAppService port and sent us the initialization message.
                    // In this case we will try to wait a couple of seconds and see if we receive IncomingCallNotificationResponse.
                    // If yes, we continue as if we processed the message in the right order.
                    // In all other cases, this is a fatal error and we have to destroy the relay.
                    lockObject.Release();

                    bool statusChanged = false;
                    log.Warn("Callee sent initialization message before we received IncomingCallNotificationResponse. We will wait to see if it arrives soon.");
                    for (int i = 0; i < 5; i++)
                    {
                        log.Warn("Attempt #{0}, waiting 1 second.", i + 1);
                        await Task.Delay(1000);

                        await lockObject.WaitAsync();

                        log.Warn("Attempt #{0}, checking relay status.", i + 1);
                        if (status != RelayConnectionStatus.WaitingForCalleeResponse)
                        {
                            log.Warn("Attempt #{0}, relay status changed to {1}.", i + 1, status);
                            statusChanged = true;
                        }

                        lockObject.Release();

                        if (statusChanged)
                        {
                            break;
                        }
                    }

                    await lockObject.WaitAsync();

                    if (statusChanged)
                    {
                        // Status of relay has change, which means either it has been destroyed already, or the IncomingCallNotificationResponse
                        // message we were waiting for arrived. In any case, we call this method recursively, but it can not happen that we would end up here again.
                        lockObject.Release();

                        log.Trace("Calling ProcessIncomingMessage recursively.");
                        res = await ProcessIncomingMessage(Client, RequestMessage, Token);

                        await lockObject.WaitAsync();
                    }
                    else
                    {
                        log.Trace("Message received from caller and relay status is WaitingForCalleeResponse and IncomingCallNotificationResponse did not arrive, closing connection to client, destroying relay.");
                        res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                        Client.ForceDisconnect = true;
                        destroyRelay           = true;
                    }
                }
                else
                {
                    log.Trace("Message received from caller and relay status is WaitingForCalleeResponse, closing connection to client, destroying relay.");
                    res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                    Client.ForceDisconnect = true;
                    destroyRelay           = true;
                }
                break;
            }

            case RelayConnectionStatus.WaitingForFirstInitMessage:
            {
                log.Debug("Received an initialization message from the first client ID '{0}' on relay '{1}', waiting for the second client.", Client.Id.ToHex(), id);
                CancelTimeoutTimerLocked();

                if (Client.Relay == null)
                {
                    Client.Relay = this;

                    // Other peer is not connected yet, so we put this request on hold and wait for the other client.
                    if (isCaller)
                    {
                        caller = Client;
                    }
                    else
                    {
                        callee = Client;
                    }

                    status = RelayConnectionStatus.WaitingForSecondInitMessage;
                    log.Trace("Relay '{0}' status changed to {1}.", id, status);

                    pendingMessage = RequestMessage;
                    timeoutTimer   = new Timer(TimeoutCallback, status, SecondAppServiceInitializationMessageDelayMaxSeconds * 1000, Timeout.Infinite);

                    // res remains null, which is OK as the request is put on hold until the other client joins the channel.
                }
                else
                {
                    // Client already sent us the initialization message, this is protocol violation error, destroy the relay.
                    // Since the relay should be upgraded to WaitingForSecondInitMessage status, this can happen
                    // only if a client does not use a separate connection for each clAppService session, which is forbidden.
                    log.Debug("Client ID {0} on relay '{1}' probably uses a single connection for two relays. Both relays will be destroyed.", Client.Id.ToHex(), id);
                    res          = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                    destroyRelay = true;
                }
                break;
            }

            case RelayConnectionStatus.WaitingForSecondInitMessage:
            {
                log.Debug("Received an initialization message from the second client on relay '{0}'.", id);
                CancelTimeoutTimerLocked();

                if (Client.Relay == null)
                {
                    Client.Relay = this;

                    // Other peer is connected already, so we just inform it by sending response to its initial ApplicationServiceSendMessageRequest.
                    if (isCaller)
                    {
                        caller = Client;
                    }
                    else
                    {
                        callee = Client;
                    }

                    status = RelayConnectionStatus.Open;
                    log.Trace("Relay '{0}' status changed to {1}.", id, status);

                    PsProtocolMessage otherClientResponse = otherClient.MessageBuilder.CreateApplicationServiceSendMessageResponse(pendingMessage);
                    pendingMessage = null;
                    if (await otherClient.SendMessageAsync(otherClientResponse))
                    {
                        // And we also send reply to the second client that the channel is now ready for communication.
                        res = Client.MessageBuilder.CreateApplicationServiceSendMessageResponse(RequestMessage);
                    }
                    else
                    {
                        log.Warn("Unable to send message to other client ID {0}, closing connection to client and destroying the relay.", otherClient.Id.ToHex());
                        res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                        Client.ForceDisconnect = true;
                        destroyRelay           = true;
                    }
                }
                else
                {
                    // Client already sent us the initialization message, this is error, destroy the relay.
                    log.Debug("Client ID {0} on relay '{1}' sent a message before receiving a reply to its initialization message. Relay will be destroyed.", Client.Id.ToHex(), id);
                    res          = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                    destroyRelay = true;
                }

                break;
            }


            case RelayConnectionStatus.Open:
            {
                if (Client.Relay == this)
                {
                    // Relay is open, this means that all incoming messages are sent to the other client.
                    byte[]              messageForOtherClient = RequestMessage.Request.SingleRequest.ApplicationServiceSendMessage.Message.ToByteArray();
                    PsProtocolMessage   otherClientMessage    = otherClient.MessageBuilder.CreateApplicationServiceReceiveMessageNotificationRequest(messageForOtherClient);
                    RelayMessageContext context = new RelayMessageContext(this, RequestMessage);
                    if (await otherClient.SendMessageAndSaveUnfinishedRequestAsync(otherClientMessage, context))
                    {
                        // res is null, which is fine, the sender is put on hold and we will get back to it once the recipient confirms that it received the message.
                        log.Debug("Message from client ID {0} has been relayed to other client ID {1}.", Client.Id.ToHex(), otherClient.Id.ToHex());
                    }
                    else
                    {
                        log.Warn("Unable to relay message to other client ID {0}, closing connection to client and destroying the relay.", otherClient.Id.ToHex());
                        res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                        Client.ForceDisconnect = true;
                        destroyRelay           = true;
                    }
                }
                else
                {
                    // This means that the client used a single clAppService port connection for two different relays, which is forbidden.
                    log.Warn("Client ID {0} mixed relay '{1}' with relay '{2}', closing connection to client and destroying both relays.", otherClient.Id.ToHex(), Client.Relay.id, id);
                    res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                    Client.ForceDisconnect = true;
                    destroyRelay           = true;
                }

                break;
            }

            case RelayConnectionStatus.Destroyed:
            {
                log.Trace("Relay has been destroyed, closing connection to client.");
                res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                Client.ForceDisconnect = true;
                break;
            }

            default:
                log.Trace("Relay status is '{0}', closing connection to client, destroying relay.", status);
                res = Client.MessageBuilder.CreateErrorNotFoundResponse(RequestMessage);
                Client.ForceDisconnect = true;
                destroyRelay           = true;
                break;
            }

            lockObject.Release();

            if (destroyRelay)
            {
                Server serverComponent = (Server)Base.ComponentDictionary[Server.ComponentName];
                await serverComponent.RelayList.DestroyNetworkRelay(this);

                if ((this != Client.Relay) && (Client.Relay != null))
                {
                    await serverComponent.RelayList.DestroyNetworkRelay(Client.Relay);
                }
            }

            log.Trace("(-)");
            return(res);
        }
Example #12
0
        /// <summary>
        /// Handles situation when the callee replied to the incoming call notification request.
        /// </summary>
        /// <param name="ResponseMessage">Full response message from the callee.</param>
        /// <param name="Request">Unfinished call request message of the caller that corresponds to the response message.</param>
        /// <returns></returns>
        public async Task <bool> CalleeRepliedToIncomingCallNotification(PsProtocolMessage ResponseMessage, UnfinishedRequest Request)
        {
            log.Trace("()");

            bool res = false;

            bool              destroyRelay        = false;
            IncomingClient    clientToSendMessage = null;
            PsProtocolMessage messageToSend       = null;

            await lockObject.WaitAsync();


            if (status == RelayConnectionStatus.WaitingForCalleeResponse)
            {
                CancelTimeoutTimerLocked();

                // The caller is still connected and waiting for an answer to its call request.
                if (ResponseMessage.Response.Status == Status.Ok)
                {
                    // The callee is now expected to connect to clAppService with its token.
                    // We need to inform caller that the callee accepted the call.
                    // This is option 4) from ProcessMessageCallIdentityApplicationServiceRequestAsync.
                    messageToSend       = caller.MessageBuilder.CreateCallIdentityApplicationServiceResponse(pendingMessage, callerToken.ToByteArray());
                    clientToSendMessage = caller;
                    pendingMessage      = null;

                    caller = null;
                    callee = null;
                    status = RelayConnectionStatus.WaitingForFirstInitMessage;
                    log.Debug("Relay '{0}' status has been changed to {1}.", id, status);

                    /// Install timeoutTimer to expire if the first client does not connect to clAppService port
                    /// and send its initialization message within reasonable time.
                    timeoutTimer = new Timer(TimeoutCallback, RelayConnectionStatus.WaitingForFirstInitMessage, FirstAppServiceInitializationMessageDelayMaxSeconds * 1000, Timeout.Infinite);

                    res = true;
                }
                else
                {
                    // The callee rejected the call or reported other error.
                    // These are options 3) and 2) from ProcessMessageCallIdentityApplicationServiceRequestAsync.
                    if (ResponseMessage.Response.Status == Status.ErrorRejected)
                    {
                        log.Debug("Callee ID '{0}' rejected the call from caller identity ID '{1}', relay '{2}'.", callee.Id.ToHex(), caller.Id.ToHex(), id);
                        messageToSend = caller.MessageBuilder.CreateErrorRejectedResponse(pendingMessage);
                    }
                    else
                    {
                        log.Warn("Callee ID '0} sent error response '{1}' for call request from caller identity ID {2}, relay '{3}'.",
                                 callee.Id.ToHex(), ResponseMessage.Response.Status, caller.Id.ToHex(), id);

                        messageToSend = caller.MessageBuilder.CreateErrorNotAvailableResponse(pendingMessage);
                    }

                    clientToSendMessage = caller;
                    destroyRelay        = true;
                }
            }
            else
            {
                // The relay has probably been destroyed, or something bad happened to it.
                // We take no action here regardless of what the callee's response is.
                // If it rejected the call, there is nothing to be done since we do not have
                // any connection to the caller anymore.
                log.Debug("Relay status is {0}, nothing to be done.", status);
            }

            lockObject.Release();


            if (messageToSend != null)
            {
                if (await clientToSendMessage.SendMessageAsync(messageToSend))
                {
                    log.Debug("Response to call initiation request sent to the caller ID {0}.", clientToSendMessage.Id.ToHex());
                }
                else
                {
                    log.Debug("Unable to reponse to call initiation request to the caller ID {0}.", clientToSendMessage.Id.ToHex());
                }
            }

            if (destroyRelay)
            {
                Server serverComponent = (Server)Base.ComponentDictionary[Server.ComponentName];
                await serverComponent.RelayList.DestroyNetworkRelay(this);
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Example #13
0
        /// <summary>
        /// Callback routine that is called once the timeoutTimer expires.
        /// <para>
        /// If relay status is WaitingForCalleeResponse, the callee has to reply to the incoming call notification
        /// within a reasonable time. If it does the timer is cancelled. If it does not, the timeout occurs.
        /// </para>
        /// <para>
        /// If relay status is WaitingForFirstInitMessage, both clients are expected to connect to clAppService port
        /// and send an initial message over that service. The timeoutTimer expires when none of the clients
        /// connects to clAppService port and sends its initialization message within a reasonable time.
        /// </para>
        /// <para>
        /// Then if relay status is WaitingForSecondInitMessage, the profile server receives a message from the first client
        /// on clAppService port, it starts the timer again, which now expires if the second client does not connect
        /// and send its initial message within a reasonable time.
        /// </para>
        /// </summary>
        /// <param name="state">Status of the relay when the timer was installed.</param>
        private async void TimeoutCallback(object State)
        {
            LogDiagnosticContext.Start();

            RelayConnectionStatus previousStatus = (RelayConnectionStatus)State;

            log.Trace("(State:{0})", previousStatus);

            IncomingClient    clientToSendMessage = null;
            PsProtocolMessage messageToSend       = null;
            bool destroyRelay = false;

            await lockObject.WaitAsync();

            if (timeoutTimer != null)
            {
                switch (status)
                {
                case RelayConnectionStatus.WaitingForCalleeResponse:
                {
                    // The caller requested the call and the callee was notified.
                    // The callee failed to send us response on time, this is situation 2)
                    // from ProcessMessageCallIdentityApplicationServiceRequestAsync.
                    // We send ERROR_NOT_AVAILABLE to the caller and destroy the relay.
                    log.Debug("Callee failed to reply to the incoming call notification, closing relay.");

                    clientToSendMessage = caller;
                    messageToSend       = caller.MessageBuilder.CreateErrorNotAvailableResponse(pendingMessage);
                    break;
                }

                case RelayConnectionStatus.WaitingForFirstInitMessage:
                {
                    // Neither client joined the channel on time, nothing to do, just destroy the relay.
                    log.Debug("None of the clients joined the relay on time, closing relay.");
                    break;
                }

                case RelayConnectionStatus.WaitingForSecondInitMessage:
                {
                    // One client is waiting for the other one to join, but the other client failed to join on time.
                    // We send ERROR_NOT_FOUND to the waiting client and close its connection.
                    log.Debug("{0} failed to join the relay on time, closing relay.", callee != null ? "Caller" : "Callee");

                    clientToSendMessage = callee != null ? callee : caller;
                    messageToSend       = clientToSendMessage.MessageBuilder.CreateErrorNotFoundResponse(pendingMessage);
                    break;
                }

                default:
                    log.Debug("Time out triggered while the relay status was {0}.", status);
                    break;
                }

                // In case of any timeouts, we just destroy the relay.
                destroyRelay = true;
            }
            else
            {
                log.Debug("Timeout timer of relay '{0}' has been destroyed, no action taken.", id);
            }

            lockObject.Release();


            if (messageToSend != null)
            {
                if (!await clientToSendMessage.SendMessageAsync(messageToSend))
                {
                    log.Warn("Unable to send message to the client ID {0} in relay '{1}', maybe it is not connected anymore.", clientToSendMessage.Id.ToHex(), id);
                }
            }

            if (destroyRelay)
            {
                Server serverComponent = (Server)Base.ComponentDictionary[Server.ComponentName];
                await serverComponent.RelayList.DestroyNetworkRelay(this);
            }

            log.Trace("(-)");

            LogDiagnosticContext.Stop();
        }
Example #14
0
        /// <summary>
        /// Checks whether AddRelatedIdentityRequest request is valid.
        /// </summary>
        /// <param name="Client">Client that sent the request.</param>
        /// <param name="AddRelatedIdentityRequest">Client's request message to validate.</param>
        /// <param name="MessageBuilder">Client's network message builder.</param>
        /// <param name="RequestMessage">Full request message from client.</param>
        /// <param name="ErrorResponse">If the function fails, this is filled with error response message that is ready to be sent to the client.</param>
        /// <returns>true if the profile update request can be applied, false otherwise.</returns>
        public static bool ValidateAddRelatedIdentityRequest(IncomingClient Client, AddRelatedIdentityRequest AddRelatedIdentityRequest, PsMessageBuilder MessageBuilder, PsProtocolMessage RequestMessage, out PsProtocolMessage ErrorResponse)
        {
            log.Trace("()");

            bool res = false;

            ErrorResponse = null;
            string details = null;

            if (AddRelatedIdentityRequest == null)
            {
                AddRelatedIdentityRequest = new AddRelatedIdentityRequest();
            }
            if (AddRelatedIdentityRequest.CardApplication == null)
            {
                AddRelatedIdentityRequest.CardApplication = new CardApplicationInformation();
            }
            if (AddRelatedIdentityRequest.SignedCard == null)
            {
                AddRelatedIdentityRequest.SignedCard = new SignedRelationshipCard();
            }
            if (AddRelatedIdentityRequest.SignedCard.Card == null)
            {
                AddRelatedIdentityRequest.SignedCard.Card = new RelationshipCard();
            }

            CardApplicationInformation cardApplication = AddRelatedIdentityRequest.CardApplication;
            SignedRelationshipCard     signedCard      = AddRelatedIdentityRequest.SignedCard;
            RelationshipCard           card            = signedCard.Card;

            byte[] applicationId = cardApplication.ApplicationId.ToByteArray();
            byte[] cardId        = card.CardId.ToByteArray();

            if ((applicationId.Length == 0) || (applicationId.Length > RelatedIdentity.CardIdentifierLength))
            {
                log.Debug("Card application ID is invalid.");
                details = "cardApplication.applicationId";
            }

            if (details == null)
            {
                byte[] appCardId = cardApplication.CardId.ToByteArray();
                if (!ByteArrayComparer.Equals(cardId, appCardId))
                {
                    log.Debug("Card IDs in application card and relationship card do not match.");
                    details = "cardApplication.cardId";
                }
            }

            if (details == null)
            {
                if (card.ValidFrom > card.ValidTo)
                {
                    log.Debug("Card validFrom field is greater than validTo field.");
                    details = "signedCard.card.validFrom";
                }
                else
                {
                    DateTime?cardValidFrom = ProtocolHelper.UnixTimestampMsToDateTime(card.ValidFrom);
                    DateTime?cardValidTo   = ProtocolHelper.UnixTimestampMsToDateTime(card.ValidTo);
                    if (cardValidFrom == null)
                    {
                        log.Debug("Card validFrom value '{0}' is not a valid timestamp.", card.ValidFrom);
                        details = "signedCard.card.validFrom";
                    }
                    else if (cardValidTo == null)
                    {
                        log.Debug("Card validTo value '{0}' is not a valid timestamp.", card.ValidTo);
                        details = "signedCard.card.validTo";
                    }
                }
            }

            if (details == null)
            {
                byte[] issuerPublicKey = card.IssuerPublicKey.ToByteArray();
                bool   pubKeyValid     = (0 < issuerPublicKey.Length) && (issuerPublicKey.Length <= ProtocolHelper.MaxPublicKeyLengthBytes);
                if (!pubKeyValid)
                {
                    log.Debug("Issuer public key has invalid length {0} bytes.", issuerPublicKey.Length);
                    details = "signedCard.card.issuerPublicKey";
                }
            }

            if (details == null)
            {
                byte[] recipientPublicKey = card.RecipientPublicKey.ToByteArray();
                if (!ByteArrayComparer.Equals(recipientPublicKey, Client.PublicKey))
                {
                    log.Debug("Caller is not recipient of the card.");
                    details = "signedCard.card.recipientPublicKey";
                }
            }

            if (details == null)
            {
                if (!Client.MessageBuilder.VerifySignedConversationRequestBodyPart(RequestMessage, cardApplication.ToByteArray(), Client.PublicKey))
                {
                    log.Debug("Caller is not recipient of the card.");
                    ErrorResponse = Client.MessageBuilder.CreateErrorInvalidSignatureResponse(RequestMessage);
                    details       = "";
                }
            }

            if (details == null)
            {
                SemVer cardVersion = new SemVer(card.Version);
                if (!cardVersion.Equals(SemVer.V100))
                {
                    log.Debug("Card version is invalid or not supported.");
                    details = "signedCard.card.version";
                }
            }

            if (details == null)
            {
                if (Encoding.UTF8.GetByteCount(card.Type) > PsMessageBuilder.MaxRelationshipCardTypeLengthBytes)
                {
                    log.Debug("Card type is too long.");
                    details = "signedCard.card.type";
                }
            }

            if (details == null)
            {
                RelationshipCard emptyIdCard = new RelationshipCard()
                {
                    CardId             = ProtocolHelper.ByteArrayToByteString(new byte[RelatedIdentity.CardIdentifierLength]),
                    Version            = card.Version,
                    IssuerPublicKey    = card.IssuerPublicKey,
                    RecipientPublicKey = card.RecipientPublicKey,
                    Type      = card.Type,
                    ValidFrom = card.ValidFrom,
                    ValidTo   = card.ValidTo
                };

                byte[] hash = Crypto.Sha256(emptyIdCard.ToByteArray());
                if (!ByteArrayComparer.Equals(hash, cardId))
                {
                    log.Debug("Card ID '{0}' does not match its hash '{1}'.", cardId.ToHex(64), hash.ToHex());
                    details = "signedCard.card.cardId";
                }
            }

            if (details == null)
            {
                byte[] issuerSignature = signedCard.IssuerSignature.ToByteArray();
                byte[] issuerPublicKey = card.IssuerPublicKey.ToByteArray();
                if (!Ed25519.Verify(issuerSignature, cardId, issuerPublicKey))
                {
                    log.Debug("Issuer signature is invalid.");
                    details = "signedCard.issuerSignature";
                }
            }

            if (details == null)
            {
                res = true;
            }
            else
            {
                if (ErrorResponse == null)
                {
                    ErrorResponse = MessageBuilder.CreateErrorInvalidValueResponse(RequestMessage, details);
                }
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
        /// <summary>
        /// Safely removes network client (peer) from all lists.
        /// </summary>
        /// <param name="Client">Network client to remove.</param>
        public void RemoveNetworkPeer(IncomingClient Client)
        {
            log.Trace("(Client.Id:{0})", Client.Id.ToHex());

            ulong internalId = Client.Id;

            byte[] identityId = Client.IdentityId;

            bool peerByInternalIdRemoveError   = false;
            bool peerByIdentityIdRemoveError   = false;
            bool clientByIdentityIdRemoveError = false;

            lock (lockObject)
            {
                // All peers should be in peersByInternalId list.
                if (peersByInternalId.ContainsKey(internalId))
                {
                    peersByInternalId.Remove(internalId);
                }
                else
                {
                    peerByInternalIdRemoveError = true;
                }

                if (identityId != null)
                {
                    // All peers with known Identity ID should be in peersByIdentityId list.
                    peerByIdentityIdRemoveError = true;
                    List <PeerListItem> list;
                    if (peersByIdentityId.TryGetValue(identityId, out list))
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            PeerListItem peerListItem = list[i];
                            if (peerListItem.Client.Id == internalId)
                            {
                                list.RemoveAt(i);
                                peerByIdentityIdRemoveError = false;
                                break;
                            }
                        }

                        // If the list is empty, delete it.
                        if (list.Count == 0)
                        {
                            peersByIdentityId.Remove(identityId);
                        }
                    }

                    // Only checked-in clients are in clientsByIdentityId list.
                    // If a checked-in client was replaced by a new connection, its IsOurCheckedInClient field was set to false.
                    if (Client.IsOurCheckedInClient)
                    {
                        if (clientsByIdentityId.ContainsKey(identityId))
                        {
                            clientsByIdentityId.Remove(identityId);
                        }
                        else
                        {
                            clientByIdentityIdRemoveError = true;
                        }
                    }
                }
            }

            if (peerByInternalIdRemoveError)
            {
                log.Error("Peer internal ID {0} not found in peersByInternalId list.", internalId.ToHex());
            }

            if (peerByIdentityIdRemoveError)
            {
                log.Error("Peer Identity ID '{0}' not found in peersByIdentityId list.", identityId.ToHex());
            }

            if (clientByIdentityIdRemoveError)
            {
                log.Error("Checked-in client Identity ID '{0}' not found in clientsByIdentityId list.", identityId.ToHex());
            }

            log.Trace("(-)");
        }