Ejemplo n.º 1
0
        public void Parse_Throws_MessageException_On_Code_Mismatch()
        {
            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Peer.BrowseRequest)
                      .Build();

            var ex = Record.Exception(() => QueueFailedResponse.FromByteArray(msg));

            Assert.NotNull(ex);
            Assert.IsType <MessageException>(ex);
        }
Ejemplo n.º 2
0
        public void Parse_Throws_MessageReadException_On_Missing_Data()
        {
            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Peer.QueueFailed)
                      .Build();

            var ex = Record.Exception(() => QueueFailedResponse.FromByteArray(msg));

            Assert.NotNull(ex);
            Assert.IsType <MessageReadException>(ex);
        }
Ejemplo n.º 3
0
        public void Parse_Returns_Expected_Data()
        {
            var file   = Guid.NewGuid().ToString();
            var reason = Guid.NewGuid().ToString();

            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Peer.QueueFailed)
                      .WriteString(file)
                      .WriteString(reason)
                      .Build();

            var response = QueueFailedResponse.FromByteArray(msg);

            Assert.Equal(file, response.Filename);
            Assert.Equal(reason, response.Message);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessageRead(object sender, byte[] message)
        {
            var connection = (IMessageConnection)sender;
            var code       = new MessageReader <MessageCode.Peer>(message).ReadCode();

            Diagnostic.Debug($"Peer message received: {code} from {connection.Username} ({connection.IPEndPoint}) (id: {connection.Id})");

            try
            {
                switch (code)
                {
                case MessageCode.Peer.SearchResponse:
                    var searchResponse = SearchResponseFactory.FromByteArray(message);

                    if (SoulseekClient.Searches.TryGetValue(searchResponse.Token, out var search))
                    {
                        search.TryAddResponse(searchResponse);
                    }

                    break;

                case MessageCode.Peer.BrowseResponse:
                    var browseWaitKey = new WaitKey(MessageCode.Peer.BrowseResponse, connection.Username);

                    try
                    {
                        SoulseekClient.Waiter.Complete(browseWaitKey, BrowseResponseFactory.FromByteArray(message));
                    }
                    catch (Exception ex)
                    {
                        SoulseekClient.Waiter.Throw(browseWaitKey, new MessageReadException("The peer returned an invalid browse response", ex));
                        throw;
                    }

                    break;

                case MessageCode.Peer.InfoRequest:
                    UserInfo outgoingInfo;

                    try
                    {
                        outgoingInfo = await SoulseekClient.Options
                                       .UserInfoResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        outgoingInfo = await new SoulseekClientOptions()
                                       .UserInfoResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);

                        Diagnostic.Warning($"Failed to resolve user info response: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(outgoingInfo.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.SearchRequest:
                    var searchRequest = PeerSearchRequest.FromByteArray(message);

                    if (SoulseekClient.Options.SearchResponseResolver == default)
                    {
                        break;
                    }

                    try
                    {
                        var peerSearchResponse = await SoulseekClient.Options.SearchResponseResolver(connection.Username, searchRequest.Token, SearchQuery.FromText(searchRequest.Query)).ConfigureAwait(false);

                        if (peerSearchResponse != null && peerSearchResponse.FileCount + peerSearchResponse.LockedFileCount > 0)
                        {
                            await connection.WriteAsync(peerSearchResponse.ToByteArray()).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Error resolving search response for query '{searchRequest.Query}' requested by {connection.Username} with token {searchRequest.Token}: {ex.Message}", ex);
                    }

                    break;

                case MessageCode.Peer.BrowseRequest:
                    BrowseResponse browseResponse;

                    try
                    {
                        browseResponse = await SoulseekClient.Options.BrowseResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        browseResponse = await new SoulseekClientOptions()
                                         .BrowseResponseResolver(connection.Username, connection.IPEndPoint).ConfigureAwait(false);

                        Diagnostic.Warning($"Failed to resolve browse response: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(browseResponse.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.FolderContentsRequest:
                    var       folderContentsRequest  = FolderContentsRequest.FromByteArray(message);
                    Directory outgoingFolderContents = null;

                    try
                    {
                        outgoingFolderContents = await SoulseekClient.Options.DirectoryContentsResponseResolver(
                            connection.Username,
                            connection.IPEndPoint,
                            folderContentsRequest.Token,
                            folderContentsRequest.DirectoryName).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Failed to resolve directory contents response: {ex.Message}", ex);
                    }

                    if (outgoingFolderContents != null)
                    {
                        var folderContentsResponseMessage = new FolderContentsResponse(folderContentsRequest.Token, outgoingFolderContents);

                        await connection.WriteAsync(folderContentsResponseMessage).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Peer.FolderContentsResponse:
                    var folderContentsResponse = FolderContentsResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.FolderContentsResponse, connection.Username, folderContentsResponse.Token), folderContentsResponse.Directory);
                    break;

                case MessageCode.Peer.InfoResponse:
                    var incomingInfo = UserInfoResponseFactory.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.InfoResponse, connection.Username), incomingInfo);
                    break;

                case MessageCode.Peer.TransferResponse:
                    var transferResponse = TransferResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferResponse, connection.Username, transferResponse.Token), transferResponse);
                    break;

                case MessageCode.Peer.QueueDownload:
                    var queueDownloadRequest = QueueDownloadRequest.FromByteArray(message);

                    var(queueRejected, queueRejectionMessage) =
                        await TryEnqueueDownloadAsync(connection.Username, connection.IPEndPoint, queueDownloadRequest.Filename).ConfigureAwait(false);

                    if (queueRejected)
                    {
                        await connection.WriteAsync(new QueueFailedResponse(queueDownloadRequest.Filename, queueRejectionMessage)).ConfigureAwait(false);
                    }
                    else
                    {
                        await TrySendPlaceInQueueAsync(connection, queueDownloadRequest.Filename).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Peer.TransferRequest:
                    var transferRequest = TransferRequest.FromByteArray(message);

                    if (transferRequest.Direction == TransferDirection.Upload)
                    {
                        if (!SoulseekClient.Downloads.IsEmpty && SoulseekClient.Downloads.Values.Any(d => d.Username == connection.Username && d.Filename == transferRequest.Filename))
                        {
                            SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, transferRequest.Filename), transferRequest);
                        }
                        else
                        {
                            // reject the transfer with an empty reason.  it was probably cancelled, but we can't be sure.
                            Diagnostic.Debug($"Rejecting unknown upload from {connection.Username} for {transferRequest.Filename} with token {transferRequest.Token}");
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, "Cancelled")).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        var(transferRejected, transferRejectionMessage) = await TryEnqueueDownloadAsync(connection.Username, connection.IPEndPoint, transferRequest.Filename).ConfigureAwait(false);

                        if (transferRejected)
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, transferRejectionMessage)).ConfigureAwait(false);

                            await connection.WriteAsync(new QueueFailedResponse(transferRequest.Filename, transferRejectionMessage)).ConfigureAwait(false);
                        }
                        else
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, "Queued")).ConfigureAwait(false);
                            await TrySendPlaceInQueueAsync(connection, transferRequest.Filename).ConfigureAwait(false);
                        }
                    }

                    break;

                case MessageCode.Peer.QueueFailed:
                    var queueFailedResponse = QueueFailedResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, queueFailedResponse.Filename), new TransferRejectedException(queueFailedResponse.Message));
                    break;

                case MessageCode.Peer.PlaceInQueueResponse:
                    var placeInQueueResponse = PlaceInQueueResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.PlaceInQueueResponse, connection.Username, placeInQueueResponse.Filename), placeInQueueResponse);
                    break;

                case MessageCode.Peer.PlaceInQueueRequest:
                    var placeInQueueRequest = PlaceInQueueRequest.FromByteArray(message);
                    await TrySendPlaceInQueueAsync(connection, placeInQueueRequest.Filename).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.UploadFailed:
                    var uploadFailedResponse = UploadFailed.FromByteArray(message);
                    var msg = $"Download of {uploadFailedResponse.Filename} reported as failed by {connection.Username}";

                    var download = SoulseekClient.Downloads.Values.FirstOrDefault(d => d.Username == connection.Username && d.Filename == uploadFailedResponse.Filename);
                    if (download != null)
                    {
                        SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, download.Username, download.Filename), new TransferException(msg));
                    }

                    Diagnostic.Debug(msg);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled peer message: {code} from {connection.Username} ({connection.IPEndPoint}); {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling peer message: {code} from {connection.Username} ({connection.IPEndPoint}); {ex.Message}", ex);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessage(object sender, byte[] message)
        {
            var connection = (IMessageConnection)sender;
            var code       = new MessageReader <MessageCode.Peer>(message).ReadCode();

            Diagnostic.Debug($"Peer message received: {code} from {connection.Username} ({connection.IPAddress}:{connection.Port})");

            try
            {
                switch (code)
                {
                case MessageCode.Peer.SearchResponse:
                    var searchResponse = SearchResponseSlim.FromByteArray(message);
                    if (SoulseekClient.Searches.TryGetValue(searchResponse.Token, out var search))
                    {
                        search.AddResponse(searchResponse);
                    }

                    break;

                case MessageCode.Peer.BrowseResponse:
                    var browseWaitKey = new WaitKey(MessageCode.Peer.BrowseResponse, connection.Username);
                    try
                    {
                        SoulseekClient.Waiter.Complete(browseWaitKey, BrowseResponse.FromByteArray(message));
                    }
                    catch (Exception ex)
                    {
                        SoulseekClient.Waiter.Throw(browseWaitKey, new MessageReadException("The peer returned an invalid browse response.", ex));
                        throw;
                    }

                    break;

                case MessageCode.Peer.InfoRequest:
                    var outgoingInfo = await new ClientOptions()
                                       .UserInfoResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);

                    try
                    {
                        outgoingInfo = await SoulseekClient.Options
                                       .UserInfoResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Failed to resolve UserInfoResponse: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(outgoingInfo.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.BrowseRequest:
                    var browseResponse = await new ClientOptions()
                                         .BrowseResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);

                    try
                    {
                        browseResponse = await SoulseekClient.Options.BrowseResponseResolver(connection.Username, connection.IPAddress, connection.Port).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Failed to resolve BrowseResponse: {ex.Message}", ex);
                    }

                    await connection.WriteAsync(browseResponse.ToByteArray()).ConfigureAwait(false);

                    break;

                case MessageCode.Peer.InfoResponse:
                    var incomingInfo = UserInfoResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.InfoResponse, connection.Username), incomingInfo);
                    break;

                case MessageCode.Peer.TransferResponse:
                    var transferResponse = TransferResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferResponse, connection.Username, transferResponse.Token), transferResponse);
                    break;

                case MessageCode.Peer.QueueDownload:
                    var queueDownloadRequest = QueueDownloadRequest.FromByteArray(message);

                    var(queueRejected, queueRejectionMessage) =
                        await TryEnqueueDownloadAsync(connection.Username, connection.IPAddress, connection.Port, queueDownloadRequest.Filename).ConfigureAwait(false);

                    if (queueRejected)
                    {
                        await connection.WriteAsync(new QueueFailedResponse(queueDownloadRequest.Filename, queueRejectionMessage).ToByteArray()).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Peer.TransferRequest:
                    var transferRequest = TransferRequest.FromByteArray(message);

                    if (transferRequest.Direction == TransferDirection.Upload)
                    {
                        SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, transferRequest.Filename), transferRequest);
                    }
                    else
                    {
                        var(transferRejected, transferRejectionMessage) = await TryEnqueueDownloadAsync(connection.Username, connection.IPAddress, connection.Port, transferRequest.Filename).ConfigureAwait(false);

                        if (transferRejected)
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, transferRejectionMessage).ToByteArray()).ConfigureAwait(false);

                            await connection.WriteAsync(new QueueFailedResponse(transferRequest.Filename, transferRejectionMessage).ToByteArray()).ConfigureAwait(false);
                        }
                        else
                        {
                            await connection.WriteAsync(new TransferResponse(transferRequest.Token, "Queued.").ToByteArray()).ConfigureAwait(false);
                        }
                    }

                    break;

                case MessageCode.Peer.QueueFailed:
                    var queueFailedResponse = QueueFailedResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, connection.Username, queueFailedResponse.Filename), new TransferRejectedException(queueFailedResponse.Message));
                    break;

                case MessageCode.Peer.PlaceInQueueResponse:
                    var placeInQueueResponse = PlaceInQueueResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(MessageCode.Peer.PlaceInQueueResponse, connection.Username, placeInQueueResponse.Filename), placeInQueueResponse);
                    break;

                case MessageCode.Peer.UploadFailed:
                    var uploadFailedResponse = UploadFailed.FromByteArray(message);
                    var msg = $"Download of {uploadFailedResponse.Filename} reported as failed by {connection.Username}.";

                    var download = SoulseekClient.Downloads.Values.FirstOrDefault(d => d.Username == connection.Username && d.Filename == uploadFailedResponse.Filename);
                    if (download != null)
                    {
                        SoulseekClient.Waiter.Throw(new WaitKey(MessageCode.Peer.TransferRequest, download.Username, download.Filename), new TransferException(msg));
                        SoulseekClient.Waiter.Throw(download.WaitKey, new TransferException(msg));
                    }

                    Diagnostic.Debug(msg);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled peer message: {code} from {connection.Username} ({connection.IPAddress}:{connection.Port}); {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling peer message: {code} from {connection.Username} ({connection.IPAddress}:{connection.Port}); {ex.Message}", ex);
            }
        }