public void Parse_Handles_Multiple_Attributes(string username, int token, byte freeUploadSlots, int uploadSpeed, long queueLength) { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString(username) .WriteInteger(token) .WriteInteger(1) // file count .WriteByte(0x2) // code .WriteString("filename") // filename .WriteLong(3) // size .WriteString("ext") // extension .WriteInteger(2) // attribute count .WriteInteger((int)FileAttributeType.BitDepth) // attribute[0].type .WriteInteger(4) // attribute[0].value .WriteInteger((int)FileAttributeType.BitRate) // attribute[0].type .WriteInteger(5) // attribute[0].value .WriteByte(freeUploadSlots) .WriteInteger(uploadSpeed) .WriteLong(queueLength) .WriteBytes(new byte[4]) // unknown 4 bytes .Compress() .Build(); var r = SearchResponseFactory.FromByteArray(msg); Assert.Single(r.Files); var file = r.Files.ToList()[0]; Assert.Equal(FileAttributeType.BitDepth, file.Attributes.ToList()[0].Type); Assert.Equal(4, file.Attributes.ToList()[0].Value); Assert.Equal(FileAttributeType.BitRate, file.Attributes.ToList()[1].Type); Assert.Equal(5, file.Attributes.ToList()[1].Value); }
public void Parse_Handles_Empty_Responses(string username, int token, byte freeUploadSlots, int uploadSpeed, long queueLength) { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString(username) .WriteInteger(token) .WriteInteger(0) // file count .WriteByte(freeUploadSlots) .WriteInteger(uploadSpeed) .WriteLong(queueLength) .WriteBytes(new byte[4]) // unknown 4 bytes .Compress() .Build(); var r = SearchResponseFactory.FromByteArray(msg); Assert.Equal(username, r.Username); Assert.Equal(token, r.Token); Assert.Equal(0, r.FileCount); Assert.Equal(freeUploadSlots, r.FreeUploadSlots); Assert.Equal(uploadSpeed, r.UploadSpeed); Assert.Equal(queueLength, r.QueueLength); Assert.Empty(r.Files); }
public void Parse_Throws_MessageReadException_On_File_Count_Mismatch() { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString("foo") .WriteInteger(0) .WriteInteger(20) // file count .WriteByte(0x2) // code .WriteString("filename") // filename .WriteLong(3) // size .WriteString("ext") // extension .WriteInteger(1) // attribute count .WriteInteger((int)FileAttributeType.BitDepth) // attribute[0].type .WriteInteger(4) // attribute[0].value .WriteByte(0x20) // code .WriteString("filename2") // filename .WriteLong(30) // size .WriteString("ext2") // extension .WriteInteger(1) // attribute count .WriteInteger((int)FileAttributeType.BitRate) // attribute[0].type .WriteInteger(40) // attribute[0].value .WriteByte(0) .WriteInteger(0) .WriteLong(0) .WriteBytes(new byte[4]) // unknown 4 bytes .Compress() .Build(); var ex = Record.Exception(() => SearchResponseFactory.FromByteArray(msg)); Assert.NotNull(ex); Assert.IsType <MessageReadException>(ex); }
public void Parse_Throws_MessageException_On_Code_Mismatch() { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.BrowseRequest) .Build(); var ex = Record.Exception(() => SearchResponseFactory.FromByteArray(msg)); Assert.NotNull(ex); Assert.IsType <MessageException>(ex); }
public void Parse_Throws_MessageReadException_On_Missing_Data() { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString("foo") .Compress() .Build(); var ex = Record.Exception(() => SearchResponseFactory.FromByteArray(msg)); Assert.NotNull(ex); Assert.IsType <MessageReadException>(ex); }
public void Parse_Throws_MessageCompressionException_On_Uncompressed_Payload() { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteBytes(new byte[] { 0x0, 0x1, 0x2, 0x3 }) .Build(); var ex = Record.Exception(() => SearchResponseFactory.FromByteArray(msg)); Assert.NotNull(ex); Assert.IsType <MessageCompressionException>(ex); Assert.IsType <ZStreamException>(ex.InnerException); }
public void Parse_Returns_Expected_Data(string username, int token, byte freeUploadSlots, int uploadSpeed, long queueLength) { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString(username) .WriteInteger(token) .WriteInteger(1) // file count .WriteByte(0x2) // code .WriteString("filename") // filename .WriteLong(3) // size .WriteString("ext") // extension .WriteInteger(1) // attribute count .WriteInteger((int)FileAttributeType.BitDepth) // attribute[0].type .WriteInteger(4) // attribute[0].value .WriteByte(freeUploadSlots) .WriteInteger(uploadSpeed) .WriteLong(queueLength) .WriteBytes(new byte[4]) // unknown 4 bytes .Compress() .Build(); var r = SearchResponseFactory.FromByteArray(msg); Assert.Equal(username, r.Username); Assert.Equal(token, r.Token); Assert.Equal(1, r.FileCount); Assert.Equal(freeUploadSlots, r.FreeUploadSlots); Assert.Equal(uploadSpeed, r.UploadSpeed); Assert.Equal(queueLength, r.QueueLength); Assert.Single(r.Files); var file = r.Files.ToList()[0]; Assert.Equal(0x2, file.Code); Assert.Equal("filename", file.Filename); Assert.Equal(3, file.Size); Assert.Equal("ext", file.Extension); Assert.Equal(1, file.AttributeCount); Assert.Single(file.Attributes); Assert.Equal(FileAttributeType.BitDepth, file.Attributes.ToList()[0].Type); Assert.Equal(4, file.Attributes.ToList()[0].Value); }
public void Parse_Handles_Empty_Attributes(string username, int token, byte freeUploadSlots, int uploadSpeed, long queueLength) { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString(username) .WriteInteger(token) .WriteInteger(1) // file count .WriteByte(0x2) // code .WriteString("filename") // filename .WriteLong(3) // size .WriteString("ext") // extension .WriteInteger(0) // attribute count .WriteByte(freeUploadSlots) .WriteInteger(uploadSpeed) .WriteLong(queueLength) .WriteBytes(new byte[4]) // unknown 4 bytes .Compress() .Build(); var r = SearchResponseFactory.FromByteArray(msg); Assert.Single(r.Files); Assert.Empty(r.Files.ToList()[0].Attributes); }
/// <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.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.ToByteArray()).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 = EnqueueDownloadRequest.FromByteArray(message); var(queueRejected, queueRejectionMessage) = await TryEnqueueDownloadAsync(connection.Username, connection.IPEndPoint, queueDownloadRequest.Filename).ConfigureAwait(false); if (queueRejected) { await connection.WriteAsync(new EnqueueFailedResponse(queueDownloadRequest.Filename, queueRejectionMessage).ToByteArray()).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. await connection.WriteAsync(new TransferResponse(transferRequest.Token, string.Empty).ToByteArray()).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).ToByteArray()).ConfigureAwait(false); await connection.WriteAsync(new EnqueueFailedResponse(transferRequest.Filename, transferRejectionMessage).ToByteArray()).ConfigureAwait(false); } else { await connection.WriteAsync(new TransferResponse(transferRequest.Token, "Queued").ToByteArray()).ConfigureAwait(false); await TrySendPlaceInQueueAsync(connection, transferRequest.Filename).ConfigureAwait(false); } } break; case MessageCode.Peer.QueueFailed: var queueFailedResponse = EnqueueFailedResponse.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); } }
public void Parse_Handles_Locked_Files(string username, int token, byte freeUploadSlots, int uploadSpeed, long queueLength) { var msg = new MessageBuilder() .WriteCode(MessageCode.Peer.SearchResponse) .WriteString(username) .WriteInteger(token) .WriteInteger(2) // file count .WriteByte(0x2) // code .WriteString("filename") // filename .WriteLong(3) // size .WriteString("ext") // extension .WriteInteger(1) // attribute count .WriteInteger((int)FileAttributeType.BitDepth) // attribute[0].type .WriteInteger(4) // attribute[0].value .WriteByte(0x20) // code .WriteString("filename2") // filename .WriteLong(30) // size .WriteString("ext2") // extension .WriteInteger(1) // attribute count .WriteInteger((int)FileAttributeType.BitRate) // attribute[0].type .WriteInteger(40) // attribute[0].value .WriteByte(freeUploadSlots) .WriteInteger(uploadSpeed) .WriteLong(queueLength) .WriteInteger(1) // locked file count .WriteByte(0x30) // code .WriteString("filename3") // filename .WriteLong(40) // size .WriteString("ext3") // extension .WriteInteger(1) // attribute count .WriteInteger((int)FileAttributeType.BitRate) // attribute[0].type .WriteInteger(50) // attribute[0].value .Compress() .Build(); var r = SearchResponseFactory.FromByteArray(msg); Assert.Equal(2, r.Files.Count); var file = r.Files.ToList(); Assert.Equal(0x2, file[0].Code); Assert.Equal("filename", file[0].Filename); Assert.Equal(3, file[0].Size); Assert.Equal("ext", file[0].Extension); Assert.Equal(1, file[0].AttributeCount); Assert.Single(file[0].Attributes); Assert.Equal(FileAttributeType.BitDepth, file[0].Attributes.ToList()[0].Type); Assert.Equal(4, file[0].Attributes.ToList()[0].Value); Assert.Equal(0x20, file[1].Code); Assert.Equal("filename2", file[1].Filename); Assert.Equal(30, file[1].Size); Assert.Equal("ext2", file[1].Extension); Assert.Equal(1, file[1].AttributeCount); Assert.Single(file[1].Attributes); Assert.Equal(FileAttributeType.BitRate, file[1].Attributes.ToList()[0].Type); Assert.Equal(40, file[1].Attributes.ToList()[0].Value); var locked = r.LockedFiles.ToList(); Assert.Equal(0x30, locked[0].Code); Assert.Equal("filename3", locked[0].Filename); Assert.Equal(40, locked[0].Size); Assert.Equal("ext3", locked[0].Extension); Assert.Equal(1, locked[0].AttributeCount); Assert.Single(locked[0].Attributes); Assert.Equal(FileAttributeType.BitRate, locked[0].Attributes.ToList()[0].Type); Assert.Equal(50, locked[0].Attributes.ToList()[0].Value); }