public IPv4AdressValidator(IStringLocalizer <ValidationMessagesRessources> localizer, String propertyName) { if (localizer is null) { throw new ArgumentNullException(nameof(localizer)); } RuleFor(x => x).NotEmpty().Must(x => { if (x == null) { return(false); } try { IPv4Address.FromString(x); return(true); } catch (Exception) { return(false); } }).WithMessage(localizer["IPv4Address_NotValid"]).WithName(propertyName); }
protected static DHCPv4ScopeAddressProperties GetScopeAddressProperties(IScopeChangeCommand request) => request.AddressProperties.DynamicRenewTime == null ? new DHCPv4ScopeAddressProperties ( IPv4Address.FromString(request.AddressProperties.Start), IPv4Address.FromString(request.AddressProperties.End), request.AddressProperties.ExcludedAddresses.Select(x => IPv4Address.FromString(x)), leaseTime: request.AddressProperties.LeaseTime, renewalTime: request.AddressProperties.RenewalTime, preferredLifetime: request.AddressProperties.PreferredLifetime, reuseAddressIfPossible: request.AddressProperties.ReuseAddressIfPossible, addressAllocationStrategy: (Core.Scopes.ScopeAddressProperties <DHCPv4ScopeAddressProperties, IPv4Address> .AddressAllocationStrategies?)request.AddressProperties.AddressAllocationStrategy, supportDirectUnicast: request.AddressProperties.SupportDirectUnicast, acceptDecline: request.AddressProperties.AcceptDecline, informsAreAllowd: request.AddressProperties.InformsAreAllowd, maskLength: request.AddressProperties.MaskLength ) : new DHCPv4ScopeAddressProperties ( IPv4Address.FromString(request.AddressProperties.Start), IPv4Address.FromString(request.AddressProperties.End), request.AddressProperties.ExcludedAddresses.Select(x => IPv4Address.FromString(x)), GetDynamicRenewTime(request.AddressProperties.DynamicRenewTime), reuseAddressIfPossible: request.AddressProperties.ReuseAddressIfPossible, addressAllocationStrategy: (Core.Scopes.ScopeAddressProperties <DHCPv4ScopeAddressProperties, IPv4Address> .AddressAllocationStrategies?)request.AddressProperties.AddressAllocationStrategy, supportDirectUnicast: request.AddressProperties.SupportDirectUnicast, acceptDecline: request.AddressProperties.AcceptDecline, informsAreAllowd: request.AddressProperties.InformsAreAllowd, maskLength: request.AddressProperties.MaskLength );
public async Task Handle_Failed_StorageEngine() { Random random = new Random(); String interfaceName = random.GetAlphanumericString(); var possibleListeners = GetPossibleListeners(); var selectedListener = possibleListeners.ElementAt(1); var command = new CreateDHCPv4InterfaceListenerCommand( selectedListener.PhysicalInterfaceId, selectedListener.Address.ToString(), interfaceName); Mock <IDHCPv4InterfaceEngine> interfaceEngineMock = new Mock <IDHCPv4InterfaceEngine>(MockBehavior.Strict); interfaceEngineMock.Setup(x => x.GetPossibleListeners()).Returns(possibleListeners).Verifiable(); interfaceEngineMock.Setup(x => x.GetActiveListeners()).ReturnsAsync(possibleListeners.Take(1)).Verifiable(); Mock <IDHCPv4StorageEngine> storageEngineMock = new Mock <IDHCPv4StorageEngine>(MockBehavior.Strict); storageEngineMock.Setup(x => x.Save(It.Is <DHCPv4Listener>(y => y.Name == interfaceName && y.PhysicalInterfaceId == command.NicId && y.Address == IPv4Address.FromString(command.IPv4Addres) ))).ReturnsAsync(false).Verifiable(); var commandHandler = new CreateDHCPv4InterfaceListenerCommandHandler( interfaceEngineMock.Object, storageEngineMock.Object, Mock.Of <ILogger <CreateDHCPv4InterfaceListenerCommandHandler> >()); Guid?result = await commandHandler.Handle(command, CancellationToken.None); Assert.False(result.HasValue); interfaceEngineMock.Verify(); storageEngineMock.Verify(); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { Boolean isValid = false; var property = validationContext.ObjectType.GetProperty(_otherPropertyName); if (property != null) { String propertyRawValue = (String)property.GetValue(validationContext.ObjectInstance); try { var adressValue = IPv4Address.FromString(propertyRawValue); var currentAdress = IPv4Address.FromString(value as String); if (currentAdress >= adressValue) { isValid = true; } } catch { } } if (isValid == true) { return(ValidationResult.Success); } return(new ValidationResult(ErrorMessage, new[] { validationContext.MemberName })); }
public async Task <Guid?> Handle(CreateDHCPv4InterfaceListenerCommand request, CancellationToken cancellationToken) { _logger.LogDebug("Handle started"); var listener = DHCPv4Listener.Create( request.NicId, DHCPListenerName.FromString(request.Name), IPv4Address.FromString(request.IPv4Addres)); var possibleListeners = _interfaceEngine.GetPossibleListeners(); if (possibleListeners.Count(x => x.Address == listener.Address && x.PhysicalInterfaceId == listener.PhysicalInterfaceId) == 0) { return(null); } var activeListeners = await _interfaceEngine.GetActiveListeners(); if (activeListeners.Count(x => x.Address == listener.Address && x.PhysicalInterfaceId == listener.PhysicalInterfaceId) > 0) { return(null); } if (await _storageEngine.Save(listener) == false) { return(null); } _interfaceEngine.OpenListener(listener); return(listener.Id); }
public void DHCPv4RelayAgentSubnetResolver_ApplyValues() { Random random = new Random(); String validMaskValue = ((Byte)random.Next(1, 32)).ToString(); String validNetworkAddressValue = random.GetIPv4Address().ToString(); IPv4SubnetMask subnetMask = new IPv4SubnetMask(new IPv4SubnetMaskIdentifier(Convert.ToInt32(validMaskValue))); IPv4Address address = IPv4Address.FromString(validNetworkAddressValue); var mock = new Mock <ISerializer>(MockBehavior.Strict); mock.Setup(x => x.Deserialze <String>(validMaskValue)).Returns(subnetMask.GetSlashNotation().ToString()); mock.Setup(x => x.Deserialze <String>(validNetworkAddressValue)).Returns(address.ToString()); DHCPv4RelayAgentSubnetResolver resolver = new DHCPv4RelayAgentSubnetResolver(); var input = new Dictionary <string, string>() { { nameof(DHCPv4RelayAgentSubnetResolver.Mask), validMaskValue }, { nameof(DHCPv4RelayAgentSubnetResolver.NetworkAddress), validNetworkAddressValue }, }; resolver.ApplyValues(input, mock.Object); Assert.Equal(subnetMask, resolver.Mask); Assert.Equal(address, resolver.NetworkAddress); }
public void Constructor_Failed_AddressNotNetwork(String rawNetwork, String rawMask) { IPv4Address address = IPv4Address.FromString(rawNetwork); IPv4SubnetMask mask = IPv4SubnetMask.FromString(rawMask); Assert.ThrowsAny <Exception>(() => new IPv4Route(address, mask)); }
public void HandleInform_InformsAreAllowed() { Random random = new Random(); IPv4Address clientAddress = IPv4Address.FromString("192.168.178.10"); IPv4HeaderInformation headerInformation = new IPv4HeaderInformation(clientAddress, IPv4Address.FromString("192.168.178.1")); Byte[] clientMacAdress = random.NextBytes(6); DHCPv4Packet requestPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, clientAddress, DHCPv4PacketFlags.Unicast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Inform) ); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.1"), IPv4Address.FromString("192.168.178.255"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.1") }, informsAreAllowd: true ), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }) }); DHCPv4Packet result = rootScope.HandleInform(requestPacket); CheckAcknowledgePacket(clientAddress, result); CheckEventAmount(1, rootScope); CheckHandeledEvent(0, InformErros.NoError, requestPacket, result, rootScope); }
public void IPv4SubnetMask_IsIPAdressANetworkAddress(String subnetMaskInput, String addressInput, Boolean expectedResult) { IPv4SubnetMask mask = IPv4SubnetMask.FromString(subnetMaskInput); IPv4Address address = IPv4Address.FromString(addressInput); Boolean actual = mask.IsIPAdressANetworkAddress(address); Assert.Equal(expectedResult, actual); }
public void IPv4Adress_IsInBetween(String start, String current, String end, Boolean expectedResult) { IPv4Address startAddress = IPv4Address.FromString(start); IPv4Address currentAddress = IPv4Address.FromString(current); IPv4Address endAddress = IPv4Address.FromString(end); Boolean actual = currentAddress.IsBetween(startAddress, endAddress); Assert.Equal(expectedResult, actual); }
public void Constructor(String rawNetwork, String rawMask) { IPv4Address address = IPv4Address.FromString(rawNetwork); IPv4SubnetMask mask = IPv4SubnetMask.FromString(rawMask); IPv4Route route = new IPv4Route(address, mask); Assert.Equal(mask, route.SubnetMask); Assert.Equal(address, route.Network); }
public static IPv4Address AsIPv4Address(this String input) { try { return(IPv4Address.FromString(input)); } catch (Exception) { return(IPv4Address.Empty); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { String rawValue = (String)reader.Value; if (String.IsNullOrEmpty(rawValue) == true) { return(null); } return(IPv4Address.FromString(rawValue)); }
public void DHCPv4ScopeAddressProperties_IsAddressInRange(String startAddressRaw, String endAddressRaw, String targetAddressRaw, Boolean expectedResult) { IPv4Address start = IPv4Address.FromString(startAddressRaw); IPv4Address end = IPv4Address.FromString(endAddressRaw); IPv4Address target = IPv4Address.FromString(targetAddressRaw); DHCPv4ScopeAddressProperties properties = new DHCPv4ScopeAddressProperties(start, end, Array.Empty <IPv4Address>()); Boolean actual = properties.IsAddressInRange(target); Assert.Equal(expectedResult, actual); }
public void IPv4Address_FromString(String input, Boolean parseable, Byte[] expectedByteSequence) { if (parseable == false) { Assert.ThrowsAny <Exception>(() => IPv4Address.FromString(input)); return; } IPv4Address address = IPv4Address.FromString(input); Byte[] actual = address.GetBytes(); Assert.Equal(expectedByteSequence, actual); }
public void IPv4Address_SpaceBetween(String first, String second, Int64 expected) { IPv4Address firstAddress = IPv4Address.FromString(first); IPv4Address secondAddress = IPv4Address.FromString(second); Int64 diff = firstAddress - secondAddress; Assert.Equal(diff, expected); Int64 otherDiff = secondAddress - firstAddress; Assert.Equal(diff * -1, otherDiff); }
public void IPv4Address_Add(String start, Int32 diff, String expected) { IPv4Address startAddress = IPv4Address.FromString(start); IPv4Address endAddress = startAddress + diff; IPv4Address expectedEndAddress = IPv4Address.FromString(expected); Assert.Equal(expectedEndAddress, endAddress); IPv4Address otherStartAddress = endAddress - diff; Assert.Equal(startAddress, otherStartAddress); }
private DHCPv4InterfaceEntry FindValidInterface(DHCPv4InterfaceOverview interfaces) { foreach (var item in interfaces.Entries) { IPv4Address address = IPv4Address.FromString(item.IPv4Address); var bytes = address.GetBytes(); if (bytes[0] == 127 || (bytes[0] == 169 && bytes[1] == 254)) { continue; } return(item); } return(null); }
public void DHCPv4RelayAgentSubnetResolver_PacketMeetsConditions2( String networkAddressInput, String maskInput, String relayAgentAddressInput, Boolean shouldPass ) { Random random = new Random(); IPv4SubnetMask mask = IPv4SubnetMask.FromString(maskInput); IPv4Address networkAddress = IPv4Address.FromString(networkAddressInput); String inputAddressValue = random.GetAlphanumericString(10); String inputMaskValue = random.GetAlphanumericString(10); Mock <ISerializer> serializer = new Mock <ISerializer>(MockBehavior.Strict); serializer.Setup(x => x.Deserialze <String>(mask.GetSlashNotation().ToString())).Returns(mask.GetSlashNotation().ToString()); serializer.Setup(x => x.Deserialze <String>(networkAddress.ToString())).Returns(networkAddress.ToString()); DHCPv4RelayAgentSubnetResolver resolver = new DHCPv4RelayAgentSubnetResolver(); Dictionary <String, String> values = new Dictionary <String, String>() { { nameof(DHCPv4RelayAgentSubnetResolver.NetworkAddress), networkAddress.ToString() }, { nameof(DHCPv4RelayAgentSubnetResolver.Mask), mask.GetSlashNotation().ToString() }, }; resolver.ApplyValues(values, serializer.Object); IPv4Address gwAddress = IPv4Address.FromString(relayAgentAddressInput); DHCPv4Packet packet = new DHCPv4Packet( new IPv4HeaderInformation(random.GetIPv4Address(), random.GetIPv4Address()), random.NextBytes(6), (UInt32)random.Next(), IPv4Address.Empty, gwAddress, IPv4Address.Empty ); Boolean actual = resolver.PacketMeetsCondition(packet); Assert.Equal(shouldPass, actual); }
public void DHCPv4ScopeAddressProperties_IsAddressRangeBetween( String startOwnRangeRaw, String endOwnRangeRaw, String startOtherRangeRaw, String endOtherRangeRaw, Boolean expectedResult ) { IPv4Address startOwn = IPv4Address.FromString(startOwnRangeRaw); IPv4Address endOwn = IPv4Address.FromString(endOwnRangeRaw); DHCPv4ScopeAddressProperties own = new DHCPv4ScopeAddressProperties(startOwn, endOwn, Array.Empty <IPv4Address>()); IPv4Address startOther = IPv4Address.FromString(startOtherRangeRaw); IPv4Address endOther = IPv4Address.FromString(endOtherRangeRaw); DHCPv4ScopeAddressProperties other = new DHCPv4ScopeAddressProperties(startOther, endOther, Array.Empty <IPv4Address>()); Boolean actual = own.IsAddressRangeBetween(other); Assert.Equal(expectedResult, actual); }
public void SerializeAndDeserialize_WithoutDynamicRenew() { Random random = new Random(); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new IPv4AddressJsonConverter()); settings.Converters.Add(new DHCPv4ScopeAddressPropertiesConverter()); var input = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.10.20"), IPv4Address.FromString("192.168.10.50"), new List <IPv4Address> { IPv4Address.FromString("192.168.10.30"), IPv4Address.FromString("192.168.10.34") }, TimeSpan.FromMinutes(random.Next(10, 20)), TimeSpan.FromMinutes(random.Next(40, 60)), TimeSpan.FromMinutes(random.Next(80, 120)), (Byte)random.Next(10, 30), random.NextBoolean(), DaAPI.Core.Scopes.ScopeAddressProperties <DHCPv4ScopeAddressProperties, IPv4Address> .AddressAllocationStrategies.Next, random.NextBoolean(), random.NextBoolean(), random.NextBoolean()); String serialized = JsonConvert.SerializeObject(input, settings); var actual = JsonConvert.DeserializeObject <DHCPv4ScopeAddressProperties>(serialized, settings); Assert.Equal(input, actual); }
public DHCPv4AddressScopeProperty(Byte optionIdentifier, String address) : this(optionIdentifier, IPv4Address.FromString(address)) { }
public void HandleDecline_AcceptDecline_RequesAddressExits_LeaseExists_LeaseIsPending_AddressIsNotSuspended() { Random random = new Random(); IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.3"); DHCPv4Packet requestPacket = GetDeclinePacket(random, leasedAddress); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-1); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.0"), IPv4Address.FromString("192.168.178.100"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.0") }, leaseTime: TimeSpan.FromDays(1), acceptDecline: true), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(requestPacket.ClientHardwareAddress).GetBytes(), ScopeId = scopeId, UniqueIdentifier = null, StartedAt = leaseCreatedAt, ValidUntil = DateTime.UtcNow.AddDays(1), }, }); DHCPv4Packet result = rootScope.HandleDecline(requestPacket); Assert.Equal(DHCPv4Packet.Empty, result); DHCPv4Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId); Assert.Equal(LeaseStates.Suspended, lease.State); CheckEventAmount(2, rootScope); CheckDeclineEvent(0, leaseId, leasedAddress, scopeId, rootScope); CheckDeclinedEvent(1, DeclineErros.NoError, requestPacket, rootScope, scopeId); }
public void HandleRelease_LeaseExists_AddressIsActive() { Random random = new Random(); IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10"); IPv4HeaderInformation headerInformation = new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1")); Byte[] clientMacAdress = random.NextBytes(6); DHCPv4Packet requestPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Unicast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release) ); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-1); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.1"), IPv4Address.FromString("192.168.178.255"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.1") }, leaseTime: TimeSpan.FromDays(1) ), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(clientMacAdress).GetBytes(), ScopeId = scopeId, UniqueIdentifier = null, StartedAt = leaseCreatedAt, ValidUntil = DateTime.UtcNow.AddDays(1), }, new DHCPv4LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, }, }); DHCPv4Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId); DHCPv4Packet result = rootScope.HandleRelease(requestPacket); Assert.Equal(DHCPv4Packet.Empty, result); CheckIfLeaseIsRelease(lease); CheckEventAmount(2, rootScope); CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId); CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope); }
public void HandleRelease_LeaseExists_AddressIsActive_NotSentDiscover() { Random random = new Random(); IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10"); IPv4HeaderInformation headerInformation = new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1")); Byte[] clientMacAdress = random.NextBytes(6); DHCPv4Packet requestPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Unicast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release) ); DHCPv4Packet discoverPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Broadcast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Discover), new DHCPv4PacketClientIdentifierOption(DHCPv4ClientIdentifier.FromIdentifierValue("random test client")) ); Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); resolverMock.Setup(x => x.PacketMeetsCondition(discoverPacket)).Returns(true); resolverMock.SetupGet(x => x.HasUniqueIdentifier).Returns(false); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-1); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.1"), IPv4Address.FromString("192.168.178.255"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.1") }, leaseTime: TimeSpan.FromDays(1), renewalTime: TimeSpan.FromHours(12), preferredLifetime: TimeSpan.FromHours(18), reuseAddressIfPossible: true, acceptDecline: true, addressAllocationStrategy: DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Next, supportDirectUnicast: true, maskLength: 24 ), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdenfier = DHCPv4ClientIdentifier.FromIdentifierValue("random test client").GetBytes(), ScopeId = scopeId, UniqueIdentifier = null, StartedAt = leaseCreatedAt, ValidUntil = DateTime.UtcNow.AddDays(1), }, new DHCPv4LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, }, }); DHCPv4Lease existingLease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId); DHCPv4Packet releaseResult = rootScope.HandleRelease(requestPacket); Assert.Equal(DHCPv4Packet.Empty, releaseResult); CheckIfLeaseIsRelease(existingLease); CheckEventAmount(2, rootScope); CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId); CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope); DHCPv4Packet discoveryResult = rootScope.HandleDiscover(discoverPacket); IPv4Address newAssignedAddress = IPv4Address.FromString("192.168.178.2"); Assert.Equal(newAssignedAddress, discoveryResult.YourIPAdress); }
public void IPv4Adress_Compare(String small, String middle, String great) { IPv4Address smallestAddress = IPv4Address.FromString(small); IPv4Address middleAddress = IPv4Address.FromString(middle); IPv4Address greatestAddress = IPv4Address.FromString(great); { Int32 firstResult = smallestAddress.CompareTo(smallestAddress); Int32 secondResult = smallestAddress.CompareTo(middleAddress); Int32 thirdResult = smallestAddress.CompareTo(greatestAddress); Assert.Equal(0, firstResult); Assert.True(secondResult < 0); Assert.True(thirdResult < 0); Assert.True(smallestAddress < middleAddress); Assert.True(smallestAddress < greatestAddress); Assert.False(smallestAddress > middleAddress); Assert.False(smallestAddress > greatestAddress); #pragma warning disable CS1718 // Comparison made to same variable Assert.True(smallestAddress <= smallestAddress); Assert.True(smallestAddress >= smallestAddress); #pragma warning restore CS1718 // Comparison made to same variable } { Int32 firstResult = middleAddress.CompareTo(smallestAddress); Int32 secondResult = middleAddress.CompareTo(middleAddress); Int32 thirdResult = middleAddress.CompareTo(greatestAddress); Assert.True(firstResult > 0); Assert.Equal(0, secondResult); Assert.True(thirdResult < 0); Assert.True(middleAddress > smallestAddress); Assert.True(middleAddress < greatestAddress); Assert.False(middleAddress > greatestAddress); Assert.False(middleAddress < smallestAddress); #pragma warning disable CS1718 // Comparison made to same variable Assert.True(middleAddress <= middleAddress); Assert.True(middleAddress >= middleAddress); #pragma warning restore CS1718 // Comparison made to same variable } { Int32 firstResult = greatestAddress.CompareTo(smallestAddress); Int32 secondResult = greatestAddress.CompareTo(middleAddress); Int32 thirdResult = greatestAddress.CompareTo(greatestAddress); Assert.True(firstResult > 0); Assert.True(secondResult > 0); Assert.Equal(0, thirdResult); Assert.True(greatestAddress > smallestAddress); Assert.True(greatestAddress > middleAddress); Assert.False(greatestAddress < smallestAddress); Assert.False(greatestAddress < middleAddress); #pragma warning disable CS1718 // Comparison made to same variable Assert.True(greatestAddress <= greatestAddress); Assert.True(greatestAddress >= greatestAddress); #pragma warning restore CS1718 // Comparison made to same variable } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { String value = reader.Value as String; return(IPv4Address.FromString(value)); }
public void Blub() { String input = "0101060115430d42062c0000000000000000000000000000c2229c0202a0574ff12f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000638253633501013d070102a0574ff12f390205003204c23763440c13524f555445524c414e434f4d313739335641573c0e4c414e434f4d20313739335641573707017903060f2bd4520d0103312f320206082697683201ff0000000000000000"; Byte[] content = StringToByteArray(input); DHCPv4Packet packet = DHCPv4Packet.FromByteArray(content, new IPv4HeaderInformation(IPv4Address.FromString("192.168.10.0"), IPv4Address.FromString("192.168.10.10"))); Assert.True(packet.IsValid); }
public void GetLeasesByScope_OnlyDirect() { Random random = new Random(); Guid scopeId = random.NextGuid(); String scopeName = "Testscope"; DHCPv4LeaseOverview activeLeaseWithoutPrefix = new DHCPv4LeaseOverview { Address = random.GetIPv4Address().ToString(), MacAddress = random.NextBytes(6), ExpectedEnd = DateTime.UtcNow.AddHours(random.Next(10, 20)), Started = DateTime.UtcNow.AddHours(-random.Next(10, 20)), Id = random.NextGuid(), UniqueIdentifier = random.NextBytes(10), State = LeaseStates.Active, Scope = new DHCPv4ScopeOverview { Id = scopeId, Name = scopeName, } }; DHCPv4LeaseOverview expiredLeaseWithPrefix = new DHCPv4LeaseOverview { Address = random.GetIPv4Address().ToString(), MacAddress = random.NextBytes(6), ExpectedEnd = DateTime.UtcNow.AddHours(random.Next(10, 20)), Started = DateTime.UtcNow.AddHours(-random.Next(10, 20)), Id = random.NextGuid(), UniqueIdentifier = Array.Empty <Byte>(), State = LeaseStates.Inactive, Scope = new DHCPv4ScopeOverview { Id = scopeId, Name = scopeName, } }; DHCPv4RootScope rootScope = GetRootScope(); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { Name = scopeName, Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = expiredLeaseWithPrefix.Id, Address = IPv4Address.FromString(expiredLeaseWithPrefix.Address.ToString()), ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(expiredLeaseWithPrefix.MacAddress).GetBytes(), ScopeId = scopeId, StartedAt = expiredLeaseWithPrefix.Started, ValidUntil = expiredLeaseWithPrefix.ExpectedEnd, UniqueIdentifier = null, }, new DHCPv4LeaseActivatedEvent { EntityId = expiredLeaseWithPrefix.Id, ScopeId = scopeId, }, new DHCPv4LeaseExpiredEvent { EntityId = expiredLeaseWithPrefix.Id, ScopeId = scopeId, }, new DHCPv4LeaseCreatedEvent { EntityId = activeLeaseWithoutPrefix.Id, Address = IPv4Address.FromString(activeLeaseWithoutPrefix.Address.ToString()), ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(activeLeaseWithoutPrefix.MacAddress).GetBytes(), ScopeId = scopeId, StartedAt = activeLeaseWithoutPrefix.Started, ValidUntil = activeLeaseWithoutPrefix.ExpectedEnd, UniqueIdentifier = activeLeaseWithoutPrefix.UniqueIdentifier }, new DHCPv4LeaseActivatedEvent { EntityId = activeLeaseWithoutPrefix.Id, ScopeId = scopeId, }, });; var controller = new DHCPv4LeaseController(rootScope, Mock.Of <ILogger <DHCPv4LeaseController> >()); var actionResult = controller.GetLeasesByScope(scopeId); var result = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv4LeaseOverview> >(true); Assert.Equal(new[] { activeLeaseWithoutPrefix, expiredLeaseWithPrefix }, result, new LeaseOverviewEqualityComparer()); }
public async Task Handle(Boolean storeResult, Boolean useDynamicTime) { Random random = new Random(); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); String name = random.GetAlphanumericString(); String description = random.GetAlphanumericString(); IPv4Address start = random.GetIPv4Address(); IPv4Address end = start + 100; String resolverName = random.GetAlphanumericString(); Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); resolverMock.Setup(x => x.GetValues()).Returns(new Dictionary <String, String>()); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(); scopeResolverMock.Setup(x => x.IsResolverInformationValid(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(true).Verifiable(); scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(resolverMock.Object).Verifiable(); Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict); factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv4RootScope> >()); DHCPv4RootScope rootScope = new DHCPv4RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object); rootScope.Load(new DomainEvent[] { new DHCPv4ScopeAddedEvent { Instructions = new DHCPv4ScopeCreateInstruction { Name = random.GetAlphanumericString(), Description = random.GetAlphanumericString(), Id = scopeId, ParentId = null, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, ScopeProperties = new DHCPv4ScopeProperties(), AddressProperties = DHCPv4ScopeAddressProperties.Empty, } }, new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = start - 100, ScopeId = scopeId, ClientIdenfier = DHCPv4ClientIdentifier.FromDuid(1, new UUIDDUID(random.NextGuid()), random.NextBytes(6)).GetBytes(), }, new DHCPv4LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, } }); Mock <IDHCPv4StorageEngine> storageMock = new Mock <IDHCPv4StorageEngine>(MockBehavior.Strict); storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(storeResult).Verifiable(); var command = new UpdateDHCPv4ScopeCommand(scopeId, name, description, null, useDynamicTime == false ? new DHCPv4ScopeAddressPropertyReqest { Start = start.ToString(), End = end.ToString(), ExcludedAddresses = Array.Empty <String>(), AcceptDecline = random.NextBoolean(), AddressAllocationStrategy = DHCPv4ScopeAddressPropertyReqest.AddressAllocationStrategies.Next, InformsAreAllowd = random.NextBoolean(), ReuseAddressIfPossible = random.NextBoolean(), SupportDirectUnicast = random.NextBoolean(), PreferredLifetime = TimeSpan.FromDays(0.5), RenewalTime = TimeSpan.FromDays(0.25), LeaseTime = TimeSpan.FromDays(1), MaskLength = (Byte)random.Next(10, 29), } : new DHCPv4ScopeAddressPropertyReqest { Start = start.ToString(), End = end.ToString(), ExcludedAddresses = Array.Empty <String>(), AcceptDecline = random.NextBoolean(), AddressAllocationStrategy = DHCPv4ScopeAddressPropertyReqest.AddressAllocationStrategies.Next, InformsAreAllowd = random.NextBoolean(), ReuseAddressIfPossible = random.NextBoolean(), SupportDirectUnicast = random.NextBoolean(), DynamicRenewTime = new DHCPv4DynamicRenewTimeRequest { Hours = 5, Minutes = 10, MinutesToEndOfLife = 45, MinutesToRebound = 35, }, MaskLength = (Byte)random.Next(10, 29), } , new CreateScopeResolverRequest { PropertiesAndValues = new Dictionary <String, String>(), Typename = resolverName, }, new DHCPv4ScopePropertyRequest[] { new DHCPv4AddressListScopePropertyRequest { OptionCode = 24, Type = DHCPv4ScopePropertyType.AddressList, Addresses = random.GetIPv4Addresses().Select(x => x.ToString()).ToArray(), }, new DHCPv4AddressScopePropertyRequest { OptionCode = 25, Type = DHCPv4ScopePropertyType.Address, Address = random.GetIPv4Address().ToString() }, new DHCPv4BooleanScopePropertyRequest { OptionCode = 26, Type = DHCPv4ScopePropertyType.Boolean, Value = random.NextBoolean() }, new DHCPv4NumericScopePropertyRequest { OptionCode = 27, Type = DHCPv4ScopePropertyType.UInt16, NumericType = DHCPv4NumericValueTypes.UInt16, Value = (UInt16)random.NextUInt16() }, new DHCPv4TextScopePropertyRequest { OptionCode = 28, Type = DHCPv4ScopePropertyType.Text, Value = random.GetAlphanumericString() }, new DHCPv4TimeScopePropertyRequest { OptionCode = 29, Type = DHCPv4ScopePropertyType.Time, Value = TimeSpan.FromSeconds(random.Next(10, 20)) }, new DHCPv4AddressListScopePropertyRequest { OptionCode = 64, MarkAsRemovedInInheritance = true, } } ); var serviceBusMock = new Mock <IServiceBus>(MockBehavior.Strict); serviceBusMock.Setup(x => x.Publish(It.Is <NewTriggerHappendMessage>(y => y.Triggers.Count() == 1 && ((PrefixEdgeRouterBindingUpdatedTrigger)y.Triggers.First()).OldBinding.Prefix == IPv4Address.FromString("fc70::0") ))).Returns(Task.CompletedTask); var handler = new UpdateDHCPv4ScopeCommandHandler(storageMock.Object, serviceBusMock.Object, rootScope, Mock.Of <ILogger <UpdateDHCPv4ScopeCommandHandler> >()); Boolean result = await handler.Handle(command, CancellationToken.None); Assert.Equal(storeResult, result); var scope = rootScope.GetRootScopes().First(); Assert.Equal(name, scope.Name); Assert.Equal(description, scope.Description); Assert.NotNull(scope.Resolver); Assert.Equal(start, scope.AddressRelatedProperties.Start); Assert.True(scope.Properties.IsMarkedAsRemovedFromInheritance(64)); Assert.False(scope.Properties.IsMarkedAsRemovedFromInheritance(24)); if (useDynamicTime == true) { Assert.True(scope.AddressRelatedProperties.UseDynamicRewnewTime); Assert.Equal(5, scope.AddressRelatedProperties.DynamicRenewTime.Hour); } else { Assert.False(scope.AddressRelatedProperties.UseDynamicRewnewTime); } scopeResolverMock.Verify(); storageMock.Verify(); serviceBusMock.Verify(); Assert.Empty(rootScope.GetTriggers()); }